context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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 NUnit.Framework;
using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestDirectoryReader:LuceneTestCase
{
protected internal Directory dir;
private Document doc1;
private Document doc2;
protected internal SegmentReader[] readers = new SegmentReader[2];
protected internal SegmentInfos sis;
public TestDirectoryReader(System.String s):base(s)
{
}
public TestDirectoryReader() : base("")
{
}
[SetUp]
public override void SetUp()
{
base.SetUp();
dir = new RAMDirectory();
doc1 = new Document();
doc2 = new Document();
DocHelper.SetupDoc(doc1);
DocHelper.SetupDoc(doc2);
DocHelper.WriteDoc(dir, doc1);
DocHelper.WriteDoc(dir, doc2);
sis = new SegmentInfos();
sis.Read(dir);
}
protected internal virtual IndexReader OpenReader()
{
IndexReader reader;
reader = IndexReader.Open(dir);
Assert.IsTrue(reader is DirectoryReader);
Assert.IsTrue(dir != null);
Assert.IsTrue(sis != null);
Assert.IsTrue(reader != null);
return reader;
}
[Test]
public virtual void Test()
{
SetUp();
DoTestDocument();
DoTestUndeleteAll();
}
public virtual void DoTestDocument()
{
sis.Read(dir);
IndexReader reader = OpenReader();
Assert.IsTrue(reader != null);
Document newDoc1 = reader.Document(0);
Assert.IsTrue(newDoc1 != null);
Assert.IsTrue(DocHelper.NumFields(newDoc1) == DocHelper.NumFields(doc1) - DocHelper.unstored.Count);
Document newDoc2 = reader.Document(1);
Assert.IsTrue(newDoc2 != null);
Assert.IsTrue(DocHelper.NumFields(newDoc2) == DocHelper.NumFields(doc2) - DocHelper.unstored.Count);
TermFreqVector vector = reader.GetTermFreqVector(0, DocHelper.TEXT_FIELD_2_KEY);
Assert.IsTrue(vector != null);
TestSegmentReader.CheckNorms(reader);
}
public virtual void DoTestUndeleteAll()
{
sis.Read(dir);
IndexReader reader = OpenReader();
Assert.IsTrue(reader != null);
Assert.AreEqual(2, reader.NumDocs());
reader.DeleteDocument(0);
Assert.AreEqual(1, reader.NumDocs());
reader.UndeleteAll();
Assert.AreEqual(2, reader.NumDocs());
// Ensure undeleteAll survives commit/close/reopen:
reader.Commit();
reader.Close();
if (reader is MultiReader)
// MultiReader does not "own" the directory so it does
// not write the changes to sis on commit:
sis.Commit(dir);
sis.Read(dir);
reader = OpenReader();
Assert.AreEqual(2, reader.NumDocs());
reader.DeleteDocument(0);
Assert.AreEqual(1, reader.NumDocs());
reader.Commit();
reader.Close();
if (reader is MultiReader)
// MultiReader does not "own" the directory so it does
// not write the changes to sis on commit:
sis.Commit(dir);
sis.Read(dir);
reader = OpenReader();
Assert.AreEqual(1, reader.NumDocs());
}
public virtual void _testTermVectors()
{
MultiReader reader = new MultiReader(readers);
Assert.IsTrue(reader != null);
}
[Test]
public virtual void TestIsCurrent()
{
RAMDirectory ramDir1 = new RAMDirectory();
AddDoc(ramDir1, "test foo", true);
RAMDirectory ramDir2 = new RAMDirectory();
AddDoc(ramDir2, "test blah", true);
IndexReader[] readers = new IndexReader[]{IndexReader.Open(ramDir1), IndexReader.Open(ramDir2)};
MultiReader mr = new MultiReader(readers);
Assert.IsTrue(mr.IsCurrent()); // just opened, must be current
AddDoc(ramDir1, "more text", false);
Assert.IsFalse(mr.IsCurrent()); // has been modified, not current anymore
AddDoc(ramDir2, "even more text", false);
Assert.IsFalse(mr.IsCurrent()); // has been modified even more, not current anymore
try
{
mr.GetVersion();
Assert.Fail();
}
catch (System.NotSupportedException e)
{
// expected exception
}
mr.Close();
}
[Test]
public virtual void TestMultiTermDocs()
{
RAMDirectory ramDir1 = new RAMDirectory();
AddDoc(ramDir1, "test foo", true);
RAMDirectory ramDir2 = new RAMDirectory();
AddDoc(ramDir2, "test blah", true);
RAMDirectory ramDir3 = new RAMDirectory();
AddDoc(ramDir3, "test wow", true);
IndexReader[] readers1 = new IndexReader[]{IndexReader.Open(ramDir1), IndexReader.Open(ramDir3)};
IndexReader[] readers2 = new IndexReader[]{IndexReader.Open(ramDir1), IndexReader.Open(ramDir2), IndexReader.Open(ramDir3)};
MultiReader mr2 = new MultiReader(readers1);
MultiReader mr3 = new MultiReader(readers2);
// test mixing up TermDocs and TermEnums from different readers.
TermDocs td2 = mr2.TermDocs();
TermEnum te3 = mr3.Terms(new Term("body", "wow"));
td2.Seek(te3);
int ret = 0;
// This should blow up if we forget to check that the TermEnum is from the same
// reader as the TermDocs.
while (td2.Next())
ret += td2.Doc();
td2.Close();
te3.Close();
// really a dummy assert to ensure that we got some docs and to ensure that
// nothing is optimized out.
Assert.IsTrue(ret > 0);
}
[Test]
public virtual void TestAllTermDocs()
{
IndexReader reader = OpenReader();
int NUM_DOCS = 2;
TermDocs td = reader.TermDocs(null);
for (int i = 0; i < NUM_DOCS; i++)
{
Assert.IsTrue(td.Next());
Assert.AreEqual(i, td.Doc());
Assert.AreEqual(1, td.Freq());
}
td.Close();
reader.Close();
}
private void AddDoc(RAMDirectory ramDir1, System.String s, bool create)
{
IndexWriter iw = new IndexWriter(ramDir1, new StandardAnalyzer(), create, IndexWriter.MaxFieldLength.LIMITED);
Document doc = new Document();
doc.Add(new Field("body", s, Field.Store.YES, Field.Index.ANALYZED));
iw.AddDocument(doc);
iw.Close();
}
}
}
| |
/*
* CP1148.cs - IBM EBCDIC (International with Euro) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-1148.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP1148 : ByteEncoding
{
public CP1148()
: base(1148, ToChars, "IBM EBCDIC (International with Euro)",
"ibm1148", "ibm1148", "ibm1148",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5',
'\u00E7', '\u00F1', '\u005B', '\u002E', '\u003C', '\u0028',
'\u002B', '\u0021', '\u0026', '\u00E9', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u005D', '\u0024', '\u002A', '\u0029', '\u003B', '\u005E',
'\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1',
'\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00A6', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u0060', '\u003A', '\u0023', '\u0040', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u20AC', '\u00B5', '\u007E',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7',
'\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9',
'\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xA1; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xA1; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xA1; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x9F; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xA1; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1148
public class ENCibm1148 : CP1148
{
public ENCibm1148() : base() {}
}; // class ENCibm1148
}; // namespace I18N.Rare
| |
//
// PointPicker.cs
//
// Author:
// Olivier Dufour <olivier.duff@gmail.com>
//
// Copyright (c) 2010 Olivier Dufour
//
// 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.ComponentModel;
using Gtk;
using Pinta.Core;
namespace Pinta.Gui.Widgets
{
[System.ComponentModel.ToolboxItem(true)]
public class PointPickerWidget : FilledAreaBin
{
private Label label;
private PointPickerGraphic pointpickergraphic1;
private Button button1;
private Button button2;
private SpinButton spinX;
private SpinButton spinY;
bool active = true;
[Category("Custom Properties")]
public string Label {
get { return label.Text; }
set { label.Text = value; }
}
[Category("Custom Properties")]
public Gdk.Point DefaultPoint { get; set; }
[Category("Custom Properties")]
public Gdk.Point Point {
get { return new Gdk.Point (spinX.ValueAsInt, spinY.ValueAsInt); }
set {
if (value.X != spinX.ValueAsInt || value.Y != spinY.ValueAsInt) {
spinX.Value = value.X;
spinY.Value = value.Y;
OnPointPicked ();
}
}
}
[Category("Custom Properties")]
public Cairo.PointD DefaultOffset {
get { return new Cairo.PointD ( (DefaultPoint.X * 2.0 /PintaCore.Workspace.ImageSize.Width) - 1.0,
(DefaultPoint.Y * 2.0 / PintaCore.Workspace.ImageSize.Height) - 1.0);}
set {DefaultPoint = new Gdk.Point ( (int) ((value.X + 1.0) * PintaCore.Workspace.ImageSize.Width / 2.0 ),
(int) ((value.Y + 1.0) * PintaCore.Workspace.ImageSize.Height / 2.0 ) );}
}
public Cairo.PointD Offset {
get { return new Cairo.PointD ((spinX.Value * 2.0 / PintaCore.Workspace.ImageSize.Width) - 1.0, (spinY.Value * 2.0 / PintaCore.Workspace.ImageSize.Height) - 1.0); }
}
public PointPickerWidget ()
{
Build ();
spinX.Adjustment.Upper = PintaCore.Workspace.ImageSize.Width;
spinY.Adjustment.Upper = PintaCore.Workspace.ImageSize.Height;
spinX.Adjustment.Lower = 0;
spinY.Adjustment.Lower = 0;
spinX.ActivatesDefault = true;
spinY.ActivatesDefault = true;
}
void HandlePointpickergraphic1PositionChanged (object sender, EventArgs e)
{
if (Point != pointpickergraphic1.Position) {
active = false;
spinX.Value = pointpickergraphic1.Position.X;
spinY.Value = pointpickergraphic1.Position.Y;
active = true;
OnPointPicked ();
}
}
private void HandleSpinXValueChanged (object sender, EventArgs e)
{
if (active) {
pointpickergraphic1.Position = Point;
OnPointPicked ();
}
}
private void HandleSpinYValueChanged (object sender, EventArgs e)
{
if (active) {
pointpickergraphic1.Position = Point;
OnPointPicked ();
}
}
protected override void OnShown ()
{
base.OnShown ();
Point = DefaultPoint;
spinX.ValueChanged += HandleSpinXValueChanged;
spinY.ValueChanged += HandleSpinYValueChanged;
pointpickergraphic1.PositionChanged += HandlePointpickergraphic1PositionChanged;
button1.Pressed += HandleButton1Pressed;
button2.Pressed += HandleButton2Pressed;
pointpickergraphic1.Init (DefaultPoint);
}
void HandleButton1Pressed (object sender, EventArgs e)
{
spinX.Value = DefaultPoint.X;
}
void HandleButton2Pressed (object sender, EventArgs e)
{
spinY.Value = DefaultPoint.Y;
}
#region Protected Methods
protected void OnPointPicked ()
{
if (PointPicked != null)
PointPicked (this, EventArgs.Empty);
}
#endregion
#region Public Events
public event EventHandler PointPicked;
#endregion
private void Build ()
{
// Section label + line
var hbox1 = new HBox (false, 6);
label = new Label ();
hbox1.PackStart (label, false, false, 0);
hbox1.PackStart (new HSeparator (), true, true, 0);
// PointPickerGraphic
var hbox2 = new HBox (false, 6);
pointpickergraphic1 = new PointPickerGraphic ();
hbox2.PackStart (pointpickergraphic1, true, false, 0);
// X spinner
var label2 = new Label ();
label2.LabelProp = "X:";
spinX = new SpinButton (0, 100, 1);
spinX.CanFocus = true;
spinX.Adjustment.PageIncrement = 10;
spinX.ClimbRate = 1;
spinX.Numeric = true;
button1 = new Button ();
button1.WidthRequest = 28;
button1.HeightRequest = 24;
button1.CanFocus = true;
button1.UseUnderline = true;
var button_image = new Image (PintaCore.Resources.GetIcon (Stock.GoBack, 16));
button1.Add (button_image);
var alignment1 = new Alignment (0.5F, 0.5F, 1F, 0F);
alignment1.Add (button1);
var x_hbox = new HBox (false, 6);
x_hbox.PackStart (label2, false, false, 0);
x_hbox.PackStart (spinX, false, false, 0);
x_hbox.PackStart (alignment1, false, false, 0);
// Y spinner
var label3 = new Label ();
label3.LabelProp = "Y:";
spinY = new SpinButton (0, 100, 1);
spinY.CanFocus = true;
spinY.Adjustment.PageIncrement = 10;
spinY.ClimbRate = 1;
spinY.Numeric = true;
button2 = new Button ();
button2.WidthRequest = 28;
button2.HeightRequest = 24;
button2.CanFocus = true;
button2.UseUnderline = true;
var button_image2 = new Image (PintaCore.Resources.GetIcon (Stock.GoBack, 16));
button2.Add (button_image2);
var alignment2 = new Alignment (0.5F, 0.5F, 1F, 0F);
alignment2.Add (button2);
var y_hbox = new HBox (false, 6);
y_hbox.PackStart (label3, false, false, 0);
y_hbox.PackStart (spinY, false, false, 0);
y_hbox.PackStart (alignment2, false, false, 0);
// Vbox for spinners
var spin_vbox = new VBox ();
spin_vbox.Add (x_hbox);
spin_vbox.Add (y_hbox);
hbox2.PackStart (spin_vbox, false, false, 0);
// Main layout
var vbox = new VBox (false, 6);
vbox.Add (hbox1);
vbox.Add (hbox2);
Add (vbox);
vbox.ShowAll ();
}
}
}
| |
using System;
using System.Threading;
using L4p.Common.Extensions;
using L4p.Common.FunnelsModel.client;
using L4p.Common.FunnelsModel.config;
using L4p.Common.FunnelsModel.io;
using L4p.Common.IoCs;
using L4p.Common.Loggers;
using L4p.Common.Schedulers;
using L4p.Common.TtlCaches;
namespace L4p.Common.FunnelsModel
{
public partial interface IFunnelsManager : IShouldBeStarted
{
IFunnelsManager Start();
void Stop();
IFunnel GetFunnelOfInstance<T>(T instance) where T : class;
IFunnel GetFunnelOfClass(Type type);
IFunnel GetCurrentFunnel();
IFunnel SetCurrentFunnel(IFunnel funnel);
}
interface IFunnelsManagerEx : IFunnelsManager
{
void CleanDeadFunnels();
void PruneFunnelData(Guid storeId, string path);
void ShopIsRemoved(comm.ShopInfo shopInfo);
bool ProcessIo();
}
public partial class FunnelsManager : IFunnelsManagerEx
{
#region members
private readonly IFmConfigRa _config;
private readonly ThreadLocal<IFunnel> _current;
private readonly IIoC _ioc;
private readonly IFunnelsRepo _repo;
private readonly ITtlCache<IFunnel, IFunnelStore> _cache;
private readonly IEventScheduler _idler;
private readonly IFunnelsAgent _agent;
private readonly IIoSink _sink;
private readonly IIoThreads _threads;
private readonly IFmFactoryEngine _factory;
#endregion
#region construction
public static IFunnelsManager New(FunnelsConfig config = null)
{
config = config ?? new FunnelsConfig();
return
new FunnelsManager(config);
}
private static IIoC create_dependencies(FunnelsConfig config, IFunnelsManagerEx self)
{
var ioc = IoC.New(self);
var log = LogFile.New("funnels.log");
ioc.SingleInstance(() => log);
ioc.SingleInstance(() => FmConfigRa.New(config));
ioc.SingleInstance(FunnelsRepo.New);
ioc.SingleInstance(IoQueue.New);
ioc.SingleInstance(IoSink.New);
ioc.SingleInstance(TtlCache<IFunnel, IFunnelStore>.New);
ioc.SingleInstance(() => EventScheduler.New(log));
ioc.SingleInstance(FunnelsAgent.New);
ioc.SingleInstance(IoThreads.New);
ioc.SingleInstance(FmFactoryEngine.New);
ioc.SingleInstance(IoConnector.New);
return ioc;
}
private FunnelsManager(FunnelsConfig config)
{
_current = new ThreadLocal<IFunnel>(() => Null.Funnel);
var ioc = create_dependencies(config, this);
_ioc = ioc;
_config = _ioc.Resolve<IFmConfigRa>();
_repo = ioc.Resolve<IFunnelsRepo>();
_cache = ioc.Resolve<ITtlCache<IFunnel, IFunnelStore>>();
_idler = ioc.Resolve<IEventScheduler>();
_agent = ioc.Resolve<IFunnelsAgent>();
_sink = ioc.Resolve<IIoSink>();
_threads = ioc.Resolve<IIoThreads>();
_factory = ioc.Resolve<IFmFactoryEngine>();
}
#endregion
#region private
private string type_to_name(Type type)
{
var name = type.Name;
return name;
}
private string enum_to_name<E>(E enumValue)
where E : struct
{
var type = typeof(E);
var value = enumValue.ToString();
var name =
"{0}/{1}".Fmt(type.Name, value);
return name;
}
private static string make_funnel_id(string name, string tag)
{
if (tag.IsEmpty())
return name;
return
"{0}/{1}".Fmt(name, tag);
}
private IFunnel make_funnel(string name, string tag)
{
var funnelId = make_funnel_id(name, tag);
var store = _repo.GetByFunnelId(funnelId);
if (store == null)
{
store = _factory.MakeStore(funnelId);
store = _repo.Add(funnelId, store);
}
var funnel = Funnel.New(this, store);
_cache.Store(funnel, store);
return funnel;
}
private IFunnel get_funnel(string name, string tag)
{
return
make_funnel(name, tag);
}
#endregion
#region IFunnelsManager
IFunnelsManager IFunnelsManager.Start()
{
var self = this as IFunnelsManagerEx;
_idler.Repeat(_config.Config.Client.CleanDeadFunnelsSpan, self.CleanDeadFunnels);
_agent.Start();
_idler.Start();
_threads.Start();
return this;
}
void IFunnelsManager.Stop()
{
_idler.Stop();
_agent.Stop();
var stores = _repo.GetAllStores();
if (stores != null)
foreach (var store in stores)
{
store.Stop();
}
}
void IFunnelsManagerEx.CleanDeadFunnels()
{
var stores = _cache.GetDeadBodies(_config.Config.Client.FunnelStoreTtlSpan);
if (stores != null)
foreach (var store in stores)
{
_repo.Remove(store);
}
var now = DateTime.UtcNow;
var toBeStopped = _repo.PopRemovedStores(now, _config.Config.Client.FunnelStoreTtlSpan);
foreach (var store in toBeStopped)
{
store.Stop();
}
}
void IFunnelsManagerEx.PruneFunnelData(Guid storeId, string path)
{
IFunnelStore store = _repo.GetByStoreId(storeId);
if (store == null)
return;
store.PruneFunnelData(path);
}
void IFunnelsManagerEx.ShopIsRemoved(comm.ShopInfo shopInfo)
{
throw new NotImplementedException();
}
bool IFunnelsManagerEx.ProcessIo()
{
return
_sink.ProcessIo();
}
IFunnel IFunnelsManager.GetFunnelOfInstance<T>(T instance)
{
throw new NotImplementedException();
}
IFunnel IFunnelsManager.GetFunnelOfClass(Type type)
{
var name = type_to_name(type);
return
make_funnel(name, null);
}
IFunnel IFunnelsManager.GetCurrentFunnel()
{
return
_current.Value;
}
IFunnel IFunnelsManager.SetCurrentFunnel(IFunnel funnel)
{
var prev = _current.Value;
_current.Value = funnel;
return prev;
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Runtime
{
// AsyncResult starts acquired; Complete releases.
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")]
internal abstract class AsyncResult : IAsyncResult
{
private static AsyncCallback s_asyncCompletionWrapperCallback;
private AsyncCallback _callback;
private bool _completedSynchronously;
private bool _endCalled;
private Exception _exception;
private bool _isCompleted;
private AsyncCompletion _nextAsyncCompletion;
private object _state;
private Action _beforePrepareAsyncCompletionAction;
private Func<IAsyncResult, bool> _checkSyncValidationFunc;
[Fx.Tag.SynchronizationObject]
private ManualResetEvent _manualResetEvent;
[Fx.Tag.SynchronizationObject(Blocking = false)]
private object _thisLock;
protected AsyncResult(AsyncCallback callback, object state)
{
_callback = callback;
_state = state;
_thisLock = new object();
}
public object AsyncState
{
get
{
return _state;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_manualResetEvent != null)
{
return _manualResetEvent;
}
lock (ThisLock)
{
if (_manualResetEvent == null)
{
_manualResetEvent = new ManualResetEvent(_isCompleted);
}
}
return _manualResetEvent;
}
}
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
}
public bool HasCallback
{
get
{
return _callback != null;
}
}
public bool IsCompleted
{
get
{
return _isCompleted;
}
}
// used in conjunction with PrepareAsyncCompletion to allow for finally blocks
protected Action<AsyncResult, Exception> OnCompleting { get; set; }
private object ThisLock
{
get
{
return _thisLock;
}
}
// subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope
protected Action<AsyncCallback, IAsyncResult> VirtualCallback
{
get;
set;
}
protected void Complete(bool completedSynchronously)
{
if (_isCompleted)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType())));
}
_completedSynchronously = completedSynchronously;
if (OnCompleting != null)
{
// Allow exception replacement, like a catch/throw pattern.
try
{
OnCompleting(this, _exception);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
_exception = exception;
}
}
if (completedSynchronously)
{
// If we completedSynchronously, then there's no chance that the manualResetEvent was created so
// we don't need to worry about a race condition.
Fx.Assert(_manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
_isCompleted = true;
}
else
{
lock (ThisLock)
{
_isCompleted = true;
if (_manualResetEvent != null)
{
_manualResetEvent.Set();
}
}
}
if (_callback != null)
{
try
{
if (VirtualCallback != null)
{
VirtualCallback(_callback, this);
}
else
{
this._callback(this);
}
}
#pragma warning disable 1634
#pragma warning suppress 56500 // transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e));
}
#pragma warning restore 1634
}
}
protected void Complete(bool completedSynchronously, Exception exception)
{
_exception = exception;
Complete(completedSynchronously);
}
private static void AsyncCompletionWrapperCallback(IAsyncResult result)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
if (result.CompletedSynchronously)
{
return;
}
AsyncResult thisPtr = (AsyncResult)result.AsyncState;
if (!thisPtr.OnContinueAsyncCompletion(result))
{
return;
}
AsyncCompletion callback = thisPtr.GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult(result);
}
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = callback(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
// Note: this should be only derived by the TransactedAsyncResult
protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
{
return true;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
{
_beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
{
_checkSyncValidationFunc = checkSyncValidationFunc;
}
protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
{
if (_beforePrepareAsyncCompletionAction != null)
{
this._beforePrepareAsyncCompletionAction();
}
_nextAsyncCompletion = callback;
if (AsyncResult.s_asyncCompletionWrapperCallback == null)
{
AsyncResult.s_asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback));
}
return AsyncResult.s_asyncCompletionWrapperCallback;
}
protected bool CheckSyncContinue(IAsyncResult result)
{
AsyncCompletion dummy;
return TryContinueHelper(result, out dummy);
}
protected bool SyncContinue(IAsyncResult result)
{
AsyncCompletion callback;
if (TryContinueHelper(result, out callback))
{
return callback(result);
}
else
{
return false;
}
}
private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
callback = null;
if (_checkSyncValidationFunc != null)
{
if (!this._checkSyncValidationFunc(result))
{
return false;
}
}
else if (!result.CompletedSynchronously)
{
return false;
}
callback = GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
}
return true;
}
private AsyncCompletion GetNextCompletion()
{
AsyncCompletion result = _nextAsyncCompletion;
_nextAsyncCompletion = null;
return result;
}
protected static void ThrowInvalidAsyncResult(IAsyncResult result)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
}
protected static void ThrowInvalidAsyncResult(string debugText)
{
string message = InternalSR.InvalidAsyncResultImplementationGeneric;
if (debugText != null)
{
#if DEBUG
message += " " + debugText;
#endif
}
throw Fx.Exception.AsError(new InvalidOperationException(message));
}
[Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")]
protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
where TAsyncResult : AsyncResult
{
if (result == null)
{
throw Fx.Exception.ArgumentNull("result");
}
TAsyncResult asyncResult = result as TAsyncResult;
if (asyncResult == null)
{
throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
}
if (asyncResult._endCalled)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
}
asyncResult._endCalled = true;
if (!asyncResult._isCompleted)
{
asyncResult.AsyncWaitHandle.WaitOne();
}
if (asyncResult._manualResetEvent != null)
{
asyncResult._manualResetEvent.Dispose();
}
if (asyncResult._exception != null)
{
throw Fx.Exception.AsError(asyncResult._exception);
}
return asyncResult;
}
// can be utilized by subclasses to write core completion code for both the sync and async paths
// in one location, signalling chainable synchronous completion with the boolean result,
// and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.
// NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine.
protected delegate bool AsyncCompletion(IAsyncResult result);
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2013 Atif Aziz. 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.
#endregion
#if !MORELINQ
//
// For projects that may include/embed this source file directly, suppress the
// following warnings since the hosting project may not require CLS compliance
// and MoreEnumerable will most probably be internal.
//
#pragma warning disable 3019 // CLS compliance checking will not be performed on 'type' because it is not visible from outside this assembly
#pragma warning disable 3021 // 'type' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute
#endif
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
partial class MoreEnumerable
{
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<bool> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Boolean);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, bool, StringBuilder> Boolean = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<byte> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Byte);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, byte, StringBuilder> Byte = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<char> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Char);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, char, StringBuilder> Char = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<decimal> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Decimal);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, decimal, StringBuilder> Decimal = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<double> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Double);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, double, StringBuilder> Double = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<float> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Single);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, float, StringBuilder> Single = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<int> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Int32);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, int, StringBuilder> Int32 = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<long> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Int64);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, long, StringBuilder> Int64 = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
[CLSCompliant(false)]
public static string ToDelimitedString(this IEnumerable<sbyte> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.SByte);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, sbyte, StringBuilder> SByte = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<short> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.Int16);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, short, StringBuilder> Int16 = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
public static string ToDelimitedString(this IEnumerable<string> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.String);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, string, StringBuilder> String = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
[CLSCompliant(false)]
public static string ToDelimitedString(this IEnumerable<uint> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.UInt32);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, uint, StringBuilder> UInt32 = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
[CLSCompliant(false)]
public static string ToDelimitedString(this IEnumerable<ulong> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.UInt64);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, ulong, StringBuilder> UInt64 = (sb, e) => sb.Append(e);
}
/// <summary>
/// Creates a delimited string from a sequence of values and
/// a given delimiter.
/// </summary>
/// <param name="source">The sequence of items to delimit. Each is converted to a string using the
/// simple ToString() conversion.</param>
/// <param name="delimiter">The delimiter to inject between elements.</param>
/// <returns>
/// A string that consists of the elements in <paramref name="source"/>
/// delimited by <paramref name="delimiter"/>. If the source sequence
/// is empty, the method returns an empty string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> or <paramref name="delimiter"/> is <c>null</c>.
/// </exception>
/// <remarks>
/// This operator uses immediate execution and effectively buffers the sequence.
/// </remarks>
[CLSCompliant(false)]
public static string ToDelimitedString(this IEnumerable<ushort> source, string delimiter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (delimiter == null) throw new ArgumentNullException(nameof(delimiter));
return ToDelimitedStringImpl(source, delimiter, StringBuilderAppenders.UInt16);
}
static partial class StringBuilderAppenders
{
public static readonly Func<StringBuilder, ushort, StringBuilder> UInt16 = (sb, e) => sb.Append(e);
}
static partial class StringBuilderAppenders {}
}
}
| |
/*
* CollectionBase.cs - Implementation of the
* "System.Collections.CollectionBase" class.
*
* Copyright (C) 2001 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Collections
{
#if !ECMA_COMPAT
using System;
public abstract class CollectionBase : IList, ICollection, IEnumerable
{
// Internal state.
private ArrayList list;
// Constructor.
protected CollectionBase()
{
list = new ArrayList();
}
// Implement the IList interface.
int IList.Add(Object value)
{
OnValidate(value);
int index = list.Count;
OnInsert(index, value);
index = list.Add(value);
try
{
OnInsertComplete(index, value);
}
catch(Exception)
{
list.RemoveAt(index);
throw;
}
return index;
}
public void Clear()
{
OnClear();
list.Clear();
OnClearComplete();
}
bool IList.Contains(Object value)
{
return list.Contains(value);
}
int IList.IndexOf(Object value)
{
return list.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
OnValidate(value);
OnInsert(index, value);
list.Insert(index, value);
try
{
OnInsertComplete(index, value);
}
catch(Exception)
{
list.RemoveAt(index);
throw;
}
}
void IList.Remove(Object value)
{
OnValidate(value);
int index = list.IndexOf(value);
if(index != -1)
{
OnRemove(index, value);
list.RemoveAt(index);
try
{
OnRemoveComplete(index, value);
}
catch(Exception)
{
list.Insert(index, value);
throw;
}
}
else
{
throw new ArgumentException(_("Arg_NotFound"));
}
}
public void RemoveAt(int index)
{
if(index < 0 || index >= list.Count)
{
throw new ArgumentOutOfRangeException
("index", _("Arg_InvalidArrayIndex"));
}
Object value = list[index];
OnRemove(index, value);
list.RemoveAt(index);
try
{
OnRemoveComplete(index, value);
}
catch(Exception)
{
list.Insert(index, value);
throw;
}
}
bool IList.IsFixedSize
{
get
{
return list.IsFixedSize;
}
}
bool IList.IsReadOnly
{
get
{
return list.IsReadOnly;
}
}
Object IList.this[int index]
{
get
{
return list[index];
}
set
{
if(index < 0 || index >= list.Count)
{
throw new ArgumentOutOfRangeException
("index", _("Arg_InvalidArrayIndex"));
}
OnValidate(value);
Object oldValue = list[index];
OnSet(index, oldValue, value);
list[index] = value;
try
{
OnSetComplete(index, oldValue, value);
}
catch(Exception)
{
list[index] = oldValue;
throw;
}
}
}
// Implement the ICollection interface.
void ICollection.CopyTo(Array array, int index)
{
list.CopyTo(array, index);
}
public int Count
{
get
{
return list.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return list.IsSynchronized;
}
}
Object ICollection.SyncRoot
{
get
{
return list.SyncRoot;
}
}
// Implement the IEnumerable interface.
public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}
// Get the inner list that is being used by this collection base.
protected ArrayList InnerList
{
get
{
return list;
}
}
// Get this collection base, represented as an IList.
protected IList List
{
get
{
return this;
}
}
// Collection control methods.
protected virtual void OnClear() {}
protected virtual void OnClearComplete() {}
protected virtual void OnInsert(int index, Object value) {}
protected virtual void OnInsertComplete(int index, Object value) {}
protected virtual void OnRemove(int index, Object value) {}
protected virtual void OnRemoveComplete(int index, Object value) {}
protected virtual void OnSet(int index, Object oldValue, Object newValue) {}
protected virtual void OnSetComplete
(int index, Object oldValue, Object newValue) {}
protected virtual void OnValidate(Object value)
{
if(value == null)
{
throw new ArgumentNullException("value");
}
}
}; // class CollectionBase
#endif // !ECMA_COMPAT
}; // namespace System.Collections
| |
// 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 lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTargetPoolsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTargetPoolRequest request = new GetTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
TargetPool expectedResponse = new TargetPool
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Instances =
{
"instances5432a96f",
},
CreationTimestamp = "creation_timestamp235e59a1",
BackupPool = "backup_pool2446601c",
Region = "regionedb20d96",
FailoverRatio = -7.1869584E+17F,
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
SelfLink = "self_link7e87f12d",
SessionAffinity = TargetPool.Types.SessionAffinity.GeneratedCookie,
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPool response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTargetPoolRequest request = new GetTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
TargetPool expectedResponse = new TargetPool
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Instances =
{
"instances5432a96f",
},
CreationTimestamp = "creation_timestamp235e59a1",
BackupPool = "backup_pool2446601c",
Region = "regionedb20d96",
FailoverRatio = -7.1869584E+17F,
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
SelfLink = "self_link7e87f12d",
SessionAffinity = TargetPool.Types.SessionAffinity.GeneratedCookie,
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TargetPool>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPool responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TargetPool responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTargetPoolRequest request = new GetTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
TargetPool expectedResponse = new TargetPool
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Instances =
{
"instances5432a96f",
},
CreationTimestamp = "creation_timestamp235e59a1",
BackupPool = "backup_pool2446601c",
Region = "regionedb20d96",
FailoverRatio = -7.1869584E+17F,
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
SelfLink = "self_link7e87f12d",
SessionAffinity = TargetPool.Types.SessionAffinity.GeneratedCookie,
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPool response = client.Get(request.Project, request.Region, request.TargetPool);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTargetPoolRequest request = new GetTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
};
TargetPool expectedResponse = new TargetPool
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Instances =
{
"instances5432a96f",
},
CreationTimestamp = "creation_timestamp235e59a1",
BackupPool = "backup_pool2446601c",
Region = "regionedb20d96",
FailoverRatio = -7.1869584E+17F,
Description = "description2cf9da67",
HealthChecks =
{
"health_checksedb1f3f8",
},
SelfLink = "self_link7e87f12d",
SessionAffinity = TargetPool.Types.SessionAffinity.GeneratedCookie,
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TargetPool>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPool responseCallSettings = await client.GetAsync(request.Project, request.Region, request.TargetPool, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TargetPool responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.TargetPool, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetHealthRequestObject()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthTargetPoolRequest request = new GetHealthTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
InstanceReferenceResource = new InstanceReference(),
};
TargetPoolInstanceHealth expectedResponse = new TargetPoolInstanceHealth
{
Kind = "kindf7aa39d9",
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPoolInstanceHealth response = client.GetHealth(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetHealthRequestObjectAsync()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthTargetPoolRequest request = new GetHealthTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
InstanceReferenceResource = new InstanceReference(),
};
TargetPoolInstanceHealth expectedResponse = new TargetPoolInstanceHealth
{
Kind = "kindf7aa39d9",
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TargetPoolInstanceHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPoolInstanceHealth responseCallSettings = await client.GetHealthAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TargetPoolInstanceHealth responseCancellationToken = await client.GetHealthAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetHealth()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthTargetPoolRequest request = new GetHealthTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
InstanceReferenceResource = new InstanceReference(),
};
TargetPoolInstanceHealth expectedResponse = new TargetPoolInstanceHealth
{
Kind = "kindf7aa39d9",
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealth(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPoolInstanceHealth response = client.GetHealth(request.Project, request.Region, request.TargetPool, request.InstanceReferenceResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetHealthAsync()
{
moq::Mock<TargetPools.TargetPoolsClient> mockGrpcClient = new moq::Mock<TargetPools.TargetPoolsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetHealthTargetPoolRequest request = new GetHealthTargetPoolRequest
{
TargetPool = "target_pool65e437ac",
Region = "regionedb20d96",
Project = "projectaa6ff846",
InstanceReferenceResource = new InstanceReference(),
};
TargetPoolInstanceHealth expectedResponse = new TargetPoolInstanceHealth
{
Kind = "kindf7aa39d9",
HealthStatus = { new HealthStatus(), },
};
mockGrpcClient.Setup(x => x.GetHealthAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TargetPoolInstanceHealth>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TargetPoolsClient client = new TargetPoolsClientImpl(mockGrpcClient.Object, null);
TargetPoolInstanceHealth responseCallSettings = await client.GetHealthAsync(request.Project, request.Region, request.TargetPool, request.InstanceReferenceResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TargetPoolInstanceHealth responseCancellationToken = await client.GetHealthAsync(request.Project, request.Region, request.TargetPool, request.InstanceReferenceResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
namespace System
{
/// <summary>
/// Memory represents a contiguous region of arbitrary memory similar to Span.
/// Unlike Span, it is not a byref-like type.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
public readonly struct Memory<T>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is an array or an owned memory
// if (_index >> 31) == 1, object _object is an OwnedMemory<T>
// else, object _object is a T[].
private readonly object _object;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_object = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(OwnedMemory<T> owner, int index, int length)
{
if (owner == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
if (index < 0 || length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_object = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Memory(object obj, int index, int length)
{
// No validation performed; caller must provide any necessary validation.
_object = obj;
_index = index;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty { get; } = SpanHelpers.PerTypeValues<T>.EmptyArray;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
{
return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
}
else if (typeof(T) == typeof(char) && _object is string s)
{
// This is dangerous, returning a writable span for a string that should be immutable.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
return new Span<T>(Unsafe.As<Pinnable<T>>(s), SpanExtensions.StringAdjustment, s.Length).Slice(_index, _length);
}
else
{
return new Span<T>((T[])_object, _index, _length);
}
}
}
/// <summary>
/// Returns a handle for the array.
/// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
/// </summary>
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_object).Pin();
memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>());
}
else
{
var handle = GCHandle.Alloc(_object, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_object).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_object);
}
else
{
memoryHandle = new MemoryHandle(null);
}
}
return memoryHandle;
}
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
public bool TryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (((OwnedMemory<T>)_object).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
return true;
}
}
else
{
T[] arr = _object as T[];
if (typeof(T) != typeof(char) || arr != null)
{
arraySegment = new ArraySegment<T>(arr, _index, _length);
return true;
}
}
arraySegment = default(ArraySegment<T>);
return false;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode());
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
// Copyright (c) 2017 Jan Pluskal
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Netfox.Core.Enums;
namespace Netfox.Framework.Models.Snoopers.Email
{
/// <summary> Represents part of the IMF MIME document.</summary>
public class MIMEpart
{
#region Implementation of IEntity
[Key]
public Guid Id { get; private set; } = Guid.NewGuid();
public DateTime FirstSeen { get; set; }
#endregion
/// <summary> Encoding type of the part content.</summary>
public enum ContentTransferEncodingType
{
/// <summary> An enum constant representing the bit 7 option.</summary>
Bit7,
/// <summary> An enum constant representing the bit 8 option.</summary>
Bit8,
/// <summary> An enum constant representing the binary option.</summary>
Binary,
/// <summary> An enum constant representing the quotedprintable option.</summary>
Quotedprintable,
/// <summary> An enum constant representing the base 64 option.</summary>
Base64,
/// <summary> An enum constant representing the ietftoken option.</summary>
Ietftoken,
/// <summary> An enum constant representing the xtoken option.</summary>
Xtoken
}
/// <summary> The encoding.</summary>
public Encoding Encoding = new ASCIIEncoding();
//private XElement _errorLogElement;
/// <summary> The email.</summary>
private MIMEemail _email;
/// <summary> The boundary.</summary>
private String _boundary;
/// <summary> The headers.</summary>
private List<MIMEheader> _headers;
private FileInfo _storedHeaders;
private FileInfo _storedContent;
#region Constructors
private MIMEpart() { }//EF
/// <summary> Constructor.</summary>
/// <param name="email"> The email. </param>
public MIMEpart(MIMEemail email)
{
this._headers = new List<MIMEheader>();
this.ContainedParts = new List<MIMEpart>();
this.IsMIMEpart = false;
this.ContentTransferEncoding = ContentTransferEncodingType.Bit7;
this._email = email;
//_errorLogElement = errorLogElement;
}
#endregion
#region debug
/// <summary> Print statistics.</summary>
/// <param name="indent"> (Optional) the indent. </param>
public void PrintStats(int indent = 0)
{
var indentString = string.Concat(Enumerable.Repeat(" ", indent));
Console.WriteLine(indentString + "-------------------");
Console.WriteLine(indentString + "IsMIMEpart: " + this.IsMIMEpart);
Console.WriteLine(indentString + "IsMultiPart: " + this.IsMultiPart);
Console.WriteLine(indentString + "ContentType: " + this.ContentType + "/" + this.ContentSubtype);
Console.WriteLine(indentString + "ContentBoundary: " + this.ContentBoundary);
Console.WriteLine(indentString + "ContentTypeName: " + this.ContentTypeName);
if(this.RawContent != null) { Console.WriteLine(indentString + "ContentSize: " + this.RawContent.Length); }
Console.WriteLine(indentString + "ContainedParts: ");
foreach(var part in this.ContainedParts) { part.PrintStats(indent + 1); }
Console.WriteLine(indentString + "-------------------");
}
#endregion
#region MIME Part properties
/// <summary> MIME parts included in this part.</summary>
/// <value> The contained parts.</value>
public List<MIMEpart> ContainedParts { get; }
/// <summary> Type of content encoding.</summary>
/// <value> The content transfer encoding.</value>
public ContentTransferEncodingType ContentTransferEncoding { get; set; }
/// <summary> Gets or sets a value indicating whether this object is mim epart.</summary>
/// <value> true if this object is mim epart, false if not.</value>
public bool IsMIMEpart { get; set; }
/// <summary> Gets the part boundary.</summary>
/// <value> The part boundary.</value>
public String PartBoundary
{
get
{
if(this._boundary == null) { return null; }
return "--" + this._boundary;
}
}
/// <summary> Gets the content boundary.</summary>
/// <value> The content boundary.</value>
public String ContentBoundary
{
get
{
if(this._boundary == null) { return null; }
return "--" + this._boundary + "--";
}
}
/// <summary> Gets or sets a value indicating whether this object is multi part.</summary>
/// <value> true if this object is multi part, false if not.</value>
public bool IsMultiPart { get; set; }
/// <summary> Gets or sets the type of the content.</summary>
/// <value> The type of the content.</value>
public string ContentType { get; set; }
/// <summary> Gets or sets the content subtype.</summary>
/// <value> The content subtype.</value>
public string ContentSubtype { get; set; }
/// <summary> Gets or sets the name of the content type.</summary>
/// <value> The name of the content type.</value>
public string ContentTypeName { get; set; }
/// <summary> Gets or sets the content type charset.</summary>
/// <value> The content type charset.</value>
public string ContentTypeCharset { get; set; }
/// <summary> Gets or sets the content disposition.</summary>
/// <value> The content disposition.</value>
public string ContentDisposition { get; set; }
/// <summary> Gets or sets the filename of the content disposition file.</summary>
/// <value> The filename of the content disposition file.</value>
public string ContentDispositionFileName { get; set; }
/// <summary> Gets or sets the identifier of the content.</summary>
/// <value> The identifier of the content.</value>
public string ContentID { get; set; }
/// <summary> Gets or sets the identifier of the message.</summary>
/// <value> The identifier of the message.</value>
public string MessageID { get; set; }
/// <summary> Gets or sets the in reply to.</summary>
/// <value> The in reply to.</value>
public string InReplyTo { get; set; }
/// <summary> Gets or sets the subject.</summary>
/// <value> The subject.</value>
public string Subject { get; set; }
/// <summary> Gets or sets the source for the.</summary>
/// <value> from.</value>
public string From { get; set; }
/// <summary> Gets or sets to.</summary>
/// <value> to.</value>
public string To { get; set; }
/// <summary> Gets or sets the Cc.</summary>
/// <value> The Cc.</value>
public string Cc { get; set; }
/// <summary> Gets or sets the Bcc.</summary>
/// <value> The Bcc.</value>
public string Bcc { get; set; }
/// <summary> Gets or sets the date.</summary>
/// <value> The date.</value>
public string Date { get; set; }
/// <summary> Gets or sets the raw content.</summary>
/// <value> The raw content.</value>
public string RawContent { get; set; }
/// <summary> Gets or sets the raw headers.</summary>
/// <value> The raw headers.</value>
public string RawHeaders { get; set; }
/// <summary> Gets or sets a value indicating whether this object has empty content.</summary>
/// <value> true if this object has empty content, false if not.</value>
public bool HasEmptyContent { get; set; }
/// <summary> Gets the filename of the suggested file.</summary>
/// <value> The filename of the suggested file.</value>
public string SuggestedFilename
{
get
{
if(!(String.IsNullOrEmpty(this.ContentDispositionFileName))) { return this.ContentDispositionFileName; }
if(!(String.IsNullOrEmpty(this.ContentTypeName))) { return this.ContentTypeName; }
return String.Empty;
}
}
/// <summary> Path to the RAW headers file. If empty, headers were not stored.</summary>
/// <value> The full pathname of the stored headers file.</value>
[NotMapped]
public FileInfo StoredHeaders
{
get { return this._storedHeaders ?? (this._storedHeaders = new FileInfo(this.StoredHeadersFilePath)); }
private set {
this._storedHeaders = value;
this.StoredHeadersFilePath = value.FullName;
}
}
public string StoredHeadersFilePath { get; set; }
public string StoredContentFilePath { get; set; }
/// <summary> Path to the part content file. If empty, content was not stored.</summary>
/// <value> The full pathname of the stored content file.</value>
[NotMapped]
public FileInfo StoredContent
{
get { return this._storedContent ?? (this._storedContent = new FileInfo(this.StoredContentFilePath)); }
private set
{
this._storedContent = value;
this.StoredContentFilePath = value.FullName;
}
}
/// <summary>
/// Determines extension for data content file. Extension is determined from headers fields.
/// </summary>
/// <value> The extension.</value>
public string Extension
{
get
{
// try to determine from Content-Type : name
if(this.ContentTypeName != String.Empty)
{
try
{
if(this.ContentTypeName != null)
{
var replaced = this.ContentTypeName.Replace("\"", "");
if(replaced != null)
{
var ext = Path.GetExtension(replaced);
if(ext != null) { return ext.Substring(1); }
}
}
}
catch(Exception ex) //todo
{
//_log.Error("Sleuth General exception", ex);
this._email.AddErrorReport(FcLogLevel.Warn, "MIME Part", "Unable to determine part extension", this.ContentTypeName, ex);
}
}
// Try to determine from content type
var extC = MIMEContentType.ContentTypeToExt(this.ContentType, this.ContentSubtype);
if(extC != String.Empty) { return extC; }
// Otherwise take default extension for text or binary data
if(this.ContentTransferEncoding == ContentTransferEncodingType.Bit7 || this.ContentTransferEncoding == ContentTransferEncodingType.Bit8) { return "txt"; }
return "bin";
}
}
#endregion
#region MIME Part modifiers
/// <summary> Add children part to list of childrens parts.</summary>
/// <param name="part"> The part. </param>
public void AddPart(MIMEpart part) { this.ContainedParts.Add(part); }
/// <summary> Store part data to files.</summary>
/// <param name="basePath"> Target directory. </param>
public void StorePartData(DirectoryInfo exportDirectoryInfo)
{
this.StorePartHeaders(exportDirectoryInfo);
this.StorePartContent(exportDirectoryInfo);
foreach(var part in this.ContainedParts) { part.StorePartData(exportDirectoryInfo); }
}
/// <summary> Clear content and headers data from memory.</summary>
public void FreeDataFromMemory()
{
this.RawContent = String.Empty;
this.RawHeaders = String.Empty;
foreach(var part in this.ContainedParts) { part.FreeDataFromMemory(); }
}
#endregion
#region Private store and convert methods
/// <summary> Stores part headers.</summary>
/// <param name="path"> Full pathname of the file. </param>
private void StorePartHeaders(DirectoryInfo exportDirectoryInfo)
{
this.StoredHeaders = new FileInfo(Path.Combine(exportDirectoryInfo.FullName, Guid.NewGuid() + "-HEADERS.txt"));
File.WriteAllText(this.StoredHeaders.FullName, this.RawHeaders);
}
/// <summary> Stores part content.</summary>
/// <param name="path"> Full pathname of the file. </param>
private void StorePartContent(DirectoryInfo exportDirectoryInfo)
{
byte[] binaryData = null;
if(this.RawContent == null) { return; }
this.StoredContent = new FileInfo(Path.Combine(exportDirectoryInfo.FullName, Guid.NewGuid() + "-CONTENT." + this.Extension));
// default content encoding is ASCII
//Encoding enc = Encoding.ASCII;
/* try
{ // try to determine content enconding according to headers
if (!String.IsNullOrEmpty(ContentTypeCharset))
enc = Encoding.GetEncoding(ContentTypeCharset);
}
catch (Exception ex)//todo
{
//TODO
_log.Error("Sleuth General exception", ex);
}
*/
if(this.ContentTransferEncoding == ContentTransferEncodingType.Bit7 || this.ContentTransferEncoding == ContentTransferEncodingType.Bit8)
{
// plaintext data
binaryData = this.Encoding.GetBytes(this.RawContent);
}
else if(this.ContentTransferEncoding == ContentTransferEncodingType.Base64)
{
// base64 encoding
try
{
//Console.WriteLine("RAWBASE64:\r\n" + RawContent);
// try to convert to binary data
binaryData = Convert.FromBase64String(this.RawContent);
}
catch(Exception ex) //todo
{
// in case of error write plaintext data
//_errorLogElement.WriteMIMEParseError(path,ex.Message);
// _log.Error("Sleuth General exception", ex);
this._email.AddErrorReport(FcLogLevel.Error, "MIME Part", "Unable to decode Base64 data", this.StoredContent.Name, ex);
/* _errorLogElement.Add(new XElement("MIMEPartError",
new XAttribute("partPath", path),
new XAttribute("exceptionMessage", ex.Message)));
*/
binaryData = Encoding.ASCII.GetBytes(this.RawContent);
}
}
else if(this.ContentTransferEncoding == ContentTransferEncodingType.Quotedprintable)
{
// quotedprintable encoding
// TODO check if works correct
var contentDecoted = this.RawContent;
var occurences = new Regex(@"(=[0-9A-Z]{2}){1,}", RegexOptions.Multiline);
var matches = occurences.Matches(contentDecoted);
foreach(Match match in matches)
{
try
{
var b = new byte[match.Groups[0].Value.Length/3];
for(var i = 0; i < match.Groups[0].Value.Length/3; i++) { b[i] = byte.Parse(match.Groups[0].Value.Substring(i*3 + 1, 2), NumberStyles.AllowHexSpecifier); }
var hexChar = this.Encoding.GetChars(b);
contentDecoted = contentDecoted.Replace(match.Groups[0].Value, hexChar[0].ToString());
}
catch(Exception ex) //todo
{
//_log.Error("Sleuth General exception", ex);
// TODO
this._email.AddErrorReport(FcLogLevel.Warn, "MIME Part", "Unable to decode Quoted printable content", this.StoredContent.Name, ex);
}
}
contentDecoted = contentDecoted.Replace("?=", "").Replace("=\r\n", "");
binaryData = this.Encoding.GetBytes(contentDecoted);
}
else
{
// Unknown conent encoding - write plainttext data
//_errorLogElement.WriteMIMEParseError(path, "Unknown Content-encoding");
/*_errorLogElement.Add(new XElement("MIMEPartError",
new XAttribute("partPath", path),
new XAttribute("exceptionMessage", "Unknown Content-encoding")));*/
this._email.AddErrorReport(FcLogLevel.Warn, "MIME Part", "Unknown Content-encoding assuming ASCII", this.StoredContent.Name);
binaryData = Encoding.ASCII.GetBytes(this.RawContent);
}
// write content data to target file
FileStream outFile;
outFile = new FileStream(this.StoredContent.FullName, FileMode.Create, FileAccess.Write);
outFile.Write(binaryData, 0, binaryData.Length);
outFile.Close();
}
#endregion
#region IMF headers processing
/// <summary>
/// Add preparsed header to the part. Important headers are analyzed and mirrored in part
/// properties.
/// </summary>
/// <param name="header"> The header. </param>
public void AddHeader(MIMEheader header)
{
if(header == null) { return; }
this._headers.Add(header);
if(header.Type.Equals("MIME-Version") && header.Value.Trim().Equals("1.0")) { this.IsMIMEpart = true; }
else if(header.Type.Equals("Content-Type")) { this.ParseContentType(header); }
else if(header.Type.Equals("Content-ID")) { this.ParseContentId(header); }
else if(header.Type.Equals("Content-Transfer-Encoding")) { this.ParseContentTransferEncoding(header); }
else if(header.Type.Equals("Message-ID")) { this.ParseMessageID(header); }
else if(header.Type.Equals("In-Reply-To")) { this.ParseInReplyTo(header); }
else if(header.Type.Equals("From")) { this.ParseFrom(header); }
else if(header.Type.Equals("To")) { this.ParseTo(header); }
else if(header.Type.Equals("Date")) { this.ParseDate(header); }
else if(header.Type.Equals("Content-Disposition")) { this.ParseContentDisposition(header); }
else if(header.Type.Equals("Cc")) { this.ParseCc(header); }
else if(header.Type.Equals("Bcc")) { this.ParseBcc(header); }
else if(header.Type.Equals("Subject")) { this.ParseSubject(header); }
}
/// <summary> Parse date.</summary>
/// <param name="header"> The header. </param>
private void ParseDate(MIMEheader header)
{
var dateString = header.Value.Trim();
var parts = dateString.Split(' ');
if(parts.Count() > 6)
{
var partsList = new List<string>(parts);
partsList.RemoveRange(6, partsList.Count - 6);
dateString = string.Join(" ", partsList);
}
var myCultureInfo = new CultureInfo("en-US");
try
{
var partDateTime = DateTime.ParseExact(dateString, "ddd, dd MMM yyyy HH:mm:ss zzzz", CultureInfo.InvariantCulture);
this.Date = partDateTime.ToUniversalTime().ToString("yyyy-MM-dd hh.mm.ss.fffffff");
}
catch(FormatException ex)
{
// _log.Error("Sleuth FormatException", ex);
this._email.AddErrorReport(FcLogLevel.Warn, "MIME Part", "Unable to parse date", dateString, ex);
//Console.WriteLine("Unable to parse '{0}' '{1}'", dateString,ex.Message);
}
}
/// <summary> Parse from.</summary>
/// <param name="header"> The header. </param>
private void ParseFrom(MIMEheader header) { this.From = header.Value.Trim(); }
/// <summary> Parse subject.</summary>
/// <param name="header"> The header. </param>
private void ParseSubject(MIMEheader header) { this.Subject = header.Value.Trim(); }
/// <summary> Parse to.</summary>
/// <param name="header"> The header. </param>
private void ParseTo(MIMEheader header) { this.To = header.Value.Trim(); }
/// <summary> Parse Cc.</summary>
/// <param name="header"> The header. </param>
private void ParseCc(MIMEheader header) { this.Cc = header.Value.Trim(); }
/// <summary> Parse Bcc.</summary>
/// <param name="header"> The header. </param>
private void ParseBcc(MIMEheader header) { this.Bcc = header.Value.Trim(); }
/// <summary> Parse message identifier.</summary>
/// <param name="header"> The header. </param>
private void ParseMessageID(MIMEheader header)
{
var messageID = header.Value.Trim();
this.MessageID = messageID;
}
/// <summary> Parse in reply to.</summary>
/// <param name="header"> The header. </param>
private void ParseInReplyTo(MIMEheader header) { this.InReplyTo = header.Value.Trim(); }
/// <summary> Parse content disposition.</summary>
/// <param name="header"> The header. </param>
private void ParseContentDisposition(MIMEheader header)
{
//From = header.Value.Trim();
var semSplit = new Regex("(?:^|;)(\"(?:[^\"]+|\"\")*\"|[^;]*)", RegexOptions.Compiled);
var first = true;
foreach(Match match in semSplit.Matches(header.Value))
{
if(first)
{
this.ContentDisposition = match.Value.Trim();
first = false;
}
else
{
var trimPart = match.Value.TrimStart(';').Trim();
var equalSeparator = new[]
{
'='
};
var partParts = trimPart.Split(equalSeparator, 2);
if(partParts.Count() == 2)
{
partParts[1] = partParts[1].Trim(' ', '\t', '\n', '\v', '\f', '\r', '"');
if(partParts[0].Equals("filename")) { this.ContentDispositionFileName = partParts[1]; }
}
}
}
}
/// <summary> Parse content transfer encoding.</summary>
/// <param name="header"> The header. </param>
private void ParseContentTransferEncoding(MIMEheader header)
{
switch(header.Value.Trim())
{
case "7bit":
this.ContentTransferEncoding = ContentTransferEncodingType.Bit7;
break;
case "8bit":
this.ContentTransferEncoding = ContentTransferEncodingType.Bit8;
break;
case "binary":
this.ContentTransferEncoding = ContentTransferEncodingType.Binary;
break;
case "quoted-printable":
this.ContentTransferEncoding = ContentTransferEncodingType.Quotedprintable;
break;
case "base64":
this.ContentTransferEncoding = ContentTransferEncodingType.Base64;
break;
case "ietf-token":
this.ContentTransferEncoding = ContentTransferEncodingType.Ietftoken;
break;
case "x-token":
this.ContentTransferEncoding = ContentTransferEncodingType.Xtoken;
break;
}
}
/// <summary> Parse content identifier.</summary>
/// <param name="header"> The header. </param>
private void ParseContentId(MIMEheader header)
{
var contentID = header.Value.Trim();
/* contentID = contentID.Remove(0, 1);
contentID = contentID.Remove(contentID.Length-1, 1);
*/
this.ContentID = contentID;
}
/// <summary> Parse content type.</summary>
/// <param name="header"> The header. </param>
private void ParseContentType(MIMEheader header)
{
var semSplit = new Regex("(?:^|;)(\"(?:[^\"]+|\"\")*\"|[^;]*)", RegexOptions.Compiled);
var first = true;
foreach(Match match in semSplit.Matches(header.Value))
{
if(first)
{
var slashSeparator = new[]
{
'/'
};
var typeParts = match.Value.Split(slashSeparator);
if(typeParts.Count() != 2) { return; }
this.ContentType = typeParts[0].Trim();
this.ContentSubtype = typeParts[1].Trim();
if(this.ContentType.Equals("multipart")) { this.IsMultiPart = true; }
first = false;
}
else
{
var trimPart = match.Value.TrimStart(';').Trim();
var equalSeparator = new[]
{
'='
};
var partParts = trimPart.Split(equalSeparator, 2);
if(partParts.Count() == 2)
{
partParts[1] = partParts[1].Trim(' ', '\t', '\n', '\v', '\f', '\r', '"');
if(partParts[0].Equals("boundary")) { this._boundary = partParts[1]; }
else if(partParts[0].Equals("name")) { this.ContentTypeName = partParts[1]; }
else if(partParts[0].Equals("charset"))
{
this.ContentTypeCharset = partParts[1];
try
{
this.Encoding = Encoding.GetEncoding(this.ContentTypeCharset);
;
}
catch(Exception ex) {
this._email.AddErrorReport(FcLogLevel.Warn, "MIME Part", "Unable to determine ConentType-Chartset", this.ContentTypeCharset, ex);
}
}
}
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.1 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public abstract class Sse41 : Ssse3
{
internal Sse41() { }
public new static bool IsSupported { [Intrinsic] get { return false; } }
public new abstract class X64 : Sse2.X64
{
internal X64() { }
public new static bool IsSupported { [Intrinsic] get { return false; } }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// PEXTRQ reg/m64, xmm, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static long Extract(Vector128<long> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// PEXTRQ reg/m64, xmm, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static ulong Extract(Vector128<ulong> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// PINSRQ xmm, reg/m64, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static Vector128<long> Insert(Vector128<long> value, long data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// PINSRQ xmm, reg/m64, imm8
/// This intrinisc is only available on 64-bit processes
/// </summary>
public static Vector128<ulong> Insert(Vector128<ulong> value, ulong data, byte index) { throw new PlatformNotSupportedException(); }
}
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// PBLENDW xmm, xmm/m128 imm8
/// </summary>
public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// PBLENDW xmm, xmm/m128 imm8
/// </summary>
public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8)
/// BLENDPS xmm, xmm/m128, imm8
/// </summary>
public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8)
/// BLENDPD xmm, xmm/m128, imm8
/// </summary>
public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// </summary>
public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// </summary>
public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<short> BlendVariable(Vector128<short> left, Vector128<short> right, Vector128<short> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<ushort> BlendVariable(Vector128<ushort> left, Vector128<ushort> right, Vector128<ushort> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<int> BlendVariable(Vector128<int> left, Vector128<int> right, Vector128<int> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<uint> BlendVariable(Vector128<uint> left, Vector128<uint> right, Vector128<uint> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<long> BlendVariable(Vector128<long> left, Vector128<long> right, Vector128<long> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// PBLENDVB xmm, xmm/m128, xmm
/// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements.
/// </summary>
public static Vector128<ulong> BlendVariable(Vector128<ulong> left, Vector128<ulong> right, Vector128<ulong> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask)
/// BLENDVPS xmm, xmm/m128, xmm0
/// </summary>
public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask)
/// BLENDVPD xmm, xmm/m128, xmm0
/// </summary>
public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ps (__m128 a)
/// ROUNDPS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> Ceiling(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_pd (__m128d a)
/// ROUNDPD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> Ceiling(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_sd (__m128d a)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> CeilingScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ss (__m128 a)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> CeilingScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_sd (__m128d a, __m128d b)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> CeilingScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ss (__m128 a, __m128 b)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> CeilingScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// PCMPEQQ xmm, xmm/m128
/// </summary>
public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// PCMPEQQ xmm, xmm/m128
/// </summary>
public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi16 (__m128i a)
/// PMOVSXBW xmm, xmm
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi16 (__m128i a)
/// PMOVZXBW xmm, xmm
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi32 (__m128i a)
/// PMOVSXBD xmm, xmm
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi32 (__m128i a)
/// PMOVZXBD xmm, xmm
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi32 (__m128i a)
/// PMOVSXWD xmm, xmm
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi32 (__m128i a)
/// PMOVZXWD xmm, xmm
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi64 (__m128i a)
/// PMOVSXBQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi64 (__m128i a)
/// PMOVZXBQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi64 (__m128i a)
/// PMOVSXWQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi64 (__m128i a)
/// PMOVZXWQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi32_epi64 (__m128i a)
/// PMOVSXDQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<int> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu32_epi64 (__m128i a)
/// PMOVZXDQ xmm, xmm
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXBW xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<short> ConvertToVector128Int16(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXBW xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<short> ConvertToVector128Int16(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXBD xmm, m32
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<int> ConvertToVector128Int32(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXBD xmm, m32
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<int> ConvertToVector128Int32(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXWD xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<int> ConvertToVector128Int32(short* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXWD xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<int> ConvertToVector128Int32(ushort* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXBQ xmm, m16
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXBQ xmm, m16
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXWQ xmm, m32
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(short* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXWQ xmm, m32
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(ushort* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVSXDQ xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(int* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// PMOVZXDQ xmm, m64
/// The native signature does not exist. We provide this additional overload for completeness.
/// </summary>
public static unsafe Vector128<long> ConvertToVector128Int64(uint* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8)
/// DPPS xmm, xmm/m128, imm8
/// </summary>
public static Vector128<float> DotProduct(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8)
/// DPPD xmm, xmm/m128, imm8
/// </summary>
public static Vector128<double> DotProduct(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi8 (__m128i a, const int imm8)
/// PEXTRB reg/m8, xmm, imm8
/// </summary>
public static byte Extract(Vector128<byte> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// PEXTRD reg/m32, xmm, imm8
/// </summary>
public static int Extract(Vector128<int> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// PEXTRD reg/m32, xmm, imm8
/// </summary>
public static uint Extract(Vector128<uint> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_ps (__m128 a, const int imm8)
/// EXTRACTPS xmm, xmm/m32, imm8
/// </summary>
public static float Extract(Vector128<float> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ps (__m128 a)
/// ROUNDPS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> Floor(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_pd (__m128d a)
/// ROUNDPD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> Floor(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_sd (__m128d a)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> FloorScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ss (__m128 a)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> FloorScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_sd (__m128d a, __m128d b)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> FloorScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ss (__m128 a, __m128 b)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> FloorScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// PINSRB xmm, reg/m8, imm8
/// </summary>
public static Vector128<sbyte> Insert(Vector128<sbyte> value, sbyte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// PINSRB xmm, reg/m8, imm8
/// </summary>
public static Vector128<byte> Insert(Vector128<byte> value, byte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// PINSRD xmm, reg/m32, imm8
/// </summary>
public static Vector128<int> Insert(Vector128<int> value, int data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// PINSRD xmm, reg/m32, imm8
/// </summary>
public static Vector128<uint> Insert(Vector128<uint> value, uint data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8)
/// INSERTPS xmm, xmm/m32, imm8
/// </summary>
public static Vector128<float> Insert(Vector128<float> value, Vector128<float> data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi8 (__m128i a, __m128i b)
/// PMAXSB xmm, xmm/m128
/// </summary>
public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu16 (__m128i a, __m128i b)
/// PMAXUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi32 (__m128i a, __m128i b)
/// PMAXSD xmm, xmm/m128
/// </summary>
public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu32 (__m128i a, __m128i b)
/// PMAXUD xmm, xmm/m128
/// </summary>
public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi8 (__m128i a, __m128i b)
/// PMINSB xmm, xmm/m128
/// </summary>
public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu16 (__m128i a, __m128i b)
/// PMINUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi32 (__m128i a, __m128i b)
/// PMINSD xmm, xmm/m128
/// </summary>
public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu32 (__m128i a, __m128i b)
/// PMINUD xmm, xmm/m128
/// </summary>
public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_minpos_epu16 (__m128i a)
/// PHMINPOSUW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8)
/// MPSADBW xmm, xmm/m128, imm8
/// </summary>
public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mul_epi32 (__m128i a, __m128i b)
/// PMULDQ xmm, xmm/m128
/// </summary>
public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
/// PMULLD xmm, xmm/m128
/// </summary>
public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
/// PMULLD xmm, xmm/m128
/// </summary>
public static Vector128<uint> MultiplyLow(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_packus_epi32 (__m128i a, __m128i b)
/// PACKUSDW xmm, xmm/m128
/// </summary>
public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ps (__m128 a, int rounding)
/// ROUNDPS xmm, xmm/m128, imm8(8)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<float> RoundToZero(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION; ROUNDPS xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_pd (__m128d a, int rounding)
/// ROUNDPD xmm, xmm/m128, imm8(8)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<double> RoundToZero(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION; ROUNDPD xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSD xmm, xmm/m128, imm8(4)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(8)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(11)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<double> RoundToZeroScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSD xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(8)
/// </summary>
public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC)
/// ROUNDSD xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<double> RoundToZeroScalar(Vector128<double> upper, Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSS xmm, xmm/m128, imm8(4)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(8)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(11)
/// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic.
/// </summary>
public static Vector128<float> RoundToZeroScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_CUR_DIRECTION)
/// ROUNDSS xmm, xmm/m128, imm8(4)
/// </summary>
public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(8)
/// </summary>
public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(9)
/// </summary>
public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(10)
/// </summary>
public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)
/// ROUNDSS xmm, xmm/m128, imm8(11)
/// </summary>
public static Vector128<float> RoundToZeroScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<sbyte> LoadAlignedVector128NonTemporal(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<byte> LoadAlignedVector128NonTemporal(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<short> LoadAlignedVector128NonTemporal(short* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<ushort> LoadAlignedVector128NonTemporal(ushort* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<int> LoadAlignedVector128NonTemporal(int* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<uint> LoadAlignedVector128NonTemporal(uint* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<long> LoadAlignedVector128NonTemporal(long* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// MOVNTDQA xmm, m128
/// </summary>
public static unsafe Vector128<ulong> LoadAlignedVector128NonTemporal(ulong* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testc_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testnzc_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testz_si128 (__m128i a, __m128i b)
/// PTEST xmm, xmm/m128
/// </summary>
public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;
using System.Diagnostics;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: in progress
/// -------------------------------------------------------------------------
/// Simon Pucher 2016
/// -------------------------------------------------------------------------
/// The indicator was taken from: http://ninjatrader.com/support/forum/showthread.php?t=37759
/// Code was generated by AgenaTrader conversion tool and modified by Simon Pucher.
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this script without any error you also need access to the utility indicator to use these global source code elements.
/// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
/// <summary>
/// OutputDescriptors horizontal rays at swing highs and lows and removes them once broken.
/// </summary>
[Description("Plots horizontal rays at swing highs and lows and removes them once broken. Returns 1 if a high has broken. Returns -1 if a low has broken. Returns 0 in all other cases.")]
public class SwingRays : UserIndicator
{
/// <summary>
/// Object is storing ray data
/// </summary>
private class RayObject
{
public RayObject(string tag, int anchor1BarsAgo, double anchor1Y, int anchor2BarsAgo, double anchor2Y) {
this.Tag = tag;
this.BarsAgo1 = anchor1BarsAgo;
this.BarsAgo2 = anchor2BarsAgo;
this.Y1 = anchor1Y;
this.Y2 = anchor2Y;
}
public string Tag { get; set; }
public int BarsAgo1 { get; set; }
public int BarsAgo2 { get; set; }
//Pen Pen { get; set; }
//DateTime X1 { get; set; }
//DateTime X2 { get; set; }
public double Y1 { get; set; }
public double Y2 { get; set; }
}
// Wizard generated variables
private int strength = 5; // number of bars required to left and right of the pivot high/low
// User defined variables (add any user defined variables below)
private Color swingHighColor = Color.Green;
private Color swingLowColor = Color.Red;
private ArrayList lastHighCache;
private ArrayList lastLowCache;
private double lastSwingHighValue = double.MaxValue; // used when testing for price breaks
private double lastSwingLowValue = double.MinValue;
private Stack<RayObject> swingHighRays; // last entry contains nearest swing high; removed when swing is broken
private Stack<RayObject> swingLowRays; // track swing lows in the same manner
private bool enableAlerts = false;
private bool keepBrokenLines = true;
//input
private Color _signal = Color.Orange;
private int _plot0Width = Const.DefaultLineWidth;
private DashStyle _dash0Style = Const.DefaultIndicatorDashStyle;
private Soundfile _soundfile = Soundfile.Blip;
/// <summary>
/// This method is used to configure the indicator and is called once before any bar data is loaded.
/// </summary>
protected override void OnInit()
{
IsShowInDataBox = false;
CalculateOnClosedBar = true;
IsOverlay = false;
PriceTypeSupported = false;
lastHighCache = new ArrayList(); // used to identify swing points; from default Swing indicator
lastLowCache = new ArrayList();
swingHighRays = new Stack<RayObject>(); // LIFO buffer; last entry contains the nearest swing high
swingLowRays = new Stack<RayObject>();
Add(new OutputDescriptor(new Pen(this.Signal, this.Plot0Width), OutputSerieDrawStyle.Line, "Signalline"));
}
/// <summary>
/// Called on each bar update event (incoming tick)
/// </summary>
protected override void OnCalculate()
{
int temp_signal_value = 0;
// build up cache of recent High and Low values
// code devised from default Swing Indicator by marqui@BMT, 10-NOV-2010
lastHighCache.Add(High[0]);
if (lastHighCache.Count > (2 * strength) + 1)
lastHighCache.RemoveAt(0); // if cache is filled, drop the oldest value
lastLowCache.Add(Low[0]);
if (lastLowCache.Count > (2 * strength) + 1)
lastLowCache.RemoveAt(0);
//
if (lastHighCache.Count == (2 * strength) + 1) // wait for cache of Highs to be filled
{
// test for swing high
bool isSwingHigh = true;
double swingHighCandidateValue = (double)lastHighCache[strength];
for (int i = 0; i < strength; i++)
if ((double)lastHighCache[i] >= swingHighCandidateValue - double.Epsilon)
isSwingHigh = false; // bar(s) to right of candidate were higher
for (int i = strength + 1; i < lastHighCache.Count; i++)
if ((double)lastHighCache[i] > swingHighCandidateValue - double.Epsilon)
isSwingHigh = false; // bar(s) to left of candidate were higher
// end of test
if (isSwingHigh)
lastSwingHighValue = swingHighCandidateValue;
if (isSwingHigh) // if we have a new swing high then we draw a ray line on the chart
{
AddChartRay("highRay" + (ProcessingBarIndex - strength), false, strength, lastSwingHighValue, 0, lastSwingHighValue, swingHighColor, DashStyle.Solid, 1);
RayObject newRayObject = new RayObject("highRay" + (ProcessingBarIndex - strength), strength, lastSwingHighValue, 0, lastSwingHighValue);
swingHighRays.Push(newRayObject); // store a reference so we can remove it from the chart later
}
else if (High[0] > lastSwingHighValue) // otherwise, we test to see if price has broken through prior swing high
{
if (swingHighRays.Count > 0) // just to be safe
{
//IRay currentRay = (IRay)swingHighRays.Pop(); // pull current ray from stack
RayObject currentRay = (RayObject)swingHighRays.Pop(); // pull current ray from stack
if (currentRay != null)
{
if (enableAlerts)
{
ShowAlert("Swing High at " + currentRay.Y1 + " broken", GlobalUtilities.GetSoundfile(this.Soundfile));
}
temp_signal_value = 1;
if (keepBrokenLines) // draw a line between swing point and break bar
{
int barsAgo = currentRay.BarsAgo1;
ITrendLine newLine = AddChartLine("highLine" + (ProcessingBarIndex - barsAgo), false, barsAgo, currentRay.Y1, 0, currentRay.Y1, swingHighColor, DashStyle.Dot, 2);
}
RemoveChartDrawing(currentRay.Tag);
if (swingHighRays.Count > 0)
{
//IRay priorRay = (IRay)swingHighRays.Peek();
RayObject priorRay = (RayObject)swingHighRays.Peek();
lastSwingHighValue = priorRay.Y1; // needed when testing the break of the next swing high
}
else
{
lastSwingHighValue = double.MaxValue; // there are no higher swings on the chart; reset to default
}
}
}
}
}
if (lastLowCache.Count == (2 * strength) + 1) // repeat the above for the swing lows
{
// test for swing low
bool isSwingLow = true;
double swingLowCandidateValue = (double)lastLowCache[strength];
for (int i = 0; i < strength; i++)
if ((double)lastLowCache[i] <= swingLowCandidateValue + double.Epsilon)
isSwingLow = false; // bar(s) to right of candidate were lower
for (int i = strength + 1; i < lastLowCache.Count; i++)
if ((double)lastLowCache[i] < swingLowCandidateValue + double.Epsilon)
isSwingLow = false; // bar(s) to left of candidate were lower
// end of test for low
if (isSwingLow)
lastSwingLowValue = swingLowCandidateValue;
if (isSwingLow) // found a new swing low; draw it on the chart
{
AddChartRay("lowRay" + (ProcessingBarIndex - strength), false, strength, lastSwingLowValue, 0, lastSwingLowValue, swingLowColor, DashStyle.Solid, 1);
RayObject newRayObject = new RayObject("lowRay" + (ProcessingBarIndex - strength), strength, lastSwingLowValue, 0, lastSwingLowValue);
swingLowRays.Push(newRayObject);
}
else if (Low[0] < lastSwingLowValue) // otherwise test to see if price has broken through prior swing low
{
if (swingLowRays.Count > 0)
{
//IRay currentRay = (IRay)swingLowRays.Pop();
RayObject currentRay = (RayObject)swingLowRays.Pop();
if (currentRay != null)
{
if (enableAlerts)
{
ShowAlert("Swing Low at " + currentRay.Y1 + " broken", GlobalUtilities.GetSoundfile(this.Soundfile));
}
temp_signal_value = -1;
if (keepBrokenLines) // draw a line between swing point and break bar
{
int barsAgo = currentRay.BarsAgo1;
ITrendLine newLine = AddChartLine("highLine" + (ProcessingBarIndex - barsAgo), false, barsAgo, currentRay.Y1, 0, currentRay.Y1, swingLowColor, DashStyle.Dot, 2);
}
RemoveChartDrawing(currentRay.Tag);
if (swingLowRays.Count > 0)
{
//IRay priorRay = (IRay)swingLowRays.Peek();
RayObject priorRay = (RayObject)swingLowRays.Peek();
lastSwingLowValue = priorRay.Y1; // price level of the prior swing low
}
else
{
lastSwingLowValue = double.MinValue; // no swing lows present; set this to default value
}
}
}
}
}
SignalLine.Set(temp_signal_value);
}
public override string ToString()
{
return "SwingRays (I)";
}
public override string DisplayName
{
get
{
return "SwingRays (I)";
}
}
#region InSeries Parameters
[Description("Number of bars before/after each pivot bar")]
[InputParameter]
[DisplayName("Strength")]
public int Strength
{
get { return strength; }
set { strength = Math.Max(2, value); }
}
[Description("Alert when swings are broken")]
[InputParameter]
[DisplayName("Enable alerts")]
public bool EnableAlerts
{
get { return enableAlerts; }
set { enableAlerts = value; }
}
[Description("Show broken swing points")]
[InputParameter]
[DisplayName("Keep broken lines")]
public bool KeepBrokenLines
{
get { return keepBrokenLines; }
set { keepBrokenLines = value; }
}
[XmlIgnore()]
[Description("Color for swing highs")]
[InputParameter]
[DisplayName("Swing high color")]
public Color SwingHighColor
{
get { return swingHighColor; }
set { swingHighColor = value; }
}
// Serialize our Color object
[Browsable(false)]
public string SwingHighColorSerialize
{
get { return SerializableColor.ToString(swingHighColor); }
set { swingHighColor = SerializableColor.FromString(value); }
}
[XmlIgnore()]
[Description("Color for swing lows")]
[InputParameter]
[DisplayName("Swing low color")]
public Color SwingLowColor
{
get { return swingLowColor; }
set { swingLowColor = value; }
}
// Serialize our Color object
[Browsable(false)]
public string SwingLowColorSerialize
{
get { return SerializableColor.ToString(swingLowColor); }
set { swingLowColor = SerializableColor.FromString(value); }
}
[XmlIgnore()]
[Description("Select the soundfile for the alert.")]
[InputParameter]
[DisplayName("Soundfile name")]
public Soundfile Soundfile
{
get { return _soundfile; }
set { _soundfile = value; }
}
#endregion
#region InSeries Drawings
[XmlIgnore()]
[Description("Select Color")]
[Category("Drawings")]
[DisplayName("Signalline")]
public Color Signal
{
get { return _signal; }
set { _signal = value; }
}
[Browsable(false)]
public string SignalSerialize
{
get { return SerializableColor.ToString(_signal); }
set { _signal = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Width for Priceline.")]
[Category("Drawings")]
[DisplayName("Line Width Priceline")]
public int Plot0Width
{
get { return _plot0Width; }
set { _plot0Width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for Priceline.")]
[Category("Drawings")]
[DisplayName("Dash Style Priceline")]
public DashStyle Dash0Style
{
get { return _dash0Style; }
set { _dash0Style = value; }
}
#endregion
#region Output properties
[Browsable(false)]
[XmlIgnore()]
public DataSeries SignalLine
{
get { return Outputs[0]; }
}
//[Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries HighRay
// {
// get { return Outputs[0]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries LowRay
// {
// get { return Outputs[1]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries HighLine
// {
// get { return Outputs[2]; }
// }
// [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
// [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
// public DataSeries LowLine
// {
// get { return Outputs[3]; }
// }
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Data.Sqlite;
// DBMS-specific:
using MySql.Data.MySqlClient;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Data.MSSQL;
using OpenSim.Data.MySQL;
using OpenSim.Data.SQLite;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Tests.Common;
using System.Data.Common;
using System.Data.SqlClient;
namespace OpenSim.Data.Tests
{
[TestFixture(Description = "Estate store tests (SQLite)")]
public class SQLiteEstateTests : EstateTests<SqliteConnection, SQLiteEstateStore>
{
}
[TestFixture(Description = "Estate store tests (MySQL)")]
public class MySqlEstateTests : EstateTests<MySqlConnection, MySQLEstateStore>
{
}
[TestFixture(Description = "Estate store tests (MS SQL Server)")]
public class MSSQLEstateTests : EstateTests<SqlConnection, MSSQLEstateStore>
{
}
public class EstateTests<TConn, TEstateStore> : BasicDataServiceTest<TConn, TEstateStore>
where TConn : DbConnection, new()
where TEstateStore : class, IEstateDataStore, new()
{
public IEstateDataStore db;
public static UUID REGION_ID = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed7");
public static UUID USER_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed1");
public static UUID USER_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed2");
public static UUID MANAGER_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed3");
public static UUID MANAGER_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed4");
public static UUID GROUP_ID_1 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed5");
public static UUID GROUP_ID_2 = new UUID("250d214e-1c7e-4f9b-a488-87c5e53feed6");
protected override void InitService(object service)
{
ClearDB();
db = (IEstateDataStore)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
// if a new table is added, it has to be dropped here
DropTables(
"estate_managers",
"estate_groups",
"estate_users",
"estateban",
"estate_settings",
"estate_map"
);
ResetMigrations("EstateStore");
}
#region 0Tests
[Test]
public void T010_EstateSettingsSimpleStorage_MinimumParameterSet()
{
TestHelpers.InMethod();
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MIN,
DataTestUtil.UNSIGNED_INTEGER_MIN,
DataTestUtil.FLOAT_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.DOUBLE_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.STRING_MIN,
DataTestUtil.UUID_MIN
);
}
[Test]
public void T011_EstateSettingsSimpleStorage_MaximumParameterSet()
{
TestHelpers.InMethod();
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MAX(64),
DataTestUtil.UNSIGNED_INTEGER_MAX,
DataTestUtil.FLOAT_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.INTEGER_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.DOUBLE_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.BOOLEAN_MAX,
DataTestUtil.STRING_MAX(255),
DataTestUtil.UUID_MAX
);
}
[Test]
public void T012_EstateSettingsSimpleStorage_AccurateParameterSet()
{
TestHelpers.InMethod();
EstateSettingsSimpleStorage(
REGION_ID,
DataTestUtil.STRING_MAX(1),
DataTestUtil.UNSIGNED_INTEGER_MIN,
DataTestUtil.FLOAT_ACCURATE,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.INTEGER_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.DOUBLE_ACCURATE,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.BOOLEAN_MIN,
DataTestUtil.STRING_MAX(1),
DataTestUtil.UUID_MIN
);
}
[Test]
public void T012_EstateSettingsRandomStorage()
{
TestHelpers.InMethod();
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
new PropertyScrambler<EstateSettings>()
.DontScramble(x => x.EstateID)
.Scramble(originalSettings);
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
// Checking that loaded values are correct.
Assert.That(loadedSettings, Constraints.PropertyCompareConstraint(originalSettings));
}
[Test]
public void T020_EstateSettingsManagerList()
{
TestHelpers.InMethod();
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateManagers = new UUID[] { MANAGER_ID_1, MANAGER_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateManagers.Length);
Assert.AreEqual(MANAGER_ID_1, loadedSettings.EstateManagers[0]);
Assert.AreEqual(MANAGER_ID_2, loadedSettings.EstateManagers[1]);
}
[Test]
public void T021_EstateSettingsUserList()
{
TestHelpers.InMethod();
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateAccess = new UUID[] { USER_ID_1, USER_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateAccess.Length);
Assert.AreEqual(USER_ID_1, loadedSettings.EstateAccess[0]);
Assert.AreEqual(USER_ID_2, loadedSettings.EstateAccess[1]);
}
[Test]
public void T022_EstateSettingsGroupList()
{
TestHelpers.InMethod();
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
originalSettings.EstateGroups = new UUID[] { GROUP_ID_1, GROUP_ID_2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateAccess.Length);
Assert.AreEqual(GROUP_ID_1, loadedSettings.EstateGroups[0]);
Assert.AreEqual(GROUP_ID_2, loadedSettings.EstateGroups[1]);
}
[Test]
public void T022_EstateSettingsBanList()
{
TestHelpers.InMethod();
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true);
EstateBan estateBan1 = new EstateBan();
estateBan1.BannedUserID = DataTestUtil.UUID_MIN;
EstateBan estateBan2 = new EstateBan();
estateBan2.BannedUserID = DataTestUtil.UUID_MAX;
originalSettings.EstateBans = new EstateBan[] { estateBan1, estateBan2 };
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(REGION_ID, true);
Assert.AreEqual(2, loadedSettings.EstateBans.Length);
Assert.AreEqual(DataTestUtil.UUID_MIN, loadedSettings.EstateBans[0].BannedUserID);
Assert.AreEqual(DataTestUtil.UUID_MAX, loadedSettings.EstateBans[1].BannedUserID);
}
#endregion 0Tests
#region Parametrizable Test Implementations
private void EstateSettingsSimpleStorage(
UUID regionId,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
// Letting estate store generate rows to database for us
EstateSettings originalSettings = db.LoadEstateSettings(regionId, true);
SetEstateSettings(originalSettings,
estateName,
parentEstateID,
billableFactor,
pricePerMeter,
redirectGridX,
redirectGridY,
useGlobalTime,
fixedSun,
sunPosition,
allowVoice,
allowDirectTeleport,
resetHomeOnTeleport,
denyAnonymous,
denyIdentified,
denyTransacted,
denyMinors,
abuseEmailToEstateOwner,
blockDwell,
estateSkipScripts,
taxFree,
publicAccess,
abuseEmail,
estateOwner
);
// Saving settings.
db.StoreEstateSettings(originalSettings);
// Loading settings to another instance variable.
EstateSettings loadedSettings = db.LoadEstateSettings(regionId, true);
// Checking that loaded values are correct.
ValidateEstateSettings(loadedSettings,
estateName,
parentEstateID,
billableFactor,
pricePerMeter,
redirectGridX,
redirectGridY,
useGlobalTime,
fixedSun,
sunPosition,
allowVoice,
allowDirectTeleport,
resetHomeOnTeleport,
denyAnonymous,
denyIdentified,
denyTransacted,
denyMinors,
abuseEmailToEstateOwner,
blockDwell,
estateSkipScripts,
taxFree,
publicAccess,
abuseEmail,
estateOwner
);
}
#endregion Parametrizable Test Implementations
#region EstateSetting Initialization and Validation Methods
private void SetEstateSettings(
EstateSettings estateSettings,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
estateSettings.EstateName = estateName;
estateSettings.ParentEstateID = parentEstateID;
estateSettings.BillableFactor = billableFactor;
estateSettings.PricePerMeter = pricePerMeter;
estateSettings.RedirectGridX = redirectGridX;
estateSettings.RedirectGridY = redirectGridY;
estateSettings.UseGlobalTime = useGlobalTime;
estateSettings.FixedSun = fixedSun;
estateSettings.SunPosition = sunPosition;
estateSettings.AllowVoice = allowVoice;
estateSettings.AllowDirectTeleport = allowDirectTeleport;
estateSettings.ResetHomeOnTeleport = resetHomeOnTeleport;
estateSettings.DenyAnonymous = denyAnonymous;
estateSettings.DenyIdentified = denyIdentified;
estateSettings.DenyTransacted = denyTransacted;
estateSettings.DenyMinors = denyMinors;
estateSettings.AbuseEmailToEstateOwner = abuseEmailToEstateOwner;
estateSettings.BlockDwell = blockDwell;
estateSettings.EstateSkipScripts = estateSkipScripts;
estateSettings.TaxFree = taxFree;
estateSettings.PublicAccess = publicAccess;
estateSettings.AbuseEmail = abuseEmail;
estateSettings.EstateOwner = estateOwner;
}
private void ValidateEstateSettings(
EstateSettings estateSettings,
string estateName,
uint parentEstateID,
float billableFactor,
int pricePerMeter,
int redirectGridX,
int redirectGridY,
bool useGlobalTime,
bool fixedSun,
double sunPosition,
bool allowVoice,
bool allowDirectTeleport,
bool resetHomeOnTeleport,
bool denyAnonymous,
bool denyIdentified,
bool denyTransacted,
bool denyMinors,
bool abuseEmailToEstateOwner,
bool blockDwell,
bool estateSkipScripts,
bool taxFree,
bool publicAccess,
string abuseEmail,
UUID estateOwner
)
{
Assert.AreEqual(estateName, estateSettings.EstateName);
Assert.AreEqual(parentEstateID, estateSettings.ParentEstateID);
DataTestUtil.AssertFloatEqualsWithTolerance(billableFactor, estateSettings.BillableFactor);
Assert.AreEqual(pricePerMeter, estateSettings.PricePerMeter);
Assert.AreEqual(redirectGridX, estateSettings.RedirectGridX);
Assert.AreEqual(redirectGridY, estateSettings.RedirectGridY);
Assert.AreEqual(useGlobalTime, estateSettings.UseGlobalTime);
Assert.AreEqual(fixedSun, estateSettings.FixedSun);
DataTestUtil.AssertDoubleEqualsWithTolerance(sunPosition, estateSettings.SunPosition);
Assert.AreEqual(allowVoice, estateSettings.AllowVoice);
Assert.AreEqual(allowDirectTeleport, estateSettings.AllowDirectTeleport);
Assert.AreEqual(resetHomeOnTeleport, estateSettings.ResetHomeOnTeleport);
Assert.AreEqual(denyAnonymous, estateSettings.DenyAnonymous);
Assert.AreEqual(denyIdentified, estateSettings.DenyIdentified);
Assert.AreEqual(denyTransacted, estateSettings.DenyTransacted);
Assert.AreEqual(denyMinors, estateSettings.DenyMinors);
Assert.AreEqual(abuseEmailToEstateOwner, estateSettings.AbuseEmailToEstateOwner);
Assert.AreEqual(blockDwell, estateSettings.BlockDwell);
Assert.AreEqual(estateSkipScripts, estateSettings.EstateSkipScripts);
Assert.AreEqual(taxFree, estateSettings.TaxFree);
Assert.AreEqual(publicAccess, estateSettings.PublicAccess);
Assert.AreEqual(abuseEmail, estateSettings.AbuseEmail);
Assert.AreEqual(estateOwner, estateSettings.EstateOwner);
}
#endregion EstateSetting Initialization and Validation Methods
}
}
| |
// 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;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterBlockTests : SharedBlockTests
{
private static IEnumerable<ParameterExpression> SingleParameter
{
get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); }
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0)));
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>)));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i < expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions.ToArray()));
}
[Theory]
[PerCompilationType(nameof(ConstantValuesAndSizes))]
public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray());
BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions);
Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile(useInterpreter)());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountCorrect(object value, int blockSize)
{
IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType()));
BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType()));
Assert.Equal(blockSize, block.Variables.Count);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
[ActiveIssue(3958)]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1);
Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions));
Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void ByRefVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1);
Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions));
Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void RepeatedVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
ParameterExpression variable = Expression.Variable(typeof(int));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2);
Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions));
Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
}
}
| |
/***************************************************************************
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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Project.Automation;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public abstract class ProjectContainerNode : ProjectNode,
IVsParentProject,
IBuildDependencyOnProjectContainer
{
#region fields
/// <summary>
/// Setting this flag to true will build all nested project when building this project
/// </summary>
private bool buildNestedProjectsOnBuild = true;
private ProjectElement nestedProjectElement;
/// <summary>
/// Defines the listener that would listen on file changes on the nested project node.
/// </summary>
///<devremark>
///This might need a refactoring when nested projects can be added and removed by demand.
/// </devremark>
private FileChangeManager nestedProjectNodeReloader;
#endregion
#region ctors
protected ProjectContainerNode()
{
}
#endregion
#region properties
/// <summary>
/// Returns teh object that handles listening to file changes on the nested project files.
/// </summary>
internal FileChangeManager NestedProjectNodeReloader
{
get
{
if(this.nestedProjectNodeReloader == null)
{
this.nestedProjectNodeReloader = new FileChangeManager(this.Site);
this.nestedProjectNodeReloader.FileChangedOnDisk += this.OnNestedProjectFileChangedOnDisk;
}
return this.nestedProjectNodeReloader;
}
}
#endregion
#region overridden properties
/// <summary>
/// This is the object that will be returned by EnvDTE.Project.Object for this project
/// </summary>
internal override object Object
{
get { return new OASolutionFolder<ProjectContainerNode>(this); }
}
#endregion
#region public overridden methods
/// <summary>
/// Gets the nested hierarchy.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="iidHierarchyNested">Identifier of the interface to be returned in ppHierarchyNested.</param>
/// <param name="ppHierarchyNested">Pointer to the interface whose identifier was passed in iidHierarchyNested.</param>
/// <param name="pItemId">Pointer to an item identifier of the root node of the nested hierarchy.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. If ITEMID is not a nested hierarchy, this method returns E_FAIL.</returns>
[CLSCompliant(false)]
public override int GetNestedHierarchy(UInt32 itemId, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pItemId)
{
pItemId = VSConstants.VSITEMID_ROOT;
ppHierarchyNested = IntPtr.Zero;
if(this.FirstChild != null)
{
for(HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling)
{
NestedProjectNode p = n as NestedProjectNode;
if(p != null && p.ID == itemId)
{
if(p.NestedHierarchy != null)
{
IntPtr iunknownPtr = IntPtr.Zero;
int returnValue = VSConstants.S_OK;
try
{
iunknownPtr = Marshal.GetIUnknownForObject(p.NestedHierarchy);
Marshal.QueryInterface(iunknownPtr, ref iidHierarchyNested, out ppHierarchyNested);
}
catch(COMException e)
{
returnValue = e.ErrorCode;
}
finally
{
if(iunknownPtr != IntPtr.Zero)
{
Marshal.Release(iunknownPtr);
}
}
return returnValue;
}
break;
}
}
}
return VSConstants.E_FAIL;
}
public override int IsItemDirty(uint itemId, IntPtr punkDocData, out int pfDirty)
{
HierarchyNode hierNode = this.NodeFromItemId(itemId);
Debug.Assert(hierNode != null, "Hierarchy node not found");
if(hierNode != this)
{
return ErrorHandler.ThrowOnFailure(hierNode.IsItemDirty(itemId, punkDocData, out pfDirty));
}
else
{
return ErrorHandler.ThrowOnFailure(base.IsItemDirty(itemId, punkDocData, out pfDirty));
}
}
public override int SaveItem(VSSAVEFLAGS dwSave, string silentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCancelled)
{
HierarchyNode hierNode = this.NodeFromItemId(itemid);
Debug.Assert(hierNode != null, "Hierarchy node not found");
if(hierNode != this)
{
return ErrorHandler.ThrowOnFailure(hierNode.SaveItem(dwSave, silentSaveAsName, itemid, punkDocData, out pfCancelled));
}
else
{
return ErrorHandler.ThrowOnFailure(base.SaveItem(dwSave, silentSaveAsName, itemid, punkDocData, out pfCancelled));
}
}
protected override bool FilterItemTypeToBeAddedToHierarchy(string itemType)
{
if(String.Compare(itemType, ProjectFileConstants.SubProject, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
return base.FilterItemTypeToBeAddedToHierarchy(itemType);
}
/// <summary>
/// Called to reload a project item.
/// Reloads a project and its nested project nodes.
/// </summary>
/// <param name="itemId">Specifies itemid from VSITEMID.</param>
/// <param name="reserved">Reserved.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public override int ReloadItem(uint itemId, uint reserved)
{
#region precondition
if(this.IsClosed)
{
return VSConstants.E_FAIL;
}
#endregion
NestedProjectNode node = this.NodeFromItemId(itemId) as NestedProjectNode;
if(node != null)
{
object propertyAsObject = node.GetProperty((int)__VSHPROPID.VSHPROPID_HandlesOwnReload);
if(propertyAsObject != null && (bool)propertyAsObject)
{
node.ReloadItem(reserved);
}
else
{
this.ReloadNestedProjectNode(node);
}
return VSConstants.S_OK;
}
return base.ReloadItem(itemId, reserved);
}
/// <summary>
/// Reloads a project and its nested project nodes.
/// </summary>
protected override void Reload()
{
base.Reload();
this.CreateNestedProjectNodes();
}
#endregion
#region IVsParentProject
public virtual int OpenChildren()
{
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not retrieve the solution from the services provided by this project");
if(solution == null)
{
return VSConstants.E_FAIL;
}
IntPtr iUnKnownForSolution = IntPtr.Zero;
int returnValue = VSConstants.S_OK; // be optimistic.
try
{
this.DisableQueryEdit = true;
this.EventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents | ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;
iUnKnownForSolution = Marshal.GetIUnknownForObject(solution);
// notify SolutionEvents listeners that we are about to add children
IVsFireSolutionEvents fireSolutionEvents = Marshal.GetTypedObjectForIUnknown(iUnKnownForSolution, typeof(IVsFireSolutionEvents)) as IVsFireSolutionEvents;
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnBeforeOpeningChildren(this));
this.AddVirtualProjects();
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnAfterOpeningChildren(this));
}
catch(Exception e)
{
// Exceptions are digested by the caller but we want then to be shown if not a ComException and if not in automation.
if(!(e is COMException) && !Utilities.IsInAutomationFunction(this.Site))
{
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, e.Message, icon, buttons, defaultButton);
}
Trace.WriteLine("Exception : " + e.Message);
throw;
}
finally
{
this.DisableQueryEdit = false;
if(iUnKnownForSolution != IntPtr.Zero)
{
Marshal.Release(iUnKnownForSolution);
}
this.EventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll;
}
return returnValue;
}
public virtual int CloseChildren()
{
int returnValue = VSConstants.S_OK; // be optimistic.
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not retrieve the solution from the services provided by this project");
if(solution == null)
{
return VSConstants.E_FAIL;
}
IntPtr iUnKnownForSolution = IntPtr.Zero;
try
{
iUnKnownForSolution = Marshal.GetIUnknownForObject(solution);
// notify SolutionEvents listeners that we are about to close children
IVsFireSolutionEvents fireSolutionEvents = Marshal.GetTypedObjectForIUnknown(iUnKnownForSolution, typeof(IVsFireSolutionEvents)) as IVsFireSolutionEvents;
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnBeforeClosingChildren(this));
// If the removal crashes we never fire the close children event. IS that a problem?
this.RemoveNestedProjectNodes();
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnAfterClosingChildren(this));
}
finally
{
if(iUnKnownForSolution != IntPtr.Zero)
{
Marshal.Release(iUnKnownForSolution);
}
}
return returnValue;
}
#endregion
#region IBuildDependencyOnProjectContainerNode
/// <summary>
/// Defines whether nested projects should be build with the parent project
/// </summary>
public virtual bool BuildNestedProjectsOnBuild
{
get { return this.buildNestedProjectsOnBuild; }
set { this.buildNestedProjectsOnBuild = value; }
}
/// <summary>
/// Enumerates the nested hierachies that should be added to the build dependency list.
/// </summary>
/// <returns></returns>
public virtual IVsHierarchy[] EnumNestedHierachiesForBuildDependency()
{
List<IVsHierarchy> nestedProjectList = new List<IVsHierarchy>();
// Add all nested project among projectContainer child nodes
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
NestedProjectNode nestedProjectNode = child as NestedProjectNode;
if(nestedProjectNode != null)
{
nestedProjectList.Add(nestedProjectNode.NestedHierarchy);
}
}
return nestedProjectList.ToArray();
}
#endregion
#region helper methods
internal protected void RemoveNestedProjectNodes()
{
for(HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling)
{
NestedProjectNode p = n as NestedProjectNode;
if(p != null)
{
p.CloseNestedProjectNode();
}
}
// We do not care of file changes after this.
this.NestedProjectNodeReloader.FileChangedOnDisk -= this.OnNestedProjectFileChangedOnDisk;
this.NestedProjectNodeReloader.Dispose();
}
/// <summary>
/// This is used when loading the project to loop through all the items
/// and for each SubProject it finds, it create the project and a node
/// in our Hierarchy to hold the project.
/// </summary>
internal protected void CreateNestedProjectNodes()
{
// 1. Create a ProjectElement with the found item and then Instantiate a new Nested project with this ProjectElement.
// 2. Link into the hierarchy.
// Read subprojects from from msbuildmodel
__VSCREATEPROJFLAGS creationFlags = __VSCREATEPROJFLAGS.CPF_NOTINSLNEXPLR | __VSCREATEPROJFLAGS.CPF_SILENT;
if(this.IsNewProject)
{
creationFlags |= __VSCREATEPROJFLAGS.CPF_CLONEFILE;
}
else
{
creationFlags |= __VSCREATEPROJFLAGS.CPF_OPENFILE;
}
foreach (MSBuild.ProjectItem item in this.BuildProject.Items)
{
if(String.Compare(item.ItemType, ProjectFileConstants.SubProject, StringComparison.OrdinalIgnoreCase) == 0)
{
this.nestedProjectElement = new ProjectElement(this, item, false);
if(!this.IsNewProject)
{
AddExistingNestedProject(null, creationFlags);
}
else
{
// If we are creating the subproject from a vstemplate/vsz file
bool isVsTemplate = Utilities.IsTemplateFile(GetProjectTemplatePath(null));
if(isVsTemplate)
{
RunVsTemplateWizard(null, true);
}
else
{
// We are cloning the specified project file
AddNestedProjectFromTemplate(null, creationFlags);
}
}
}
}
this.nestedProjectElement = null;
}
/// <summary>
/// Add an existing project as a nested node of our hierarchy.
/// This is used while loading the project and can also be used
/// to add an existing project to our hierarchy.
/// </summary>
protected internal virtual NestedProjectNode AddExistingNestedProject(ProjectElement element, __VSCREATEPROJFLAGS creationFlags)
{
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
throw new ArgumentNullException("element");
}
string filename = elementToUse.GetFullPathForElement();
// Delegate to AddNestedProjectFromTemplate. Because we pass flags that specify open project rather then clone, this will works.
Debug.Assert((creationFlags & __VSCREATEPROJFLAGS.CPF_OPENFILE) == __VSCREATEPROJFLAGS.CPF_OPENFILE, "__VSCREATEPROJFLAGS.CPF_OPENFILE should have been specified, did you mean to call AddNestedProjectFromTemplate?");
return AddNestedProjectFromTemplate(filename, Path.GetDirectoryName(filename), Path.GetFileName(filename), elementToUse, creationFlags);
}
/// <summary>
/// Let the wizard code execute and provide us the information we need.
/// Our SolutionFolder automation object should be called back with the
/// details at which point it will call back one of our method to add
/// a nested project.
/// If you are trying to add a new subproject this is probably the
/// method you want to call. If you are just trying to clone a template
/// project file, then AddNestedProjectFromTemplate is what you want.
/// </summary>
/// <param name="element">The project item to use as the base of the nested project.</param>
/// <param name="silent">true if the wizard should run silently, otherwise false.</param>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Vs")]
protected internal void RunVsTemplateWizard(ProjectElement element, bool silent)
{
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
throw new ArgumentNullException("element");
}
this.nestedProjectElement = elementToUse;
Automation.OAProject oaProject = GetAutomationObject() as Automation.OAProject;
if(oaProject == null || oaProject.ProjectItems == null)
throw new System.InvalidOperationException(SR.GetString(SR.InvalidAutomationObject, CultureInfo.CurrentUICulture));
Debug.Assert(oaProject.Object != null, "The project automation object should have set the Object to the SolutionFolder");
Automation.OASolutionFolder<ProjectContainerNode> folder = oaProject.Object as Automation.OASolutionFolder<ProjectContainerNode>;
// Prepare the parameters to pass to RunWizardFile
string destination = elementToUse.GetFullPathForElement();
string template = this.GetProjectTemplatePath(elementToUse);
object[] wizParams = new object[7];
wizParams[0] = EnvDTE.Constants.vsWizardAddSubProject;
wizParams[1] = Path.GetFileNameWithoutExtension(destination);
wizParams[2] = oaProject.ProjectItems;
wizParams[3] = Path.GetDirectoryName(destination);
wizParams[4] = Path.GetFileNameWithoutExtension(destination);
wizParams[5] = Path.GetDirectoryName(folder.DTE.FullName); //VS install dir
wizParams[6] = silent;
IVsDetermineWizardTrust wizardTrust = this.GetService(typeof(SVsDetermineWizardTrust)) as IVsDetermineWizardTrust;
if(wizardTrust != null)
{
Guid guidProjectAdding = Guid.Empty;
// In case of a project template an empty guid should be added as the guid parameter. See env\msenv\core\newtree.h IsTrustedTemplate method definition.
ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardInitiated(template, ref guidProjectAdding));
}
try
{
// Make the call to execute the wizard. This should cause AddNestedProjectFromTemplate to be
// called back with the correct set of parameters.
EnvDTE.IVsExtensibility extensibilityService = (EnvDTE.IVsExtensibility)GetService(typeof(EnvDTE.IVsExtensibility));
EnvDTE.wizardResult result = extensibilityService.RunWizardFile(template, 0, ref wizParams);
if(result == EnvDTE.wizardResult.wizardResultFailure)
throw new COMException();
}
finally
{
if(wizardTrust != null)
{
ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardCompleted());
}
}
}
/// <summary>
/// This will clone a template project file and add it as a
/// subproject to our hierarchy.
/// If you want to create a project for which there exist a
/// vstemplate, consider using RunVsTemplateWizard instead.
/// </summary>
protected internal virtual NestedProjectNode AddNestedProjectFromTemplate(ProjectElement element, __VSCREATEPROJFLAGS creationFlags)
{
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
throw new ArgumentNullException("element");
}
string destination = elementToUse.GetFullPathForElement();
string template = this.GetProjectTemplatePath(elementToUse);
return this.AddNestedProjectFromTemplate(template, Path.GetDirectoryName(destination), Path.GetFileName(destination), elementToUse, creationFlags);
}
/// <summary>
/// This can be called directly or through RunVsTemplateWizard.
/// This will clone a template project file and add it as a
/// subproject to our hierarchy.
/// If you want to create a project for which there exist a
/// vstemplate, consider using RunVsTemplateWizard instead.
/// </summary>
protected internal virtual NestedProjectNode AddNestedProjectFromTemplate(string fileName, string destination, string projectName, ProjectElement element, __VSCREATEPROJFLAGS creationFlags)
{
// If this is project creation and the template specified a subproject in its project file, this.nestedProjectElement will be used
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
// If this is null, this means MSBuild does not know anything about our subproject so add an MSBuild item for it
elementToUse = new ProjectElement(this, fileName, ProjectFileConstants.SubProject);
}
NestedProjectNode node = CreateNestedProjectNode(elementToUse);
node.Init(fileName, destination, projectName, creationFlags);
// In case that with did not have an existing element, or the nestedProjectelement was null
// and since Init computes the final path, set the MSBuild item to that path
if(this.nestedProjectElement == null)
{
string relativePath = node.Url;
if(Path.IsPathRooted(relativePath))
{
relativePath = this.ProjectFolder;
if(!relativePath.EndsWith("/\\", StringComparison.Ordinal))
{
relativePath += Path.DirectorySeparatorChar;
}
relativePath = new Url(relativePath).MakeRelative(new Url(node.Url));
}
elementToUse.Rename(relativePath);
}
this.AddChild(node);
return node;
}
/// <summary>
/// Override this method if you want to provide your own type of nodes.
/// This would be the case if you derive a class from NestedProjectNode
/// </summary>
protected virtual NestedProjectNode CreateNestedProjectNode(ProjectElement element)
{
return new NestedProjectNode(this, element);
}
/// <summary>
/// Links the nested project nodes to the solution. The default implementation parses all nested project nodes and calles AddVirtualProjectEx on them.
/// </summary>
protected virtual void AddVirtualProjects()
{
for(HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
{
NestedProjectNode nestedProjectNode = child as NestedProjectNode;
if(nestedProjectNode != null)
{
nestedProjectNode.AddVirtualProject();
}
}
}
/// <summary>
/// Based on the Template and TypeGuid properties of the
/// element, generate the full template path.
///
/// TypeGuid should be the Guid of a registered project factory.
/// Template can be a full path, a project template (for projects
/// that support VsTemplates) or a relative path (for other projects).
/// </summary>
protected virtual string GetProjectTemplatePath(ProjectElement element)
{
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
throw new ArgumentNullException("element");
}
string templateFile = elementToUse.GetMetadata(ProjectFileConstants.Template);
Debug.Assert(!String.IsNullOrEmpty(templateFile), "No template file has been specified in the template attribute in the project file");
string fullPath = templateFile;
if(!Path.IsPathRooted(templateFile))
{
RegisteredProjectType registeredProjectType = this.GetRegisteredProject(elementToUse);
// This is not a full path
Debug.Assert(registeredProjectType != null && (!String.IsNullOrEmpty(registeredProjectType.DefaultProjectExtensionValue) || !String.IsNullOrEmpty(registeredProjectType.WizardTemplatesDirValue)), " Registered wizard directory value not set in the registry.");
// See if this specify a VsTemplate file
fullPath = registeredProjectType.GetVsTemplateFile(templateFile);
if(String.IsNullOrEmpty(fullPath))
{
// Default to using the WizardTemplateDir to calculate the absolute path
fullPath = Path.Combine(registeredProjectType.WizardTemplatesDirValue, templateFile);
}
}
return fullPath;
}
/// <summary>
/// Get information from the registry based for the project
/// factory corresponding to the TypeGuid of the element
/// </summary>
private RegisteredProjectType GetRegisteredProject(ProjectElement element)
{
ProjectElement elementToUse = (element == null) ? this.nestedProjectElement : element;
if(elementToUse == null)
{
throw new ArgumentNullException("element");
}
// Get the project type guid from project elementToUse
string typeGuidString = elementToUse.GetMetadataAndThrow(ProjectFileConstants.TypeGuid, new Exception());
Guid projectFactoryGuid = new Guid(typeGuidString);
EnvDTE.DTE dte = this.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
Debug.Assert(dte != null, "Could not get the automation object from the services exposed by this project");
if(dte == null)
throw new InvalidOperationException();
RegisteredProjectType registeredProjectType = RegisteredProjectType.CreateRegisteredProjectType(projectFactoryGuid);
Debug.Assert(registeredProjectType != null, "Could not read the registry setting associated to this project.");
if(registeredProjectType == null)
{
throw new InvalidOperationException();
}
return registeredProjectType;
}
/// <summary>
/// Reloads a nested project node by deleting it and readding it.
/// </summary>
/// <param name="node">The node to reload.</param>
protected virtual void ReloadNestedProjectNode(NestedProjectNode node)
{
if(node == null)
{
throw new ArgumentNullException("node");
}
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
if(solution == null)
{
throw new InvalidOperationException();
}
NestedProjectNode newNode = null;
try
{
// (VS 2005 UPDATE) When deleting and re-adding the nested project,
// we do not want SCC to see this as a delete and add operation.
this.EventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;
// notify SolutionEvents listeners that we are about to add children
IVsFireSolutionEvents fireSolutionEvents = solution as IVsFireSolutionEvents;
if(fireSolutionEvents == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnBeforeUnloadProject(node.NestedHierarchy));
int isDirtyAsInt = 0;
this.IsDirty(out isDirtyAsInt);
bool isDirty = (isDirtyAsInt == 0) ? false : true;
ProjectElement element = node.ItemNode;
node.CloseNestedProjectNode();
// Remove from the solution
this.RemoveChild(node);
// Now readd it
try
{
__VSCREATEPROJFLAGS flags = __VSCREATEPROJFLAGS.CPF_NOTINSLNEXPLR | __VSCREATEPROJFLAGS.CPF_SILENT | __VSCREATEPROJFLAGS.CPF_OPENFILE;
newNode = this.AddExistingNestedProject(element, flags);
newNode.AddVirtualProject();
}
catch(Exception e)
{
// We get a System.Exception if anything failed, thus we have no choice but catch it.
// Exceptions are digested by VS. Show the error if not in automation.
if(!Utilities.IsInAutomationFunction(this.Site))
{
string message = (String.IsNullOrEmpty(e.Message)) ? SR.GetString(SR.NestedProjectFailedToReload, CultureInfo.CurrentUICulture) : e.Message;
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
}
// Do not digest exception. let the caller handle it. If in a later stage this exception is not digested then the above messagebox is not needed.
throw;
}
#if DEBUG
IVsHierarchy nestedHierarchy;
ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(newNode.GetMkDocument(), out nestedHierarchy));
Debug.Assert(nestedHierarchy != null && Utilities.IsSameComObject(nestedHierarchy, newNode.NestedHierarchy), "The nested hierrachy was not reloaded correctly.");
#endif
this.SetProjectFileDirty(isDirty);
ErrorHandler.ThrowOnFailure(fireSolutionEvents.FireOnAfterLoadProject(newNode.NestedHierarchy));
}
finally
{
// In this scenario the nested project failed to unload or reload the nested project. We will unload the whole project, otherwise the nested project is lost.
// This is similar to the scenario when one wants to open a project and the nested project cannot be loaded because for example the project file has xml errors.
// We should note that we rely here that if the unload fails then exceptions are not digested and are shown to the user.
if(newNode == null || newNode.NestedHierarchy == null)
{
ErrorHandler.ThrowOnFailure(solution.CloseSolutionElement((uint)__VSSLNCLOSEOPTIONS.SLNCLOSEOPT_UnloadProject | (uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, this, 0));
}
else
{
this.EventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll;
}
}
}
/// <summary>
/// Event callback. Called when one of the nested project files is changed.
/// </summary>
/// <param name="sender">The FileChangeManager object.</param>
/// <param name="e">Event args containing the file name that was updated.</param>
private void OnNestedProjectFileChangedOnDisk(object sender, FileChangedOnDiskEventArgs e)
{
#region Pre-condition validation
Debug.Assert(e != null, "No event args specified for the FileChangedOnDisk event");
// We care only about time change for reload.
if((e.FileChangeFlag & _VSFILECHANGEFLAGS.VSFILECHG_Time) == 0)
{
return;
}
// test if we actually have a document for this id.
string moniker;
this.GetMkDocument(e.ItemID, out moniker);
Debug.Assert(NativeMethods.IsSamePath(moniker, e.FileName), " The file + " + e.FileName + " has changed but we could not retrieve the path for the item id associated to the path.");
#endregion
bool reload = true;
if(!Utilities.IsInAutomationFunction(this.Site))
{
// Prompt to reload the nested project file. We use the moniker here since the filename from the event arg is canonicalized.
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.QueryReloadNestedProject, CultureInfo.CurrentUICulture), moniker);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_INFO;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNO;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
reload = (VsShellUtilities.ShowMessageBox(this.Site, message, title, icon, buttons, defaultButton) == NativeMethods.IDYES);
}
if(reload)
{
// We have to use here the interface method call, since it might be that specialized project nodes like the project container item
// is owerwriting the default functionality.
this.ReloadItem(e.ItemID, 0);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DotVVM.Framework.Parser;
using DotVVM.Framework.Parser.Dothtml;
using DotVVM.Framework.Parser.Dothtml.Tokenizer;
namespace DotVVM.Framework.Tests.Parser.Dothtml
{
[TestClass]
public class DothtmlTokenizerDirectivesTests : DothtmlTokenizerTestsBase
{
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Valid_TwoDirectives()
{
var input = @"
@viewmodel DotVVM.Samples.Sample1.IndexViewModel
@masterpage ~/Site.dothtml
this is a test content";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
// first line
var i = 0;
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Valid_NoDirectives_WhiteSpaceOnStart()
{
var input = @"
this is a test content";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
// first line
var i = 0;
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Valid_NoDirectives_NoWhiteSpaceOnStart()
{
var input = @"this is a test content";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
// first line
var i = 0;
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_OnlyAtSymbol()
{
var input = @"@";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_DirectiveName()
{
var input = @"@viewmodel";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.AreEqual("viewmodel", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_WhiteSpace_DirectiveName()
{
var input = @"@ viewmodel";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual("viewmodel", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_NewLine_Content()
{
var input = @"@
test";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_DirectiveName_NewLine_Content()
{
var input = @"@viewmodel
test";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.AreEqual("viewmodel", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual("\r\n", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual("test", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_DirectiveName_Space_NewLine_Content()
{
var input = @"@viewmodel
test";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.AreEqual("viewmodel", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.AreEqual(2, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual("\r\n", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual("test", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_Space_NewLine_Content()
{
var input = @"@
test";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.AreEqual(2, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
Assert.AreEqual("\r\n", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual("test", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type);
}
[TestMethod]
public void DothtmlTokenizer_DirectiveParsing_Invalid_AtSymbol_AtSymbol_Content()
{
var input = @"@@test";
// parse
var tokenizer = new DothtmlTokenizer();
tokenizer.Tokenize(new StringReader(input));
CheckForErrors(tokenizer, input.Length);
var i = 0;
Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.DirectiveName, tokenizer.Tokens[i++].Type);
Assert.IsTrue(tokenizer.Tokens[i].HasError);
Assert.AreEqual(0, tokenizer.Tokens[i].Length);
Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type);
Assert.AreEqual("@test", tokenizer.Tokens[i].Text);
Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokenizer.Tokens[i++].Type);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.TaxonomyMenuWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TramUrWay.Android
{
public class RouteLink
{
public string From { get; set; }
public Step To { get; set; }
public Line Line { get; set; }
internal float Weight;
public override string ToString()
{
return $"[{Line?.Number.ToString() ?? "W"}] {From} > {To.Stop.Name} ({Weight})";
}
}
public class RouteSegment
{
public Step From { get; set; }
public DateTime DateFrom { get; set; }
public Step To { get; set; }
public DateTime DateTo { get; set; }
public Line Line { get; set; }
public TimeStep[] TimeSteps { get; set; }
public override string ToString()
{
return $"On L{Line.Number}, from {From.Stop.Name} ({DateFrom}) to {To.Stop.Name} ({DateTo})";
}
}
public class RouteSearch
{
public class RouteSearchSettings
{
public bool AllowBusLinks { get; set; } = true;
public bool AllowWalkLinks { get; set; } = true;
public int WalkLinksCount { get; set; } = 3;
public int BestRoutesCount { get; set; } = 3;
public float TramWeight { get; set; } = 1.0f;
public float BusWeight { get; set; } = 1.5f;
public float WalkWeight { get; set; } = 2.0f;
public float ChangeWeight { get; set; } = 60.0f;
}
public RouteSearchSettings Settings { get; } = new RouteSearchSettings();
private Dictionary<string, List<RouteLink>> routeLinks = new Dictionary<string, List<RouteLink>>();
public void Prepare(IEnumerable<Line> lines)
{
routeLinks.Clear();
// Flush prior queries
lines = lines.ToArray();
// Build steps cache
foreach (Line line in lines)
{
if (!Settings.AllowBusLinks && line.Type == LineType.Bus)
continue;
foreach (Route route in line.Routes)
for (int i = 0; i < route.Steps.Length - 1; i++)
{
Step fromStep = route.Steps[i];
Step toStep = route.Steps[i + 1];
List<RouteLink> stepLinks;
if (!routeLinks.TryGetValue(fromStep.Stop.Name, out stepLinks))
routeLinks.Add(fromStep.Stop.Name, stepLinks = new List<RouteLink>());
if (stepLinks.Any(l => l.Line == fromStep.Route.Line && l.To.Stop.Name == toStep.Stop.Name))
continue;
TimeSpan duration = fromStep.Duration ?? TimeSpan.FromMinutes(0);
if (duration.TotalMinutes == 0)
duration = TimeSpan.FromMinutes(2);
stepLinks.Add(new RouteLink() { From = fromStep.Stop.Name, To = toStep, Line = line, Weight = (float)duration.TotalSeconds * (line.Type == LineType.Tram ? Settings.TramWeight : Settings.BusWeight) });
}
}
if (Settings.AllowWalkLinks)
{
// Find nearest steps
Dictionary<string, List<RouteLink>> walkLinks = new Dictionary<string, List<RouteLink>>();
Step[] allSteps = lines.SelectMany(l => l.Routes).SelectMany(r => r.Steps).ToArray();
foreach (Step step in allSteps)
{
IEnumerable<Step> sortedSteps = allSteps.Where(s => s.Stop.Name != step.Stop.Name)
.OrderBy(s => s.Stop.Position - step.Stop.Position);
List<RouteLink> stepLinks;
if (!walkLinks.TryGetValue(step.Stop.Name, out stepLinks))
walkLinks.Add(step.Stop.Name, stepLinks = new List<RouteLink>());
foreach (Step toStep in sortedSteps.Take(Settings.WalkLinksCount))
stepLinks.Add(new RouteLink() { From = step.Stop.Name, To = toStep, Line = null, Weight = (toStep.Stop.Position - step.Stop.Position) * Settings.WalkWeight });
stepLinks = stepLinks.GroupBy(l => l.To.Stop.Name).Select(g => g.OrderBy(l => l.Weight).First()).ToList();
stepLinks.Sort((l1, l2) => (int)(l1.Weight - l2.Weight));
walkLinks[step.Stop.Name] = stepLinks;
}
// Merge links
foreach (var pair in walkLinks)
{
List<RouteLink> stepLinks;
if (!routeLinks.TryGetValue(pair.Key, out stepLinks))
routeLinks.Add(pair.Key, stepLinks = new List<RouteLink>());
stepLinks.AddRange(pair.Value);
}
}
}
#region Path finding
public IEnumerable<RouteLink[]> FindRoutes(Stop from, Stop to)
{
AutoResetEvent resultEvent = new AutoResetEvent(false);
bool searchEnded = false;
List<float> bestWeights = new List<float>(Settings.BestRoutesCount);
ConcurrentQueue<RouteLink[]> bestRoutes = new ConcurrentQueue<RouteLink[]>();
float maxWeight = to.Position - from.Position;
bestWeights.Add(maxWeight);
Action<RouteLink[], string, float> browseRoutes = null;
browseRoutes = (route, last, weight) =>
{
List<RouteLink> links;
if (!routeLinks.TryGetValue(last, out links))
return;
RouteLink lastLink = route.LastOrDefault();
foreach (RouteLink link in links)
{
string linkTo = link.To.Stop.Name;
// Skip loops
if (route.Any(l => l.From == linkTo))
continue;
// Skip reusage of same line
if (lastLink != null && lastLink.Line != link.Line && route.Any(l => l.Line == link.Line))
continue;
// Avoid leaving the line we search
if (lastLink != null && lastLink.Line != link.Line && lastLink.Line == to.Line)
continue;
// Skip reusage of same stop
if (route.Any(l => l.Line == link.Line && l.To.Stop.Name == linkTo))
continue;
float linkWeight = weight + link.Weight;
// Add an arbitraty weight when changing line
if (lastLink?.Line != link?.Line)
linkWeight += Settings.ChangeWeight;
// Skip too long routes
if (linkWeight > maxWeight)
continue;
lock (bestWeights)
{
// Skip too long routes
if (linkWeight > bestWeights.First() * 2)
continue;
// Keep only shortest routes
if (bestWeights.Count == 3 && linkWeight > bestWeights.Last())
continue;
}
// Build the route
RouteLink[] linkRoute = route.Concat(link).ToArray();
// If the destination is found, register the answer
if (linkTo == to.Name)
{
lock (bestWeights)
{
if (bestWeights.Count == Settings.BestRoutesCount)
bestWeights.RemoveAt(Settings.BestRoutesCount - 1);
bestWeights.Add(linkWeight);
bestWeights.Sort();
bestRoutes.Enqueue(linkRoute);
resultEvent.Set();
}
}
else
browseRoutes(linkRoute, linkTo, linkWeight);
}
};
// Start pathfinding
Task routesTask = Task.Run(() =>
{
browseRoutes(new RouteLink[0], from.Name, 0);
searchEnded = true;
resultEvent.Set();
});
while (true)
{
resultEvent.WaitOne();
RouteLink[] route;
while (bestRoutes.TryDequeue(out route))
yield return route;
if (searchEnded)
break;
}
yield break;
}
public async Task<RouteLink[][]> FindRoutesAsync(Stop from, Stop to)
{
return await Task.Run(() => FindRoutes(from, to).ToArray());
}
public async Task<RouteLink[][]> FindRoutesAsync(Stop from, Stop to, TimeSpan timeout)
{
return await Task.Run(() =>
{
DateTime end = DateTime.Now + timeout;
List<RouteLink[]> routes = new List<RouteLink[]>();
IEnumerable<RouteLink[]> routesEnumerable = FindRoutes(from, to);
IEnumerator<RouteLink[]> routesEnumerator = routesEnumerable.GetEnumerator();
while (true)
{
Task<bool> moveNextTask = Task.Run(() => routesEnumerator.MoveNext());
// Exit if timed out
timeout = end - DateTime.Now;
if (!moveNextTask.Wait(timeout))
break;
// Exit of enumeration finished
if (moveNextTask.Result == false)
break;
routes.Add(routesEnumerator.Current);
}
routes.Sort((r1, r2) => (int)(r1.Sum(l => l.Weight) - r2.Sum(l => l.Weight)));
return routes.ToArray();
});
}
#endregion
#region Time simulation
public IEnumerable<RouteSegment[]> SimulateTimeStepsFrom(RouteLink[] route, DateTime date)
{
return SimulateTimeStepsFrom(route, date, TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(15));
}
public IEnumerable<RouteSegment[]> SimulateTimeStepsFrom(RouteLink[] route, DateTime date, TimeSpan lowerTolerance, TimeSpan upperTolerance)
{
RouteLink[] changes = route.Distinct(l => l.Line).ToArray();
RouteLink last = route.Last();
if (route.Any(l => l.To.Route.TimeTable == null))
yield break;
RouteLink firstLink = route.First();
//Step firstStep = firstLink.Line?.Routes?.SelectMany(r => r.Steps)?.First(s => s.Stop.Name == firstLink.From && s.Next?.Stop?.Name == firstLink.To.Stop.Name);
Step firstStep = firstLink.To.Route.Steps.First(s => s.Stop.Name == firstLink.From && s.Next?.Stop?.Name == firstLink.To.Stop.Name);
// Setup simulation
DateTime simulationDate = date;
DateTime lowerBound = simulationDate - lowerTolerance;
DateTime upperBound = simulationDate + upperTolerance;
TimeStep[] timeSteps = firstStep.Route.TimeTable.GetStepsFromStep(firstStep, lowerBound).Take(3).ToArray();
TimeStep lastTimeStep;
List<TimeStep> segmentTimeSteps;
foreach (TimeStep timeStep in timeSteps)
{
List<RouteSegment> segments = new List<RouteSegment>();
RouteSegment segment;
lastTimeStep = timeStep;
simulationDate = lastTimeStep.Date;
Step lastStep = firstStep;
foreach (RouteLink change in changes.Skip(1))
{
segment = new RouteSegment() { From = lastStep, DateFrom = lastTimeStep.Date, Line = lastStep.Route.Line };
segments.Add(segment);
segmentTimeSteps = new List<TimeStep>();
while (lastStep.Stop.Name != change.From)
{
segmentTimeSteps.Add(lastTimeStep);
lastStep = lastStep.Next;
lastTimeStep = lastStep.Route.TimeTable.GetStepsFromStep(lastStep, simulationDate).FirstOrDefault();
simulationDate = lastTimeStep.Date;
}
segment.TimeSteps = segmentTimeSteps.ToArray();
segment.To = lastStep;
segment.DateTo = simulationDate;
//lastStep = change.Line?.Routes?.SelectMany(r => r.Steps)?.First(s => s.Stop.Name == change.From && s.Next?.Stop?.Name == change.To.Stop.Name);
lastStep = change.To.Route.Steps.First(s => s.Stop.Name == change.From && s.Next?.Stop?.Name == change.To.Stop.Name);
lastTimeStep = lastStep.Route.TimeTable.GetStepsFromStep(lastStep, simulationDate).FirstOrDefault();
if (lastTimeStep == null)
yield break;
simulationDate = lastTimeStep.Date;
}
segment = new RouteSegment() { From = lastStep, DateFrom = lastTimeStep.Date, Line = lastStep.Route.Line };
segments.Add(segment);
segmentTimeSteps = new List<TimeStep>();
while (lastStep.Stop.Name != last.To.Stop.Name)
{
segmentTimeSteps.Add(lastTimeStep);
lastStep = lastStep.Next;
lastTimeStep = lastStep.Route.TimeTable.GetStepsFromStep(lastStep, simulationDate).FirstOrDefault();
simulationDate = lastTimeStep.Date;
}
segment.TimeSteps = segmentTimeSteps.ToArray();
segment.To = lastStep;
segment.DateTo = simulationDate;
yield return segments.ToArray();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
using System.Text;
namespace System.Data.Common
{
internal partial class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal readonly bool _hasUserIdKeyword;
// differences between OleDb and Odbc
// ODBC:
// https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqldriverconnect-function
// do not support == -> = in keywords
// first key-value pair wins
// quote values using \{ and \}, only driver= and pwd= appear to generically allow quoting
// do not strip quotes from value, or add quotes except for driver keyword
// OLEDB:
// https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax#oledb-connection-string-syntax
// support == -> = in keywords
// last key-value pair wins
// quote values using \" or \'
// strip quotes from value
internal readonly bool _useOdbcRules;
// called by derived classes that may cache based on connectionString
public DbConnectionOptions(string connectionString)
: this(connectionString, null, false)
{
}
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms, bool useOdbcRules)
{
_useOdbcRules = useOdbcRules;
_parsetable = new Dictionary<string, string>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
_keyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, _useOdbcRules);
_hasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
_hasUserIdKeyword = (_parsetable.ContainsKey(KEY.User_ID) || _parsetable.ContainsKey(SYNONYM.UID));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
_hasPasswordKeyword = connectionOptions._hasPasswordKeyword;
_hasUserIdKeyword = connectionOptions._hasUserIdKeyword;
_useOdbcRules = connectionOptions._useOdbcRules;
_parsetable = connectionOptions._parsetable;
_keyChain = connectionOptions._keyChain;
}
internal string UsersConnectionStringForTrace()
{
return UsersConnectionString(true, true);
}
internal bool HasBlankPassword
{
get
{
if (!ConvertValueToIntegratedSecurity())
{
if (_parsetable.ContainsKey(KEY.Password))
{
return string.IsNullOrEmpty((string)_parsetable[KEY.Password]);
}
else
if (_parsetable.ContainsKey(SYNONYM.Pwd))
{
return string.IsNullOrEmpty((string)_parsetable[SYNONYM.Pwd]); // MDAC 83097
}
else
{
return ((_parsetable.ContainsKey(KEY.User_ID) && !string.IsNullOrEmpty((string)_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !string.IsNullOrEmpty((string)_parsetable[SYNONYM.UID])));
}
}
return false;
}
}
public bool IsEmpty
{
get { return (null == _keyChain); }
}
internal Dictionary<string, string> Parsetable
{
get { return _parsetable; }
}
public ICollection Keys
{
get { return _parsetable.Keys; }
}
public string this[string keyword]
{
get { return (string)_parsetable[keyword]; }
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules)
{
ADP.CheckArgumentNull(builder, nameof(builder));
ADP.CheckArgumentLength(keyName, nameof(keyName));
if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
{
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue))
{
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
{
builder.Append(";");
}
if (useOdbcRules)
{
builder.Append(keyName);
}
else
{
builder.Append(keyName.Replace("=", "=="));
}
builder.Append("=");
if (null != keyValue)
{ // else <keyword>=;
if (useOdbcRules)
{
if ((0 < keyValue.Length) &&
// string.Contains(char) is .NetCore2.1+ specific
(('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (0 == string.Compare(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
!s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
{
// always quote Driver value (required for ODBC Version 2.65 and earlier)
// always quote values that contain a ';'
builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
}
else
{
builder.Append(keyValue);
}
}
else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
{
// <value> -> <value>
builder.Append(keyValue);
}
// string.Contains(char) is .NetCore2.1+ specific
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
{
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else
{
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
public bool ConvertValueToIntegratedSecurity()
{
object value = _parsetable[KEY.Integrated_Security];
if (null == value)
{
return false;
}
return ConvertValueToIntegratedSecurityInternal((string)value);
}
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
public int ConvertValueToInt32(string keyName, int defaultValue)
{
object value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
}
return ConvertToInt32Internal(keyName, (string)value);
}
internal static int ConvertToInt32Internal(string keyname, string stringValue)
{
try
{
return int.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
public string ConvertValueToString(string keyName, string defaultValue)
{
string value = (string)_parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
public bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
// SxS notes:
// * this method queries "DataDirectory" value from the current AppDomain.
// This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource".
// * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
internal static string ExpandDataDirectory(string keyword, string value, ref string datadir)
{
string fullPath = null;
if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase))
{
string rootFolderPath = datadir;
if (null == rootFolderPath)
{
// find the replacement path
object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
rootFolderPath = (rootFolderObject as string);
if ((null != rootFolderObject) && (null == rootFolderPath))
{
throw ADP.InvalidDataDirectory();
}
else if (string.IsNullOrEmpty(rootFolderPath))
{
rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
}
if (null == rootFolderPath)
{
rootFolderPath = "";
}
// cache the |DataDir| for ExpandDataDirectories
datadir = rootFolderPath;
}
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length - 1] == '\\';
bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
// replace |datadirectory| with root folder path
if (!rootFolderEndsWith && !fileNameStartsWith)
{
// need to insert '\'
fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
}
else if (rootFolderEndsWith && fileNameStartsWith)
{
// need to strip one out
fullPath = rootFolderPath + value.Substring(fileNamePosition + 1);
}
else
{
// simply concatenate the strings
fullPath = rootFolderPath + value.Substring(fileNamePosition);
}
// verify root folder path is a real path without unexpected "..\"
if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal))
{
throw ADP.InvalidConnectionOptionValue(keyword);
}
}
return fullPath;
}
internal string ExpandDataDirectories(ref string filename, ref int position)
{
string value = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
string datadir = null;
int copyPosition = 0;
bool expanded = false;
for (NameValuePair current = _keyChain; null != current; current = current.Next)
{
value = current.Value;
// remove duplicate keyswords from connectionstring
//if ((object)this[current.Name] != (object)value) {
// expanded = true;
// copyPosition += current.Length;
// continue;
//}
// There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
if (_useOdbcRules)
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Driver:
case DbConnectionOptionKeywords.Pwd:
case DbConnectionOptionKeywords.UID:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
else
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Provider:
case DbConnectionOptionKeywords.DataProvider:
case DbConnectionOptionKeywords.RemoteProvider:
case DbConnectionOptionKeywords.ExtendedProperties:
case DbConnectionOptionKeywords.UserID:
case DbConnectionOptionKeywords.Password:
case DbConnectionOptionKeywords.UID:
case DbConnectionOptionKeywords.Pwd:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
if (null == value)
{
value = current.Value;
}
if (_useOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name))
{
if (value != current.Value)
{
expanded = true;
AppendKeyValuePairBuilder(builder, current.Name, value, _useOdbcRules);
builder.Append(';');
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
}
else
{
// strip out 'File Name=myconnection.udl' for OleDb
// remembering is value for which UDL file to open
// and where to insert the strnig
expanded = true;
filename = value;
position = builder.Length;
}
copyPosition += current.Length;
}
if (expanded)
{
value = builder.ToString();
}
else
{
value = null;
}
return value;
}
internal string ExpandKeyword(string keyword, string replacementValue)
{
// preserve duplicates, updated keyword value with replacement value
// if keyword not specified, append to end of the string
bool expanded = false;
int copyPosition = 0;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for (NameValuePair current = _keyChain; null != current; current = current.Next)
{
if ((current.Name == keyword) && (current.Value == this[keyword]))
{
// only replace the parse end-result value instead of all values
// so that when duplicate-keywords occur other original values remain in place
AppendKeyValuePairBuilder(builder, current.Name, replacementValue, _useOdbcRules);
builder.Append(';');
expanded = true;
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
copyPosition += current.Length;
}
if (!expanded)
{
//
Debug.Assert(!_useOdbcRules, "ExpandKeyword not ready for Odbc");
AppendKeyValuePairBuilder(builder, keyword, replacementValue, _useOdbcRules);
}
return builder.ToString();
}
internal static void ValidateKeyValuePair(string keyword, string value)
{
if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword))
{
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value))
{
throw ADP.InvalidValue(keyword);
}
}
}
}
| |
/*
* Original author: Nicholas Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2016 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace pwiz.Common.PeakFinding
{
internal class FoundPeak : IFoundPeak
{
private readonly IList<float> _allIntensities;
private readonly float _baselineIntensity;
// Only used in calculation of FWHM.
// This is an extra integer that gets added to the start and end of the peak, which slightly affects
// the way floating point numbers get rounded.
private readonly int _widthDataWings;
/// <param name="widthDataWings">Extra number that gets added to start and end of peak. Only used so that floating point numbers
/// get rounded exactly the way they were in the old Crawdad.</param>
/// <param name="intensities"></param>
/// <param name="baselineIntensity"></param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
public FoundPeak(int widthDataWings, IList<float> intensities, float baselineIntensity, int startIndex, int endIndex)
{
_allIntensities = intensities;
_baselineIntensity = baselineIntensity;
_widthDataWings = widthDataWings;
SetBoundaries(startIndex, endIndex);
}
public int StartIndex { get; private set; }
void IDisposable.Dispose()
{
}
public int EndIndex { get; private set; }
public int TimeIndex { get; private set; }
public float Area { get; private set; }
public float RawArea { get; private set; }
public float BackgroundArea { get; private set; }
public float Height { get; private set; }
public float RawHeight { get; private set; }
public float Fwhm { get; private set; }
public bool FwhmDegenerate { get; private set; }
public bool Identified { get; internal set; }
public int Length
{
get { return EndIndex - StartIndex + 1; }
}
public override string ToString()
{
return PeakFinders.PeakToString(this);
}
public void ResetBoundaries(int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
throw new ArgumentException();
}
StartIndex = startIndex;
EndIndex = endIndex;
}
private void SetBoundaries(int startIndex, int endIndex)
{
float backgroundLevel = Math.Min(SafeGetIntensity(startIndex), SafeGetIntensity(endIndex));
IList<float> intensitiesToSum = Enumerable.Range(startIndex, endIndex - startIndex + 1)
.Select(SafeGetIntensity).ToArray();
int maxIndex = startIndex;
float rawHeight = SafeGetIntensity(startIndex);
for (int i = startIndex + 1; i < endIndex; i++)
{
if (SafeGetIntensity(i) > rawHeight)
{
maxIndex = i;
rawHeight = SafeGetIntensity(i);
}
}
float rawArea = GetAreaUnderCurve(intensitiesToSum);
float backgroundArea = GetAreaUnderCurve(intensitiesToSum.Select(intensity => Math.Min(backgroundLevel, intensity)));
float height = rawHeight - backgroundLevel;
float halfMax = rawHeight - height / 2;
int? halfHeightStartIndex = null;
for (int i = startIndex; i < maxIndex; i++)
{
if (SafeGetIntensity(i) <= halfMax && SafeGetIntensity(i + 1) > halfMax)
{
halfHeightStartIndex = i;
break;
}
}
int? halfHeightEndIndex = null;
for (int i = maxIndex; i < endIndex; i++)
{
if (SafeGetIntensity(i) >= halfMax && SafeGetIntensity(i + 1) < halfMax)
{
halfHeightEndIndex = i;
break;
}
}
double halfHeightStart;
if (!halfHeightStartIndex.HasValue)
{
halfHeightStart = startIndex + _widthDataWings;
}
else
{
double frac_delta = (halfMax - SafeGetIntensity(halfHeightStartIndex.Value)) /
(SafeGetIntensity(halfHeightStartIndex.Value + 1) - SafeGetIntensity(halfHeightStartIndex.Value));
halfHeightStart = halfHeightStartIndex.Value + frac_delta + _widthDataWings;
}
double halfHeightEnd;
if (!halfHeightEndIndex.HasValue)
{
halfHeightEnd = endIndex + _widthDataWings;
}
else
{
double frac_delta = (SafeGetIntensity(halfHeightEndIndex.Value) - halfMax) /
(SafeGetIntensity(halfHeightEndIndex.Value) - SafeGetIntensity(halfHeightEndIndex.Value + 1));
halfHeightEnd = halfHeightEndIndex.Value + frac_delta + _widthDataWings;
}
StartIndex = ConstrainIndex(startIndex);
EndIndex = ConstrainIndex(endIndex);
TimeIndex = ConstrainIndex(maxIndex);
Height = height;
RawHeight = rawHeight;
Area = rawArea - backgroundArea;
RawArea = rawArea;
BackgroundArea = backgroundArea;
Fwhm = (float)halfHeightEnd - (float)halfHeightStart;
FwhmDegenerate = !halfHeightStartIndex.HasValue || !halfHeightEndIndex.HasValue;
}
private float GetAreaUnderCurve(IEnumerable<float> intensities)
{
bool first = true;
float firstValue = 0;
float lastValue = 0;
double sum = 0;
foreach (var intensity in intensities)
{
if (first)
{
firstValue = intensity;
first = false;
}
lastValue = intensity;
sum += intensity;
}
return (float) (sum - firstValue/2 - lastValue/2);
}
public float SafeGetIntensity(int index)
{
if (index < 0 || index >= _allIntensities.Count)
{
return _baselineIntensity;
}
return _allIntensities[index];
}
private int ConstrainIndex(int index)
{
return Math.Min(_allIntensities.Count - 1, Math.Max(0, index));
}
}
}
| |
using System;
namespace GuruComponents.Netrix.HtmlFormatting
{
/// <summary>
/// This class creates a stream of tokens from the input string. The tokens control how the
/// formatter will place the elements in line or on a new line and how to indent.
/// </summary>
sealed class HtmlTokenizer
{
/// <summary>
/// The Tokenizer codes to set the state of the currently found or checked character state.
/// </summary>
internal class HtmlTokenizerStates
{
public const int BeginCommentTag1 = 100;
public const int BeginCommentTag2 = 101;
public const int BeginDoubleQuote = 19;
public const int BeginSingleQuote = 20;
public const int EndCommentTag1 = 103;
public const int EndCommentTag2 = 104;
public const int EndDoubleQuote = 11;
public const int EndSingleQuote = 13;
public const int EndTag = 17;
public const int EqualsChar = 18;
public const int Error = 16;
public const int ExpAttr = 6;
public const int ExpAttrVal = 9;
public const int ExpEquals = 8;
public const int ExpTag = 2;
public const int ExpTagAfterSlash = 4;
public const int ForwardSlash = 3;
public const int InAttr = 7;
public const int InAttrVal = 14;
public const int InCommentTag = 102;
public const int InDoubleQuoteAttrVal = 10;
public const int InSingleQuoteAttrVal = 12;
public const int InTagName = 5;
public const int RunAtServerState = 2048;
public const int RunAtState = 1024;
public const int Script = 40;
public const int ScriptState = 256;
public const int SelfTerminating = 15;
public const int ServerSideScript = 30;
public const int StartTag = 1;
public const int Style = 50;
public const int StyleState = 512;
public const int Text = 0;
public const int XmlDirective = 60;
public HtmlTokenizerStates ()
{
return;
}
}
/// <summary>
/// Start search for the first token with the current content. The content comes in
/// array of char, which is build in the <see cref="HtmlFormatter"/> class.
/// </summary>
/// <param name="chars"></param>
/// <returns></returns>
public static Token GetFirstToken(char[] chars)
{
if (chars == null)
{
throw new ArgumentNullException("chars");
}
else
{
return GetNextToken(chars, chars.Length, 0, 0);
}
}
/// <summary>
/// Start with the first token at a specific position.
/// </summary>
/// <param name="chars">Content array</param>
/// <param name="length">Start position</param>
/// <param name="initialState">Current State from which the token is searched.</param>
/// <returns></returns>
public static Token GetFirstToken(char[] chars, int length, int initialState)
{
return GetNextToken(chars, length, 0, initialState);
}
/// <summary>
/// The next token in the stream
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public static Token GetNextToken(Token token)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
else
{
return GetNextToken(token.Chars, token.CharsLength, token.EndIndex, token.EndState);
}
}
/// <summary>
/// The next token within the stream from a given start position and state. The tokenizer loops through the
/// chars and determines the next token based on the given state and an "expected" state (Exp = expected).
/// If the expected state is recognized, the token is build, otherwise the search goes further until the
/// current state is completely resolved or an error is thrown.
/// </summary>
/// <param name="chars">Content array</param>
/// <param name="length">Length, number of chars to beeing searched.</param>
/// <param name="startIndex">Start index, point from which the search starts.</param>
/// <param name="startState">The current state of the tokenizer.</param>
/// <returns></returns>
public static Token GetNextToken(char[] chars, int length, int startIndex, int startState)
{
Token token;
if (chars == null)
{
throw new ArgumentNullException("chars");
}
if (startIndex >= length)
{
return null;
}
int currentState = startState;
bool IsScriptState = (startState & HtmlTokenizerStates.ScriptState) == 0 == false; // ScriptState
int scriptState = !IsScriptState ? 0 : HtmlTokenizerStates.ScriptState;
bool IsStyleState = (startState & HtmlTokenizerStates.StyleState) == 0 == false; // StyleState
int styleState = !IsStyleState ? 0 : HtmlTokenizerStates.StyleState;
bool IsRunAtState = (startState & HtmlTokenizerStates.RunAtState) == 0 == false; // RunAtState
int runAtState = !IsRunAtState ? 0 : HtmlTokenizerStates.RunAtState;
bool IsRunAtServerState = (startState & HtmlTokenizerStates.RunAtServerState) == 0 == false; // RunAtServerState
int runAtServerState = !IsRunAtServerState ? 0 : HtmlTokenizerStates.RunAtServerState;
int index1 = startIndex;
int index2 = startIndex;
int index3;
for (token = null; token == null && index1 < length; index1++)
{
char ch = chars[index1];
int currentBaseState = currentState & 255;
if (currentBaseState <= HtmlTokenizerStates.Style)
{
switch (currentBaseState)
{
case HtmlTokenizerStates.Text:
if (ch != '<')
{
continue;
}
currentState = HtmlTokenizerStates.StartTag;
index3 = index1;
token = new Token(TokenType.TextToken, currentState, index2, index3, chars, length);
break;
case HtmlTokenizerStates.StartTag:
if (ch != '<')
{
currentState = HtmlTokenizerStates.Error;
}
else if (
// Check for <% Tag (ASP/ASP.NET)
(index1 + 1 < length && chars[index1 + 1] == '%')
||
// Check for PHP short script tag
(index1 + 4 < length && (chars[index1 + 1] == '?' && chars[index1 + 2] == '='))
)
{
currentState = HtmlTokenizerStates.ServerSideScript | scriptState | styleState;
index2 = index1;
// slip thru the end tag
}
else
{
currentState = HtmlTokenizerStates.ExpTag | scriptState | styleState;
index3 = index1 + 1;
token = new Token(TokenType.OpenBracket, currentState, index2, index3, chars, length);
}
break;
case HtmlTokenizerStates.ExpTag:
if (ch == '/')
{
currentState = HtmlTokenizerStates.ForwardSlash | scriptState | styleState;
index3 = index1;
token = new Token(TokenType.Empty, currentState, index2, index3, chars, length);
}
else if (ch == '!')
{
currentState = HtmlTokenizerStates.BeginCommentTag1 | scriptState | styleState;
index2 = index1;
}
else if (ch == '%')
{
currentState = HtmlTokenizerStates.ServerSideScript;
index2 = index1;
}
else if (IsWordChar(ch))
{
currentState = HtmlTokenizerStates.InTagName | scriptState | styleState;
index2 = index1;
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.ServerSideScript:
int indexAspClose = IndexOf(chars, index1, length, "%>"); // Detect end of <% %> section for ASP/ASP.NET
if (indexAspClose > -1)
{
currentState = HtmlTokenizerStates.Text;
index3 = indexAspClose + 2;
token = new Token(TokenType.InlineServerScript, currentState, index2, index3, chars, length);
break;
}
int indexPhpClose = IndexOf(chars, index1, length, "?>"); // Detect end of <? ?> section for PHP
if (indexPhpClose > -1)
{
currentState = HtmlTokenizerStates.Text;
index3 = indexPhpClose + 2;
token = new Token(TokenType.PhpScriptTag, currentState, index2, index3, chars, length);
break;
}
index1 = length - 1;
break;
case HtmlTokenizerStates.ForwardSlash:
if (ch == '/')
{
currentState = HtmlTokenizerStates.ExpTagAfterSlash | scriptState | styleState;
index3 = index1 + 1;
token = new Token(TokenType.ForwardSlash, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.ExpTagAfterSlash:
if (IsWordChar(ch))
{
currentState = HtmlTokenizerStates.InTagName | scriptState | styleState;
index2 = index1;
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.InTagName:
if (IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.ExpAttr;
index3 = index1;
string str1 = new String(chars, index2, index3 - index2);
if (str1.ToLower().Equals("script"))
{
if (!IsScriptState)
{
currentState |= HtmlTokenizerStates.ScriptState;
}
}
else if (str1.ToLower().Equals("style") && !IsStyleState)
{
currentState |= HtmlTokenizerStates.StyleState;
}
token = new Token(TokenType.TagName, currentState, index2, index3, chars, length);
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag;
index3 = index1;
string str2 = new String(chars, index2, index3 - index2);
if (str2.ToLower().Equals("script"))
{
if (!IsScriptState)
{
currentState |= HtmlTokenizerStates.ScriptState;
}
}
else if (str2.ToLower().Equals("style") && !IsStyleState)
{
currentState |= HtmlTokenizerStates.StyleState;
}
token = new Token(TokenType.TagName, currentState, index2, index3, chars, length);
}
else if (!IsWordChar(ch))
{
if (ch == '/')
{
currentState = HtmlTokenizerStates.SelfTerminating;
index3 = index1;
string str3 = new String(chars, index2, index3 - index2);
if (str3.ToLower().Equals("script"))
{
if (!IsScriptState)
{
currentState |= HtmlTokenizerStates.ScriptState;
}
}
else if (str3.ToLower().Equals("style") && !IsStyleState)
{
currentState |= HtmlTokenizerStates.StyleState;
}
token = new Token(TokenType.TagName, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
}
break;
case HtmlTokenizerStates.ExpAttr:
if (IsWordChar(ch))
{
currentState = HtmlTokenizerStates.InAttr | scriptState | styleState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag | scriptState | styleState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (ch == '/')
{
currentState = HtmlTokenizerStates.SelfTerminating | scriptState | styleState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (!IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.InAttr:
if (IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.ExpEquals | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsScriptState && new String(chars, index2, index3 - index2).ToLower() == "runat")
{
currentState |= 1024;
}
token = new Token(TokenType.AttrName, currentState, index2, index3, chars, length);
}
else if (ch == '=')
{
currentState = HtmlTokenizerStates.ExpEquals | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsScriptState && new String(chars, index2, index3 - index2).ToLower() == "runat")
{
currentState |= HtmlTokenizerStates.RunAtState;
}
token = new Token(TokenType.AttrName, currentState, index2, index3, chars, length);
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag | scriptState | styleState | runAtServerState;
index3 = index1;
token = new Token(TokenType.AttrName, currentState, index2, index3, chars, length);
}
else if (ch == '/')
{
currentState = HtmlTokenizerStates.SelfTerminating | scriptState | styleState;
index3 = index1;
token = new Token(TokenType.AttrName, currentState, index2, index3, chars, length);
}
else if (!IsWordChar(ch))
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.ExpEquals:
if (ch == '=')
{
currentState = HtmlTokenizerStates.ExpAttrVal | scriptState | styleState | runAtState | runAtServerState;
index2 = index1;
index3 = index1 + 1;
token = new Token(TokenType.EqualsChar, currentState, index2, index3, chars, length);
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag | scriptState | styleState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (ch == '/')
{
currentState = HtmlTokenizerStates.SelfTerminating;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (IsWordChar(ch))
{
currentState = HtmlTokenizerStates.InAttr | scriptState | styleState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (!IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.EqualsChar:
if (ch == '=')
{
currentState = HtmlTokenizerStates.ExpAttrVal | scriptState | styleState | runAtState | runAtServerState;
index3 = index1 + 1;
token = new Token(TokenType.EqualsChar, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.ExpAttrVal:
if (ch == '\'')
{
currentState = HtmlTokenizerStates.BeginSingleQuote | scriptState | styleState | runAtState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (ch == '\"')
{
currentState = HtmlTokenizerStates.BeginDoubleQuote | scriptState | styleState | runAtState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (IsWordChar(ch) || ch == '/') // here we need to recognize the forward slash, because the parameter can contain a unix path
{
currentState = HtmlTokenizerStates.InAttrVal | scriptState | styleState | runAtState | runAtServerState;
index3 = index1;
token = new Token(TokenType.Whitespace, currentState, index2, index3, chars, length);
}
else if (!IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.BeginDoubleQuote:
if (ch == '\"')
{
currentState = HtmlTokenizerStates.InDoubleQuoteAttrVal | scriptState | styleState | runAtState | runAtServerState;
index3 = index1 + 1;
token = new Token(TokenType.DoubleQuote, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
System.Diagnostics.Debug.WriteLine("BeginDoubleQuote");
}
break;
case HtmlTokenizerStates.InDoubleQuoteAttrVal:
if (ch != '\"')
{
continue; // goto IL_0c11;
}
currentState = HtmlTokenizerStates.EndDoubleQuote | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsRunAtState && new String(chars, index2, index3 - index2).ToLower() == "server")
{
currentState |= HtmlTokenizerStates.RunAtServerState;
}
token = new Token(TokenType.AttrVal, currentState, index2, index3, chars, length);
break;
case HtmlTokenizerStates.EndDoubleQuote:
if (ch == '\"')
{
currentState = HtmlTokenizerStates.ExpAttr | scriptState | styleState | runAtServerState;
index3 = index1 + 1;
token = new Token(TokenType.DoubleQuote, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.BeginSingleQuote:
if (ch == '\'')
{
currentState = HtmlTokenizerStates.InSingleQuoteAttrVal | scriptState | styleState | runAtState | runAtServerState;
index3 = index1 + 1;
token = new Token(TokenType.SingleQuote, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.InSingleQuoteAttrVal:
if (ch != '\'')
{
continue;
}
currentState = HtmlTokenizerStates.EndSingleQuote | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsRunAtState && new String(chars, index2, index3 - index2).ToLower() == "server")
{
currentState |= HtmlTokenizerStates.RunAtServerState;
}
token = new Token(TokenType.AttrVal, currentState, index2, index3, chars, length);
break;
case HtmlTokenizerStates.EndSingleQuote:
if (ch == '\'')
{
currentState = HtmlTokenizerStates.ExpAttr | scriptState | styleState | runAtServerState;
index3 = index1 + 1;
token = new Token(TokenType.SingleQuote, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.InAttrVal:
if (IsWhitespace(ch))
{
currentState = HtmlTokenizerStates.ExpAttr | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsRunAtState && new String(chars, index2, index3 - index2).ToLower() == "server")
{
currentState |= HtmlTokenizerStates.RunAtServerState;
}
token = new Token(TokenType.AttrVal, currentState, index2, index3, chars, length);
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsRunAtState && new String(chars, index2, index3 - index2).ToLower() == "server")
{
currentState |= HtmlTokenizerStates.RunAtServerState;
}
token = new Token(TokenType.AttrVal, currentState, index2, index3, chars, length);
}
else if (ch == '/' && index1 + 1 < length && chars[index1 + 1] == '>')
{
currentState = HtmlTokenizerStates.SelfTerminating | scriptState | styleState | runAtServerState;
index3 = index1;
if (IsRunAtState && new String(chars, index2, index3 - index2).ToLower() == "server")
{
currentState |= HtmlTokenizerStates.RunAtServerState;
}
token = new Token(TokenType.AttrVal, currentState, index2, index3, chars, length);
}
break;
case HtmlTokenizerStates.SelfTerminating:
if (ch == '/' && index1 + 1 < length && chars[index1 + 1] == '>')
{
currentState = HtmlTokenizerStates.Text;
index3 = index1 + 2;
token = new Token(TokenType.SelfTerminating, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.EndTag:
if (ch == '>')
{
if (IsScriptState)
{
currentState = HtmlTokenizerStates.Script | scriptState | styleState | runAtServerState;
}
else if (IsStyleState)
{
currentState = HtmlTokenizerStates.Style | scriptState | styleState;
}
else
{
currentState = HtmlTokenizerStates.Text;
}
index3 = index1 + 1;
token = new Token(TokenType.CloseBracket, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.Script:
int endScriptIndex = IndexOf(chars, index1, length, "</script>");
if (endScriptIndex > -1)
{
currentState = HtmlTokenizerStates.StartTag | scriptState | styleState | runAtServerState;
index3 = endScriptIndex;
if (IsRunAtServerState)
{
token = new Token(TokenType.ServerScriptBlock, currentState, index2, index3, chars, length);
}
else
{
token = new Token(TokenType.ClientScriptBlock, currentState, index2, index3, chars, length);
}
}
else
{
index1 = length - 1;
}
break;
case HtmlTokenizerStates.Error:
if (ch != '>')
{
continue;
}
currentState = HtmlTokenizerStates.EndTag;
index3 = index1;
token = new Token(TokenType.Error, currentState, index2, index3, chars, length);
break;
// some mixed states we ignore here
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
break;
default:
if (currentBaseState != HtmlTokenizerStates.Style)
{
continue;
}
int endStyleIndex = IndexOf(chars, index1, length, "</style>");
if (endStyleIndex > -1)
{
currentState = HtmlTokenizerStates.StartTag | scriptState | styleState;
index3 = endStyleIndex;
token = new Token(TokenType.Style, currentState, index2, index3, chars, length);
}
else
{
index1 = length - 1;
}
break;
}
}
else if (currentBaseState != HtmlTokenizerStates.XmlDirective)
{
switch (currentBaseState)
{
case HtmlTokenizerStates.BeginCommentTag1:
if (ch == '-')
{
currentState = HtmlTokenizerStates.BeginCommentTag2;
}
else if (IsWordChar(ch))
{
currentState = HtmlTokenizerStates.XmlDirective;
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.BeginCommentTag2:
if (ch == '-')
{
currentState = HtmlTokenizerStates.InCommentTag;
}
else
{
currentState = HtmlTokenizerStates.Error;
}
break;
case HtmlTokenizerStates.InCommentTag:
if (ch != '-')
{
continue;
}
currentState = HtmlTokenizerStates.EndCommentTag1;
break;
case HtmlTokenizerStates.EndCommentTag1:
if (ch == '-')
{
currentState = HtmlTokenizerStates.EndCommentTag2;
}
else
{
currentState = HtmlTokenizerStates.InCommentTag;
}
break;
case HtmlTokenizerStates.EndCommentTag2:
if (Char.IsWhiteSpace(ch))
{
continue;
}
if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag;
index3 = index1;
token = new Token(TokenType.Comment, currentState, index2, index3, chars, length);
}
else
{
currentState = HtmlTokenizerStates.InCommentTag;
}
break;
}
}
else if (ch == '>')
{
currentState = HtmlTokenizerStates.EndTag;
index3 = index1;
token = new Token(TokenType.XmlDirective, currentState, index2, index3, chars, length);
}
}
if (index1 >= length && token == null)
{
TokenType tokenType;
int currentBaseState = currentState & 255;
if (currentBaseState <= 14)
{
if (currentBaseState != HtmlTokenizerStates.Text)
{
switch (currentBaseState)
{
case HtmlTokenizerStates.InAttr:
tokenType = TokenType.AttrName;
currentState = HtmlTokenizerStates.ExpAttr;
break;
case HtmlTokenizerStates.ExpAttr:
tokenType = TokenType.Whitespace;
break;
default:
if (currentBaseState != HtmlTokenizerStates.InAttrVal)
{
return token;
}
tokenType = TokenType.AttrVal;
currentState = HtmlTokenizerStates.ExpAttr;
break;
}
}
else
{
tokenType = TokenType.TextToken;
}
}
else if (currentBaseState <= HtmlTokenizerStates.Script)
{
if (currentBaseState != HtmlTokenizerStates.ServerSideScript)
{
if (currentBaseState != HtmlTokenizerStates.Script)
{
return token;
}
if (IsRunAtServerState)
{
tokenType = TokenType.ServerScriptBlock;
}
else
{
tokenType = TokenType.ClientScriptBlock;
}
}
else
{
tokenType = TokenType.InlineServerScript;
}
}
else if (currentBaseState != HtmlTokenizerStates.Style)
{
switch (currentBaseState)
{
case HtmlTokenizerStates.BeginCommentTag1:
case HtmlTokenizerStates.BeginCommentTag2:
case HtmlTokenizerStates.InCommentTag:
case HtmlTokenizerStates.EndCommentTag1:
case HtmlTokenizerStates.EndCommentTag2:
tokenType = TokenType.Comment;
break;
default:
tokenType = TokenType.Error;
currentState = HtmlTokenizerStates.Error;
break;
}
}
else
{
tokenType = TokenType.Style;
}
index3 = index1;
token = new Token(tokenType, currentState, index2, index3, chars, length);
}
return token;
}
/// <summary>
/// Checks the char is a whitespace.
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private static bool IsWhitespace(char c)
{
return Char.IsWhiteSpace(c);
}
/// <summary>
/// Checks the char is a word character, which is a letter, a digit or one of the characters
/// '_' (underline), ':' (colon), '#' (hash sign), '-' (minus sign), '*' (asterisk), '.' (dot), and '^'.
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private static bool IsWordChar(char c)
{
if (!Char.IsLetterOrDigit(c) && c != '_' && c != ':' && c != '#' && c != '-' && c != '*' && c != '^' && c != ',')
{
return c == '.';
}
else
{
return true;
}
}
/// <summary>
/// Searches for a specific character or string within the chars array from a specific position
/// and to a specific position.
/// </summary>
/// <param name="chars">Chars array</param>
/// <param name="startIndex">Start position</param>
/// <param name="endColumnNumber">End position</param>
/// <param name="s">String to be searched for</param>
/// <returns></returns>
private static int IndexOf(char[] chars, int startIndex, int endColumnNumber, string s)
{
int currentState = s.Length;
int j = endColumnNumber - currentState + 1;
for (int k = startIndex; k < j; k++)
{
bool flag = true;
for (int runAtState = 0; runAtState < currentState; runAtState++)
{
if (Char.ToUpper(chars[k + runAtState]) != Char.ToUpper(s[runAtState]))
{
flag = false;
break;
}
}
if (flag)
{
return k;
}
}
return -1;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/23/2009 11:18:39 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
/// <summary>
/// TransverseMercator
/// </summary>
public class TransverseMercator : EllipticalTransform
{
#region Private Variables
private const double FC1 = 1.0;
private const double FC2 = .5;
private const double FC3 = .16666666666666666666;
private const double FC4 = .08333333333333333333;
private const double FC5 = .05;
private const double FC6 = .03333333333333333333;
private const double FC7 = .02380952380952380952;
private const double FC8 = .01785714285714285714;
private double[] _en;
private double _esp;
private double _ml0;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of TransverseMercator
/// </summary>
public TransverseMercator()
{
Name = "Transverse_Mercator";
Proj4Name = "tmerc";
}
#endregion
#region Methods
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
protected override void OnInit(ProjectionInfo projInfo)
{
if (Es != 0)
{
_en = MeridionalDistance.GetEn(Es);
if (_en == null) throw new ProjectionException(0);
_ml0 = MeridionalDistance.MeridionalLength(Phi0, Math.Sin(Phi0), Math.Cos(Phi0), _en);
_esp = Es / (1 - Es);
}
else
{
_esp = K0;
_ml0 = .5 * _esp;
}
}
#endregion
#region Private Methods
/// <summary>
/// The forward transform in the special case where there is no flattening of the spherical model of the earth.
/// </summary>
/// <param name="lp">The input lambda and phi geodetic values organized in an array</param>
/// <param name="xy">The output x and y values organized in an array</param>
/// <param name="startIndex">The zero based integer start index</param>
/// <param name="numPoints">The integer count of the number of xy pairs in the lp and xy arrays</param>
protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double cosphi;
/*
* Fail if our longitude is more than 90 degrees from the
* central meridian since the results are essentially garbage.
* Is error -20 really an appropriate return value?
*
* http://trac.osgeo.org/proj/ticket/5
*/
if (lp[lam] < -HALF_PI || lp[lam] > HALF_PI)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//ProjectionException(14);
}
double b = (cosphi = Math.Cos(lp[phi])) * Math.Sin(lp[lam]);
if (Math.Abs(Math.Abs(b) - 1) <= EPS10)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//ProjectionException(20);
}
xy[x] = _ml0 * Math.Log((1 + b) / (1 - b));
if ((b = Math.Abs(xy[y] = cosphi * Math.Cos(lp[lam]) / Math.Sqrt(1 - b * b))) >= 1)
{
if ((b - 1) > EPS10)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//ProjectionException(20);
}
xy[y] = 0;
}
else
{
xy[y] = Math.Acos(xy[y]);
}
if (lp[phi] < 0) xy[y] = -xy[y];
xy[y] = _esp * (xy[y] - Phi0);
}
}
/// <summary>
/// The forward transform where the spheroidal model of the earth has a flattening factor,
/// matching more closely with the oblique spheroid of the actual earth
/// </summary>
/// <param name="lp">The double values for geodetic lambda and phi organized into a one dimensional array</param>
/// <param name="xy">The double values for linear x and y organized into a one dimensional array</param>
/// <param name="startIndex">The zero based integer start index</param>
/// <param name="numPoints">The integer count of the number of xy pairs in the lp and xy arrays</param>
protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
/*
* Fail if our longitude is more than 90 degrees from the
* central meridian since the results are essentially garbage.
* Is error -20 really an appropriate return value?
*
* http://trac.osgeo.org/proj/ticket/5
*/
if (lp[lam] < -HALF_PI || lp[lam] > HALF_PI)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//ProjectionException(14);
}
double sinphi = Math.Sin(lp[phi]);
double cosphi = Math.Cos(lp[phi]);
double t = Math.Abs(cosphi) > 1E-10 ? sinphi / cosphi : 0;
t *= t;
double al = cosphi * lp[lam];
double als = al * al;
al /= Math.Sqrt(1 - Es * sinphi * sinphi);
double n = _esp * cosphi * cosphi;
xy[x] = K0 * al * (FC1 +
FC3 * als * (1 - t + n +
FC5 * als * (5 + t * (t - 18) + n * (14 - 58 * t) +
FC7 * als * (61 + t * (t * (179 - t) - 479)))));
xy[y] = K0 * (MeridionalDistance.MeridionalLength(lp[phi], sinphi, cosphi, _en) - _ml0 +
sinphi * al * lp[lam] * FC2 * (1 +
FC4 * als * (5 - t + n * (9 + 4 * n) +
FC6 * als * (61 + t * (t - 58) + n * (270 - 330 * t) +
FC8 * als * (1385 + t * (t * (543 - t) - 3111))))));
}
}
/// <summary>
/// Performs the inverse transform from a single coordinate of linear units to the same coordinate in geodetic lambda and
/// phi units in the special case where the shape of the earth is being approximated as a perfect sphere.
/// </summary>
/// <param name="xy">The double linear input x and y values organized into a 1 dimensional array</param>
/// <param name="lp">The double geodetic output lambda and phi values organized into a 1 dimensional array</param>
/// <param name="startIndex">The zero based integer start index</param>
/// <param name="numPoints">The integer count of the number of xy pairs in the lp and xy arrays</param>
protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double h = Math.Exp(xy[x] / _esp);
double g = .5 * (h - 1 / h);
h = Math.Cos(Phi0 + xy[y] / _esp);
lp[phi] = Math.Asin(Math.Sqrt((1 - h * h) / (1 + g * g)));
if (xy[y] < 0) lp[phi] = -lp[phi];
lp[lam] = ((g != 0 || h != 0) ? Math.Atan2(g, h) : 0);
}
}
/// <summary>
/// Performs the inverse transfrom from a single coordinate of linear units to the same coordinate in geodetic units
/// </summary>
/// <param name="xy">The double linear input x and y values organized into a 1 dimensional array</param>
/// <param name="lp">The double geodetic output lambda and phi values organized into a 1 dimensional array</param>
/// <param name="startIndex">The zero based integer start index</param>
/// <param name="numPoints">The integer count of the number of xy pairs in the lp and xy arrays</param>
protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
lp[phi] = MeridionalDistance.AngularDistance(_ml0 + xy[y] / K0, Es, _en);
if (Math.Abs(lp[phi]) >= HALF_PI)
{
lp[phi] = xy[y] < 0 ? -HALF_PI : HALF_PI;
lp[lam] = 0;
}
else
{
double sinphi = Math.Sin(lp[phi]);
double cosphi = Math.Cos(lp[phi]);
double t = Math.Abs(cosphi) > 1e-10 ? sinphi / cosphi : 0;
double n = _esp * cosphi * cosphi;
double con;
double d = xy[x] * Math.Sqrt(con = 1 - Es * sinphi * sinphi) / K0;
con *= t;
t *= t;
double ds = d * d;
lp[phi] -= (con * ds / (1 - Es)) * FC2 * (1 -
ds * FC4 * (5 + t * (3 - 9 * n) + n * (1 - 4 * n) -
ds * FC6 * (61 + t * (90 - 252 * n +
45 * t) + 46 * n
- ds * FC8 * (1385 + t * (3633 + t * (4095 + 1574 * t))))));
lp[lam] = d * (FC1 -
ds * FC3 * (1 + 2 * t + n -
ds * FC5 * (5 + t * (28 + 24 * t + 8 * n) + 6 * n
- ds * FC7 * (61 + t * (662 + t * (1320 + 720 * t)))))) / cosphi;
}
}
}
#endregion
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Globalization;
namespace System.Web.UI
{
public partial class HtmlBuilder
{
private Stack<Element> _elementStack = new Stack<Element>();
private string _formName;
private bool _isInAnchor = false;
private Control _commandTargetControl;
private HtmlBuilderDivTag _divTag;
private HtmlBuilderFormTag _formTag;
private HtmlBuilderTableTag _tableTag;
private HtmlOption _option;
/// <summary>
/// Element
/// </summary>
private struct Element
{
public HtmlTag Tag;
public string ValueIfUnknown;
public object State;
public Element(HtmlTag tag, object state)
{
Tag = tag;
State = state;
ValueIfUnknown = null;
}
public Element(string tag, object state)
{
Tag = HtmlTag.Unknown;
State = state;
ValueIfUnknown = tag;
}
}
/// <summary>
/// DivElementState
/// </summary>
private struct DivElementState
{
public bool IsState;
public HtmlBuilderDivTag DivState;
public DivElementState(bool isState, HtmlBuilderDivTag divState)
{
IsState = isState;
DivState = divState;
}
}
public class HtmlOption
{
public HtmlBuilderOptionType Type;
public string Key;
public string Value;
public int Size;
}
public Control CommandTargetControl
{
get { return _commandTargetControl; }
protected set { _commandTargetControl = value; }
}
public HtmlBuilderDivTag DivTag
{
get { return _divTag; }
}
public HtmlBuilderFormTag FormTag
{
get { return _formTag; }
}
public HtmlBuilderTableTag TableTag
{
get { return _tableTag; }
}
public void ElementPop(HtmlTag tag, string valueIfUnknown, HtmlTag stopTag, string stopValueIfUnknown)
{
var stackTag = HtmlTag.__Undefined;
string stackValueIfUnknown = null;
while (((stackTag != tag) || (stackValueIfUnknown != valueIfUnknown)) && (_elementStack.Count > 0))
{
Element peekElement;
if (stopTag != HtmlTag.__Undefined)
{
peekElement = _elementStack.Peek();
HtmlTag peekElementTag = peekElement.Tag;
switch (stopTag)
{
case HtmlTag.__OlUl:
if ((peekElementTag == HtmlTag.Ol) || (peekElementTag == HtmlTag.Ul))
return;
break;
default:
if ((peekElementTag == stopTag) && (peekElement.ValueIfUnknown == stopValueIfUnknown))
return;
break;
}
}
var element = _elementStack.Pop();
stackTag = element.Tag;
stackValueIfUnknown = element.ValueIfUnknown;
switch (stackTag)
{
case HtmlTag._CommandTarget:
_commandTargetControl = (Control)element.State;
break;
case HtmlTag.Script:
_writeCount++;
_textWriter.Write("//--> ]]>");
_textWriter.RenderEndTag();
break;
// Container
case HtmlTag.Div:
_writeCount++;
var divElementState = (DivElementState)element.State;
if (divElementState.IsState)
_divTag = divElementState.DivState;
_textWriter.RenderEndTag();
break;
// Content
case HtmlTag.A:
_writeCount++;
_isInAnchor = false;
_textWriter.RenderEndTag();
break;
// H1-3
case HtmlTag.H1:
case HtmlTag.H2:
case HtmlTag.H3:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Paragraph
case HtmlTag.P:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Span
case HtmlTag.Span:
_writeCount++;
_textWriter.RenderEndTag();
break;
// List
case HtmlTag.Li:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Ol:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Ul:
_writeCount++;
_textWriter.RenderEndTag();
break;
// Table
case HtmlTag.Colgroup:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Table:
_writeCount++;
_tableTag = (HtmlBuilderTableTag)element.State;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tbody:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Td:
string nullTdBody;
if (((int)element.State == _writeCount) && ((nullTdBody = _tableTag.NullTdBody).Length > 0))
_textWriter.Write(nullTdBody);
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tfoot:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Th:
string nullTdBody2;
if (((int)element.State == _writeCount) && ((nullTdBody2 = _tableTag.NullTdBody).Length > 0))
_textWriter.Write(nullTdBody2);
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Thead:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Tr:
var trCloseMethod = _tableTag.TrCloseMethod;
if (trCloseMethod != HtmlBuilderTableTag.TableTrCloseMethod.Undefined)
{
int tdCount = (_tableTag.ColumnCount - _tableTag.ColumnIndex);
switch (trCloseMethod)
{
case HtmlBuilderTableTag.TableTrCloseMethod.Td:
for (int tdIndex = 1; tdIndex < tdCount; tdIndex++)
{
_tableTag.AddAttribute(this, _textWriter, HtmlTag.Td, null);
_textWriter.RenderBeginTag(HtmlTextWriterTag.Td);
string nullTdBody3 = _tableTag.NullTdBody;
if (nullTdBody3.Length > 0)
_textWriter.Write(nullTdBody3);
_textWriter.RenderEndTag();
}
break;
case HtmlBuilderTableTag.TableTrCloseMethod.TdColspan:
if (tdCount > 0)
{
if (tdCount > 1)
_textWriter.AddAttribute(HtmlTextWriterAttribute.Colspan, tdCount.ToString());
_tableTag.AddAttribute(this, _textWriter, HtmlTag.Td, null);
_textWriter.RenderBeginTag(HtmlTextWriterTag.Td);
string nullTdBody4 = _tableTag.NullTdBody;
if (nullTdBody4.Length > 0)
_textWriter.Write(nullTdBody4);
_textWriter.RenderEndTag();
}
break;
}
}
_tableTag.IsTrHeader = false;
_writeCount++;
_textWriter.RenderEndTag();
break;
// Form
case HtmlTag._FormReference:
if (_formTag != null)
_formTag = null;
break;
case HtmlTag.Button:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Fieldset:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Form:
_writeCount++;
//Http.Instance.ExitForm(this);
if (_formTag != null)
_formTag = null;
_formName = null;
_textWriter.RenderEndTag();
break;
case HtmlTag.Label:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Option:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Select:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Textarea:
_writeCount++;
_textWriter.RenderEndTag();
break;
case HtmlTag.Unknown:
_writeCount++;
switch (element.ValueIfUnknown)
{
case "optgroup":
_textWriter.RenderEndTag();
break;
default:
_textWriter.RenderEndTag();
break;
}
break;
default:
_writeCount++;
_textWriter.RenderEndTag();
break;
}
}
}
public void ElementPush(HtmlTag tag, object state) { _elementStack.Push(new Element(tag, state)); }
public void ElementPush(string tag, object state) { _elementStack.Push(new Element(tag, state)); }
}
}
| |
using System;
using System.ComponentModel;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Controls
{
/// <summary>
/// Base class for Avalonia controls.
/// </summary>
/// <remarks>
/// The control class extends <see cref="InputElement"/> and adds the following features:
///
/// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control.
/// - <see cref="ContextRequestedEvent"/> and other context menu related members.
/// </remarks>
public class Control : InputElement, IControl, INamed, IVisualBrushInitialize, ISetterValue
{
/// <summary>
/// Defines the <see cref="FocusAdorner"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IControl>?> FocusAdornerProperty =
AvaloniaProperty.Register<Control, ITemplate<IControl>?>(nameof(FocusAdorner));
/// <summary>
/// Defines the <see cref="Tag"/> property.
/// </summary>
public static readonly StyledProperty<object?> TagProperty =
AvaloniaProperty.Register<Control, object?>(nameof(Tag));
/// <summary>
/// Defines the <see cref="ContextMenu"/> property.
/// </summary>
public static readonly StyledProperty<ContextMenu?> ContextMenuProperty =
AvaloniaProperty.Register<Control, ContextMenu?>(nameof(ContextMenu));
/// <summary>
/// Defines the <see cref="ContextFlyout"/> property
/// </summary>
public static readonly StyledProperty<FlyoutBase?> ContextFlyoutProperty =
AvaloniaProperty.Register<Control, FlyoutBase?>(nameof(ContextFlyout));
/// <summary>
/// Event raised when an element wishes to be scrolled into view.
/// </summary>
public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent =
RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble);
/// <summary>
/// Provides event data for the <see cref="ContextRequested"/> event.
/// </summary>
public static readonly RoutedEvent<ContextRequestedEventArgs> ContextRequestedEvent =
RoutedEvent.Register<Control, ContextRequestedEventArgs>(nameof(ContextRequested),
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
private DataTemplates? _dataTemplates;
private IControl? _focusAdorner;
/// <summary>
/// Gets or sets the control's focus adorner.
/// </summary>
public ITemplate<IControl>? FocusAdorner
{
get => GetValue(FocusAdornerProperty);
set => SetValue(FocusAdornerProperty, value);
}
/// <summary>
/// Gets or sets the data templates for the control.
/// </summary>
/// <remarks>
/// Each control may define data templates which are applied to the control itself and its
/// children.
/// </remarks>
public DataTemplates DataTemplates => _dataTemplates ??= new DataTemplates();
/// <summary>
/// Gets or sets a context menu to the control.
/// </summary>
public ContextMenu? ContextMenu
{
get => GetValue(ContextMenuProperty);
set => SetValue(ContextMenuProperty, value);
}
/// <summary>
/// Gets or sets a context flyout to the control
/// </summary>
public FlyoutBase? ContextFlyout
{
get => GetValue(ContextFlyoutProperty);
set => SetValue(ContextFlyoutProperty, value);
}
/// <summary>
/// Gets or sets a user-defined object attached to the control.
/// </summary>
public object? Tag
{
get => GetValue(TagProperty);
set => SetValue(TagProperty, value);
}
/// <summary>
/// Occurs when the user has completed a context input gesture, such as a right-click.
/// </summary>
public event EventHandler<ContextRequestedEventArgs> ContextRequested
{
add => AddHandler(ContextRequestedEvent, value);
remove => RemoveHandler(ContextRequestedEvent, value);
}
public new IControl? Parent => (IControl?)base.Parent;
/// <inheritdoc/>
bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null;
/// <inheritdoc/>
void ISetterValue.Initialize(ISetter setter)
{
if (setter is Setter s && s.Property == ContextFlyoutProperty)
{
return; // Allow ContextFlyout to not need wrapping in <Template>
}
throw new InvalidOperationException(
"Cannot use a control as a Setter value. Wrap the control in a <Template>.");
}
/// <inheritdoc/>
void IVisualBrushInitialize.EnsureInitialized()
{
if (VisualRoot == null)
{
if (!IsInitialized)
{
foreach (var i in this.GetSelfAndVisualDescendants())
{
var c = i as IControl;
if (c?.IsInitialized == false && c is ISupportInitialize init)
{
init.BeginInit();
init.EndInit();
}
}
}
if (!IsArrangeValid)
{
Measure(Size.Infinity);
Arrange(new Rect(DesiredSize));
}
}
}
/// <summary>
/// Gets the element that receives the focus adorner.
/// </summary>
/// <returns>The control that receives the focus adorner.</returns>
protected virtual IControl? GetTemplateFocusTarget() => this;
/// <inheritdoc/>
protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
InitializeIfNeeded();
}
/// <inheritdoc/>
protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (IsFocused &&
(e.NavigationMethod == NavigationMethod.Tab ||
e.NavigationMethod == NavigationMethod.Directional))
{
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
if (adornerLayer != null)
{
if (_focusAdorner == null)
{
var template = GetValue(FocusAdornerProperty);
if (template != null)
{
_focusAdorner = template.Build();
}
}
if (_focusAdorner != null && GetTemplateFocusTarget() is Visual target)
{
AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target);
adornerLayer.Children.Add(_focusAdorner);
}
}
}
}
/// <inheritdoc/>
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (_focusAdorner?.Parent != null)
{
var adornerLayer = (IPanel)_focusAdorner.Parent;
adornerLayer.Children.Remove(_focusAdorner);
_focusAdorner = null;
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (e.Source == this
&& !e.Handled
&& e.InitialPressMouseButton == MouseButton.Right)
{
var args = new ContextRequestedEventArgs(e);
RaiseEvent(args);
e.Handled = args.Handled;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (e.Source == this
&& !e.Handled)
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>()?.OpenContextMenu;
if (keymap is null)
return;
var matches = false;
for (var index = 0; index < keymap.Count; index++)
{
var key = keymap[index];
matches |= key.Matches(e);
if (matches)
{
break;
}
}
if (matches)
{
var args = new ContextRequestedEventArgs();
RaiseEvent(args);
e.Handled = args.Handled;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Xml;
using Codentia.Common.Logging;
using Codentia.Common.Logging.BL;
namespace Codentia.Common.Net
{
/// <summary>
/// Static class to handle email functionality
/// </summary>
public sealed class EmailManager : IDisposable
{
private static object _instanceLock = new object();
private static EmailManager _instance;
private string _templateBasePath = null;
private HttpContext _context = null;
private bool _fakeEmailFailure = false;
private EmailManager()
{
}
/// <summary>
/// Gets or sets the base path from which email templates should be loaded
/// </summary>
public string TemplateBasePath
{
get
{
return _templateBasePath;
}
set
{
if (this.Context == null || this.Context.Server == null)
{
_templateBasePath = value;
}
else
{
_templateBasePath = this.Context.Server.MapPath(value);
}
}
}
/// <summary>
/// Gets or sets the context.
/// </summary>
/// <value>The context.</value>
public HttpContext Context
{
get
{
return _context;
}
set
{
_context = value;
}
}
/// <summary>
/// Sets a value indicating whether [fake email failure].
/// </summary>
/// <value><c>true</c> if [fake email failure]; otherwise, <c>false</c>.</value>
public bool FakeEmailFailure
{
set
{
_fakeEmailFailure = value;
}
}
/// <summary>
/// Get an instance of EmailManager for use
/// </summary>
/// <returns>EmailManager object</returns>
public static EmailManager GetInstance()
{
return GetInstance(null);
}
/// <summary>
/// Get an instance of EmailManager for use in a web context (supports mapping paths using server object)
/// </summary>
/// <param name="context">HttpContext for use in mapping paths (ignored if null)</param>
/// <returns>EmailManager object</returns>
public static EmailManager GetInstance(HttpContext context)
{
lock (_instanceLock)
{
if (_instance == null)
{
_instance = new EmailManager();
_instance.Context = context;
}
}
return _instance;
}
/// <summary>
/// Creates the email body from template.
/// </summary>
/// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
/// <param name="template">The template.</param>
/// <param name="replacementValues">The replacement values.</param>
/// <returns>string of email body</returns>
public string CreateEmailBodyFromInlineTemplate(bool isHtml, string template, Dictionary<string, string> replacementValues)
{
// now strip carriage returns and tabs from html
template = template.Replace("\r", string.Empty);
template = template.Replace("\n", string.Empty);
template = template.Replace("\t", string.Empty);
if (replacementValues != null)
{
Dictionary<string, string>.Enumerator replacementEnumerator = replacementValues.GetEnumerator();
while (replacementEnumerator.MoveNext())
{
template = template.Replace(string.Format("~~{0}~~", replacementEnumerator.Current.Key), replacementEnumerator.Current.Value).Trim();
}
}
if (string.IsNullOrEmpty(template) || template.Contains("~~"))
{
LogValues(replacementValues);
throw new Exception("Failed to complete generation of content for template");
}
return template;
}
/// <summary>
/// Create a formatted email body string (content)
/// </summary>
/// <param name="isHtml">Should the HTML template be used?</param>
/// <param name="templateFile">Template to use (filename only)</param>
/// <param name="replacementValues">Dictionary of tag replacement values to insert into email template</param>
/// <returns>string of email body</returns>
public string CreateEmailBodyFromTemplate(bool isHtml, string templateFile, Dictionary<string, string> replacementValues)
{
// check for null only, not empty string
if (_templateBasePath == null)
{
throw new Exception("TemplateBasePath has not been set");
}
XmlDocument template = new XmlDocument();
string content = string.Empty;
try
{
template.Load(string.Format("{0}{1}{2}.xml", _templateBasePath, System.IO.Path.DirectorySeparatorChar, templateFile));
}
catch (Exception ex)
{
LogValues(replacementValues);
LogManager.Instance.AddToLog(LogMessageType.NonFatalError, "EmailManager", string.Format("Unable to load XML template {0}", templateFile));
LogManager.Instance.AddToLog(ex, "EmailManager");
}
if (template.DocumentElement != null)
{
XmlNode templateNode = null;
if (isHtml)
{
templateNode = template.DocumentElement.SelectSingleNode("html");
content = templateNode.OuterXml;
}
else
{
templateNode = template.DocumentElement.SelectSingleNode("plaintext");
content = templateNode.InnerText;
}
content = CreateEmailBodyFromInlineTemplate(isHtml, content, replacementValues);
}
else
{
LogValues(replacementValues);
throw new Exception(string.Format("Unable to load message template: {0}", templateFile));
}
return content;
}
/// <summary>
/// Sends the email.
/// </summary>
/// <param name="fromAddress">From address.</param>
/// <param name="replyToAddress">The reply to address.</param>
/// <param name="toAddress">To address.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
public void SendEmail(string fromAddress, string replyToAddress, string toAddress, string subject, string body, bool isHtml)
{
this.SendEmail(fromAddress, replyToAddress, toAddress, subject, body, isHtml, null);
}
/// <summary>
/// Send an email.
/// </summary>
/// <param name="fromAddress">From address - this should be a valid address authorised to send email (e.g. a system one)</param>
/// <param name="replyToAddress">ReplyTo address - this should be the address to which replies should be sent</param>
/// <param name="toAddress">to address</param>
/// <param name="subject">subject of email</param>
/// <param name="body">body of email</param>
/// <param name="isHtml">is this an html message?</param>
/// <param name="attachments">The attachments.</param>
public void SendEmail(string fromAddress, string replyToAddress, string toAddress, string subject, string body, bool isHtml, Attachment[] attachments)
{
// if in test "fake email failure" mode, then fail
if (_fakeEmailFailure)
{
throw new Exception("FakeEmailFailure=true, message not sent");
}
if (ConfigurationManager.AppSettings["SendEmails"] != "N")
{
if (string.IsNullOrEmpty(fromAddress) || string.IsNullOrEmpty(replyToAddress) || string.IsNullOrEmpty(toAddress))
{
LogManager.Instance.AddToLog(LogMessageType.FatalError, "Common.Net", string.Format("EmailManager.SendEmail from={0}, to={1}, replyTo={2}, subject={3}, body={4}, isHtml={5}", fromAddress, toAddress, replyToAddress, subject, body, isHtml));
}
LogManager.Instance.AddToLog(LogMessageType.Information, "Common.Net", string.Format("EmailManager.SendEmail from={0}, to={1}, subject={2}, body={3}, isHtml={4}", fromAddress, toAddress, subject, body, isHtml));
try
{
SmtpClient client = new SmtpClient();
MailMessage msg = new MailMessage(fromAddress, toAddress, subject, body);
msg.ReplyToList.Add(new MailAddress(replyToAddress));
msg.IsBodyHtml = isHtml;
if (attachments != null)
{
for (int i = 0; i < attachments.Length; i++)
{
msg.Attachments.Add(attachments[i]);
}
}
client.Send(msg);
}
catch (Exception ex)
{
LogManager.Instance.AddToLog(ex, "Codentia.Common.Net.EmailManager.SendEmail");
}
}
}
/// <summary>
/// Dispose the current instance
/// </summary>
public void Dispose()
{
lock (_instanceLock)
{
_instance = null;
}
}
private void LogValues(Dictionary<string, string> values)
{
StringBuilder sb = new StringBuilder();
if (values != null)
{
Dictionary<string, string>.Enumerator valueEnum = values.GetEnumerator();
while (valueEnum.MoveNext())
{
sb.AppendFormat("{2}{0}={1}", valueEnum.Current.Key, valueEnum.Current.Value, sb.Length > 0 ? ", " : string.Empty);
}
}
else
{
sb.Append("No values were specified");
}
LogManager.Instance.AddToLog(LogMessageType.Information, "Codentia.Common.Net", sb.ToString());
}
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System;
using System.Diagnostics;
using System.Text;
using i16 = System.Int16;
using u8 = System.Byte;
using u16 = System.UInt16;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2005 May 23
**
** 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 functions used to access the internal hash tables
** of user defined functions and collation sequences.
*************************************************************************
** 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: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the encoding enc of name zName, length nName.
*/
static void callCollNeeded( sqlite3 db, int enc, string zName )
{
Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null );
if ( db.xCollNeeded != null )
{
string zExternal = zName;// sqlite3DbStrDup(db, zName);
if ( zExternal == null )
return;
db.xCollNeeded( db.pCollNeededArg, db, enc, zExternal );
sqlite3DbFree( db, ref zExternal );
}
#if !SQLITE_OMIT_UTF16
if( db.xCollNeeded16!=null ){
string zExternal;
sqlite3_value pTmp = sqlite3ValueNew(db);
sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
if( zExternal!="" ){
db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal);
}
sqlite3ValueFree(ref pTmp);
}
#endif
}
/*
** This routine is called if the collation factory fails to deliver a
** collation function in the best encoding but there may be other versions
** of this collation function (for other text encodings) available. Use one
** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
** possible.
*/
static int synthCollSeq( sqlite3 db, CollSeq pColl )
{
CollSeq pColl2;
string z = pColl.zName;
int i;
byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
for ( i = 0; i < 3; i++ )
{
pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 );
if ( pColl2.xCmp != null )
{
pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
pColl.xDel = null; /* Do not copy the destructor */
return SQLITE_OK;
}
}
return SQLITE_ERROR;
}
/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**
** If it is not NULL, then pColl must point to the database native encoding
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
static CollSeq sqlite3GetCollSeq(
sqlite3 db, /* The database connection */
u8 enc, /* The desired encoding for the collating sequence */
CollSeq pColl, /* Collating sequence with native encoding, or NULL */
string zName /* Collating sequence name */
)
{
CollSeq p;
p = pColl;
if ( p == null )
{
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p == null || p.xCmp == null )
{
/* No collation sequence of this type for this encoding is registered.
** Call the collation factory to see if it can supply us with one.
*/
callCollNeeded( db, enc, zName );
p = sqlite3FindCollSeq( db, enc, zName, 0 );
}
if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 )
{
p = null;
}
Debug.Assert( p == null || p.xCmp != null );
return p;
}
/*
** This routine is called on a collation sequence before it is used to
** check that it is defined. An undefined collation sequence exists when
** a database is loaded that contains references to collation sequences
** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work,
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl )
{
if ( pColl != null )
{
string zName = pColl.zName;
sqlite3 db = pParse.db;
CollSeq p = sqlite3GetCollSeq( db, ENC( db ), pColl, zName );
if ( null == p )
{
sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
pParse.nErr++;
return SQLITE_ERROR;
}
//
//Debug.Assert(p == pColl);
if ( p != pColl ) // Had to lookup appropriate sequence
{
pColl.enc = p.enc;
pColl.pUser = p.pUser;
pColl.type = p.type;
pColl.xCmp = p.xCmp;
pColl.xDel = p.xDel;
}
}
return SQLITE_OK;
}
/*
** Locate and return an entry from the db.aCollSeq hash table. If the entry
** specified by zName and nName is not found and parameter 'create' is
** true, then create a new entry. Otherwise return NULL.
**
** Each pointer stored in the sqlite3.aCollSeq hash table contains an
** array of three CollSeq structures. The first is the collation sequence
** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
**
** Stored immediately after the three collation sequences is a copy of
** the collation sequence name. A pointer to this string is stored in
** each collation sequence structure.
*/
static CollSeq[] findCollSeqEntry(
sqlite3 db, /* Database connection */
string zName, /* Name of the collating sequence */
int create /* Create a new entry if true */
)
{
CollSeq[] pColl;
int nName = sqlite3Strlen30( zName );
pColl = sqlite3HashFind( db.aCollSeq, zName, nName, (CollSeq[])null );
if ( ( null == pColl ) && create != 0 )
{
pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
if ( pColl != null )
{
CollSeq pDel = null;
pColl[0] = new CollSeq();
pColl[0].zName = zName;
pColl[0].enc = SQLITE_UTF8;
pColl[1] = new CollSeq();
pColl[1].zName = zName;
pColl[1].enc = SQLITE_UTF16LE;
pColl[2] = new CollSeq();
pColl[2].zName = zName;
pColl[2].enc = SQLITE_UTF16BE;
//memcpy(pColl[0].zName, zName, nName);
//pColl[0].zName[nName] = 0;
CollSeq[] pDelArray = sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl );
if ( pDelArray != null )
pDel = pDelArray[0];
/* If a malloc() failure occurred in sqlite3HashInsert(), it will
** return the pColl pointer to be deleted (because it wasn't added
** to the hash table).
*/
Debug.Assert( pDel == null || pDel == pColl[0] );
if ( pDel != null )
{
//// db.mallocFailed = 1;
pDel = null; //was sqlite3DbFree(db,ref pDel);
pColl = null;
}
}
}
return pColl;
}
/*
** Parameter zName points to a UTF-8 encoded string nName bytes long.
** Return the CollSeq* pointer for the collation sequence named zName
** for the encoding 'enc' from the database 'db'.
**
** If the entry specified is not found and 'create' is true, then create a
** new entry. Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine. sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
*/
static CollSeq sqlite3FindCollSeq(
sqlite3 db,
u8 enc,
string zName,
u8 create
)
{
CollSeq[] pColl;
if ( zName != null )
{
pColl = findCollSeqEntry( db, zName, create );
}
else
{
pColl = new CollSeq[enc];
pColl[enc - 1] = db.pDfltColl;
}
Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 );
Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE );
if ( pColl != null )
{
enc -= 1; // if (pColl != null) pColl += enc - 1;
return pColl[enc];
}
else
return null;
}
/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
** encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
** requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality( FuncDef p, int nArg, int enc )
{
int match = 0;
if ( p.nArg == -1 || p.nArg == nArg
|| ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) )
)
{
match = 1;
if ( p.nArg == nArg || nArg == -1 )
{
match = 4;
}
if ( enc == p.iPrefEnc )
{
match += 2;
}
else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) ||
( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) )
{
match += 1;
}
}
return match;
}
/*
** Search a FuncDefHash for a function with the given name. Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef functionSearch(
FuncDefHash pHash, /* Hash table to search */
int h, /* Hash of the name */
string zFunc, /* Name of function */
int nFunc /* Number of bytes in zFunc */
)
{
FuncDef p;
for ( p = pHash.a[h]; p != null; p = p.pHash )
{
if ( p.zName.Length == nFunc && p.zName.StartsWith( zFunc, StringComparison.InvariantCultureIgnoreCase ) )
{
return p;
}
}
return null;
}
/*
** Insert a new FuncDef into a FuncDefHash hash table.
*/
static void sqlite3FuncDefInsert(
FuncDefHash pHash, /* The hash table into which to insert */
FuncDef pDef /* The function definition to insert */
)
{
FuncDef pOther;
int nName = sqlite3Strlen30( pDef.zName );
u8 c1 = (u8)pDef.zName[0];
int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a );
pOther = functionSearch( pHash, h, pDef.zName, nName );
if ( pOther != null )
{
Debug.Assert( pOther != pDef && pOther.pNext != pDef );
pDef.pNext = pOther.pNext;
pOther.pNext = pDef;
}
else
{
pDef.pNext = null;
pDef.pHash = pHash.a[h];
pHash.a[h] = pDef;
}
}
/*
** Locate a user function given a name, a number of arguments and a flag
** indicating whether the function prefers UTF-16 over UTF-8. Return a
** pointer to the FuncDef structure that defines that function, or return
** NULL if the function does not exist.
**
** If the createFlag argument is true, then a new (blank) FuncDef
** structure is created and liked into the "db" structure if a
** no matching function previously existed. When createFlag is true
** and the nArg parameter is -1, then only a function that accepts
** any number of arguments will be returned.
**
** If createFlag is false and nArg is -1, then the first valid
** function found is returned. A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
static FuncDef sqlite3FindFunction(
sqlite3 db, /* An open database */
string zName, /* Name of the function. Not null-terminated */
int nName, /* Number of characters in the name */
int nArg, /* Number of arguments. -1 means any number */
u8 enc, /* Preferred text encoding */
u8 createFlag /* Create new entry if true and does not otherwise exist */
)
{
FuncDef p; /* Iterator variable */
FuncDef pBest = null; /* Best match found so far */
int bestScore = 0;
int h; /* Hash value */
Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE );
h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a );
/* First search for a match amongst the application-defined functions.
*/
p = functionSearch( db.aFunc, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
/* If no match is found, search the built-in functions.
**
** If the SQLITE_PreferBuiltin flag is set, then search the built-in
** functions even if a prior app-defined function was found. And give
** priority to built-in functions.
**
** Except, if createFlag is true, that means that we are trying to
** install a new function. Whatever FuncDef structure is returned it will
** have fields overwritten with new information appropriate for the
** new function. But the FuncDefs for built-in functions are read-only.
** So we must not search for built-ins when creating a new function.
*/
if ( 0 == createFlag && ( pBest == null || ( db.flags & SQLITE_PreferBuiltin ) != 0 ) )
{
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
#else
FuncDefHash pHash = sqlite3GlobalFunctions;
#endif
bestScore = 0;
p = functionSearch( pHash, h, zName, nName );
while ( p != null )
{
int score = matchQuality( p, nArg, enc );
if ( score > bestScore )
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
}
/* If the createFlag parameter is true and the search did not reveal an
** exact match for the name, number of arguments and encoding, then add a
** new entry to the hash table and return it.
*/
if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) &&
( pBest = new FuncDef() ) != null )
{ //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
//pBest.zName = (char *)&pBest[1];
pBest.nArg = (i16)nArg;
pBest.iPrefEnc = enc;
pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
//pBest.zName[nName] = 0;
sqlite3FuncDefInsert( db.aFunc, pBest );
}
if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) )
{
return pBest;
}
return null;
}
/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
** pointer itself, it just cleans up subsidiary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
static void sqlite3SchemaClear( Schema p )
{
Hash temp1;
Hash temp2;
HashElem pElem;
Schema pSchema = p;
temp1 = pSchema.tblHash;
temp2 = pSchema.trigHash;
sqlite3HashInit( pSchema.trigHash );
sqlite3HashClear( pSchema.idxHash );
for ( pElem = sqliteHashFirst( temp2 ); pElem != null; pElem = sqliteHashNext( pElem ) )
{
Trigger pTrigger = (Trigger)sqliteHashData( pElem );
sqlite3DeleteTrigger( null, ref pTrigger );
}
sqlite3HashClear( temp2 );
sqlite3HashInit( pSchema.trigHash );
for ( pElem = temp1.first; pElem != null; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
{
Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
sqlite3DeleteTable( null, ref pTab );
}
sqlite3HashClear( temp1 );
sqlite3HashClear( pSchema.fkeyHash );
pSchema.pSeqTab = null;
if ( ( pSchema.flags & DB_SchemaLoaded ) != 0 )
{
pSchema.iGeneration++;
pSchema.flags = (u16)( pSchema.flags & ( ~DB_SchemaLoaded ) );
}
p.Clear();
}
/*
** Find and return the schema associated with a BTree. Create
** a new one if necessary.
*/
static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt )
{
Schema p;
if ( pBt != null )
{
p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaClear );//Schema.Length, sqlite3SchemaFree);
}
else
{
p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
}
if ( p == null )
{
//// db.mallocFailed = 1;
}
else if ( 0 == p.file_format )
{
sqlite3HashInit( p.tblHash );
sqlite3HashInit( p.idxHash );
sqlite3HashInit( p.trigHash );
sqlite3HashInit( p.fkeyHash );
p.enc = SQLITE_UTF8;
}
return p;
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder MSBuild Tasks
// File : BuildHelp.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 10/27/2009
// Note : Copyright 2008-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the MSBuild task used to build help file output using the
// Sandcastle Help File Builder.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.8.0.0 06/27/2008 EFW Created the code
// 1.8.0.1 12/19/2008 EFW Updated to work with MSBuild 3.5 and Team Build
// 1.8.0.2 04/20/2009 EFW Added DumpLogOnFailure property
// 1.8.0.3 07/06/2009 EFW Added support for MS Help Viewer output files
// 1.8.1.3 07/05/2010 JI Updated to use MSBuild 4.0.
// ============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using SandcastleBuilder.Utils.BuildEngine;
using Project = Microsoft.Build.Evaluation.Project;
using Microsoft.Build.Evaluation;
namespace SandcastleBuilder.Utils.MSBuild
{
/// <summary>
/// This task is used to build help file output using the Sandcastle Help
/// File Builder.
/// </summary>
public class BuildHelp : Task
{
#region Private data members
//=====================================================================
private static Regex reParseMessage = new Regex(@"^(\w{2,}):\s*(.*?)" +
@"\s*\W(warning|error)\W\s*(\w+?\d*?):\s*(.*)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
private bool verbose, alwaysLoadProject, isPriorMSBuildVersion,
dumpLogOnFailure;
private BuildStep lastBuildStep;
private SandcastleProject sandcastleProject;
private BuildProcess buildProcess;
private string projectFile, configuration, platform, outDir;
#endregion
#region Task input properties
//=====================================================================
/// <summary>
/// This is used to pass in the project filename
/// </summary>
/// <remarks>Since <see cref="SandcastleProject" /> already wraps the
/// MSBuild project, it seemed redundant to define each and every
/// property on this task and map them to the project properties. As
/// such, this task will attempt to use the executing project to create
/// the Sandcastle project instance. If that fails or
/// <see cref="AlwaysLoadProject" /> is true, this file will be
/// loaded instead. The downside is that property overrides on the
/// command line will be ignored.</remarks>
[Required]
public string ProjectFile
{
get { return projectFile; }
set { projectFile = value; }
}
/// <summary>
/// This is used to pass in the configuration to use for the build
/// </summary>
[Required]
public string Configuration
{
get { return configuration; }
set { configuration = value; }
}
/// <summary>
/// This is used to pass in the platform to use for the build
/// </summary>
[Required]
public string Platform
{
get { return platform; }
set { platform = value; }
}
/// <summary>
/// This is used to specify the output directory containing the build
/// output for solution and project documentation sources when using
/// Team Build.
/// </summary>
/// <value>This property is optional. If not specified, the default
/// output path in project file documentation sources will be used.</value>
public string OutDir
{
get { return outDir; }
set { outDir = value; }
}
/// <summary>
/// This is used to set or get the output logging verbosity flag
/// </summary>
/// <value>This property is optional. If set to false (the default),
/// only build steps are written to the task log. If set to true, all
/// output from the build process is written to the task log.</value>
public bool Verbose
{
get { return verbose; }
set { verbose = value; }
}
/// <summary>
/// This is used to set or get whether the log file is dumped to the
/// task log if the help file project build fails.
/// </summary>
/// <value>This property is optional. If set to false (the default),
/// the log is not dumped if the build fails. If set to true, all
/// output from the build process is written to the task log if the
/// build fails.</value>
public bool DumpLogOnFailure
{
get { return dumpLogOnFailure; }
set { dumpLogOnFailure = value; }
}
/// <summary>
/// This is used to specify whether or not to load the specified
/// <see cref="ProjectFile" /> rather than use the executing project.
/// </summary>
/// <value>This property is optional. If set to false, the default,
/// the executing project is used as the Sandcastle project to build.
/// If set to true, the specified <see cref="ProjectFile" /> is loaded.
/// In such cases, command line property overrides are ignored.</value>
public bool AlwaysLoadProject
{
get { return alwaysLoadProject; }
set { alwaysLoadProject = value; }
}
#endregion
#region Task output properties
//=====================================================================
/// <summary>
/// This is used to return a list of the HTML Help 1 (CHM) files that
/// resulted from the build.
/// </summary>
[Output]
public ITaskItem[] Help1Files
{
get
{
List<ITaskItem> files = new List<ITaskItem>();
if(buildProcess != null && lastBuildStep == BuildStep.Completed)
foreach(string file in buildProcess.Help1Files)
files.Add(new TaskItem(file));
return files.ToArray();
}
}
/// <summary>
/// This is used to return a list of the MS Help 2 (HxS) files that
/// resulted from the build.
/// </summary>
[Output]
public ITaskItem[] Help2Files
{
get
{
List<ITaskItem> files = new List<ITaskItem>();
if(buildProcess != null && lastBuildStep == BuildStep.Completed)
foreach(string file in buildProcess.Help2Files)
files.Add(new TaskItem(file));
return files.ToArray();
}
}
/// <summary>
/// This is used to return a list of the MS Help Viewer (MSHC) files
/// that resulted from the build.
/// </summary>
[Output]
public ITaskItem[] HelpViewerFiles
{
get
{
List<ITaskItem> files = new List<ITaskItem>();
if(buildProcess != null && lastBuildStep == BuildStep.Completed)
foreach(string file in buildProcess.HelpViewerFiles)
files.Add(new TaskItem(file));
return files.ToArray();
}
}
/// <summary>
/// This is used to return a list of the website files that resulted
/// from the build.
/// </summary>
[Output]
public ITaskItem[] WebsiteFiles
{
get
{
List<ITaskItem> files = new List<ITaskItem>();
if(buildProcess != null && lastBuildStep == BuildStep.Completed)
foreach(string file in buildProcess.WebsiteFiles)
files.Add(new TaskItem(file));
return files.ToArray();
}
}
/// <summary>
/// This is used to return a list of all files that resulted from the
/// build (all help formats).
/// </summary>
[Output]
public ITaskItem[] AllHelpFiles
{
get
{
return this.Help1Files.Concat(
this.Help2Files.Concat(
this.HelpViewerFiles.Concat(
this.WebsiteFiles))).ToArray();
}
}
#endregion
#region Execute method
//=====================================================================
/// <summary>
/// This is used to execute the task and perform the build
/// </summary>
/// <returns>True on success or false on failure.</returns>
public override bool Execute()
{
Project msBuildProject = null;
string line;
try
{
if(!alwaysLoadProject)
{
// Use the current project if possible. This is preferable
// as we can make use of command line property overrides
// and any other user-defined properties.
msBuildProject = this.GetCurrentProject();
if(msBuildProject == null)
{
// We can't use a prior MSBuild version
if(isPriorMSBuildVersion)
{
Log.LogError(null, "BHT0004", "BHT0004", "SHFB",
0, 0, 0, 0, "An older MSBuild version is " +
"being used. Unable to build help project.");
return false;
}
Log.LogWarning(null, "BHT0001", "BHT0001", "SHFB",
0, 0, 0, 0, "Unable to get executing project: " +
"Unable to obtain internal reference. The " +
"specified project will be loaded but command " +
"line property overrides will be ignored.");
}
}
}
catch(Exception ex)
{
// Ignore exceptions but issue a warning and fall back to using
// the passed project filename instead.
Log.LogWarning(null, "BHT0001", "BHT0001", "SHFB", 0, 0, 0, 0,
"Unable to get executing project: {0}. The specified " +
"project will be loaded but command line property " +
"overrides will be ignored.", ex.Message);
}
if(msBuildProject == null)
{
if (!File.Exists(projectFile))
throw new BuilderException("BHT0003", "The specified " +
"project file does not exist: " + projectFile);
var globalProperties = new Dictionary<string, string>();
globalProperties.Add(ProjectElement.Configuration, configuration);
globalProperties.Add(ProjectElement.Platform, platform);
// Override the OutDir property if defined for Team Build
if (!String.IsNullOrEmpty(outDir))
globalProperties.Add(ProjectElement.OutDir, outDir);
// Create the project and set the configuration and platform
// options.
msBuildProject = new Project(
projectFile,
globalProperties,
null,
ProjectCollection.GlobalProjectCollection);
}
// Load the MSBuild project and associate it with a SHFB
// project instance.
sandcastleProject = new SandcastleProject(msBuildProject, true);
try
{
buildProcess = new BuildProcess(sandcastleProject);
buildProcess.BuildStepChanged +=
new EventHandler<BuildProgressEventArgs>(
buildProcess_BuildStepChanged);
buildProcess.BuildProgress +=
new EventHandler<BuildProgressEventArgs>(
buildProcess_BuildProgress);
// Since this is an MSBuild task, we'll run it directly rather
// than in a background thread.
Log.LogMessage("Building {0}", msBuildProject.FullPath);
buildProcess.Build();
}
catch(Exception ex)
{
Log.LogError(null, "BHT0002", "BHT0002", "SHFB", 0, 0, 0, 0,
"Unable to build project '{0}': {1}",
msBuildProject.FullPath, ex);
}
if(dumpLogOnFailure && lastBuildStep == BuildStep.Failed)
using(StreamReader sr = new StreamReader(buildProcess.LogFilename))
{
Log.LogMessage(MessageImportance.High, "Log Content:");
do
{
line = sr.ReadLine();
// Don't output the XML elements, just the text
if(line != null && (line.Trim().Length == 0 ||
line.Trim()[0] != '<'))
Log.LogMessage(MessageImportance.High, line);
} while(line != null);
}
return (lastBuildStep == BuildStep.Completed);
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// This is used to obtain a reference to the project that is currently
/// being built.
/// </summary>
/// <returns>The current project if possible or null if it could not
/// be obtained.</returns>
/// <remarks>The build engine provides no way to get a reference to
/// the current project. As such, we have to resort to reflection to
/// get it. This was much easier under .NET 2.0 as the project was a
/// project of the BuildEngine object. The .NET 3.5 build engine hides
/// it way down in the object hierarchy. We could build the project
/// without it but we lose the ability to use command line overrides
/// and changes to user-defined properties.</remarks>
private Project GetCurrentProject()
{
Type type;
FieldInfo fieldInfo;
object obj;
if(base.BuildEngine == null)
return null;
// From the EngineProxy ...
type = base.BuildEngine.GetType();
fieldInfo = type.GetField("parentModule",
BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo == null)
{
// If null, it's probably running under MSBuild 2.0
fieldInfo = type.GetField("project",
BindingFlags.NonPublic | BindingFlags.Instance);
// Unfortunately, we can't cast a copy of the object from
// a prior MSBuild version to this version's Project type
// so it will fail to build.
if(fieldInfo != null)
isPriorMSBuildVersion = true;
return null;
}
obj = fieldInfo.GetValue(base.BuildEngine);
if(obj == null)
return null;
// ... we go to the TaskExecutionModule ...
type = obj.GetType();
fieldInfo = type.GetField("engineCallback",
BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo == null)
return null;
obj = fieldInfo.GetValue(obj);
if(obj == null)
return null;
// ... then into the EngineCallBack ...
type = obj.GetType();
fieldInfo = type.GetField("parentEngine",
BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo == null)
return null;
obj = fieldInfo.GetValue(obj);
if(obj == null)
return null;
// ... and finally we arrive at the Engine object ...
type = obj.GetType();
fieldInfo = type.GetField("cacheOfBuildingProjects",
BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo == null)
return null;
obj = fieldInfo.GetValue(obj);
if(obj == null)
return null;
// ... which has the cache of bulding projects ...
type = obj.GetType();
fieldInfo = type.GetField("projects",
BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo == null)
return null;
obj = fieldInfo.GetValue(obj);
if(obj == null)
return null;
// ... which contains the hash table we need containing the
// actual project reference.
foreach(DictionaryEntry entry in (Hashtable)obj)
foreach(Project project in (ArrayList)entry.Value)
if (project.FullPath == projectFile)
return project;
return null;
}
/// <summary>
/// This is called by the build process thread to update the
/// application with the current build step.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void buildProcess_BuildStepChanged(object sender,
BuildProgressEventArgs e)
{
string outputPath;
if(!verbose)
Log.LogMessage(e.BuildStep.ToString());
if(e.HasCompleted)
{
// If successful, report the location of the help file/website
if(e.BuildStep == BuildStep.Completed)
{
outputPath = buildProcess.OutputFolder +
sandcastleProject.HtmlHelpName;
switch(sandcastleProject.HelpFileFormat)
{
case HelpFileFormat.HtmlHelp1:
outputPath += ".chm";
break;
case HelpFileFormat.MSHelp2:
outputPath += ".hxs";
break;
case HelpFileFormat.MSHelpViewer:
outputPath += ".mshc";
break;
default:
break;
}
// Report single file or multi-format output location
if(File.Exists(outputPath))
Log.LogMessage("The help file is located at: {0}",
outputPath);
else
Log.LogMessage("The help output is located at: {0}",
buildProcess.OutputFolder);
}
if(File.Exists(buildProcess.LogFilename))
Log.LogMessage("Build details can be found in {0}",
buildProcess.LogFilename);
}
lastBuildStep = e.BuildStep;
}
/// <summary>
/// This is called by the build process thread to update the
/// task with information about progress.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void buildProcess_BuildProgress(object sender,
BuildProgressEventArgs e)
{
Match m = reParseMessage.Match(e.Message);
// Always log errors and warnings
if(m.Success)
{
if(String.Compare(m.Groups[3].Value, "warning",
StringComparison.OrdinalIgnoreCase) == 0)
Log.LogWarning(null, m.Groups[4].Value, m.Groups[4].Value,
m.Groups[1].Value, 0, 0, 0, 0,
m.Groups[5].Value.Trim());
else
if(String.Compare(m.Groups[3].Value, "error",
StringComparison.OrdinalIgnoreCase) == 0)
Log.LogError(null, m.Groups[4].Value, m.Groups[4].Value,
m.Groups[1].Value, 0, 0, 0, 0,
m.Groups[5].Value.Trim());
else
Log.LogMessage(e.Message);
}
else
if(verbose)
Log.LogMessage(e.Message);
}
#endregion
}
}
| |
namespace Appleseed.Services.Knowledge.Model.Illumination.Services.AlchemyIlluminator
{
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Configuration;
public class AlchemyAPI
{
private string _apiKey;
private string _requestUri;
public AlchemyAPI()
{
this._requestUri = "https://gateway-a.watsonplatform.net/calls/info/GetAPIKeyInfo?apikey=";
}
public void SetAPIHost(string apiHost)
{
if (apiHost.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Error setting API host.");
throw ex;
}
this._requestUri = "http://" + apiHost + ".alchemyapi.com/calls/";
}
public void SetAPIKey(string apiKey)
{
this._apiKey = apiKey;
if (this._apiKey.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException("Error setting API key.");
throw ex;
}
}
public void LoadAPIKey(string filename)
{
StreamReader reader;
reader = File.OpenText(filename);
string line = reader.ReadLine();
reader.Close();
this._apiKey = line.Trim();
if (this._apiKey.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException("Error loading API key.");
throw ex;
}
}
public string URLGetAuthor(string url)
{
this.CheckURL(url);
return this.URLGetAuthor(url, new AlchemyAPI_BaseParams());
}
public string URLGetAuthor(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetAuthor", "url", parameters);
}
public string HTMLGetAuthor(string html,string url)
{
this.CheckHTML(html, url);
return this.HTMLGetAuthor(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetAuthor(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetAuthor", "html", parameters);
}
public string URLGetRankedNamedEntities(string url)
{
this.CheckURL(url);
return this.URLGetRankedNamedEntities(url, new AlchemyAPI_EntityParams());
}
public string URLGetRankedNamedEntities(string url, AlchemyAPI_EntityParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetRankedNamedEntities", "url", parameters);
}
public string HTMLGetRankedNamedEntities(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetRankedNamedEntities(html, url, new AlchemyAPI_EntityParams());
}
public string HTMLGetRankedNamedEntities(string html, string url, AlchemyAPI_EntityParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetRankedNamedEntities", "html", parameters);
}
public string TextGetRankedNamedEntities(string text)
{
this.CheckText(text);
return this.TextGetRankedNamedEntities(text,new AlchemyAPI_EntityParams());
}
public string TextGetRankedNamedEntities(string text, AlchemyAPI_EntityParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetRankedNamedEntities", "text", parameters);
}
public string URLGetRankedConcepts(string url)
{
this.CheckURL(url);
return this.URLGetRankedConcepts(url, new AlchemyAPI_ConceptParams());
}
public string URLGetRankedConcepts(string url, AlchemyAPI_ConceptParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetRankedConcepts", "url", parameters);
}
public string HTMLGetRankedConcepts(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetRankedConcepts(html, url, new AlchemyAPI_ConceptParams());
}
public string HTMLGetRankedConcepts(string html, string url, AlchemyAPI_ConceptParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetRankedConcepts", "html", parameters);
}
public string TextGetRankedConcepts(string text)
{
this.CheckText(text);
return this.TextGetRankedConcepts(text,new AlchemyAPI_ConceptParams());
}
public string TextGetRankedConcepts(string text, AlchemyAPI_ConceptParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetRankedConcepts", "text", parameters);
}
public string URLGetRankedKeywords(string url)
{
this.CheckURL(url);
return this.URLGetRankedKeywords(url, new AlchemyAPI_KeywordParams());
}
public string URLGetRankedKeywords(string url, AlchemyAPI_KeywordParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetRankedKeywords", "url", parameters);
}
public string HTMLGetRankedKeywords(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetRankedKeywords(html, url, new AlchemyAPI_KeywordParams());
}
public string HTMLGetRankedKeywords(string html, string url, AlchemyAPI_KeywordParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetRankedKeywords", "html", parameters);
}
public string TextGetRankedKeywords(string text)
{
this.CheckText(text);
return this.TextGetRankedKeywords(text,new AlchemyAPI_KeywordParams());
}
public string TextGetRankedKeywords(string text, AlchemyAPI_KeywordParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetRankedKeywords", "text", parameters);
}
public string URLGetLanguage(string url)
{
this.CheckURL(url);
return this.URLGetLanguage(url,new AlchemyAPI_LanguageParams());
}
public string URLGetLanguage(string url, AlchemyAPI_LanguageParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetLanguage", "url", parameters);
}
public string HTMLGetLanguage(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetLanguage(html,url,new AlchemyAPI_LanguageParams());
}
public string HTMLGetLanguage(string html, string url, AlchemyAPI_LanguageParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetLanguage", "html", parameters);
}
public string TextGetLanguage(string text)
{
this.CheckText(text);
return this.TextGetLanguage(text, new AlchemyAPI_LanguageParams());
}
public string TextGetLanguage(string text, AlchemyAPI_LanguageParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetLanguage", "text", parameters);
}
public string URLGetCategory(string url)
{
this.CheckURL(url);
return this.URLGetCategory(url, new AlchemyAPI_CategoryParams() );
}
public string URLGetCategory(string url, AlchemyAPI_CategoryParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetCategory", "url", parameters);
}
public string HTMLGetCategory(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetCategory(html, url, new AlchemyAPI_CategoryParams());
}
public string HTMLGetCategory(string html, string url, AlchemyAPI_CategoryParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetCategory", "html", parameters);
}
public string TextGetCategory(string text)
{
this.CheckText(text);
return this.TextGetCategory(text, new AlchemyAPI_CategoryParams());
}
public string TextGetCategory(string text, AlchemyAPI_CategoryParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetCategory", "text", parameters);
}
public string URLGetText(string url)
{
this.CheckURL(url);
return this.URLGetText(url, new AlchemyAPI_TextParams());
}
public string URLGetText(string url, AlchemyAPI_TextParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetText", "url", parameters);
}
public string HTMLGetText(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetText(html,url, new AlchemyAPI_TextParams());
}
public string HTMLGetText(string html, string url,AlchemyAPI_TextParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetText", "html", parameters);
}
public string URLGetRawText(string url)
{
this.CheckURL(url);
return this.URLGetRawText(url, new AlchemyAPI_BaseParams());
}
public string URLGetRawText(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetRawText", "url", parameters);
}
public string HTMLGetRawText(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetRawText(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetRawText(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetRawText", "html", parameters);
}
public string URLGetTitle(string url)
{
this.CheckURL(url);
return this.URLGetTitle(url, new AlchemyAPI_BaseParams());
}
public string URLGetTitle(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetTitle", "url", parameters);
}
public string HTMLGetTitle(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetTitle(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetTitle(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetTitle", "html", parameters);
}
public string URLGetFeedLinks(string url)
{
this.CheckURL(url);
return this.URLGetFeedLinks(url, new AlchemyAPI_BaseParams());
}
public string URLGetFeedLinks(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetFeedLinks", "url", parameters);
}
public string HTMLGetFeedLinks(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetFeedLinks(html,url, new AlchemyAPI_BaseParams());
}
public string HTMLGetFeedLinks(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetFeedLinks", "html", parameters);
}
public string URLGetMicroformats(string url)
{
this.CheckURL(url);
return this.URLGetMicroformats(url, new AlchemyAPI_BaseParams());
}
public string URLGetMicroformats(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetMicroformatData", "url", parameters);
}
public string HTMLGetMicroformats(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetMicroformats(html,url, new AlchemyAPI_BaseParams());
}
public string HTMLGetMicroformats(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetMicroformatData", "html", parameters);
}
public string URLGetConstraintQuery(string url, string query)
{
this.CheckURL(url);
if (query.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams();
cqParams.setCQuery(query);
return this.URLGetConstraintQuery(url,cqParams);
}
public string URLGetConstraintQuery(string url, AlchemyAPI_ConstraintQueryParams parameters)
{
this.CheckURL(url);
if (parameters.getCQuery().Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
parameters.setUrl(url);
return this.POST("URLGetConstraintQuery", "url", parameters);
}
public string HTMLGetConstraintQuery(string html, string url, string query)
{
this.CheckHTML(html, url);
if (query.Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams();
cqParams.setCQuery(query);
return this.HTMLGetConstraintQuery(html, url, cqParams);
}
public string HTMLGetConstraintQuery(string html, string url, AlchemyAPI_ConstraintQueryParams parameters)
{
this.CheckHTML(html, url);
if (parameters.getCQuery().Length < 2)
{
System.ApplicationException ex =
new System.ApplicationException("Invalid constraint query specified.");
throw ex;
}
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetConstraintQuery", "html", parameters);
}
public string URLGetTextSentiment(string url)
{
this.CheckURL(url);
return this.URLGetTextSentiment(url, new AlchemyAPI_BaseParams());
}
public string URLGetTextSentiment(string url, AlchemyAPI_BaseParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetTextSentiment", "url", parameters);
}
public string HTMLGetTextSentiment(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetTextSentiment(html, url, new AlchemyAPI_BaseParams());
}
public string HTMLGetTextSentiment(string html, string url, AlchemyAPI_BaseParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetTextSentiment", "html", parameters);
}
public string TextGetTextSentiment(string text)
{
this.CheckText(text);
return this.TextGetTextSentiment(text,new AlchemyAPI_BaseParams());
}
public string TextGetTextSentiment(string text, AlchemyAPI_BaseParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetTextSentiment", "text", parameters);
}
//------
public string URLGetTargetedSentiment(string url, string target)
{
this.CheckURL(url);
this.CheckText(target);
return this.URLGetTargetedSentiment(url, target, new AlchemyAPI_TargetedSentimentParams());
}
public string URLGetTargetedSentiment(string url, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
this.CheckURL(url);
this.CheckText(target);
parameters.setUrl(url);
parameters.setTarget(target);
return this.GET("URLGetTargetedSentiment", "url", parameters);
}
public string HTMLGetTargetedSentiment(string html, string url, string target)
{
this.CheckHTML(html, url);
this.CheckText(target);
return this.HTMLGetTargetedSentiment(html, url, target, new AlchemyAPI_TargetedSentimentParams());
}
public string HTMLGetTargetedSentiment(string html, string url, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
this.CheckHTML(html, url);
this.CheckText(target);
parameters.setHtml(html);
parameters.setUrl(url);
parameters.setTarget(target);
return this.POST("HTMLGetTargetedSentiment", "html", parameters);
}
public string TextGetTargetedSentiment(string text, string target)
{
this.CheckText(text);
this.CheckText(target);
return this.TextGetTargetedSentiment(text, target, new AlchemyAPI_TargetedSentimentParams());
}
public string TextGetTargetedSentiment(string text, string target, AlchemyAPI_TargetedSentimentParams parameters)
{
this.CheckText(text);
this.CheckText(target);
parameters.setText(text);
parameters.setTarget(target);
return this.POST("TextGetTargetedSentiment", "text", parameters);
}
//------
public string URLGetRelations(string url)
{
this.CheckURL(url);
return this.URLGetRelations(url, new AlchemyAPI_RelationParams());
}
public string URLGetRelations(string url, AlchemyAPI_RelationParams parameters)
{
this.CheckURL(url);
parameters.setUrl(url);
return this.GET("URLGetRelations", "url", parameters);
}
public string HTMLGetRelations(string html, string url)
{
this.CheckHTML(html, url);
return this.HTMLGetRelations(html, url, new AlchemyAPI_RelationParams());
}
public string HTMLGetRelations(string html, string url, AlchemyAPI_RelationParams parameters)
{
this.CheckHTML(html, url);
parameters.setHtml(html);
parameters.setUrl(url);
return this.POST("HTMLGetRelations", "html", parameters);
}
public string TextGetRelations(string text)
{
this.CheckText(text);
return this.TextGetRelations(text,new AlchemyAPI_RelationParams());
}
public string TextGetRelations(string text, AlchemyAPI_RelationParams parameters)
{
this.CheckText(text);
parameters.setText(text);
return this.POST("TextGetRelations", "text", parameters);
}
private void CheckHTML(string html, string url)
{
if (html.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException("Enter a HTML document to analyze.");
throw ex;
}
if (url.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException("Enter a web URL to analyze.");
throw ex;
}
}
private void CheckText(string text)
{
if (text.Length < 5)
{
System.ApplicationException ex =
new System.ApplicationException("Enter some text to analyze.");
throw ex;
}
}
private void CheckURL(string url)
{
if (url.Length < 10)
{
System.ApplicationException ex =
new System.ApplicationException("Enter a web URL to analyze.");
throw ex;
}
}
private string GET(string callName, string callPrefix, AlchemyAPI_BaseParams parameters)
{ // callMethod, callPrefix, ... params
StringBuilder uri = new StringBuilder();
uri.Append(this._requestUri).Append(callPrefix).Append("/").Append(callName);
uri.Append("?apikey=").Append(this._apiKey).Append(parameters.getParameterString());
parameters.resetBaseParams();
Uri address = new Uri(uri.ToString());
HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest;
wreq.Proxy = GlobalProxySelection.GetEmptyWebProxy();
wreq.Method = "GET";
return this.DoRequest(wreq, parameters.getOutputMode());
}
private string POST(string callName, string callPrefix, AlchemyAPI_BaseParams parameters)
{ // callMethod, callPrefix, ... params
Uri address = new Uri(this._requestUri + callPrefix + "/" + callName);
HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest;
wreq.Proxy = GlobalProxySelection.GetEmptyWebProxy();
wreq.Method = "POST";
wreq.ContentType = "application/x-www-form-urlencoded";
StringBuilder d = new StringBuilder();
d.Append("apikey=").Append(this._apiKey).Append(parameters.getParameterString());
parameters.resetBaseParams();
byte[] bd = UTF8Encoding.UTF8.GetBytes(d.ToString());
wreq.ContentLength = bd.Length;
using (Stream ps = wreq.GetRequestStream()) { ps.Write(bd, 0, bd.Length); }
return this.DoRequest(wreq, parameters.getOutputMode());
}
private string DoRequest(HttpWebRequest wreq, AlchemyAPI_BaseParams.OutputMode outputMode)
{
using (HttpWebResponse wres = wreq.GetResponse() as HttpWebResponse)
{
StreamReader r = new StreamReader(wres.GetResponseStream());
string xml = r.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlElement root = xmlDoc.DocumentElement;
if (AlchemyAPI_BaseParams.OutputMode.XML == outputMode)
{
XmlNode status = root.SelectSingleNode("/results/status");
if (status.InnerText != "OK")
{
var statusInfo = root.SelectSingleNode("/results/statusInfo");
throw new System.ApplicationException("Error making API call: " + statusInfo.InnerText);
}
}
else if (AlchemyAPI_BaseParams.OutputMode.RDF == outputMode)
{
XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
nm.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
nm.AddNamespace("aapi", "http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#");
XmlNode status = root.SelectSingleNode("/rdf:RDF/rdf:Description/aapi:ResultStatus",nm);
if (status.InnerText != "OK")
{
var statusInfo = root.SelectSingleNode("/results/statusInfo");
throw new System.ApplicationException("Error making API call: " + statusInfo.InnerText);
}
}
return xml;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type long with 2 columns and 4 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct lmat2x4 : IReadOnlyList<long>, IEquatable<lmat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public long m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public long m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public long m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
[DataMember]
public long m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public long m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public long m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public long m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
[DataMember]
public long m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public lmat2x4(long m00, long m01, long m02, long m03, long m10, long m11, long m12, long m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a lmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a lmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a lmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a lmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lvec2 c0, lvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0;
this.m03 = 0;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lvec3 c0, lvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = 0;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = 0;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public lmat2x4(lvec4 c0, lvec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public long[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public long[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public lvec4 Column0
{
get
{
return new lvec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public lvec4 Column1
{
get
{
return new lvec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public lvec2 Row0
{
get
{
return new lvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public lvec2 Row1
{
get
{
return new lvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public lvec2 Row2
{
get
{
return new lvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public lvec2 Row3
{
get
{
return new lvec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static lmat2x4 Zero { get; } = new lmat2x4(0, 0, 0, 0, 0, 0, 0, 0);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static lmat2x4 Ones { get; } = new lmat2x4(1, 1, 1, 1, 1, 1, 1, 1);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static lmat2x4 Identity { get; } = new lmat2x4(1, 0, 0, 0, 0, 1, 0, 0);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static lmat2x4 AllMaxValue { get; } = new lmat2x4(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static lmat2x4 DiagonalMaxValue { get; } = new lmat2x4(long.MaxValue, 0, 0, 0, 0, long.MaxValue, 0, 0);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static lmat2x4 AllMinValue { get; } = new lmat2x4(long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static lmat2x4 DiagonalMinValue { get; } = new lmat2x4(long.MinValue, 0, 0, 0, 0, long.MinValue, 0, 0);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<long> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public long this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public long this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(lmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is lmat2x4 && Equals((lmat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(lmat2x4 lhs, lmat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(lmat2x4 lhs, lmat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public lmat4x2 Transposed => new lmat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public long MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public long MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public double Length => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public double LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public long Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public double Norm => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public double Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public double Norm2 => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public long NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2x4 * lmat2 -> lmat2x4.
/// </summary>
public static lmat2x4 operator*(lmat2x4 lhs, lmat2 rhs) => new lmat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2x4 * lmat3x2 -> lmat3x4.
/// </summary>
public static lmat3x4 operator*(lmat2x4 lhs, lmat3x2 rhs) => new lmat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication lmat2x4 * lmat4x2 -> lmat4.
/// </summary>
public static lmat4 operator*(lmat2x4 lhs, lmat4x2 rhs) => new lmat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static lvec4 operator*(lmat2x4 m, lvec2 v) => new lvec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static lmat2x4 CompMul(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static lmat2x4 CompDiv(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static lmat2x4 CompAdd(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static lmat2x4 CompSub(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static lmat2x4 operator+(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static lmat2x4 operator+(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static lmat2x4 operator+(long lhs, lmat2x4 rhs) => new lmat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static lmat2x4 operator-(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static lmat2x4 operator-(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static lmat2x4 operator-(long lhs, lmat2x4 rhs) => new lmat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static lmat2x4 operator/(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static lmat2x4 operator/(long lhs, lmat2x4 rhs) => new lmat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static lmat2x4 operator*(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static lmat2x4 operator*(long lhs, lmat2x4 rhs) => new lmat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
/// <summary>
/// Executes a component-wise % (modulo).
/// </summary>
public static lmat2x4 operator%(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m03 % rhs.m03, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12, lhs.m13 % rhs.m13);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static lmat2x4 operator%(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m03 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs, lhs.m13 % rhs);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static lmat2x4 operator%(long lhs, lmat2x4 rhs) => new lmat2x4(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m03, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12, lhs % rhs.m13);
/// <summary>
/// Executes a component-wise ^ (xor).
/// </summary>
public static lmat2x4 operator^(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m03 ^ rhs.m03, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12, lhs.m13 ^ rhs.m13);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static lmat2x4 operator^(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m03 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs, lhs.m13 ^ rhs);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static lmat2x4 operator^(long lhs, lmat2x4 rhs) => new lmat2x4(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m03, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12, lhs ^ rhs.m13);
/// <summary>
/// Executes a component-wise | (bitwise-or).
/// </summary>
public static lmat2x4 operator|(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m03 | rhs.m03, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12, lhs.m13 | rhs.m13);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static lmat2x4 operator|(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m03 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs, lhs.m13 | rhs);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static lmat2x4 operator|(long lhs, lmat2x4 rhs) => new lmat2x4(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m03, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12, lhs | rhs.m13);
/// <summary>
/// Executes a component-wise & (bitwise-and).
/// </summary>
public static lmat2x4 operator&(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m03 & rhs.m03, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12, lhs.m13 & rhs.m13);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static lmat2x4 operator&(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m03 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs, lhs.m13 & rhs);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static lmat2x4 operator&(long lhs, lmat2x4 rhs) => new lmat2x4(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m03, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12, lhs & rhs.m13);
/// <summary>
/// Executes a component-wise left-shift with a scalar.
/// </summary>
public static lmat2x4 operator<<(lmat2x4 lhs, int rhs) => new lmat2x4(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m03 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs, lhs.m13 << rhs);
/// <summary>
/// Executes a component-wise right-shift with a scalar.
/// </summary>
public static lmat2x4 operator>>(lmat2x4 lhs, int rhs) => new lmat2x4(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m03 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs, lhs.m13 >> rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x4 operator<(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(long lhs, lmat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x4 operator<=(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(long lhs, lmat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x4 operator>(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(long lhs, lmat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x4 operator>=(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(long lhs, lmat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
#region Enums
public enum CCClipMode
{
None, // No clipping of children
Bounds, // Clipping with a ScissorRect
BoundsWithRenderTarget // Clipping with the ScissorRect and in a RenderTarget
}
// Conform to XNA 4.0
public enum CCDepthFormat
{
None = Microsoft.Xna.Framework.Graphics.DepthFormat.None,
Depth16 = Microsoft.Xna.Framework.Graphics.DepthFormat.Depth16,
Depth24 = Microsoft.Xna.Framework.Graphics.DepthFormat.Depth24,
Depth24Stencil8 = Microsoft.Xna.Framework.Graphics.DepthFormat.Depth24Stencil8,
}
public enum CCBufferUsage
{
None,
WriteOnly
}
#endregion Enums
internal class CCDrawManager
{
const int DefaultQuadBufferSize = 1024 * 4;
const int NumOfIndicesPerQuad = 6;
const int NumOfVerticesPerQuad = 4;
const int MaxNumQuads = 200;
const int MaxNumQuadVertices = NumOfVerticesPerQuad * MaxNumQuads;
const int MaxNumQuadIndices = NumOfIndicesPerQuad * MaxNumQuads;
bool needReinitResources;
bool textureEnabled;
bool vertexColorEnabled;
bool worldMatrixChanged;
bool projectionMatrixChanged;
bool viewMatrixChanged;
bool textureChanged;
bool effectChanged;
bool depthTest;
bool allowNonPower2Textures;
bool hasStencilBuffer;
bool maskOnceLog = false;
int stackIndex;
int maskLayer = -1;
CCBlendFunc currBlend;
CCDepthFormat platformDepthFormat;
CCQuadVertexBuffer quadsBuffer;
CCIndexBuffer<short> quadsIndexBuffer;
CCV3F_C4B_T2F[] quadsVertices;
short[] quadsIndices;
readonly Matrix[] matrixStack;
Matrix worldMatrix;
Matrix viewMatrix;
Matrix projectionMatrix;
Matrix matrix;
Matrix tmpMatrix;
Matrix transform;
readonly Dictionary<CCBlendFunc, BlendState> blendStates;
DepthStencilState depthEnableStencilState;
DepthStencilState depthDisableStencilState;
DepthStencilState[] maskSavedStencilStates = new DepthStencilState[8];
MaskState[] maskStates = new MaskState[8];
MaskDepthStencilStateCacheEntry[] maskStatesCache = new MaskDepthStencilStateCacheEntry[8];
readonly Stack<Effect> effectStack;
BasicEffect defaultEffect;
Effect currentEffect;
RenderTarget2D currentRenderTarget;
RenderTarget2D previousRenderTarget;
Texture2D currentTexture;
GraphicsDevice graphicsDevice;
List<RasterizerState> rasterizerStatesCache;
#region Properties
public static CCDrawManager SharedDrawManager { get; set; }
public SpriteBatch SpriteBatch { get; set; }
internal ulong DrawCount { get; set; }
internal ulong DrawPrimitivesCount { get; set; }
internal BasicEffect PrimitiveEffect { get; private set; }
internal AlphaTestEffect AlphaTestEffect { get; private set; }
internal CCRawList<CCV3F_C4B_T2F> TmpVertices { get; private set; }
internal CCRenderer Renderer { get; private set; }
public bool VertexColorEnabled
{
get { return vertexColorEnabled; }
set
{
if (vertexColorEnabled != value)
{
vertexColorEnabled = value;
textureChanged = true;
}
}
}
public bool TextureEnabled
{
get { return textureEnabled; }
set
{
if (textureEnabled != value)
{
textureEnabled = value;
textureChanged = true;
}
}
}
public bool ScissorRectEnabled
{
get { return graphicsDevice.RasterizerState.ScissorTestEnable; }
set
{
if (graphicsDevice.RasterizerState.ScissorTestEnable != value)
{
graphicsDevice.RasterizerState = GetScissorRasterizerState(value);
}
}
}
public bool DepthTest
{
get { return depthTest; }
set
{
depthTest = value;
// NOTE: This must be disabled when primitives are drawing, e.g. lines, polylines, etc.
graphicsDevice.DepthStencilState = value ? depthEnableStencilState : depthDisableStencilState;
}
}
internal BlendState BlendState
{
get { return graphicsDevice.BlendState; }
set
{
graphicsDevice.BlendState = value;
currBlend.Source = -1;
currBlend.Destination = -1;
}
}
public DepthStencilState DepthStencilState
{
get { return graphicsDevice.DepthStencilState; }
set { graphicsDevice.DepthStencilState = value; }
}
internal CCRect ScissorRectInPixels
{
get { return new CCRect(graphicsDevice.ScissorRectangle); }
set
{
graphicsDevice.ScissorRectangle
= new Rectangle ((int)value.Origin.X, (int)value.Origin.Y, (int)value.Size.Width, (int)value.Size.Height);
}
}
internal Viewport Viewport
{
get { return graphicsDevice.Viewport; }
set
{
graphicsDevice.Viewport = value;
}
}
internal Matrix ViewMatrix
{
get { return viewMatrix; }
set
{
viewMatrix = value;
viewMatrixChanged = true;
}
}
internal Matrix ProjectionMatrix
{
get { return projectionMatrix; }
set
{
projectionMatrix = value;
projectionMatrixChanged = true;
}
}
internal Matrix WorldMatrix
{
get { return matrix; }
set
{
matrix = worldMatrix = value;
worldMatrixChanged = true;
}
}
internal GraphicsDevice XnaGraphicsDevice
{
get { return graphicsDevice; }
}
internal RenderTarget2D CurrentRenderTarget
{
get { return currentRenderTarget; }
set
{
previousRenderTarget = currentRenderTarget;
currentRenderTarget = value;
if (graphicsDevice != null && graphicsDevice.GraphicsDeviceStatus == GraphicsDeviceStatus.Normal)
{
graphicsDevice.SetRenderTarget(currentRenderTarget);
}
}
}
#endregion Properties
#region Initialization
internal CCDrawManager(GraphicsDevice device)
{
Renderer = new CCRenderer(this);
depthTest = true;
allowNonPower2Textures = true;
hasStencilBuffer = true;
currBlend = CCBlendFunc.AlphaBlend;
platformDepthFormat = CCDepthFormat.Depth24;
transform = Matrix.Identity;
TmpVertices = new CCRawList<CCV3F_C4B_T2F>();
matrixStack = new Matrix[100];
blendStates = new Dictionary<CCBlendFunc, BlendState>();
effectStack = new Stack<Effect>();
InitializeRawQuadBuffers();
rasterizerStatesCache = new List<RasterizerState>();
hasStencilBuffer = true;
graphicsDevice = device;
InitializeGraphicsDevice();
}
void InitializeRawQuadBuffers()
{
quadsIndices = new short[MaxNumQuadIndices];
quadsVertices = new CCV3F_C4B_T2F[MaxNumQuadVertices];
int i6 = 0;
short i4 = 0;
for (int i = 0; i < MaxNumQuads; i++)
{
quadsIndices [i6 + 0] = (short)(i4 + 0);
quadsIndices [i6 + 1] = (short)(i4 + 1);
quadsIndices [i6 + 2] = (short)(i4 + 2);
quadsIndices [i6 + 3] = (short)(i4 + 3);
quadsIndices [i6 + 4] = (short)(i4 + 2);
quadsIndices [i6 + 5] = (short)(i4 + 1);
i4 += 4;
i6 += 6;
}
}
void PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
var gdipp = e.GraphicsDeviceInformation.PresentationParameters;
PresentationParameters presParams = new PresentationParameters();
presParams.RenderTargetUsage = RenderTargetUsage.PreserveContents;
presParams.DepthStencilFormat = DepthFormat.Depth24Stencil8;
presParams.BackBufferFormat = SurfaceFormat.Color;
presParams.RenderTargetUsage = RenderTargetUsage.PreserveContents;
gdipp.RenderTargetUsage = presParams.RenderTargetUsage;
gdipp.DepthStencilFormat = presParams.DepthStencilFormat;
gdipp.BackBufferFormat = presParams.BackBufferFormat;
gdipp.RenderTargetUsage = presParams.RenderTargetUsage;
}
void InitializeGraphicsDevice()
{
SpriteBatch = new SpriteBatch(graphicsDevice);
defaultEffect = new BasicEffect(graphicsDevice);
AlphaTestEffect = new AlphaTestEffect(graphicsDevice);
PrimitiveEffect = new BasicEffect(graphicsDevice)
{
TextureEnabled = false,
VertexColorEnabled = true
};
depthEnableStencilState = new DepthStencilState
{
DepthBufferEnable = true,
DepthBufferWriteEnable = true,
TwoSidedStencilMode = true
};
depthDisableStencilState = new DepthStencilState
{
DepthBufferEnable = false
};
#if !WINDOWS_PHONE && !XBOX && !WINDOWS &&!NETFX_CORE
List<string> extensions = CCUtils.GetGLExtensions();
foreach(string s in extensions)
{
switch(s)
{
case "GL_OES_depth24":
platformDepthFormat = CCDepthFormat.Depth24;
break;
case "GL_IMG_texture_npot":
allowNonPower2Textures = true;
break;
case "GL_NV_depth_nonlinear": // nVidia Depth 16 non-linear
platformDepthFormat = CCDepthFormat.Depth16;
break;
case "GL_NV_texture_npot_2D_mipmap": // nVidia - nPot textures and mipmaps
allowNonPower2Textures = true;
break;
}
}
#endif
projectionMatrix = Matrix.Identity;
viewMatrix = Matrix.Identity;
worldMatrix = Matrix.Identity;
matrix = Matrix.Identity;
worldMatrixChanged = viewMatrixChanged = projectionMatrixChanged = true;
graphicsDevice.Disposing += GraphicsDeviceDisposing;
graphicsDevice.DeviceLost += GraphicsDeviceDeviceLost;
graphicsDevice.DeviceReset += GraphicsDeviceDeviceReset;
graphicsDevice.DeviceResetting += GraphicsDeviceDeviceResetting;
graphicsDevice.ResourceCreated += GraphicsDeviceResourceCreated;
graphicsDevice.ResourceDestroyed += GraphicsDeviceResourceDestroyed;
DepthTest = false;
ResetDevice();
}
#endregion Initialization
RasterizerState GetScissorRasterizerState(bool scissorEnabled)
{
var currentState = graphicsDevice.RasterizerState;
for (int i = 0; i < rasterizerStatesCache.Count; i++)
{
var state = rasterizerStatesCache[i];
if (
state.ScissorTestEnable == scissorEnabled &&
currentState.CullMode == state.CullMode &&
currentState.DepthBias == state.DepthBias &&
currentState.FillMode == state.FillMode &&
currentState.MultiSampleAntiAlias == state.MultiSampleAntiAlias &&
currentState.SlopeScaleDepthBias == state.SlopeScaleDepthBias
)
{
return state;
}
}
var newState = new RasterizerState
{
ScissorTestEnable = scissorEnabled,
CullMode = currentState.CullMode,
DepthBias = currentState.DepthBias,
FillMode = currentState.FillMode,
MultiSampleAntiAlias = currentState.MultiSampleAntiAlias,
SlopeScaleDepthBias = currentState.SlopeScaleDepthBias
};
rasterizerStatesCache.Add(newState);
return newState;
}
#region GraphicsDevice callbacks
void GraphicsDeviceResourceDestroyed(object sender, ResourceDestroyedEventArgs e)
{
}
void GraphicsDeviceResourceCreated(object sender, ResourceCreatedEventArgs e)
{
}
void GraphicsDeviceDeviceResetting(object sender, EventArgs e)
{
CCSpriteFontCache.SharedSpriteFontCache.Clear();
#if XNA
CCContentManager.SharedContentManager.ReloadGraphicsAssets();
#endif
needReinitResources = true;
}
void GraphicsDeviceDeviceReset(object sender, EventArgs e)
{
}
void GraphicsDeviceDeviceLost(object sender, EventArgs e)
{
}
void GraphicsDeviceDisposing(object sender, EventArgs e)
{
}
#endregion GraphicsDevice callbacks
#region Cleanup
public void PurgeDrawManager()
{
graphicsDevice = null;
SpriteBatch = null;
blendStates.Clear();
depthEnableStencilState = null;
depthDisableStencilState = null;
effectStack.Clear();
PrimitiveEffect = null;
AlphaTestEffect = null;
defaultEffect = null;
currentEffect = null;
currentRenderTarget = null;
quadsBuffer = null;
quadsIndexBuffer = null;
currentTexture = null;
quadsVertices = null;
quadsIndices = null;
TmpVertices.Clear();
}
internal void ResetDevice()
{
vertexColorEnabled = true;
worldMatrixChanged = false;
projectionMatrixChanged = false;
viewMatrixChanged = false;
textureChanged = false;
effectChanged = false;
DepthTest = depthTest;
defaultEffect.VertexColorEnabled = true;
defaultEffect.TextureEnabled = false;
defaultEffect.Alpha = 1f;
defaultEffect.Texture = null;
defaultEffect.View = viewMatrix;
defaultEffect.World = worldMatrix;
defaultEffect.Projection = projectionMatrix;
matrix = worldMatrix;
effectStack.Clear();
currentEffect = defaultEffect;
currentTexture = null;
graphicsDevice.RasterizerState = RasterizerState.CullNone;
graphicsDevice.BlendState = BlendState.AlphaBlend;
graphicsDevice.SetVertexBuffer(null);
graphicsDevice.SetRenderTarget(null);
graphicsDevice.Indices = null;
graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
}
#endregion Cleanup
#region Drawing
internal void Clear(ClearOptions options, Color color, float depth, int stencil)
{
graphicsDevice.Clear(options, color, depth, stencil);
}
public void Clear(CCColor4B color, float depth, int stencil)
{
Clear(ClearOptions.Target | ClearOptions.Stencil | ClearOptions.DepthBuffer, color.ToColor(), depth, stencil);
}
public void Clear(CCColor4B color, float depth)
{
Clear(color, depth, 0);
}
public void Clear(CCColor4B color)
{
Clear(color, 1.0f);
}
internal void BeginDraw()
{
if (graphicsDevice == null || graphicsDevice.IsDisposed)
{
// We are exiting the game
return;
}
if (needReinitResources)
{
//CCGraphicsResource.ReinitAllResources();
needReinitResources = false;
}
ResetDevice();
if (hasStencilBuffer)
{
try
{
Clear(CCColor4B.Transparent, 1, 0);
}
catch (InvalidOperationException)
{
// no stencil buffer
hasStencilBuffer = false;
Clear(CCColor4B.Transparent);
}
}
else
{
Clear(CCColor4B.Transparent);
}
DrawCount = 0;
DrawPrimitivesCount = 0;
}
internal void UpdateStats()
{
var metrics = graphicsDevice.Metrics;
DrawCount += metrics.DrawCount;
DrawPrimitivesCount += metrics.PrimitiveCount;
}
internal void EndDraw()
{
if (graphicsDevice == null || graphicsDevice.IsDisposed)
{
// We are exiting the game
return;
}
Debug.Assert(stackIndex == 0);
if (currentRenderTarget != null)
{
graphicsDevice.SetRenderTarget(null);
SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, DepthStencilState, null, AlphaTestEffect);
SpriteBatch.Draw(currentRenderTarget, new Vector2(0, 0), Color.White);
SpriteBatch.End();
}
ResetDevice();
}
internal void DrawPrimitives<T>(PrimitiveType type, T[] vertices, int offset, int count) where T : struct, IVertexType
{
if (count <= 0)
{
return;
}
ApplyEffectParams();
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawUserPrimitives(type, vertices, offset, count);
}
}
internal void DrawIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData,
int indexOffset, int primitiveCount) where T : struct, IVertexType
{
if (primitiveCount <= 0)
{
return;
}
ApplyEffectParams();
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset,
primitiveCount);
}
}
internal void DrawQuads(CCRawList<CCV3F_C4B_T2F_Quad> quads, int start, int n)
{
if (n == 0)
return;
ApplyEffectParams();
// We unbox our quads into our vertex array that is passed onto MonoGame
// Our vertex array is of a fixed size, so split up into multiple draw calls if required
while (n > 0)
{
int nIteration = Math.Min (n, MaxNumQuads);
int i4 = 0;
for (int i = start, N = start + nIteration; i < N; i++)
{
quadsVertices[i4 + 0] = quads[i].TopLeft;
quadsVertices[i4 + 1] = quads[i].BottomLeft;
quadsVertices[i4 + 2] = quads[i].TopRight;
quadsVertices[i4 + 3] = quads[i].BottomRight;
i4 += 4;
}
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawUserIndexedPrimitives(
PrimitiveType.TriangleList, quadsVertices, 0, nIteration * NumOfVerticesPerQuad, quadsIndices, 0, nIteration * 2);
}
n -= nIteration;
start += nIteration;
}
}
internal void DrawBuffer<T, T2>(CCVertexBuffer<T> vertexBuffer, CCIndexBuffer<T2> indexBuffer, int start, int count)
where T : struct, IVertexType
where T2 : struct
{
graphicsDevice.Indices = indexBuffer.IndexBuffer;
graphicsDevice.SetVertexBuffer(vertexBuffer.VertexBuffer);
ApplyEffectParams();
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexBuffer.VertexCount, start, count);
}
graphicsDevice.SetVertexBuffer(null);
graphicsDevice.Indices = null;
}
internal void DrawRawBuffer<T>(T[] vertexBuffer, int vStart, int vCount, short[] indexBuffer, int iStart, int iCount)
where T : struct, IVertexType
{
ApplyEffectParams();
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawUserIndexedPrimitives (PrimitiveType.TriangleList,
vertexBuffer, vStart, vCount,
indexBuffer, iStart, iCount);
}
}
internal void DrawQuadsBuffer<T>(CCVertexBuffer<T> vertexBuffer, int start, int n) where T : struct, IVertexType
{
if (n == 0)
{
return;
}
CheckQuadsIndexBuffer(start + n);
graphicsDevice.Indices = quadsIndexBuffer.IndexBuffer;
graphicsDevice.SetVertexBuffer(vertexBuffer.VertexBuffer);
ApplyEffectParams();
EffectPassCollection passes = currentEffect.CurrentTechnique.Passes;
for (int i = 0; i < passes.Count; i++)
{
passes[i].Apply();
graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexBuffer.VertexCount, start * 6, n * 2);
}
graphicsDevice.SetVertexBuffer(null);
graphicsDevice.Indices = null;
}
#endregion Drawing
#region Effect management
internal void PushEffect(Effect effect)
{
effectStack.Push(currentEffect);
currentEffect = effect;
effectChanged = true;
}
internal void PopEffect()
{
currentEffect = effectStack.Pop();
effectChanged = true;
}
void ApplyEffectTexture()
{
if (currentEffect is BasicEffect)
{
var effect = (BasicEffect)currentEffect;
effect.TextureEnabled = textureEnabled;
effect.VertexColorEnabled = vertexColorEnabled;
effect.Texture = currentTexture;
}
else if (currentEffect is AlphaTestEffect)
{
var effect = (AlphaTestEffect)currentEffect;
effect.VertexColorEnabled = vertexColorEnabled;
effect.Texture = currentTexture;
}
else
{
throw new Exception(String.Format("Effect {0} not supported", currentEffect.GetType().Name));
}
}
void ApplyEffectParams()
{
if (effectChanged)
{
var matrices = currentEffect as IEffectMatrices;
if (matrices != null)
{
matrices.Projection = projectionMatrix;
matrices.View = viewMatrix;
matrices.World = matrix;
}
ApplyEffectTexture();
}
else
{
if (worldMatrixChanged || projectionMatrixChanged || viewMatrixChanged)
{
var matrices = currentEffect as IEffectMatrices;
if (matrices != null)
{
if (worldMatrixChanged)
{
matrices.World = matrix;
}
if (projectionMatrixChanged)
{
matrices.Projection = projectionMatrix;
}
if (viewMatrixChanged)
{
matrices.View = viewMatrix;
}
}
}
if (textureChanged)
{
ApplyEffectTexture();
}
}
effectChanged = false;
textureChanged = false;
worldMatrixChanged = false;
projectionMatrixChanged = false;
viewMatrixChanged = false;
}
#endregion Effect management
public void BlendFunc(CCBlendFunc blendFunc)
{
BlendState bs = null;
if (blendFunc == CCBlendFunc.AlphaBlend)
{
bs = BlendState.AlphaBlend;
}
else if (blendFunc == CCBlendFunc.Additive)
{
bs = BlendState.Additive;
}
else if (blendFunc == CCBlendFunc.NonPremultiplied)
{
bs = BlendState.NonPremultiplied;
}
else if (blendFunc == CCBlendFunc.Opaque)
{
bs = BlendState.Opaque;
}
else
{
if (!blendStates.TryGetValue(blendFunc, out bs))
{
bs = new BlendState();
bs.ColorSourceBlend = CCOGLES.GetXNABlend(blendFunc.Source);
bs.AlphaSourceBlend = CCOGLES.GetXNABlend(blendFunc.Source);
bs.ColorDestinationBlend = CCOGLES.GetXNABlend(blendFunc.Destination);
bs.AlphaDestinationBlend = CCOGLES.GetXNABlend(blendFunc.Destination);
blendStates.Add(blendFunc, bs);
}
}
graphicsDevice.BlendState = bs;
currBlend.Source = blendFunc.Source;
currBlend.Destination = blendFunc.Destination;
}
#region Texture managment
internal Texture2D CreateTexture2D(int width, int height)
{
PresentationParameters pp = graphicsDevice.PresentationParameters;
if (!allowNonPower2Textures)
{
width = CCUtils.CCNextPOT(width);
height = CCUtils.CCNextPOT(height);
}
return new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color);
}
public void BindTexture(CCTexture2D texture)
{
Texture2D tex = texture != null ? texture.XNATexture : null;
if (!graphicsDevice.IsDisposed && graphicsDevice.GraphicsDeviceStatus == GraphicsDeviceStatus.Normal)
{
if (tex == null)
{
graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
TextureEnabled = false;
}
else
{
graphicsDevice.SamplerStates[0] = texture.SamplerState;
TextureEnabled = true;
}
if (currentTexture != tex)
{
currentTexture = tex;
textureChanged = true;
}
}
}
#endregion Texture management
#region Render target management
internal void CreateRenderTarget(CCTexture2D texture, CCRenderTargetUsage usage)
{
CCSize size = texture.ContentSizeInPixels;
var rtarget = CreateRenderTarget((int)size.Width, (int)size.Height, CCTexture2D.DefaultAlphaPixelFormat,
platformDepthFormat, usage);
texture.InitWithTexture(rtarget, CCTexture2D.DefaultAlphaPixelFormat, true, false);
}
internal RenderTarget2D CreateRenderTarget(int width, int height, CCRenderTargetUsage usage)
{
return CreateRenderTarget(width, height, CCTexture2D.DefaultAlphaPixelFormat, CCDepthFormat.None, usage);
}
internal RenderTarget2D CreateRenderTarget(int width, int height, CCSurfaceFormat colorFormat, CCRenderTargetUsage usage)
{
return CreateRenderTarget(width, height, colorFormat, CCDepthFormat.None, usage);
}
internal RenderTarget2D CreateRenderTarget(int width, int height, CCSurfaceFormat colorFormat, CCDepthFormat depthFormat,
CCRenderTargetUsage usage)
{
if (!allowNonPower2Textures)
{
width = CCUtils.CCNextPOT(width);
height = CCUtils.CCNextPOT(height);
}
return new RenderTarget2D(graphicsDevice, width, height, false, (SurfaceFormat)colorFormat, (DepthFormat)depthFormat, 0, (RenderTargetUsage)usage);
}
public void SetRenderTarget(CCTexture2D texture)
{
RenderTarget2D target = null;
if (texture != null)
target = texture.XNATexture as RenderTarget2D;
CurrentRenderTarget = target;
}
public void RestoreRenderTarget()
{
CurrentRenderTarget = previousRenderTarget;
}
#endregion Render target management
void CheckQuadsIndexBuffer(int capacity)
{
if (quadsIndexBuffer == null || quadsIndexBuffer.Capacity < capacity * 6)
{
capacity = Math.Max(capacity, DefaultQuadBufferSize);
if (quadsIndexBuffer == null)
{
quadsIndexBuffer = new CCIndexBuffer<short>(capacity * 6, BufferUsage.WriteOnly);
quadsIndexBuffer.Count = quadsIndexBuffer.Capacity;
}
if (quadsIndexBuffer.Capacity < capacity * 6)
{
quadsIndexBuffer.Capacity = capacity * 6;
quadsIndexBuffer.Count = quadsIndexBuffer.Capacity;
}
var indices = quadsIndexBuffer.Data.Elements;
int i6 = 0;
int i4 = 0;
for (int i = 0; i < capacity; ++i)
{
indices[i6 + 0] = (short)(i4 + 0);
indices[i6 + 1] = (short)(i4 + 2);
indices[i6 + 2] = (short)(i4 + 1);
indices[i6 + 3] = (short)(i4 + 1);
indices[i6 + 4] = (short)(i4 + 2);
indices[i6 + 5] = (short)(i4 + 3);
i6 += 6;
i4 += 4;
}
quadsIndexBuffer.UpdateBuffer();
}
}
void CheckQuadsVertexBuffer(int capacity)
{
if (quadsBuffer == null || quadsBuffer.Capacity < capacity)
{
capacity = Math.Max(capacity, DefaultQuadBufferSize);
if (quadsBuffer == null)
{
quadsBuffer = new CCQuadVertexBuffer(capacity, CCBufferUsage.WriteOnly);
}
else
{
quadsBuffer.Capacity = capacity;
}
}
}
#region Matrix management
public void SetIdentityMatrix()
{
matrix = Matrix.Identity;
worldMatrixChanged = true;
}
public void PushMatrix()
{
matrixStack[stackIndex++] = matrix;
}
public void PopMatrix()
{
matrix = matrixStack[--stackIndex];
worldMatrixChanged = true;
Debug.Assert(stackIndex >= 0);
}
public void Translate(float x, float y, int z)
{
tmpMatrix = Matrix.CreateTranslation(x, y, z);
Matrix.Multiply(ref tmpMatrix, ref matrix, out matrix);
worldMatrixChanged = true;
}
public void MultMatrix(ref Matrix matrixIn)
{
Matrix.Multiply(ref matrixIn, ref matrix, out matrix);
worldMatrixChanged = true;
}
public void MultMatrix(CCAffineTransform transform, float z)
{
MultMatrix(ref transform, z);
}
public void MultMatrix(ref CCAffineTransform affineTransform, float z)
{
transform.M11 = affineTransform.A;
transform.M21 = affineTransform.C;
transform.M12 = affineTransform.B;
transform.M22 = affineTransform.D;
transform.M41 = affineTransform.Tx;
transform.M42 = affineTransform.Ty;
transform.M43 = z;
matrix = Matrix.Multiply(transform, matrix);
worldMatrixChanged = true;
}
#endregion Matrix management
#region Mask management
public void SetClearMaskState(int layer, bool inverted)
{
DepthStencilState = maskStatesCache[layer].GetClearState(layer, inverted);
}
public void SetDrawMaskState(int layer, bool inverted)
{
DepthStencilState = maskStatesCache[layer].GetDrawMaskState(layer, inverted);
}
public void SetDrawMaskedState(int layer, bool depth)
{
DepthStencilState = maskStatesCache[layer].GetDrawContentState(layer, depth, maskSavedStencilStates, this.maskLayer);
}
public bool BeginDrawMask(CCRect screenRect, bool inverted=false, float alphaTreshold=1f)
{
if (maskLayer + 1 == 8) //DepthFormat.Depth24Stencil8
{
if (maskOnceLog)
{
CCLog.Log(
@"Nesting more than 8 stencils is not supported.
Everything will be drawn without stencil for this node and its childs."
);
maskOnceLog = false;
}
return false;
}
maskLayer++;
var maskState = new MaskState() { Layer = maskLayer, Inverted = inverted, AlphaTreshold = alphaTreshold };
maskStates[maskLayer] = maskState;
maskSavedStencilStates[maskLayer] = DepthStencilState;
int newMaskLayer = 1 << this.maskLayer;
///////////////////////////////////
// CLEAR STENCIL BUFFER
SetClearMaskState(newMaskLayer, maskState.Inverted);
// draw a fullscreen solid rectangle to clear the stencil buffer
XnaGraphicsDevice.Clear (ClearOptions.Target | ClearOptions.Stencil, Color.Transparent, 1, 0);
///////////////////////////////////
// PREPARE TO DRAW MASK
SetDrawMaskState(newMaskLayer, maskState.Inverted);
if (maskState.AlphaTreshold < 1f)
{
AlphaTestEffect.AlphaFunction = CompareFunction.Greater;
AlphaTestEffect.ReferenceAlpha = (byte)(255 * maskState.AlphaTreshold);
PushEffect(AlphaTestEffect);
}
return true;
}
public void EndDrawMask()
{
var maskState = maskStates[maskLayer];
///////////////////////////////////
// PREPARE TO DRAW MASKED CONTENT
if (maskState.AlphaTreshold < 1)
{
PopEffect();
}
SetDrawMaskedState(maskLayer, maskSavedStencilStates[maskLayer].DepthBufferEnable);
}
public void EndMask()
{
///////////////////////////////////
// RESTORE STATE
DepthStencilState = maskSavedStencilStates[maskLayer];
maskLayer--;
}
#endregion
}
internal struct MaskState
{
public int Layer;
public bool Inverted;
public float AlphaTreshold;
}
internal struct MaskDepthStencilStateCacheEntry
{
public DepthStencilState Clear;
public DepthStencilState ClearInvert;
public DepthStencilState DrawMask;
public DepthStencilState DrawMaskInvert;
public DepthStencilState DrawContent;
public DepthStencilState DrawContentDepth;
public DepthStencilState GetClearState(int layer, bool inverted)
{
DepthStencilState result = inverted ? ClearInvert : Clear;
if (result == null)
{
int maskLayer = 1 << layer;
result = new DepthStencilState()
{
DepthBufferEnable = false,
StencilEnable = true,
StencilFunction = CompareFunction.Never,
StencilMask = maskLayer,
StencilWriteMask = maskLayer,
ReferenceStencil = maskLayer,
StencilFail = !inverted ? StencilOperation.Zero : StencilOperation.Replace
};
if (inverted)
{
ClearInvert = result;
}
else
{
Clear = result;
}
}
return result;
}
public DepthStencilState GetDrawMaskState(int layer, bool inverted)
{
DepthStencilState result = inverted ? DrawMaskInvert : DrawMask;
if (result == null)
{
int maskLayer = 1 << layer;
result = new DepthStencilState()
{
DepthBufferEnable = false,
StencilEnable = true,
StencilFunction = CompareFunction.Never,
StencilMask = maskLayer,
StencilWriteMask = maskLayer,
ReferenceStencil = maskLayer,
StencilFail = !inverted ? StencilOperation.Replace : StencilOperation.Zero,
};
if (inverted)
{
DrawMaskInvert = result;
}
else
{
DrawMask = result;
}
}
return result;
}
public DepthStencilState GetDrawContentState(int layer, bool depth, DepthStencilState[] maskSavedStencilStates, int currentMaskLayer)
{
DepthStencilState result = depth ? DrawContentDepth : DrawContent;
if (result == null)
{
int maskLayer = 1 << layer;
int maskLayerL = maskLayer - 1;
int maskLayerLe = maskLayer | maskLayerL;
result = new DepthStencilState()
{
DepthBufferEnable = maskSavedStencilStates[currentMaskLayer].DepthBufferEnable,
StencilEnable = true,
StencilMask = maskLayerLe,
StencilWriteMask = 0,
ReferenceStencil = maskLayerLe,
StencilFunction = CompareFunction.Equal,
StencilPass = StencilOperation.Zero,
StencilFail = StencilOperation.Zero,
};
if (depth)
{
DrawContentDepth = result;
}
else
{
DrawContent = result;
}
}
return result;
}
}
public class CCGraphicsResource : IDisposable
{
bool isDisposed;
public bool IsDisposed
{
get { return isDisposed; }
}
#region Constructors
public CCGraphicsResource()
{
}
#endregion Constructors
#region Cleaning up
~CCGraphicsResource()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
isDisposed = true;
}
}
#endregion Cleaning up
public virtual void ReinitResource()
{
}
}
internal class CCVertexBuffer<T> : CCGraphicsResource where T : struct, IVertexType
{
protected VertexBuffer vertexBuffer;
protected CCBufferUsage usage;
protected CCRawList<T> data;
#region Properties
internal VertexBuffer VertexBuffer
{
get { return vertexBuffer; }
}
public CCRawList<T> Data
{
get { return data; }
}
public int Count
{
get { return data.Count; }
set
{
Debug.Assert(value <= data.Capacity);
data.Count = value;
}
}
public int Capacity
{
get { return data.Capacity; }
set
{
if (data.Capacity != value)
{
data.Capacity = value;
ReinitResource();
}
}
}
#endregion Properties
#region Constructors
public CCVertexBuffer(int vertexCount, CCBufferUsage usage)
{
data = new CCRawList<T>(vertexCount);
this.usage = usage;
ReinitResource();
}
#endregion Constructors
public override void ReinitResource()
{
if (vertexBuffer != null && !vertexBuffer.IsDisposed)
{
vertexBuffer.Dispose();
}
vertexBuffer = new VertexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(T), data.Capacity, (BufferUsage)usage);
}
public void UpdateBuffer()
{
UpdateBuffer(0, data.Count);
}
public virtual void UpdateBuffer(int startIndex, int elementCount)
{
if (elementCount > 0)
{
int vertexByteSize = vertexBuffer.VertexDeclaration.VertexStride;
vertexBuffer.SetData(vertexByteSize * startIndex, data.Elements, startIndex, elementCount, vertexByteSize);
}
}
}
internal class CCQuadVertexBuffer : CCVertexBuffer<CCV3F_C4B_T2F_Quad>
{
public CCQuadVertexBuffer(int vertexCount, CCBufferUsage usage)
: base(vertexCount, usage)
{
}
public void UpdateBuffer(CCRawList<CCV3F_C4B_T2F_Quad> dataIn, int startIndex, int elementCount)
{
//TODO:
var tmp = data;
data = dataIn;
UpdateBuffer(startIndex, elementCount);
data = tmp;
}
public override void UpdateBuffer(int startIndex, int elementCount)
{
if (elementCount == 0)
{
return;
}
var quads = data.Elements;
var tmp = CCDrawManager.SharedDrawManager.TmpVertices;
while (tmp.Capacity < elementCount)
{
tmp.Capacity = tmp.Capacity * 2;
}
tmp.Count = elementCount * 4;
var vertices = tmp.Elements;
int i4 = 0;
for (int i = startIndex; i < startIndex + elementCount; i++)
{
vertices[i4 + 0] = quads[i].TopLeft;
vertices[i4 + 1] = quads[i].BottomLeft;
vertices[i4 + 2] = quads[i].TopRight;
vertices[i4 + 3] = quads[i].BottomRight;
i4 += 4;
}
int vertexByteSize = vertexBuffer.VertexDeclaration.VertexStride;
vertexBuffer.SetData(vertexByteSize * startIndex * 4, vertices, 0, elementCount * 4, vertexByteSize);
}
public override void ReinitResource()
{
if (vertexBuffer != null && !vertexBuffer.IsDisposed)
{
vertexBuffer.Dispose();
}
vertexBuffer = new VertexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(CCV3F_C4B_T2F), data.Capacity * 4, (BufferUsage)usage);
UpdateBuffer();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && vertexBuffer != null && !vertexBuffer.IsDisposed)
{
vertexBuffer.Dispose();
}
vertexBuffer = null;
}
}
internal class CCIndexBuffer<T> : CCGraphicsResource where T : struct
{
IndexBuffer indexBuffer;
BufferUsage usage;
CCRawList<T> data;
#region Properties
internal IndexBuffer IndexBuffer
{
get { return indexBuffer; }
}
public CCRawList<T> Data
{
get { return data; }
}
public int Count
{
get { return data.Count; }
set
{
Debug.Assert(value <= data.Capacity);
data.Count = value;
}
}
public int Capacity
{
get { return data.Capacity; }
set
{
if (data.Capacity != value)
{
data.Capacity = value;
ReinitResource();
}
}
}
#endregion Properties
#region Constructors
public CCIndexBuffer(int indexCount, BufferUsage usage)
{
data = new CCRawList<T>(indexCount);
this.usage = usage;
ReinitResource();
}
#endregion Constructors
public override void ReinitResource()
{
if (indexBuffer != null && !indexBuffer.IsDisposed)
{
indexBuffer.Dispose();
}
indexBuffer = new IndexBuffer(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, typeof(T), data.Capacity, usage);
UpdateBuffer();
}
public void UpdateBuffer()
{
UpdateBuffer(0, data.Count);
}
public void UpdateBuffer(int startIndex, int elementCount)
{
if (elementCount > 0)
{
indexBuffer.SetData(data.Elements, startIndex, elementCount);
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && indexBuffer != null && !indexBuffer.IsDisposed)
{
indexBuffer.Dispose();
}
indexBuffer = null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.Azure.Management.DataLake.Store;
using Microsoft.Azure.Management.DataLake.Store.Models;
using Xunit;
using Microsoft.Azure.Test.HttpRecorder;
using System.Diagnostics;
namespace DataLakeStore.Tests
{
public class FileSystemOperationTests : TestBase
{
#region internal constants
internal const string folderToCreate = "SDKTestFolder01";
internal const string folderToMove = "SDKTestMoveFolder01";
internal const string fileToCreate = "SDKTestFile01.txt";
internal const string fileToCreateWithContents = "SDKTestFile02.txt";
internal const string fileToCopy = "SDKTestCopyFile01.txt";
internal const string fileToConcatTo = "SDKTestConcatFile01.txt";
internal const string fileToMove = "SDKTestMoveFile01.txt";
internal const string fileContentsToAdd = "These are some random test contents 1234!@";
internal const string fileContentsToAppend = "More test contents, that were appended!";
#endregion
private CommonTestFixture commonData;
#region SDK Tests
[Fact]
public void DataLakeStoreFileSystemValidateDefaultTimeout()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
Assert.Equal(TimeSpan.FromMinutes(5), commonData.DataLakeStoreFileSystemClient.HttpClient.Timeout);
}
}
}
[Fact]
public void DataLakeStoreFileSystemFolderCreate()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var folderPath = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath,
FileType.DIRECTORY, 0);
}
}
}
[Fact]
public void DataLakeStoreFileSystemSetAndRemoveExpiry()
{
const long maxTimeInMilliseconds = 253402300800000;
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// verify it does not have an expiration
var fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
Assert.True(fileInfo.FileStatus.ExpirationTime <= 0 || fileInfo.FileStatus.ExpirationTime == maxTimeInMilliseconds, "Expiration time was not equal to 0 or DateTime.MaxValue.Ticks! Actual value reported: " + fileInfo.FileStatus.ExpirationTime);
// set the expiration time as an absolute value
var toSetAbsolute = ToUnixTimeStampMs(HttpMockServer.GetVariable("absoluteTime", DateTime.UtcNow.AddSeconds(120).ToString()));
commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.Absolute, toSetAbsolute);
fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
VerifyTimeInAcceptableRange(toSetAbsolute, fileInfo.FileStatus.ExpirationTime.Value);
// set the expiration time relative to now
var toSetRelativeToNow = ToUnixTimeStampMs(HttpMockServer.GetVariable("relativeTime", DateTime.UtcNow.AddSeconds(120).ToString()));
commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.RelativeToNow, 120 * 1000);
fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
VerifyTimeInAcceptableRange(toSetRelativeToNow, fileInfo.FileStatus.ExpirationTime.Value);
// set expiration time relative to the creation time
var toSetRelativeCreationTime = fileInfo.FileStatus.ModificationTime.Value + (120 * 1000);
commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.RelativeToCreationDate, 120 * 1000);
fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
VerifyTimeInAcceptableRange(toSetRelativeCreationTime, fileInfo.FileStatus.ExpirationTime.Value);
// reset expiration time to never
commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.NeverExpire);
fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
Assert.True(fileInfo.FileStatus.ExpirationTime <= 0 || fileInfo.FileStatus.ExpirationTime == maxTimeInMilliseconds, "Expiration time was not equal to 0 or DateTime.MaxValue.Ticks! Actual value reported: " + fileInfo.FileStatus.ExpirationTime);
}
}
}
[Fact]
public void DataLakeStoreFileSystemNegativeExpiry()
{
const long maxTimeInMilliseconds = 253402300800000;
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// verify it does not have an expiration
var fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
Assert.True(fileInfo.FileStatus.ExpirationTime <= 0 || fileInfo.FileStatus.ExpirationTime == maxTimeInMilliseconds, "Expiration time was not equal to 0 or DateTime.MaxValue.Ticks! Actual value reported: " + fileInfo.FileStatus.ExpirationTime);
// set the expiration time as an absolute value that is less than the creation time
var toSetAbsolute = ToUnixTimeStampMs(HttpMockServer.GetVariable("absoluteNegativeTime", DateTime.UtcNow.AddSeconds(-120).ToString()));
Assert.Throws<AdlsErrorException>(() => commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.Absolute, toSetAbsolute));
// set the expiration time as an absolute value that is greater than max allowed time
toSetAbsolute = ToUnixTimeStampMs(DateTime.MaxValue.ToString()) + 1000;
Assert.Throws<AdlsErrorException>(() => commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.Absolute, toSetAbsolute));
// reset expiration time to never with a value and confirm the value is not honored
commonData.DataLakeStoreFileSystemClient.FileSystem.SetFileExpiry(commonData.DataLakeStoreFileSystemAccountName, filePath, ExpiryOptionType.NeverExpire, 400);
fileInfo = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, filePath);
Assert.True(fileInfo.FileStatus.ExpirationTime <= 0 || fileInfo.FileStatus.ExpirationTime == maxTimeInMilliseconds, "Expiration time was not equal to 0 or DateTime.MaxValue.Ticks! Actual value reported: " + fileInfo.FileStatus.ExpirationTime);
}
}
}
[Fact]
public void DataLakeStoreFileSystemListFolderContents()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var folderPath = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath,
FileType.DIRECTORY, 0);
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true, folderPath);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// List all the contents in the folder
var listFolderResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.ListFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
folderPath);
// We know that this directory is brand new, so the contents should only be the one file.
Assert.Equal(1, listFolderResponse.FileStatuses.FileStatus.Count);
Assert.Equal(FileType.FILE, listFolderResponse.FileStatuses.FileStatus[0].Type);
}
}
}
[Fact]
public void DataLakeStoreFileSystemGetNonExistentFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
try
{
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.DataLakeStoreFileSystemAccountName, "/nonexistentfile001.txt");
}
catch (AdlsErrorException e)
{
Assert.Equal(typeof(AdlsFileNotFoundException), e.Body.RemoteException.GetType());
}
}
}
}
[Fact(Skip = "skipping this out until we have a good test for validating access denied within the same tenant")]
public void DataLakeStoreFileSystemTestAccessDenied()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
try
{
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(commonData.NoPermissionDataLakeStoreAccountName, "/");
}
catch (AdlsErrorException e)
{
Assert.Equal(typeof(AdlsAccessControlException), e.Body.RemoteException.GetType());
}
}
}
}
[Fact]
public void DataLakeStoreFileSystemEmptyFileCreate()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
}
}
}
[Fact]
public void DataLakeStoreFileSystemTestFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
Assert.False(commonData.DataLakeStoreFileSystemClient.FileSystem.PathExists(commonData.DataLakeStoreFileSystemAccountName, "nonexistentfile"));
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
Assert.True(commonData.DataLakeStoreFileSystemClient.FileSystem.PathExists(commonData.DataLakeStoreFileSystemAccountName, filePath));
}
}
}
[Fact]
public void DataLakeStoreFileSystemFileAlreadyExists()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// now try to recreate the file
try
{
commonData.DataLakeStoreFileSystemClient.FileSystem.Create(commonData.DataLakeStoreFileSystemAccountName, filePath, new MemoryStream());
Assert.True(false, "Recreation of an existing file without overwrite should have failed and did not.");
}
catch (AdlsErrorException ex)
{
Assert.Equal(typeof(AdlsFileAlreadyExistsException), ex.Body.RemoteException.GetType());
}
}
}
}
[Fact]
public void DataLakeStoreFileSystemFileCreateWithContents()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length);
CompareFileContents(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath,
fileContentsToAdd);
}
}
}
[Fact]
public void DataLakeStoreFileSystemGetContentSummaryForFileAndFolder()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length);
CompareFileContents(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath,
fileContentsToAdd);
// get content summary for the root folder, which should contain the file and directory created
// it should also have at least one more directory.
var contentSummary = commonData.DataLakeStoreFileSystemClient.FileSystem.GetContentSummary(
commonData.DataLakeStoreFileSystemAccountName,
"/");
Assert.True(contentSummary.ContentSummary.FileCount >= 1);
Assert.True(contentSummary.ContentSummary.DirectoryCount >= 2);
Assert.True(contentSummary.ContentSummary.Length >= fileContentsToAdd.Length);
Assert.True(contentSummary.ContentSummary.SpaceConsumed >= fileContentsToAdd.Length);
// get content summary for the folder
contentSummary = commonData.DataLakeStoreFileSystemClient.FileSystem.GetContentSummary(
commonData.DataLakeStoreFileSystemAccountName,
folderToCreate);
Assert.Equal(1, contentSummary.ContentSummary.FileCount);
Assert.Equal(1, contentSummary.ContentSummary.DirectoryCount);
Assert.Equal(fileContentsToAdd.Length, contentSummary.ContentSummary.Length);
Assert.Equal(fileContentsToAdd.Length, contentSummary.ContentSummary.SpaceConsumed);
// get the content summary for the file
contentSummary = commonData.DataLakeStoreFileSystemClient.FileSystem.GetContentSummary(
commonData.DataLakeStoreFileSystemAccountName,
filePath);
Assert.Equal(1, contentSummary.ContentSummary.FileCount);
Assert.Equal(0, contentSummary.ContentSummary.DirectoryCount);
Assert.Equal(fileContentsToAdd.Length, contentSummary.ContentSummary.Length);
Assert.Equal(fileContentsToAdd.Length, contentSummary.ContentSummary.SpaceConsumed);
}
}
}
[Fact]
public void DataLakeStoreFileSystemAppendToFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// Append to the file that we created
commonData.DataLakeStoreFileSystemClient.FileSystem.Append(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAppend)));
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAppend.Length);
}
}
}
[Fact]
public void DataLakeStoreFileSystemAppendToFileWithOffset()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, fileContentsToAdd.Length);
// Append to the file that we created, but starting at the beginning of the file, which should wipe out the data.
commonData.DataLakeStoreFileSystemClient.FileSystem.Append(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAdd)), fileContentsToAdd.Length);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length*2);
}
}
}
[Fact]
public void DataLakeStoreFileSystemAppendToFileWithBadOffset()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, fileContentsToAdd.Length);
try
{
// Append to the file that we created, but starting at the beginning of the file, which should wipe out the data.
commonData.DataLakeStoreFileSystemClient.FileSystem.Append(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAdd)), 0);
Assert.True(false, "Successfully appended content at an offset where content already exists. This should have thrown.");
}
catch (AdlsErrorException ex)
{
Assert.Equal(typeof(AdlsBadOffsetException), ex.Body.RemoteException.GetType());
}
}
}
}
[Fact]
public void DataLakeStoreFileSystemConcurrentAppendToFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, false, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, 0);
// Append to the file that we created
commonData.DataLakeStoreFileSystemClient.FileSystem.ConcurrentAppend(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAppend)));
CompareFileContents(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, fileContentsToAppend);
//compare length
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, fileContentsToAppend.Length);
}
}
}
[Fact]
public void DataLakeStoreFileSystemNegativeConcurrentAppend()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = TestUtilities.GenerateName(string.Format("{0}/{1}", folderToCreate, fileToCreate));
// Concurrent append to the file that we will create during the concurrent append call.
commonData.DataLakeStoreFileSystemClient.FileSystem.ConcurrentAppend(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAppend)), AppendModeType.Autocreate);
CompareFileContents(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, fileContentsToAppend);
// attempt to append after concurrently appending (should fail)
Assert.Throws<AdlsErrorException>(() => commonData.DataLakeStoreFileSystemClient.FileSystem.Append(
commonData.DataLakeStoreFileSystemAccountName,
filePath,
new MemoryStream()));
// Now create a file with contents and attempt to concurrent append onto it.
filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
// Append to the file that we created
Assert.Throws<AdlsErrorException>(() => commonData.DataLakeStoreFileSystemClient.FileSystem.ConcurrentAppend(
commonData.DataLakeStoreFileSystemAccountName,
filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAppend))));
}
}
}
[Fact]
public void DataLakeStoreFileSystemConcurrentAppendCreateFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = TestUtilities.GenerateName(string.Format("{0}/{1}", folderToCreate, fileToCreate));
// Concurrent append to the file that we will create during the concurrent append call.
commonData.DataLakeStoreFileSystemClient.FileSystem.ConcurrentAppend(commonData.DataLakeStoreFileSystemAccountName, filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAppend)), AppendModeType.Autocreate);
CompareFileContents(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, fileContentsToAppend);
// compare length to ensure metadata is updated.
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE, fileContentsToAppend.Length);
}
}
}
[Fact]
public void DataLakeStoreFileSystemConcatenateFiles()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath1 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath1, FileType.FILE,
fileContentsToAdd.Length);
var filePath2 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath2, FileType.FILE,
fileContentsToAdd.Length);
var targetFolder = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
commonData.DataLakeStoreFileSystemClient.FileSystem.Concat(
commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
new List<string> { filePath1, filePath2 });
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
FileType.FILE,
fileContentsToAdd.Length*2);
// Attempt to get the files that were concatted together, which should fail and throw
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath1));
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath2));
}
}
}
[Fact]
public void DataLakeStoreFileSystemMsConcatenateFiles()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath1 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath1, FileType.FILE,
fileContentsToAdd.Length);
var filePath2 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath2, FileType.FILE,
fileContentsToAdd.Length);
var targetFolder = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
commonData.DataLakeStoreFileSystemClient.FileSystem.MsConcat(
commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
new MemoryStream(Encoding.UTF8.GetBytes(string.Format("sources={0},{1}", filePath1, filePath2))));
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
FileType.FILE,
fileContentsToAdd.Length*2);
// Attempt to get the files that were concatted together, which should fail and throw
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath1));
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath2));
}
}
}
[Fact]
public void DataLakeStoreFileSystemMsConcatDeleteDir()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var concatFolderPath = string.Format("{0}/{1}", folderToCreate,
"msconcatFolder");
var filePath1 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true,
concatFolderPath);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath1, FileType.FILE,
fileContentsToAdd.Length);
var filePath2 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true,
concatFolderPath);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath2, FileType.FILE,
fileContentsToAdd.Length);
var targetFolder = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
commonData.DataLakeStoreFileSystemClient.FileSystem.MsConcat(
commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
new MemoryStream(Encoding.UTF8.GetBytes(string.Format("sources={0},{1}", filePath1, filePath2))),
deleteSourceDirectory: true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder, fileToConcatTo),
FileType.FILE,
fileContentsToAdd.Length*2);
// Attempt to get the files that were concatted together, which should fail and throw
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath1));
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath2));
// Attempt to get the folder that was created for concat, which should fail and be deleted.
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
concatFolderPath));
}
}
}
[Fact]
public void DataLakeStoreFileSystemMoveFileAndFolder()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length);
var targetFolder1 = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
var targetFolder2 = TestUtilities.GenerateName(folderToMove);
// Move file first
var moveFileResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Rename(
commonData.DataLakeStoreFileSystemAccountName,
filePath,
string.Format("{0}/{1}", targetFolder1, fileToMove));
Assert.True(moveFileResponse.OperationResult);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName,
string.Format("{0}/{1}", targetFolder1, fileToMove),
FileType.FILE,
fileContentsToAdd.Length);
// Ensure the old file is gone
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath));
// Now move folder completely.
var moveFolderResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Rename(
commonData.DataLakeStoreFileSystemAccountName,
targetFolder1,
targetFolder2);
Assert.True(moveFolderResponse.OperationResult);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, targetFolder2,
FileType.DIRECTORY, 0);
// ensure all the contents of the folder moved
// List all the contents in the folder
var listFolderResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.ListFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
targetFolder2);
// We know that this directory is brand new, so the contents should only be the one file.
Assert.Equal(1, listFolderResponse.FileStatuses.FileStatus.Count);
Assert.Equal(FileType.FILE, listFolderResponse.FileStatuses.FileStatus[0].Type);
Assert.Throws<AdlsErrorException>(() =>
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
targetFolder1));
}
}
}
[Fact]
public void DataLakeStoreFileSystemDeleteFolder()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var folderPath = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath,
FileType.DIRECTORY, 0);
DeleteFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath, true, false);
//WORK AROUND: Bug 4717659 makes it so even empty folders have contents.
// delete again expecting failure.
DeleteFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath, false, true);
// delete a folder with contents
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true, folderPath);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length);
// should fail if recurse is not set
DeleteFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath, false, true);
// Now actually delete
DeleteFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath, true, false);
// delete again expecting failure.
DeleteFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, folderPath, true, true);
}
}
}
[Fact]
public void DataLakeStoreFileSystemDeleteFile()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
GetAndCompareFileOrFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, FileType.FILE,
fileContentsToAdd.Length);
DeleteFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, false);
// try to delete it again, which should fail
DeleteFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, filePath, true);
}
}
}
[Fact]
public void DataLakeStoreFileSystemGetAndSetAcl()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var currentAcl = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName, "/"));
var originalPermission = currentAcl.AclStatus.Permission;
var aclToReplaceWith = new List<string>(currentAcl.AclStatus.Entries);
var originalOther = string.Empty;
var toReplace = "other::rwx";
for (var i = 0; i < aclToReplaceWith.Count; i++)
{
if (aclToReplaceWith[i].StartsWith("other"))
{
originalOther = aclToReplaceWith[i];
aclToReplaceWith[i] = toReplace;
break;
}
}
Assert.False(string.IsNullOrEmpty(originalOther));
// Set the other acl to RWX
commonData.DataLakeStoreFileSystemClient.FileSystem.SetAcl(
commonData.DataLakeStoreFileSystemAccountName,
"/",
string.Join(",", aclToReplaceWith));
var newAcl = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName, "/"));
// verify the ACL actually changed
// Check the access first and assert that it returns OK (note: this is currently only for the user making the request, so it is not testing "other")
commonData.DataLakeStoreFileSystemClient.FileSystem.CheckAccess(
commonData.DataLakeStoreFileSystemAccountName, "/", "rwx");
var foundIt = false;
foreach (var entry in newAcl.AclStatus.Entries.Where(entry => entry.StartsWith("other")))
{
foundIt = true;
Assert.Equal(toReplace, entry);
break;
}
Assert.True(foundIt);
Assert.NotEqual(originalPermission, newAcl.AclStatus.Permission);
// Set it back using specific entry
commonData.DataLakeStoreFileSystemClient.FileSystem.ModifyAclEntries(
commonData.DataLakeStoreFileSystemAccountName, "/",
originalOther);
// Now confirm that it equals the original ACL
var finalAclStatus = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName, "/"))
.AclStatus;
var finalEntries = finalAclStatus.Entries;
foreach (var entry in finalEntries)
{
Assert.Contains(currentAcl.AclStatus.Entries, original => original.Equals(entry, StringComparison.CurrentCultureIgnoreCase));
}
Assert.Equal(finalEntries.Count, currentAcl.AclStatus.Entries.Count);
Assert.Equal(originalPermission, finalAclStatus.Permission);
}
}
}
[Fact]
public void DataLakeStoreFileSystemSetFileProperties()
{
// This test simply tests that all bool/empty return actions return successfully
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (
commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var filePath = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true);
var originalFileStatus =
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
filePath
)
.FileStatus;
// TODO: Set replication on file, this has been removed until it is confirmed as a supported API.
/*
var replicationResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.SetReplication(filePath,
commonData.DataLakeStoreFileSystemAccountName, 3);
Assert.True(replicationResponse.Boolean);
*/
/*
* This API is available but all values put into it are ignored. Commenting this out until this API is fully functional.
Assert.Equal(3,
dataLakeFileSystemClient.FileSystem.GetFileStatus(filePath, commonData.DataLakeStoreFileSystemAccountName)
.FileStatus.Replication);
*/
// set the time on the file
// We use a static date for now since we aren't interested in whether the value is set properly, only that the method returns a 200.
/* TODO: Re enable once supported.
var timeToSet = new DateTime(2015, 10, 26, 14, 30, 0).Ticks;
commonData.DataLakeStoreFileSystemClient.FileSystem.SetTimes(filePath,
commonData.DataLakeStoreFileSystemAccountName, timeToSet, timeToSet);
var fileStatusAfterTime =
commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(filePath,
commonData.DataLakeStoreFileSystemAccountName)
.FileStatus;
*/
/*
* This API is available but all values put into it are ignored. Commenting this out until this API is fully functional.
Assert.True(
fileStatusAfterTime.ModificationTime == timeToSet && fileStatusAfterTime.AccessTime == timeToSet);
*/
// TODO: Symlink creation is explicitly not supported, but when it is this should be enabled.
/*
var symLinkName = TestUtilities.GenerateName("testPath/symlinktest1");
Assert.Throws<AdlsErrorException>(() => commonData.DataLakeStoreFileSystemClient.FileSystem.CreateSymLink(filePath,
commonData.DataLakeStoreFileSystemAccountName, symLinkName, true));
*/
// Once symlinks are available, remove the throws test and uncomment out this code.
// Assert.True(createSymLinkResponse.StatusCode == HttpStatusCode.OK);
// Assert.DoesNotThrow(() => dataLakeFileSystemClient.FileSystem.GetFileStatus(symLinkName, commonData.DataLakeStoreFileSystemAccountName));
}
}
}
[Fact]
public void DataLakeStoreFileSystemGetAcl()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName, "/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
Assert.True(!string.IsNullOrEmpty(aclGetResponse.AclStatus.Owner));
Assert.True(!string.IsNullOrEmpty(aclGetResponse.AclStatus.Group));
}
}
}
[Fact]
public void DataLakeStoreFileSystemSetAcl()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName,
"/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
var currentCount = aclGetResponse.AclStatus.Entries.Count;
// add an entry to the ACL Entries
var newAcls = string.Join(",", aclGetResponse.AclStatus.Entries);
newAcls += string.Format(",user:{0}:rwx", commonData.AclUserId);
commonData.DataLakeStoreFileSystemClient.FileSystem.SetAcl(
commonData.DataLakeStoreFileSystemAccountName,
"/",
newAcls);
// retrieve the ACL again and confirm the new entry is present
aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName, "/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
Assert.Equal(currentCount + 1, aclGetResponse.AclStatus.Entries.Count);
Assert.Contains(aclGetResponse.AclStatus.Entries, entry => entry.Contains(commonData.AclUserId));
}
}
}
[Fact]
public void DataLakeStoreFileSystemSetDeleteAclEntry()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
var aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName,
"/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
var currentCount = aclGetResponse.AclStatus.Entries.Count;
// add an entry to the ACL Entries
var newAce = string.Format("user:{0}:rwx", commonData.AclUserId);
commonData.DataLakeStoreFileSystemClient.FileSystem.ModifyAclEntries(
commonData.DataLakeStoreFileSystemAccountName,
"/",
newAce);
// retrieve the ACL again and confirm the new entry is present
aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName,
"/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
Assert.Equal(currentCount + 1, aclGetResponse.AclStatus.Entries.Count);
Assert.Contains(aclGetResponse.AclStatus.Entries, entry => entry.Contains(commonData.AclUserId));
// now remove the entry
var aceToRemove = string.Format(",user:{0}", commonData.AclUserId);
commonData.DataLakeStoreFileSystemClient.FileSystem.RemoveAclEntries(
commonData.DataLakeStoreFileSystemAccountName,
"/",
aceToRemove);
// retrieve the ACL again and confirm the new entry is gone
aclGetResponse = GetFullAcl(commonData.DataLakeStoreFileSystemClient.FileSystem.GetAclStatus(
commonData.DataLakeStoreFileSystemAccountName,
"/"));
Assert.NotNull(aclGetResponse.AclStatus);
Assert.NotEmpty(aclGetResponse.AclStatus.Entries);
Assert.Equal(currentCount, aclGetResponse.AclStatus.Entries.Count);
Assert.DoesNotContain(aclGetResponse.AclStatus.Entries, entry => entry.Contains(commonData.AclUserId));
}
}
}
#endregion
#region upload download tests
[Fact]
public void DataLakeStoreDownloadUploadFileAndFolder()
{
using (var context = MockContext.Start(this.GetType()))
{
commonData = new CommonTestFixture(context);
using (commonData.DataLakeStoreFileSystemClient = commonData.GetDataLakeStoreFileSystemManagementClient(context))
{
// create a folder and two files with content. Then download the folder and files, then re-upload the folder and files
var folderName = CreateFolder(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true);
var file1 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true, folderName);
var file2 = CreateFile(commonData.DataLakeStoreFileSystemClient, commonData.DataLakeStoreFileSystemAccountName, true, true, folderName);
var localTargetFolder = Path.Combine(Path.GetTempPath(), folderName);
try
{
// download the folder
commonData.DataLakeStoreFileSystemClient.FileSystem.DownloadFolder(commonData.DataLakeStoreFileSystemAccountName, folderName, localTargetFolder);
// verify the downloaded contents
var localDir = new DirectoryInfo(localTargetFolder);
Assert.True(localDir.Exists);
var localFiles = localDir.GetFiles();
Assert.Equal(2, localFiles.Count());
Assert.Equal(fileContentsToAdd.Length * 2, localFiles.Sum(f => f.Length));
// download just one file
commonData.DataLakeStoreFileSystemClient.FileSystem.DownloadFile(
commonData.DataLakeStoreFileSystemAccountName,
file1,
Path.Combine(
localTargetFolder,
"specificFileDownload.out"));
var newFile = new FileInfo(
Path.Combine(
localTargetFolder,
"specificFileDownload.out"));
Assert.True(newFile.Exists);
Assert.Equal(fileContentsToAdd.Length, newFile.Length);
var targetFolder = folderName + "/upload";
// Upload the folder with these files, then upload a single file
commonData.DataLakeStoreFileSystemClient.FileSystem.UploadFolder(commonData.DataLakeStoreFileSystemAccountName, localTargetFolder, targetFolder);
var folderStatus = commonData.DataLakeStoreFileSystemClient.FileSystem.ListFileStatus(
commonData.DataLakeStoreFileSystemAccountName,
targetFolder);
Assert.Equal(3, folderStatus.FileStatuses.FileStatus.Count());
Assert.Equal(fileContentsToAdd.Length * 3, folderStatus.FileStatuses.FileStatus.Sum(f => f.Length));
// upload one more file
var targetFile = string.Format("{0}/{1}.new", targetFolder, newFile.Name);
commonData.DataLakeStoreFileSystemClient.FileSystem.UploadFile(commonData.DataLakeStoreFileSystemAccountName, newFile.FullName, targetFile);
GetAndCompareFileOrFolder(
commonData.DataLakeStoreFileSystemClient,
commonData.DataLakeStoreFileSystemAccountName,
targetFile,
FileType.FILE,
fileContentsToAdd.Length);
CompareFileContents(
commonData.DataLakeStoreFileSystemClient,
commonData.DataLakeStoreFileSystemAccountName,
targetFile,
fileContentsToAdd);
}
finally
{
if (Directory.Exists(localTargetFolder))
{
Directory.Delete(localTargetFolder, true);
}
}
}
}
}
#endregion
#region helpers
internal AclStatusResult GetFullAcl(AclStatusResult acl)
{
if (acl.AclStatus.Entries != null && !string.IsNullOrEmpty(acl.AclStatus.Permission) && acl.AclStatus.Permission.Length >= 3)
{
var permissionString = acl.AclStatus.Permission;
var permissionLength = permissionString.Length;
var ownerOctal = permissionString.ElementAt(permissionLength - 3).ToString();
var groupOctal = permissionString.ElementAt(permissionLength - 2).ToString();
var otherOctal = permissionString.ElementAt(permissionLength - 1).ToString();
acl.AclStatus.Entries.Add(string.Format("user::{0}", octalToPermission(int.Parse(ownerOctal))));
acl.AclStatus.Entries.Add(string.Format("other::{0}", octalToPermission(int.Parse(otherOctal))));
if (!string.IsNullOrEmpty(acl.AclStatus.Entries.First(e => e.StartsWith("group::"))))
{
acl.AclStatus.Entries.Add(string.Format("mask::{0}", octalToPermission(int.Parse(groupOctal))));
}
else
{
acl.AclStatus.Entries.Add(string.Format("group::{0}", octalToPermission(int.Parse(groupOctal))));
}
}
return acl;
}
private string octalToPermission(int octal)
{
return string.Format("{0}{1}{2}",
(octal & 4) > 0 ? "r" : "-",
(octal & 2) > 0 ? "w" : "-",
(octal & 1) > 0 ? "x" : "-");
}
internal string CreateFolder(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, bool randomName = false)
{
// Create a folder
var folderPath = randomName
? TestUtilities.GenerateName(folderToCreate)
: folderToCreate;
var response = commonData.DataLakeStoreFileSystemClient.FileSystem.Mkdirs(caboAccountName, folderPath);
Assert.True(response.OperationResult);
return folderPath;
}
internal string CreateFile(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, bool withContents, bool randomName = false, string folderName = folderToCreate)
{
var filePath = randomName ? TestUtilities.GenerateName(string.Format("{0}/{1}", folderName, fileToCreate)) : string.Format("{0}/{1}", folderName, fileToCreate);
if (!withContents)
{
commonData.DataLakeStoreFileSystemClient.FileSystem.Create(
caboAccountName,
filePath,
new MemoryStream(),
syncFlag: SyncFlag.DATA);
}
else
{
commonData.DataLakeStoreFileSystemClient.FileSystem.Create(
caboAccountName,
filePath,
new MemoryStream(Encoding.UTF8.GetBytes(fileContentsToAdd)));
}
return filePath;
}
internal FileStatusResult GetAndCompareFileOrFolder(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, string fileOrFolderPath, FileType expectedType, long expectedLength)
{
var getResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.GetFileStatus(caboAccountName, fileOrFolderPath);
Assert.Equal(expectedLength, getResponse.FileStatus.Length);
Assert.Equal(expectedType, getResponse.FileStatus.Type);
return getResponse;
}
internal void CompareFileContents(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, string filePath, string expectedContents)
{
// download a file and ensure they are equal
try
{
Stream openResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Open(caboAccountName, filePath, null);
Assert.NotNull(openResponse);
string toCompare = new StreamReader(openResponse).ReadToEnd();
Assert.Equal(expectedContents, toCompare);
}
catch (Exception e)
{
throw e;
}
}
internal void DeleteFolder(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, string folderPath, bool recursive, bool failureExpected)
{
if (failureExpected)
{
// try to delete a folder that doesn't exist or should fail
try
{
var deleteFolderResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Delete(caboAccountName, folderPath, recursive);
Assert.True(!deleteFolderResponse.OperationResult);
}
catch (Exception e)
{
Assert.Equal(typeof(AdlsErrorException), e.GetType());
}
}
else
{
// Delete a folder
var deleteFolderResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Delete(caboAccountName, folderPath, recursive);
Assert.True(deleteFolderResponse.OperationResult);
}
}
internal void DeleteFile(DataLakeStoreFileSystemManagementClient dataLakeStoreFileSystemClient, string caboAccountName, string filePath, bool failureExpected)
{
if (failureExpected)
{
// try to delete a file that doesn't exist
try
{
var deleteFileResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Delete(caboAccountName, filePath, false);
Assert.True(!deleteFileResponse.OperationResult);
}
catch (Exception e)
{
Assert.Equal(typeof(AdlsErrorException), e.GetType());
}
}
else
{
// Delete a file
var deleteFileResponse = commonData.DataLakeStoreFileSystemClient.FileSystem.Delete(caboAccountName, filePath, false);
Assert.True(deleteFileResponse.OperationResult);
}
}
internal long ToUnixTimeStampMs(string date)
{
var convertedDate = Convert.ToDateTime(date);
// NOTE: This assumes the date being passed in is already UTC.
return (long)(convertedDate - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
}
internal DateTime FromUnixTimestampMs(long unixTimestampInMs)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(unixTimestampInMs);
}
internal void VerifyTimeInAcceptableRange(long expected, long actual)
{
// We give a +- 100 ticks range due to timing constraints in the service.
Assert.InRange<long>(actual, expected - 5000, expected + 5000);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsHead
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestHeadTestService : ServiceClient<AutoRestHeadTestService>, IAutoRestHeadTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IHttpSuccessOperations.
/// </summary>
public virtual IHttpSuccessOperations HttpSuccess { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestHeadTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestHeadTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestHeadTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestHeadTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestHeadTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.HttpSuccess = new HttpSuccessOperations(this);
this.BaseUri = new Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region ItemCmdletProvider accessors
#region GetItem
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The item at the specified path.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> GetItem(string[] paths, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
GetItem(paths, context);
context.ThrowFirstErrorOrDoNothing();
// Since there was not errors return the accumulated objects
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing is returned, but all objects should be written to the WriteObject
/// method of the <paramref name="context"/> parameter.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void GetItem(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
GetItemPrivate(providerInstance, providerPath, context);
}
}
}
/// <summary>
/// Gets the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void GetItemPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.GetItem(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetItemProviderException",
SessionStateStrings.GetItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the get-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object GetItemDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return GetItemDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the get-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object GetItemDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.GetItemDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetItemDynamicParametersProviderException",
SessionStateStrings.GetItemDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion GetItem
#region SetItem
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="value">
/// The new value for the item at the specified path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The item that was modified at the specified path.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> SetItem(string[] paths, object value, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
SetItem(paths, value, context);
context.ThrowFirstErrorOrDoNothing();
// Since there was no errors return the accumulated objects
return context.GetAccumulatedObjects();
}
/// <summary>
/// Sets the specified object to the specified value.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="value">
/// The new value of the item at the specified path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void SetItem(
string[] paths,
object value,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
SetItem(providerInstance, providerPath, value, context);
}
}
}
}
/// <summary>
/// Sets item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="value">
/// The value of the item.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void SetItem(
CmdletProvider providerInstance,
string path,
object value,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.SetItem(path, value, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetItemProviderException",
SessionStateStrings.SetItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the set-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="value">
/// The new value of the item at the specified path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object SetItemDynamicParameters(string path, object value, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return SetItemDynamicParameters(providerInstance, providerPaths[0], value, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the set-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="value">
/// The value to be set.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object SetItemDynamicParameters(
CmdletProvider providerInstance,
string path,
object value,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.SetItemDynamicParameters(path, value, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetItemDynamicParametersProviderException",
SessionStateStrings.SetItemDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion SetItem
#region ClearItem
/// <summary>
/// Clears the specified object. Depending on the provider that the path
/// maps to, this could mean the properties and/or content and/or value is
/// cleared.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The items that were cleared.
/// </returns>
/// <remarks>
/// If an error occurs that error will be thrown.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> ClearItem(string[] paths, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
ClearItem(paths, context);
context.ThrowFirstErrorOrDoNothing();
return context.GetAccumulatedObjects();
}
/// <summary>
/// Clears the specified item. Depending on the provider that the path
/// maps to, this could mean the properties and/or content and/or value is
/// cleared.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void ClearItem(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
ClearItemPrivate(providerInstance, providerPath, context);
}
}
}
}
/// <summary>
/// Clears the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void ClearItemPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.ClearItem(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearItemProviderException",
SessionStateStrings.ClearItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object ClearItemDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return ClearItemDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the clear-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object ClearItemDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.ClearItemDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearItemProviderException",
SessionStateStrings.ClearItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion ClearItem
#region InvokeDefaultAction
/// <summary>
/// Performs the default action on the specified item. The default action is
/// determined by the provider.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path(s).
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <remarks>
/// If an error occurs that error will be thrown.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal void InvokeDefaultAction(string[] paths, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.SuppressWildcardExpansion = literalPath;
InvokeDefaultAction(paths, context);
context.ThrowFirstErrorOrDoNothing();
}
/// <summary>
/// Performs the default action on the specified item. The default action
/// is determined by the provider.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute paths.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void InvokeDefaultAction(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("paths");
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
InvokeDefaultActionPrivate(providerInstance, providerPath, context);
}
}
}
}
/// <summary>
/// Invokes the default action on the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void InvokeDefaultActionPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.InvokeDefaultAction(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"InvokeDefaultActionProviderException",
SessionStateStrings.InvokeDefaultActionProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the invoke-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object InvokeDefaultActionDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return InvokeDefaultActionDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the invoke-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object InvokeDefaultActionDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.InvokeDefaultActionDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"InvokeDefaultActionDynamicParametersProviderException",
SessionStateStrings.InvokeDefaultActionDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion InvokeDefaultAction
#endregion ItemCmdletProvider accessors
}
}
#pragma warning restore 56500
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace Shielded
{
/// <summary>
/// Supports adding at both ends O(1), taking from head O(1), and every other op
/// involves a search, O(n). Enumerating must be done in transaction, unless you
/// read only one element, e.g. using LINQ Any or First.
/// For a faster version, but with no Count property, see <see cref="ShieldedSeqNc<T>"/>.
/// </summary>
public class ShieldedSeq<T> : IList<T>
{
private readonly ShieldedSeqNc<T> _seq;
private readonly Shielded<int> _count;
/// <summary>
/// Initialize a new sequence with the given initial contents.
/// </summary>
public ShieldedSeq(T[] items, object owner)
{
_seq = new ShieldedSeqNc<T>(items, owner ?? this);
_count = new Shielded<int>(items.Length, owner ?? this);
}
/// <summary>
/// Initialize a new sequence with the given initial contents.
/// </summary>
public ShieldedSeq(params T[] items) : this(items, null) { }
/// <summary>
/// Initialize a new empty sequence.
/// </summary>
public ShieldedSeq(object owner = null)
{
_seq = new ShieldedSeqNc<T>(owner ?? this);
_count = new Shielded<int>(this);
}
/// <summary>
/// Prepend an item, i.e. insert at index 0.
/// </summary>
public void Prepend(T val)
{
_seq.Prepend(val);
_count.Commute((ref int c) => c++);
}
/// <summary>
/// Peek at the first element. Throws <see cref="InvalidOperationException"/> if
/// there is none.
/// </summary>
public T Head
{
get
{
return _seq.Head;
}
}
/// <summary>
/// Remove the first element of the sequence, and return it.
/// </summary>
public T TakeHead()
{
var h = _seq.TakeHead();
_count.Commute((ref int c) => c--);
return h;
}
/// <summary>
/// Remove and yield elements from the head of the sequence.
/// </summary>
public IEnumerable<T> Consume
{
get
{
foreach (var a in _seq.Consume)
{
_count.Commute((ref int c) => c--);
yield return a;
}
}
}
/// <summary>
/// Append the specified value, commutatively - if you don't / haven't touched the
/// sequence in this transaction (using other methods/properties), this will not cause
/// conflicts! Effectively, the value is simply appended to whatever the sequence
/// is at commit time. Multiple calls to Append made in one transaction will
/// append the items in that order - they commute with other transactions only.
/// </summary>
public void Append(T val)
{
_seq.Append(val);
_count.Commute((ref int c) => c++);
}
/// <summary>
/// Get or set the item at the specified index. This iterates through the internal
/// linked list, so it is not efficient for large sequences.
/// </summary>
public T this [int index]
{
get
{
return _seq[index];
}
set
{
_seq[index] = value;
}
}
/// <summary>
/// Get the number of items in this sequence.
/// </summary>
public int Count
{
get
{
return _count;
}
}
/// <summary>
/// Remove from the sequence all items that satisfy the given predicate.
/// </summary>
public void RemoveAll(Func<T, bool> condition)
{
int removed = 0;
try
{
_seq.RemoveAll(condition, out removed);
}
finally
{
_count.Commute((ref int c) => c -= removed);
}
}
/// <summary>
/// Clear the sequence.
/// </summary>
public void Clear()
{
_seq.Clear();
_count.Value = 0;
}
/// <summary>
/// Remove the item at the given index.
/// </summary>
public void RemoveAt(int index)
{
_seq.RemoveAt(index);
_count.Commute((ref int c) => c--);
}
/// <summary>
/// Remove the specified item from the sequence.
/// </summary>
public bool Remove(T item, IEqualityComparer<T> comp = null)
{
if (_seq.Remove(item, comp))
{
_count.Commute((ref int c) => c--);
return true;
}
return false;
}
/// <summary>
/// Search the sequence for the given item.
/// </summary>
/// <returns>The index of the item in the sequence.</returns>
public int IndexOf(T item, IEqualityComparer<T> comp = null)
{
return _seq.IndexOf(item, comp);
}
/// <summary>
/// Search the sequence for the given item.
/// </summary>
/// <returns>The index of the item in the sequence.</returns>
public int IndexOf(T item)
{
return _seq.IndexOf(item, null);
}
/// <summary>
/// Get an enumerator for the sequence. Although it is just a read, it must be
/// done in a transaction since concurrent changes would make the result unstable.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
return _seq.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _seq.GetEnumerator();
}
/// <summary>
/// Add the specified item to the end of the sequence. Same as <see cref="Append"/>,
/// so, it's commutable.
/// </summary>
public void Add(T item)
{
Append(item);
}
/// <summary>
/// Check if the sequence contains a given item.
/// </summary>
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copy the sequence to an array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">Index in the array where to begin the copy.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_seq.CopyTo(array, arrayIndex);
}
/// <summary>
/// Remove the specified item from the sequence.
/// </summary>
public bool Remove(T item)
{
return Remove(item, null);
}
bool ICollection<T>.IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Insert an item at the specified index.
/// </summary>
public void Insert(int index, T item)
{
_seq.Insert(index, item);
_count.Commute((ref int c) => c++);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml.XPath;
using System.Xml.Xsl.IlGen;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Runtime.Versioning;
namespace System.Xml.Xsl
{
internal delegate void ExecuteDelegate(XmlQueryRuntime runtime);
/// <summary>
/// This internal class is the entry point for creating Msil assemblies from QilExpression.
/// </summary>
/// <remarks>
/// Generate will return an AssemblyBuilder with the following setup:
/// Assembly Name = "MS.Internal.Xml.CompiledQuery"
/// Module Dll Name = "MS.Internal.Xml.CompiledQuery.dll"
/// public class MS.Internal.Xml.CompiledQuery.Test {
/// public static void Execute(XmlQueryRuntime runtime);
/// public static void Root(XmlQueryRuntime runtime);
/// private static ... UserMethod1(XmlQueryRuntime runtime, ...);
/// ...
/// private static ... UserMethodN(XmlQueryRuntime runtime, ...);
/// }
///
/// XmlILGenerator incorporates a number of different technologies in order to generate efficient code that avoids caching
/// large result sets in memory:
///
/// 1. Code Iterators - Query results are computed using a set of composable, interlocking iterators that alone perform a
/// simple task, but together execute complex queries. The iterators are actually little blocks of code
/// that are connected to each other using a series of jumps. Because each iterator is not instantiated
/// as a separate object, the number of objects and number of function calls is kept to a minimum during
/// execution. Also, large result sets are often computed incrementally, with each iterator performing one step in a
/// pipeline of sequence items.
///
/// 2. Analyzers - During code generation, QilToMsil traverses the semantic tree representation of the query (QIL) several times.
/// As visits to each node in the tree start and end, various Analyzers are invoked. These Analyzers incrementally
/// collect and store information that is later used to generate faster and smaller code.
/// </remarks>
internal class XmlILGenerator
{
private QilExpression _qil;
private GenerateHelper _helper;
private XmlILOptimizerVisitor _optVisitor;
private XmlILVisitor _xmlIlVisitor;
private XmlILModule _module;
/// <summary>
/// Always output debug information in debug mode.
/// </summary>
public XmlILGenerator()
{
}
/// <summary>
/// Given the logical query plan (QilExpression) generate a physical query plan (MSIL) that can be executed.
/// </summary>
// SxS Note: The way the trace file names are created (hardcoded) is NOT SxS safe. However the files are
// created only for internal tracing purposes. In addition XmlILTrace class is not compiled into retail
// builds. As a result it is fine to suppress the FxCop SxS warning.
public XmlILCommand Generate(QilExpression query, TypeBuilder typeBldr)
{
_qil = query;
bool useLRE = (
!_qil.IsDebug &&
(typeBldr == null)
#if DEBUG
&& !XmlILTrace.IsEnabled // Dump assembly to disk; can't do this when using LRE
#endif
);
bool emitSymbols = _qil.IsDebug;
// In debug code, ensure that input QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil before optimization
XmlILTrace.WriteQil(_qil, "qilbefore.xml");
// Trace optimizations
XmlILTrace.TraceOptimizations(_qil, "qilopt.xml");
#endif
// Optimize and annotate the Qil graph
_optVisitor = new XmlILOptimizerVisitor(_qil, !_qil.IsDebug);
_qil = _optVisitor.Optimize();
// In debug code, ensure that output QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil after optimization
XmlILTrace.WriteQil(_qil, "qilafter.xml");
#endif
// Create module in which methods will be generated
if (typeBldr != null)
{
_module = new XmlILModule(typeBldr);
}
else
{
_module = new XmlILModule(useLRE, emitSymbols);
}
// Create a code generation helper for the module; enable optimizations if IsDebug is false
_helper = new GenerateHelper(_module, _qil.IsDebug);
// Create helper methods
CreateHelperFunctions();
// Create metadata for the Execute function, which is the entry point to the query
// public static void Execute(XmlQueryRuntime);
MethodInfo methExec = _module.DefineMethod("Execute", typeof(void), new Type[] { }, new string[] { }, XmlILMethodAttributes.NonUser);
// Create metadata for the root expression
// public void Root()
Debug.Assert(_qil.Root != null);
XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine == null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
MethodInfo methRoot = _module.DefineMethod("Root", typeof(void), new Type[] { }, new string[] { }, methAttrs);
// Declare all early bound function objects
foreach (EarlyBoundInfo info in _qil.EarlyBoundTypes)
{
_helper.StaticData.DeclareEarlyBound(info.NamespaceUri, info.EarlyBoundType);
}
// Create metadata for each QilExpression function that has at least one caller
CreateFunctionMetadata(_qil.FunctionList);
// Create metadata for each QilExpression global variable and parameter
CreateGlobalValueMetadata(_qil.GlobalVariableList);
CreateGlobalValueMetadata(_qil.GlobalParameterList);
// Generate Execute method
GenerateExecuteFunction(methExec, methRoot);
// Visit the QilExpression graph
_xmlIlVisitor = new XmlILVisitor();
_xmlIlVisitor.Visit(_qil, _helper, methRoot);
// Collect all static information required by the runtime
XmlQueryStaticData staticData = new XmlQueryStaticData(
_qil.DefaultWriterSettings,
_qil.WhitespaceRules,
_helper.StaticData
);
// Create static constructor that initializes XmlQueryStaticData instance at runtime
if (typeBldr != null)
{
CreateTypeInitializer(staticData);
// Finish up creation of the type
_module.BakeMethods();
return null;
}
else
{
// Finish up creation of the type
_module.BakeMethods();
// Create delegate over "Execute" method
ExecuteDelegate delExec = (ExecuteDelegate)_module.CreateDelegate("Execute", typeof(ExecuteDelegate));
return new XmlILCommand(delExec, staticData);
}
}
/// <summary>
/// Create MethodBuilder metadata for the specified QilExpression function. Annotate ndFunc with the
/// MethodBuilder. Also, each QilExpression argument type should be converted to a corresponding Clr type.
/// Each argument QilExpression node should be annotated with the resulting ParameterBuilder.
/// </summary>
private void CreateFunctionMetadata(IList<QilNode> funcList)
{
MethodInfo methInfo;
Type[] paramTypes;
string[] paramNames;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilFunction ndFunc in funcList)
{
paramTypes = new Type[ndFunc.Arguments.Count];
paramNames = new string[ndFunc.Arguments.Count];
// Loop through all other parameters and save their types in the array
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
QilParameter ndParam = (QilParameter)ndFunc.Arguments[arg];
Debug.Assert(ndParam.NodeType == QilNodeType.Parameter);
// Get the type of each argument as a Clr type
paramTypes[arg] = XmlILTypeHelper.GetStorageType(ndParam.XmlType);
// Get the name of each argument
if (ndParam.DebugName != null)
paramNames[arg] = ndParam.DebugName;
}
// Get the type of the return value
if (XmlILConstructInfo.Read(ndFunc).PushToWriterLast)
{
// Push mode functions do not have a return value
typReturn = typeof(void);
}
else
{
// Pull mode functions have a return value
typReturn = XmlILTypeHelper.GetStorageType(ndFunc.XmlType);
}
// Create the method metadata
methAttrs = ndFunc.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndFunc.DebugName, typReturn, paramTypes, paramNames, methAttrs);
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
// Set location of parameter on Let node annotation
XmlILAnnotation.Write(ndFunc.Arguments[arg]).ArgumentPosition = arg;
}
// Annotate function with the MethodInfo
XmlILAnnotation.Write(ndFunc).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate metadata for a method that calculates a global value.
/// </summary>
private void CreateGlobalValueMetadata(IList<QilNode> globalList)
{
MethodInfo methInfo;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilReference ndRef in globalList)
{
// public T GlobalValue()
typReturn = XmlILTypeHelper.GetStorageType(ndRef.XmlType);
methAttrs = ndRef.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndRef.DebugName.ToString(), typReturn, new Type[] { }, new string[] { }, methAttrs);
// Annotate function with MethodBuilder
XmlILAnnotation.Write(ndRef).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate the "Execute" method, which is the entry point to the query.
/// </summary>
private MethodInfo GenerateExecuteFunction(MethodInfo methExec, MethodInfo methRoot)
{
_helper.MethodBegin(methExec, null, false);
// Force some or all global values to be evaluated at start of query
EvaluateGlobalValues(_qil.GlobalVariableList);
EvaluateGlobalValues(_qil.GlobalParameterList);
// Root(runtime);
_helper.LoadQueryRuntime();
_helper.Call(methRoot);
_helper.MethodEnd();
return methExec;
}
/// <summary>
/// Create and generate various helper methods, which are called by the generated code.
/// </summary>
private void CreateHelperFunctions()
{
MethodInfo meth;
Label lblClone;
// public static XPathNavigator SyncToNavigator(XPathNavigator, XPathNavigator);
meth = _module.DefineMethod(
"SyncToNavigator",
typeof(XPathNavigator),
new Type[] { typeof(XPathNavigator), typeof(XPathNavigator) },
new string[] { null, null },
XmlILMethodAttributes.NonUser | XmlILMethodAttributes.Raw);
_helper.MethodBegin(meth, null, false);
// if (navigatorThis != null && navigatorThis.MoveTo(navigatorThat))
// return navigatorThis;
lblClone = _helper.DefineLabel();
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavMoveTo);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ret);
// LabelClone:
// return navigatorThat.Clone();
_helper.MarkLabel(lblClone);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavClone);
_helper.MethodEnd();
}
/// <summary>
/// Generate code to force evaluation of some or all global variables and/or parameters.
/// </summary>
private void EvaluateGlobalValues(IList<QilNode> iterList)
{
MethodInfo methInfo;
foreach (QilIterator ndIter in iterList)
{
// Evaluate global if generating debug code, or if global might have side effects
if (_qil.IsDebug || OptimizerPatterns.Read(ndIter).MatchesPattern(OptimizerPatternName.MaybeSideEffects))
{
// Get MethodInfo that evaluates the global value and discard its return value
methInfo = XmlILAnnotation.Write(ndIter).FunctionBinding;
Debug.Assert(methInfo != null, "MethodInfo for global value should have been created previously.");
_helper.LoadQueryRuntime();
_helper.Call(methInfo);
_helper.Emit(OpCodes.Pop);
}
}
}
/// <summary>
/// Create static constructor that initializes XmlQueryStaticData instance at runtime.
/// </summary>
public void CreateTypeInitializer(XmlQueryStaticData staticData)
{
byte[] data;
Type[] ebTypes;
FieldInfo fldInitData, fldData, fldTypes;
ConstructorInfo cctor;
staticData.GetObjectData(out data, out ebTypes);
fldInitData = _module.DefineInitializedData("__" + XmlQueryStaticData.DataFieldName, data);
fldData = _module.DefineField(XmlQueryStaticData.DataFieldName, typeof(object));
fldTypes = _module.DefineField(XmlQueryStaticData.TypesFieldName, typeof(Type[]));
cctor = _module.DefineTypeInitializer();
_helper.MethodBegin(cctor, null, false);
// s_data = new byte[s_initData.Length] { s_initData };
_helper.LoadInteger(data.Length);
_helper.Emit(OpCodes.Newarr, typeof(byte));
_helper.Emit(OpCodes.Dup);
_helper.Emit(OpCodes.Ldtoken, fldInitData);
_helper.Call(XmlILMethods.InitializeArray);
_helper.Emit(OpCodes.Stsfld, fldData);
if (ebTypes != null)
{
// Type[] types = new Type[s_ebTypes.Length];
LocalBuilder locTypes = _helper.DeclareLocal("$$$types", typeof(Type[]));
_helper.LoadInteger(ebTypes.Length);
_helper.Emit(OpCodes.Newarr, typeof(Type));
_helper.Emit(OpCodes.Stloc, locTypes);
for (int idx = 0; idx < ebTypes.Length; idx++)
{
// types[idx] = ebTypes[idx];
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.LoadInteger(idx);
_helper.LoadType(ebTypes[idx]);
_helper.Emit(OpCodes.Stelem_Ref);
}
// s_types = types;
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.Emit(OpCodes.Stsfld, fldTypes);
}
_helper.MethodEnd();
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
using DebugCallback = Interop.Http.DebugCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
internal Uri _targetUri;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
_targetUri = requestMessage.RequestUri;
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetMultithreading();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetCredentials(_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
// If the response message hasn't been published yet, do any final processing of it before it is.
if (!Task.IsCompleted)
{
// On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length
// headers are removed from the response. Do the same thing here.
DecompressionMethods dm = _handler.AutomaticDecompression;
if (dm != DecompressionMethods.None)
{
HttpContentHeaders contentHeaders = _responseMessage.Content.Headers;
IEnumerable<string> encodings;
if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings))
{
foreach (string encoding in encodings)
{
if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) ||
((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase)))
{
contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding);
contentHeaders.Remove(HttpKnownHeaderNames.ContentLength);
break;
}
}
}
}
}
// Now ensure it's published.
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
if (_callbackHandle != null)
_callbackHandle.Dispose();
}
private void SetUrl()
{
EventSourceTrace("Url: {0}", _requestMessage.RequestUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
EventSourceTrace("HTTP version: {0}", v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
EventSourceTrace("Unsupported protocol: {0}", v);
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
EventSourceTrace<string>("Encoding: {0}", encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (!_handler._useProxy)
{
// Explicitly disable the use of a proxy. This will prevent libcurl from using
// any proxy, including ones set via environment variable.
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("UseProxy false, disabling proxy");
return;
}
if (_handler.Proxy == null)
{
// UseProxy was true, but Proxy was null. Let libcurl do its default handling,
// which includes checking the http_proxy environment variable.
EventSourceTrace("UseProxy true, Proxy null, using default proxy");
return;
}
// Custom proxy specified.
Uri proxyUri;
try
{
// Should we bypass a proxy for this URI?
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy");
return;
}
// Get the proxy Uri for this request.
proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
EventSourceTrace("GetProxy returned null, using default.");
return;
}
}
catch (PlatformNotSupportedException)
{
// WebRequest.DefaultWebProxy throws PlatformNotSupportedException,
// in which case we should use the default rather than the custom proxy.
EventSourceTrace("PlatformNotSupportedException from proxy, using default");
return;
}
// Configure libcurl with the gathered proxy information
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
EventSourceTrace("Proxy: {0}", proxyUri);
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(_requestMessage.RequestUri, _handler.Proxy.Credentials, AuthTypesPermittedByCredentialKind(_handler.Proxy.Credentials));
NetworkCredential credentials = credentialScheme.Key;
if (credentials == CredentialCache.DefaultCredentials)
{
// No "default credentials" on Unix; nop just like UseDefaultCredentials.
EventSourceTrace("Default proxy credentials. Skipping.");
}
else if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
EventSourceTrace("Proxy credentials set.");
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
EventSourceTrace("Credentials set.");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
EventSourceTrace<string>("Cookies: {0}", cookieValues);
}
}
internal void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSListHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.Http.SListAppend(slist, NoContentType))
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.Http.SListAppend(slist, NoTransferEncoding))
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback,
DebugCallback debugCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
if (EventSourceTracingEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
_easyHandle,
debugCallback,
easyGCHandle,
ref _callbackHandle);
if (curlResult != CURLcode.CURLE_OK)
{
EventSourceTrace("Failed to register debug callback.");
}
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
if (!Interop.Http.SListAppend(handle, headerKeyAndValue))
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
internal void SetRedirectUri(Uri redirectUri)
{
_targetUri = _requestMessage.RequestUri;
_requestMessage.RequestUri = redirectUri;
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName);
}
private void EventSourceTrace(string message, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName);
}
}
}
}
| |
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
using MIVSDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.Threading.Tasks;
namespace MIVServer
{
public class Server
{
public static Server instance;
public ServerApi api;
public ServerChat chat;
public INIReader config;
public List<ServerPlayer> playerpool;
public ServerVehicleController vehicleController;
private GamemodeManager gamemodeManager;
private HTTPServer http_server;
private TcpListener server;
public int UDPStartPort;
public Server()
{
config = new INIReader(System.IO.File.ReadAllLines("config.ini"));
chat = new ServerChat();
instance = this;
vehicleController = new ServerVehicleController();
api = new ServerApi(this);
gamemodeManager = new GamemodeManager(api);
gamemodeManager.loadFromFile("gamemodes/" + config.getString("gamemode"));
server = new TcpListener(IPAddress.Any, config.getInt("game_port"));
server.Start();
server.BeginAcceptTcpClient(onIncomingConnection, null);
playerpool = new List<ServerPlayer>();
Timer timer = new Timer();
timer.Elapsed += onBroadcastTimer;
timer.Interval = config.getInt("broadcast_interval");
timer.Enabled = true;
timer.Start();
UDPStartPort = config.getInt("udp_start_port");
Timer timer_slow = new Timer();
timer_slow.Elapsed += timer_slow_Elapsed;
timer_slow.Interval = config.getInt("slow_interval");
timer_slow.Enabled = true;
timer_slow.Start();
http_server = new HTTPServer();
Console.WriteLine("Started game server on port " + config.getInt("game_port").ToString());
Console.WriteLine("Started http server on port " + config.getInt("http_port").ToString());
}
public void broadcastData(ServerPlayer player)
{
if (player.data.client_has_been_set) return;
else player.data.client_has_been_set = true;
try
{
if (player.data != null)
{
InvokeParallelForEachPlayer((single) =>
{
if (single.id != player.id)
{
var bpf = new BinaryPacketFormatter(Commands.UpdateData);
bpf.Add(player.id);
bpf.Add(player.data);
single.connection.write(bpf.getBytes());
//Console.WriteLine("Streaming to Player " + single.Value.nick);
}
});
}
}
catch (Exception e) { Console.WriteLine(e); }
}
public void broadcastNPCsToPlayer(ServerPlayer player)
{
foreach (var pair in ServerNPC.NPCPool)
{
var bpf = new BinaryPacketFormatter(Commands.NPC_create);
bpf.Add(pair.Value.id);
bpf.Add(pair.Value.Position);
bpf.Add(pair.Value.Heading);
bpf.Add(pair.Value.Model);
bpf.Add(pair.Value.Name);
player.connection.write(bpf.getBytes());
}
}
public void broadcastPlayerModel(ServerPlayer player)
{
InvokeParallelForEachPlayer((single) =>
{
if (single != player)
{
var bpf = new BinaryPacketFormatter(Commands.Global_setPlayerModel);
bpf.Add(player.id);
bpf.Add(ModelDictionary.getPedModelByName(player.Model));
single.connection.write(bpf.getBytes());
}
});
}
public void broadcastPlayerName(ServerPlayer player)
{
InvokeParallelForEachPlayer((single) =>
{
if (single != player)
{
var bpf = new BinaryPacketFormatter(Commands.Global_setPlayerName);
bpf.Add(player.id);
bpf.Add(player.Nick);
single.connection.write(bpf.getBytes());
}
});
}
public void broadcastVehiclesToPlayer(ServerPlayer player)
{
foreach (var pair in vehicleController.vehicles)
{
var bpf = new BinaryPacketFormatter(Commands.Vehicle_create);
bpf.Add(pair.Value.id);
bpf.Add(pair.Value.position);
bpf.Add(pair.Value.orientation);
bpf.Add(ModelDictionary.getVehicleByName(pair.Value.model));
player.connection.write(bpf.getBytes());
}
}
public ServerPlayer getPlayerById(uint id)
{
try
{
return playerpool.First(a => a.id == id);
}
catch
{
return null;
}
}
public void updateNPCsToPlayer(ServerPlayer player)
{
foreach (var pair in ServerNPC.NPCPool)
{
var bpf = new BinaryPacketFormatter(Commands.NPC_update);
bpf.Add(pair.Value.id);
bpf.Add(pair.Value.Position);
bpf.Add(pair.Value.Heading);
bpf.Add(pair.Value.Model);
bpf.Add(pair.Value.Name);
player.connection.write(bpf.getBytes());
}
}
private byte findLowestFreeId()
{
for (byte i = 0; i < byte.MaxValue; i++)
{
if (playerpool.Count(a => a.id == i) == 0) return i;
}
throw new Exception("No free ids");
}
private void onBroadcastTimer(object sender, ElapsedEventArgs e)
{
string currentMessage;
while ((currentMessage = chat.dequeue()) != null)
{
string message = currentMessage;
InvokeParallelForEachPlayer((player) =>
{
var bpf = new BinaryPacketFormatter(Commands.Chat_writeLine);
bpf.Add(message);
player.connection.write(bpf.getBytes());
});
}
InvokeParallelForEachPlayer((player) =>
{
player.connection.flush();
player.udpTunnel.broadcastPlayers();
});
}
public void InvokeParallelForEachPlayer(Action<ServerPlayer> action)
{
if (playerpool == null || playerpool.Count == 0) return;
for (int i = 0; i < playerpool.Count; i++)
{
/*
ServerPlayer Player = playerpool[i];
new Task(() =>
{
lock (Player)
{
action.Invoke(Player);
}
}).Start();
*/
action.Invoke(playerpool[i]);
}
}
private void onIncomingConnection(IAsyncResult iar)
{
Console.WriteLine("Connecting");
TcpClient client = server.EndAcceptTcpClient(iar);
server.BeginAcceptTcpClient(onIncomingConnection, null);
ClientConnection connection = new ClientConnection(client);
connection.OnConnect += delegate(string nick)
{
if (playerpool.Count >= config.getInt("max_players"))
{
Console.WriteLine("Connection from " + nick + " rejected due to Player limit");
client.Close();
return;
}
Console.WriteLine("Connect from " + nick);
uint id = findLowestFreeId();
ServerPlayer player = new ServerPlayer(id, nick, connection);
connection.SetPlayer(player);
InvokeParallelForEachPlayer((p) =>
{
player.connection.write(
new BinaryPacketFormatter(Commands.Global_createPlayer, p.id, ModelDictionary.getPedModelByName(p.Model), p.Nick)
.getBytes());
p.connection.write(
new BinaryPacketFormatter(Commands.Global_createPlayer, player.id, ModelDictionary.getPedModelByName("M_Y_SWAT"), nick)
.getBytes());
});
player.Nick = nick;
player.Model = "M_Y_SWAT";
playerpool.Add(player);
broadcastVehiclesToPlayer(player);
broadcastNPCsToPlayer(player);
//broadcastPlayerName(Player);
//broadcastPlayerModel(Player);
api.invokeOnPlayerConnect(client.Client.RemoteEndPoint, player);
api.invokeOnPlayerSpawn(player);
var starter = new BinaryPacketFormatter(Commands.Client_resumeBroadcast);
connection.write(starter.getBytes());
connection.write(new BinaryPacketFormatter(Commands.Client_enableUDPTunnel, player.udpTunnel.getPort()).getBytes());
connection.flush();
};
connection.startReceiving();
}
private void timer_slow_Elapsed(object sender, ElapsedEventArgs e)
{
InvokeParallelForEachPlayer((player) =>
{
updateNPCsToPlayer(player);
});
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Client.Cache
{
using System.Linq;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Impl.Client.Cache;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Tests.Cache;
using NUnit.Framework;
/// <summary>
/// Tests dynamic cache start from client nodes.
/// </summary>
public class CreateCacheTest : ClientTestBase
{
/** Template cache name. */
private const string TemplateCacheName = "template-cache-*";
/// <summary>
/// Tears down the test.
/// </summary>
[TearDown]
public void TearDown()
{
DestroyCaches();
}
/// <summary>
/// Destroys caches.
/// </summary>
private void DestroyCaches()
{
foreach (var cacheName in Client.GetCacheNames())
{
Client.DestroyCache(cacheName);
}
}
/// <summary>
/// Tests the GetCacheNames.
/// </summary>
[Test]
public void TestGetCacheNames()
{
DestroyCaches();
Assert.AreEqual(0, Client.GetCacheNames().Count);
Client.CreateCache<int, int>("a");
Assert.AreEqual("a", Client.GetCacheNames().Single());
Client.CreateCache<int, int>("b");
Assert.AreEqual(new[] {"a", "b"}, Client.GetCacheNames().OrderBy(x => x).ToArray());
Client.DestroyCache("a");
Assert.AreEqual("b", Client.GetCacheNames().Single());
}
/// <summary>
/// Tests create from template.
/// </summary>
[Test]
public void TestCreateFromTemplate()
{
// No template: default configuration.
var cache = Client.CreateCache<int, int>("foobar");
AssertExtensions.ReflectionEqual(new CacheClientConfiguration("foobar"), cache.GetConfiguration());
// Create when exists.
var ex = Assert.Throws<IgniteClientException>(() => Client.CreateCache<int, int>(cache.Name));
Assert.AreEqual(
"Failed to start cache (a cache with the same name is already started): foobar", ex.Message);
Assert.AreEqual(ClientStatusCode.CacheExists, ex.StatusCode);
// Template: custom configuration.
cache = Client.CreateCache<int, int>(TemplateCacheName.Replace("*", "1"));
var cfg = cache.GetConfiguration();
Assert.AreEqual(CacheAtomicityMode.Transactional, cfg.AtomicityMode);
Assert.AreEqual(3, cfg.Backups);
Assert.AreEqual(CacheMode.Partitioned, cfg.CacheMode);
}
/// <summary>
/// Tests getOrCreate from template.
/// </summary>
[Test]
public void TestGetOrCreateFromTemplate()
{
// No template: default configuration.
var cache = Client.GetOrCreateCache<int, int>("foobar");
AssertExtensions.ReflectionEqual(new CacheClientConfiguration { Name = "foobar"}, cache.GetConfiguration());
cache[1] = 1;
// Create when exists.
cache = Client.GetOrCreateCache<int, int>("foobar");
Assert.AreEqual(1, cache[1]);
// Template: custom configuration.
cache = Client.GetOrCreateCache<int, int>(TemplateCacheName.Replace("*", "1"));
var cfg = cache.GetConfiguration();
Assert.AreEqual(CacheAtomicityMode.Transactional, cfg.AtomicityMode);
Assert.AreEqual(3, cfg.Backups);
Assert.AreEqual(CacheMode.Partitioned, cfg.CacheMode);
// Create when exists.
cache[1] = 1;
cache = Client.GetOrCreateCache<int, int>(cache.Name);
Assert.AreEqual(1, cache[1]);
}
/// <summary>
/// Tests cache creation from configuration.
/// </summary>
[Test]
public void TestCreateFromConfiguration()
{
// Default config.
var cfg = new CacheClientConfiguration("a");
var cache = Client.CreateCache<int, int>(cfg);
AssertExtensions.ReflectionEqual(cfg, cache.GetConfiguration());
// Create when exists.
var ex = Assert.Throws<IgniteClientException>(() => Client.CreateCache<int, int>(cfg));
Assert.AreEqual(
"Failed to start cache (a cache with the same name is already started): a", ex.Message);
Assert.AreEqual(ClientStatusCode.CacheExists, ex.StatusCode);
// Custom config.
cfg = GetFullCacheConfiguration("b");
cache = Client.CreateCache<int, int>(cfg);
AssertClientConfigsAreEqual(cfg, cache.GetConfiguration());
}
/// <summary>
/// Tests cache creation from partial configuration.
/// </summary>
[Test]
public void TestCreateFromPartialConfiguration()
{
// Default config.
var cfg = new CacheClientConfiguration("a") {Backups = 7};
var client = (IgniteClient) Client;
// Create cache directly through a socket with only some config properties provided.
client.Socket.DoOutInOp<object>(ClientOp.CacheCreateWithConfiguration, s =>
{
var w = client.Marshaller.StartMarshal(s);
w.WriteInt(2 + 2 + 6 + 2 + 4); // config length in bytes.
w.WriteShort(2); // 2 properties.
w.WriteShort(3); // backups opcode.
w.WriteInt(cfg.Backups);
w.WriteShort(0); // name opcode.
w.WriteString(cfg.Name);
}, null);
var cache = new CacheClient<int, int>(client, cfg.Name);
AssertExtensions.ReflectionEqual(cfg, cache.GetConfiguration());
}
/// <summary>
/// Tests cache creation from configuration.
/// </summary>
[Test]
public void TestGetOrCreateFromConfiguration()
{
// Default configur.
var cfg = new CacheClientConfiguration("a");
var cache = Client.GetOrCreateCache<int, int>(cfg);
AssertExtensions.ReflectionEqual(cfg, cache.GetConfiguration());
cache[1] = 1;
// Create when exists.
cache = Client.GetOrCreateCache<int, int>("a");
Assert.AreEqual(1, cache[1]);
// Custom config.
cfg = GetFullCacheConfiguration("b");
cache = Client.GetOrCreateCache<int, int>(cfg);
AssertClientConfigsAreEqual(cfg, cache.GetConfiguration());
}
/// <summary>
/// Gets the full cache configuration.
/// </summary>
private static CacheClientConfiguration GetFullCacheConfiguration(string name)
{
return new CacheClientConfiguration(CacheConfigurationTest.GetCustomCacheConfiguration(name), true);
}
/** <inheritdoc /> */
protected override IgniteConfiguration GetIgniteConfiguration()
{
return new IgniteConfiguration(base.GetIgniteConfiguration())
{
CacheConfiguration = new[]
{
new CacheConfiguration(TemplateCacheName)
{
AtomicityMode = CacheAtomicityMode.Transactional,
Backups = 3
}
},
DataStorageConfiguration = new DataStorageConfiguration
{
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "myMemPolicy"
}
}
}
};
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module Android Native Plugin for Unity3D
// @author Osipov Stanislav (Stan's Assets)
// @support stans.assets@gmail.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
public class AndroidGoogleAdsExample_old : MonoBehaviour {
//replace with your ids
private const string MY_BANNERS_AD_UNIT_ID = "ca-app-pub-6101605888755494/1824764765";
private const string MY_INTERSTISIALS_AD_UNIT_ID = "ca-app-pub-6101605888755494/3301497967";
private GUIStyle style;
private GUIStyle style2;
private GoogleMobileAdBanner banner1;
private GoogleMobileAdBanner banner2;
private bool IsInterstisialsAdReady = false;
//--------------------------------------
// INITIALIZE
//--------------------------------------
void Start() {
AndroidAdMobController.Instance.Init(MY_BANNERS_AD_UNIT_ID);
//I whant to use Interstisial ad also, so I have to set additional id for it
AndroidAdMobController.Instance.SetInterstisialsUnitID(MY_INTERSTISIALS_AD_UNIT_ID);
//Optional, add data for better ad targeting
AndroidAdMobController.Instance.SetGender(GoogleGender.Male);
AndroidAdMobController.Instance.AddKeyword("game");
AndroidAdMobController.Instance.SetBirthday(1989, AndroidMonth.MARCH, 18);
AndroidAdMobController.Instance.TagForChildDirectedTreatment(false);
//Causes a device to receive test ads. The deviceId can be obtained by viewing the logcat output after creating a new ad
AndroidAdMobController.Instance.AddTestDevice("6B9FA8031AEFDC4758B7D8987F77A5A6");
AndroidAdMobController.Instance.OnInterstitialLoaded += OnInterstisialsLoaded;
AndroidAdMobController.Instance.OnInterstitialOpened += OnInterstisialsOpen;
InitStyles();
}
private void InitStyles () {
style = new GUIStyle();
style.normal.textColor = Color.white;
style.fontSize = 16;
style.fontStyle = FontStyle.BoldAndItalic;
style.alignment = TextAnchor.UpperLeft;
style.wordWrap = true;
style2 = new GUIStyle();
style2.normal.textColor = Color.white;
style2.fontSize = 12;
style2.fontStyle = FontStyle.Italic;
style2.alignment = TextAnchor.UpperLeft;
style2.wordWrap = true;
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
void OnGUI() {
float StartY = 20;
float StartX = 10;
GUI.Label(new Rect(StartX, StartY, Screen.width, 40), "Interstisal Example", style);
StartY+= 40;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Start Interstitial Ad")) {
AndroidAdMobController.Instance.StartInterstitialAd ();
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Load Interstitial Ad")) {
AndroidAdMobController.Instance.LoadInterstitialAd ();
}
StartX += 170;
GUI.enabled = IsInterstisialsAdReady;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Show Interstitial Ad")) {
AndroidAdMobController.Instance.ShowInterstitialAd ();
}
GUI.enabled = true;
StartY+= 80;
StartX = 10;
GUI.Label(new Rect(StartX, StartY, Screen.width, 40), "Banners Example", style);
GUI.enabled = false;
if(banner1 == null) {
GUI.enabled = true;
}
StartY+= 40;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Custom Pos")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(300, 100, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Top Left")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.UpperLeft, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Top Center")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.UpperCenter, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Top Right")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.UpperRight, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Bottom Left")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.LowerLeft, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Bottom Center")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.LowerCenter, GADBannerSize.BANNER);
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Banner Bottom Right")) {
banner1 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.LowerRight, GADBannerSize.BANNER);
}
GUI.enabled = false;
if(banner1 != null) {
if(banner1.IsLoaded) {
GUI.enabled = true;
}
}
StartY+= 80;
StartX = 10;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Refresh")) {
banner1.Refresh();
}
GUI.enabled = false;
if(banner1 != null) {
if(banner1.IsLoaded && banner1.IsOnScreen) {
GUI.enabled = true;
}
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Hide")) {
banner1.Hide();
}
GUI.enabled = false;
if(banner1 != null) {
if(banner1.IsLoaded && !banner1.IsOnScreen) {
GUI.enabled = true;
}
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Show")) {
banner1.Show();
}
GUI.enabled = false;
if(banner1 != null) {
GUI.enabled = true;
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Destroy")) {
AndroidAdMobController.Instance.DestroyBanner(banner1.id);
banner1 = null;
}
GUI.enabled = true;
StartY+= 80;
StartX = 10;
GUI.Label(new Rect(StartX, StartY, Screen.width, 40), "Banner 2", style);
GUI.enabled = false;
if(banner2 == null) {
GUI.enabled = true;
}
StartY+= 40;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Smart Banner")) {
banner2 = AndroidAdMobController.Instance.CreateAdBanner(TextAnchor.LowerLeft, GADBannerSize.SMART_BANNER);
}
GUI.enabled = false;
if(banner2 != null) {
if(banner2.IsLoaded) {
GUI.enabled = true;
}
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Refresh")) {
banner2.Refresh();
}
GUI.enabled = false;
if(banner2 != null) {
if(banner2.IsLoaded && banner2.IsOnScreen) {
GUI.enabled = true;
}
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Hide")) {
banner2.Hide();
}
GUI.enabled = false;
if(banner2 != null) {
if(banner2.IsLoaded && !banner2.IsOnScreen) {
GUI.enabled = true;
}
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Show")) {
banner2.Show();
}
GUI.enabled = false;
if(banner2 != null) {
GUI.enabled = true;
}
StartX += 170;
if(GUI.Button(new Rect(StartX, StartY, 150, 50), "Destroy")) {
AndroidAdMobController.Instance.DestroyBanner(banner2.id);
banner2 = null;
}
GUI.enabled = true;
}
//--------------------------------------
// GET/SET
//--------------------------------------
//--------------------------------------
// EVENTS
//--------------------------------------
private void OnInterstisialsLoaded() {
IsInterstisialsAdReady = true;
}
private void OnInterstisialsOpen() {
IsInterstisialsAdReady = false;
}
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
//--------------------------------------
// DESTROY
//--------------------------------------
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessTests : ProcessTestBase
{
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public void TestUseShellExecute_Unix_Succeeds()
{
using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
{
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(42, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect.");
}
[Fact]
public void TestId()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact, PlatformSpecific(~PlatformID.OSX)]
public void TestMainModuleOnNonOSX()
{
string fileName = "corerun";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
fileName = "CoreRun.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr addr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[ActiveIssue(3281, PlatformID.OSX)]
[Fact]
public void TestWorkingSet64()
{
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact, ActiveIssue(3037)]
public void TestProcessStartTime()
{
DateTime timeBeforeCreatingProcess = DateTime.UtcNow;
Process p = CreateProcessLong();
Assert.Throws<InvalidOperationException>(() => p.StartTime);
try
{
p.Start();
// Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time.
// Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will
// be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms.
// On Windows, timer resolution is 15 ms from MSDN DateTime.Now. Hence, allowing error in 15ms [max(10,15)].
long intervalTicks = new TimeSpan(0, 0, 0, 0, 15).Ticks;
long beforeTicks = timeBeforeCreatingProcess.Ticks - intervalTicks;
try
{
// Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started.
Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id);
long startTicks = p.StartTime.ToUniversalTime().Ticks;
long afterTicks = DateTime.UtcNow.Ticks + intervalTicks;
Assert.InRange(startTicks, beforeTicks, afterTicks);
}
catch (InvalidOperationException)
{
Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks);
}
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void TestProcessName()
{
Assert.Equal(_process.ProcessName, HostRunner, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
}
else
{
sessionId = (uint)Interop.getsid(_process.Id);
}
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
Interop.GetCurrentProcessId() :
Interop.getpid();
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void TestGetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed");
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
[Theory, PlatformSpecific(PlatformID.Windows)]
[MemberData("GetTestProcess")]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessLong();
process.Start();
Assert.Equal(HostRunner, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessLong();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestConsoleApp);
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Utilities.IO;
namespace Org.BouncyCastle.Asn1
{
/**
* a general purpose ASN.1 decoder - note: this class differs from the
* others in that it returns null after it has read the last object in
* the stream. If an ASN.1 Null is encountered a Der/BER Null object is
* returned.
*/
public class Asn1InputStream
: FilterStream
{
private readonly int limit;
internal static int FindLimit(Stream input)
{
if (input is LimitedInputStream)
{
return ((LimitedInputStream)input).GetRemaining();
}
else if (input is MemoryStream)
{
MemoryStream mem = (MemoryStream)input;
return (int)(mem.Length - mem.Position);
}
return int.MaxValue;
}
public Asn1InputStream(
Stream inputStream)
: this(inputStream, FindLimit(inputStream))
{
}
/**
* Create an ASN1InputStream where no DER object will be longer than limit.
*
* @param input stream containing ASN.1 encoded data.
* @param limit maximum size of a DER encoded object.
*/
public Asn1InputStream(
Stream inputStream,
int limit)
: base(inputStream)
{
this.limit = limit;
}
/**
* Create an ASN1InputStream based on the input byte array. The length of DER objects in
* the stream is automatically limited to the length of the input array.
*
* @param input array containing ASN.1 encoded data.
*/
public Asn1InputStream(
byte[] input)
: this(new MemoryStream(input, false), input.Length)
{
}
/**
* build an object given its tag and the number of bytes to construct it from.
*/
private Asn1Object BuildObject(
int tag,
int tagNo,
int length)
{
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length);
if ((tag & Asn1Tags.Application) != 0)
{
return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new Asn1StreamParser(defIn).ReadTaggedObject(isConstructed, tagNo);
}
if (isConstructed)
{
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
//
// yes, people actually do this...
//
return new BerOctetString(BuildDerEncodableVector(defIn));
case Asn1Tags.Sequence:
return CreateDerSequence(defIn);
case Asn1Tags.Set:
return CreateDerSet(defIn);
case Asn1Tags.External:
return new DerExternal(BuildDerEncodableVector(defIn));
default:
return new DerUnknownTag(true, tagNo, defIn.ToArray());
}
}
return CreatePrimitiveDerObject(tagNo, defIn.ToArray());
}
internal Asn1EncodableVector BuildEncodableVector()
{
Asn1EncodableVector v = new Asn1EncodableVector();
Asn1Object o;
while ((o = ReadObject()) != null)
{
v.Add(o);
}
return v;
}
internal virtual Asn1EncodableVector BuildDerEncodableVector(
DefiniteLengthInputStream dIn)
{
return new Asn1InputStream(dIn).BuildEncodableVector();
}
internal virtual DerSequence CreateDerSequence(
DefiniteLengthInputStream dIn)
{
return DerSequence.FromVector(BuildDerEncodableVector(dIn));
}
internal virtual DerSet CreateDerSet(
DefiniteLengthInputStream dIn)
{
return DerSet.FromVector(BuildDerEncodableVector(dIn), false);
}
public Asn1Object ReadObject()
{
int tag = ReadByte();
if (tag <= 0)
{
if (tag == 0)
throw new IOException("unexpected end-of-contents marker");
return null;
}
//
// calculate tag number
//
int tagNo = ReadTagNumber(this, tag);
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
//
// calculate length
//
int length = ReadLength(this, limit);
if (length < 0) // indefinite length method
{
if (!isConstructed)
throw new IOException("indefinite length primitive encoding encountered");
IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this, limit);
Asn1StreamParser sp = new Asn1StreamParser(indIn, limit);
if ((tag & Asn1Tags.Application) != 0)
{
return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object();
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object();
}
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
return new BerOctetStringParser(sp).ToAsn1Object();
case Asn1Tags.Sequence:
return new BerSequenceParser(sp).ToAsn1Object();
case Asn1Tags.Set:
return new BerSetParser(sp).ToAsn1Object();
case Asn1Tags.External:
return new DerExternalParser(sp).ToAsn1Object();
default:
throw new IOException("unknown BER object encountered");
}
}
else
{
try
{
return BuildObject(tag, tagNo, length);
}
catch (ArgumentException e)
{
throw new Asn1Exception("corrupted stream detected", e);
}
}
}
internal static int ReadTagNumber(
Stream s,
int tag)
{
int tagNo = tag & 0x1f;
//
// with tagged object tag number is bottom 5 bits, or stored at the start of the content
//
if (tagNo == 0x1f)
{
tagNo = 0;
int b = s.ReadByte();
// X.690-0207 8.1.2.4.2
// "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
if ((b & 0x7f) == 0) // Note: -1 will pass
{
throw new IOException("Corrupted stream - invalid high tag number found");
}
while ((b >= 0) && ((b & 0x80) != 0))
{
tagNo |= (b & 0x7f);
tagNo <<= 7;
b = s.ReadByte();
}
if (b < 0)
throw new EndOfStreamException("EOF found inside tag value.");
tagNo |= (b & 0x7f);
}
return tagNo;
}
internal static int ReadLength(
Stream s,
int limit)
{
int length = s.ReadByte();
if (length < 0)
throw new EndOfStreamException("EOF found when length expected");
if (length == 0x80)
return -1; // indefinite-length encoding
if (length > 127)
{
int size = length & 0x7f;
// Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
if (size > 4)
throw new IOException("DER length more than 4 bytes: " + size);
length = 0;
for (int i = 0; i < size; i++)
{
int next = s.ReadByte();
if (next < 0)
throw new EndOfStreamException("EOF found reading length");
length = (length << 8) + next;
}
if (length < 0)
throw new IOException("Corrupted stream - negative length found");
if (length >= limit) // after all we must have read at least 1 byte
throw new IOException("Corrupted stream - out of bounds length found");
}
return length;
}
internal static Asn1Object CreatePrimitiveDerObject(
int tagNo,
byte[] bytes)
{
switch (tagNo)
{
case Asn1Tags.BitString:
return DerBitString.FromAsn1Octets(bytes);
case Asn1Tags.BmpString:
return new DerBmpString(bytes);
case Asn1Tags.Boolean:
return new DerBoolean(bytes);
case Asn1Tags.Enumerated:
return new DerEnumerated(bytes);
case Asn1Tags.GeneralizedTime:
return new DerGeneralizedTime(bytes);
case Asn1Tags.GeneralString:
return new DerGeneralString(bytes);
case Asn1Tags.IA5String:
return new DerIA5String(bytes);
case Asn1Tags.Integer:
return new DerInteger(bytes);
case Asn1Tags.Null:
return DerNull.Instance; // actual content is ignored (enforce 0 length?)
case Asn1Tags.NumericString:
return new DerNumericString(bytes);
case Asn1Tags.ObjectIdentifier:
return new DerObjectIdentifier(bytes);
case Asn1Tags.OctetString:
return new DerOctetString(bytes);
case Asn1Tags.PrintableString:
return new DerPrintableString(bytes);
case Asn1Tags.T61String:
return new DerT61String(bytes);
case Asn1Tags.UniversalString:
return new DerUniversalString(bytes);
case Asn1Tags.UtcTime:
return new DerUtcTime(bytes);
case Asn1Tags.Utf8String:
return new DerUtf8String(bytes);
case Asn1Tags.VisibleString:
return new DerVisibleString(bytes);
default:
return new DerUnknownTag(false, tagNo, bytes);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Apress.Recipes.WebApi.Areas.HelpPage.Models;
namespace Apress.Recipes.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kohei TAKETA <k-tak@void.in> (Java port)
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using System;
/// <summary>
/// Escaped charsets state machines
/// </summary>
namespace Ude.Core
{
public class HZSMModel : SMModel
{
private readonly static int[] HZ_cls = {
BitPackage.Pack4bits(1,0,0,0,0,0,0,0), // 00 - 07
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 08 - 0f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17
BitPackage.Pack4bits(0,0,0,1,0,0,0,0), // 18 - 1f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 20 - 27
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 28 - 2f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 40 - 47
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 48 - 4f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77
BitPackage.Pack4bits(0,0,0,4,0,5,2,0), // 78 - 7f
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 80 - 87
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 88 - 8f
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 90 - 97
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 98 - 9f
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // a0 - a7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // a8 - af
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // b0 - b7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // b8 - bf
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // c0 - c7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // c8 - cf
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // d0 - d7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // d8 - df
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // e0 - e7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // e8 - ef
BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // f0 - f7
BitPackage.Pack4bits(1,1,1,1,1,1,1,1) // f8 - ff
};
private readonly static int[] HZ_st = {
BitPackage.Pack4bits(START, ERROR, 3, START, START, START, ERROR, ERROR),//00-07
BitPackage.Pack4bits(ERROR, ERROR, ERROR, ERROR, ITSME, ITSME, ITSME, ITSME),//08-0f
BitPackage.Pack4bits(ITSME, ITSME, ERROR, ERROR, START, START, 4, ERROR),//10-17
BitPackage.Pack4bits( 5, ERROR, 6, ERROR, 5, 5, 4, ERROR),//18-1f
BitPackage.Pack4bits( 4, ERROR, 4, 4, 4, ERROR, 4, ERROR),//20-27
BitPackage.Pack4bits( 4, ITSME, START, START, START, START, START, START) //28-2f
};
private readonly static int[] HZCharLenTable = {0, 0, 0, 0, 0, 0};
public HZSMModel() : base(
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, HZ_cls),
6,
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, HZ_st),
HZCharLenTable, "HZ-GB-2312")
{
}
}
public class ISO2022CNSMModel : SMModel
{
private readonly static int[] ISO2022CN_cls = {
BitPackage.Pack4bits(2,0,0,0,0,0,0,0), // 00 - 07
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 08 - 0f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17
BitPackage.Pack4bits(0,0,0,1,0,0,0,0), // 18 - 1f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 20 - 27
BitPackage.Pack4bits(0,3,0,0,0,0,0,0), // 28 - 2f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f
BitPackage.Pack4bits(0,0,0,4,0,0,0,0), // 40 - 47
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 48 - 4f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 78 - 7f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 80 - 87
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 88 - 8f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 90 - 97
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 98 - 9f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a0 - a7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a8 - af
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c8 - cf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e0 - e7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e8 - ef
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // f0 - f7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2) // f8 - ff
};
private readonly static int[] ISO2022CN_st = {
BitPackage.Pack4bits(START, 3,ERROR,START,START,START,START,START),//00-07
BitPackage.Pack4bits(START,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//08-0f
BitPackage.Pack4bits(ERROR,ERROR,ITSME,ITSME,ITSME,ITSME,ITSME,ITSME),//10-17
BitPackage.Pack4bits(ITSME,ITSME,ITSME,ERROR,ERROR,ERROR, 4,ERROR),//18-1f
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ITSME,ERROR,ERROR,ERROR,ERROR),//20-27
BitPackage.Pack4bits( 5, 6,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//28-2f
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ITSME,ERROR,ERROR,ERROR,ERROR),//30-37
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ITSME,ERROR,START) //38-3f
};
private readonly static int[] ISO2022CNCharLenTable = {0, 0, 0, 0, 0, 0, 0, 0, 0};
public ISO2022CNSMModel() : base(
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022CN_cls),
9,
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022CN_st),
ISO2022CNCharLenTable, "ISO-2022-CN")
{
}
}
public class ISO2022JPSMModel : SMModel
{
private readonly static int[] ISO2022JP_cls = {
BitPackage.Pack4bits(2,0,0,0,0,0,0,0), // 00 - 07
BitPackage.Pack4bits(0,0,0,0,0,0,2,2), // 08 - 0f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17
BitPackage.Pack4bits(0,0,0,1,0,0,0,0), // 18 - 1f
BitPackage.Pack4bits(0,0,0,0,7,0,0,0), // 20 - 27
BitPackage.Pack4bits(3,0,0,0,0,0,0,0), // 28 - 2f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f
BitPackage.Pack4bits(6,0,4,0,8,0,0,0), // 40 - 47
BitPackage.Pack4bits(0,9,5,0,0,0,0,0), // 48 - 4f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 78 - 7f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 80 - 87
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 88 - 8f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 90 - 97
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 98 - 9f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a0 - a7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a8 - af
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c8 - cf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e0 - e7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e8 - ef
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // f0 - f7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2) // f8 - ff
};
private readonly static int[] ISO2022JP_st = {
BitPackage.Pack4bits(START, 3, ERROR,START,START,START,START,START),//00-07
BitPackage.Pack4bits(START, START, ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//08-0f
BitPackage.Pack4bits(ERROR, ERROR, ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//10-17
BitPackage.Pack4bits(ITSME, ITSME, ITSME,ITSME,ITSME,ITSME,ERROR,ERROR),//18-1f
BitPackage.Pack4bits(ERROR, 5, ERROR,ERROR,ERROR, 4,ERROR,ERROR),//20-27
BitPackage.Pack4bits(ERROR, ERROR, ERROR, 6,ITSME,ERROR,ITSME,ERROR),//28-2f
BitPackage.Pack4bits(ERROR, ERROR, ERROR,ERROR,ERROR,ERROR,ITSME,ITSME),//30-37
BitPackage.Pack4bits(ERROR, ERROR, ERROR,ITSME,ERROR,ERROR,ERROR,ERROR),//38-3f
BitPackage.Pack4bits(ERROR, ERROR, ERROR,ERROR,ITSME,ERROR,START,START) //40-47
};
private readonly static int[] ISO2022JPCharLenTable = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
public ISO2022JPSMModel() : base(
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022JP_cls),
10,
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022JP_st),
ISO2022JPCharLenTable, "ISO-2022-JP")
{
}
}
public class ISO2022KRSMModel : SMModel
{
private readonly static int[] ISO2022KR_cls = {
BitPackage.Pack4bits(2,0,0,0,0,0,0,0), // 00 - 07
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 08 - 0f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17
BitPackage.Pack4bits(0,0,0,1,0,0,0,0), // 18 - 1f
BitPackage.Pack4bits(0,0,0,0,3,0,0,0), // 20 - 27
BitPackage.Pack4bits(0,4,0,0,0,0,0,0), // 28 - 2f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f
BitPackage.Pack4bits(0,0,0,5,0,0,0,0), // 40 - 47
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 48 - 4f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77
BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 78 - 7f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 80 - 87
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 88 - 8f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 90 - 97
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 98 - 9f
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a0 - a7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a8 - af
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c8 - cf
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e0 - e7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e8 - ef
BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // f0 - f7
BitPackage.Pack4bits(2,2,2,2,2,2,2,2) // f8 - ff
};
private readonly static int[] ISO2022KR_st = {
BitPackage.Pack4bits(START, 3,ERROR,START,START,START,ERROR,ERROR),//00-07
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//08-0f
BitPackage.Pack4bits(ITSME,ITSME,ERROR,ERROR,ERROR, 4,ERROR,ERROR),//10-17
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR, 5,ERROR,ERROR,ERROR),//18-1f
BitPackage.Pack4bits(ERROR,ERROR,ERROR,ITSME,START,START,START,START) //20-27
};
private readonly static int[] ISO2022KRCharLenTable = {0, 0, 0, 0, 0, 0};
public ISO2022KRSMModel() : base(
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022KR_cls),
6,
new BitPackage(BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS, ISO2022KR_st),
ISO2022KRCharLenTable, "ISO-2022-KR")
{
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#if NETFRAMEWORK
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
namespace NUnit.Framework.Assertions
{
[TestFixture]
[Platform(Exclude = "Mono,MonoTouch", Reason = "Mono does not implement Code Access Security")]
public class LowTrustFixture
{
private TestSandBox _sandBox;
[OneTimeSetUp]
public void CreateSandBox()
{
_sandBox = new TestSandBox();
}
[OneTimeTearDown]
public void DisposeSandBox()
{
if (_sandBox != null)
{
_sandBox.Dispose();
_sandBox = null;
}
}
[Test]
public void AssertEqualityInLowTrustSandBox()
{
_sandBox.Run(() =>
{
Assert.That(1, Is.EqualTo(1));
});
}
[Test]
public void AssertEqualityWithToleranceInLowTrustSandBox()
{
_sandBox.Run(() =>
{
Assert.That(10.5, Is.EqualTo(10.5));
});
}
[Test]
public void AssertThrowsInLowTrustSandBox()
{
_sandBox.Run(() =>
{
Assert.Throws<SecurityException>(() => new SecurityPermission(SecurityPermissionFlag.Infrastructure).Demand());
});
}
}
/// <summary>
/// A facade for an <see cref="AppDomain"/> with partial trust privileges.
/// </summary>
public class TestSandBox : IDisposable
{
private AppDomain _appDomain;
#region Constructor(s)
/// <summary>
/// Creates a low trust <see cref="TestSandBox"/> instance.
/// </summary>
/// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param>
public TestSandBox(params Assembly[] fullTrustAssemblies)
: this(null, fullTrustAssemblies)
{ }
/// <summary>
/// Creates a partial trust <see cref="TestSandBox"/> instance with a given set of permissions.
/// </summary>
/// <param name="permissions">Optional <see cref="TestSandBox"/> permission set. By default a minimal trust
/// permission set is used.</param>
/// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param>
public TestSandBox(PermissionSet permissions, params Assembly[] fullTrustAssemblies)
{
var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };
var strongNames = new HashSet<StrongName>();
// Grant full trust to NUnit.Framework assembly to enable use of NUnit assertions in sandboxed test code.
strongNames.Add(GetStrongName(typeof(TestAttribute).Assembly));
if (fullTrustAssemblies != null)
{
foreach (var assembly in fullTrustAssemblies)
{
strongNames.Add(GetStrongName(assembly));
}
}
_appDomain = AppDomain.CreateDomain(
"TestSandBox" + DateTime.Now.Ticks, null, setup,
permissions ?? GetLowTrustPermissionSet(),
strongNames.ToArray());
}
#endregion
#region Finalizer and Dispose methods
/// <summary>
/// The <see cref="TestSandBox"/> finalizer.
/// </summary>
~TestSandBox()
{
Dispose(false);
}
/// <summary>
/// Unloads the <see cref="AppDomain"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Unloads the <see cref="AppDomain"/>.
/// </summary>
/// <param name="disposing">Indicates whether this method is called from <see cref="Dispose()"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (_appDomain != null)
{
AppDomain.Unload(_appDomain);
_appDomain = null;
}
}
#endregion
#region PermissionSet factory methods
public static PermissionSet GetLowTrustPermissionSet()
{
var permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new SecurityPermission(
SecurityPermissionFlag.Execution | // Required to execute test code
SecurityPermissionFlag.SerializationFormatter)); // Required to support cross-appdomain test result formatting by NUnit TestContext
permissions.AddPermission(new ReflectionPermission(
ReflectionPermissionFlag.MemberAccess)); // Required to instantiate classes that contain test code and to get cross-appdomain communication to work.
return permissions;
}
#endregion
#region Run methods
public T Run<T>(Func<T> func)
{
return (T)Run(func.Method);
}
public void Run(Action action)
{
Run(action.Method);
}
public object Run(MethodInfo method, params object[] parameters)
{
if (method == null) throw new ArgumentNullException(nameof(method));
if (_appDomain == null) throw new ObjectDisposedException(null);
var methodRunnerType = typeof(MethodRunner);
var methodRunnerProxy = (MethodRunner)_appDomain.CreateInstanceAndUnwrap(
methodRunnerType.Assembly.FullName, methodRunnerType.FullName);
try
{
return methodRunnerProxy.Run(method, parameters);
}
catch (Exception e)
{
throw e is TargetInvocationException
? e.InnerException
: e;
}
}
#endregion
#region Private methods
private static StrongName GetStrongName(Assembly assembly)
{
AssemblyName assemblyName = assembly.GetName();
byte[] publicKey = assembly.GetName().GetPublicKey();
if (publicKey == null || publicKey.Length == 0)
{
throw new InvalidOperationException("Assembly is not strongly named");
}
return new StrongName(new StrongNamePublicKeyBlob(publicKey), assemblyName.Name, assemblyName.Version);
}
#endregion
#region Inner classes
[Serializable]
internal class MethodRunner : MarshalByRefObject
{
public object Run(MethodInfo method, params object[] parameters)
{
var instance = method.IsStatic
? null
: Activator.CreateInstance(method.ReflectedType);
try
{
return method.Invoke(instance, parameters);
}
catch (TargetInvocationException e)
{
if (e.InnerException == null) throw;
throw e.InnerException;
}
}
}
#endregion
}
}
#endif
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
[assembly: PythonModule("itertools", typeof(IronPython.Modules.PythonIterTools))]
namespace IronPython.Modules {
public static class PythonIterTools {
public const string __doc__ = "Provides functions and classes for working with iterable objects.";
public static object tee(object iterable) {
return tee(iterable, 2);
}
public static object tee(object iterable, int n) {
if (n < 0) throw PythonOps.ValueError("n cannot be negative");
object[] res = new object[n];
if (!(iterable is TeeIterator)) {
IEnumerator iter = PythonOps.GetEnumerator(iterable);
List dataList = new List();
for (int i = 0; i < n; i++) {
res[i] = new TeeIterator(iter, dataList);
}
} else if (n != 0) {
// if you pass in a tee you get back the original tee
// and other iterators that share the same data.
TeeIterator ti = iterable as TeeIterator;
res[0] = ti;
for (int i = 1; i < n; i++) {
res[1] = new TeeIterator(ti._iter, ti._data);
}
}
return PythonTuple.MakeTuple(res);
}
/// <summary>
/// Base class used for iterator wrappers.
/// </summary>
[PythonType, PythonHidden]
public class IterBase : IEnumerator {
private IEnumerator _inner;
internal IEnumerator InnerEnumerator {
set { _inner = value; }
}
#region IEnumerator Members
object IEnumerator.Current {
get { return _inner.Current; }
}
bool IEnumerator.MoveNext() {
return _inner.MoveNext();
}
void IEnumerator.Reset() {
_inner.Reset();
}
public object __iter__() {
return this;
}
#endregion
}
[PythonType]
public class chain : IterBase {
private chain() { }
public chain(params object[] iterables) {
InnerEnumerator = LazyYielder(iterables);
}
[ClassMethod]
public static chain from_iterable(CodeContext/*!*/ context, PythonType cls, object iterables) {
chain res;
if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(chain))) {
res = new chain();
res.InnerEnumerator = LazyYielder(iterables);
} else {
res = (chain)cls.CreateInstance(context);
res.InnerEnumerator = LazyYielder(iterables);
}
return res;
}
private static IEnumerator<object> LazyYielder(object iterables) {
IEnumerator ie = PythonOps.GetEnumerator(iterables);
while (ie.MoveNext()) {
IEnumerator inner = PythonOps.GetEnumerator(ie.Current);
while (inner.MoveNext()) {
yield return inner.Current;
}
}
}
}
[PythonType]
public class compress : IterBase {
private compress() { }
public compress(CodeContext/*!*/ context, [NotNull]object data, [NotNull]object selectors) {
EnsureIterator(context, data);
EnsureIterator(context, selectors);
InnerEnumerator = LazyYielder(data, selectors);
}
private static void EnsureIterator(CodeContext/*!*/ context, object iter) {
if (iter is IEnumerable || iter is IEnumerator ||
iter is IEnumerable<object> || iter is IEnumerator<object>) {
return;
}
if (iter == null ||
!PythonOps.HasAttr(context, iter, "__iter__") &&
!PythonOps.HasAttr(context, iter, "__getitem__")) {
if (iter is OldInstance) {
throw PythonOps.TypeError("iteration over non-sequence");
} else {
throw PythonOps.TypeError("'{0}' object is not iterable", PythonTypeOps.GetName(iter));
}
}
}
// (d for d, s in zip(data, selectors) if s)
private static IEnumerator<object> LazyYielder(object data, object selectors) {
IEnumerator de = PythonOps.GetEnumerator(data);
IEnumerator se = PythonOps.GetEnumerator(selectors);
while (de.MoveNext()) {
if (!se.MoveNext()) {
break;
}
if (PythonOps.IsTrue(se.Current)) {
yield return de.Current;
}
}
}
}
[PythonType]
public class count : IterBase, ICodeFormattable {
private int _curInt;
private object _step, _cur;
public count() {
_curInt = 0;
_step = 1;
InnerEnumerator = IntYielder(this, 0, 1);
}
public count(int start) {
_curInt = start;
_step = 1;
InnerEnumerator = IntYielder(this, start, 1);
}
public count(BigInteger start) {
_cur = start;
_step = 1;
InnerEnumerator = BigIntYielder(this, start, 1);
}
public count([DefaultParameterValue(0)]int start, [DefaultParameterValue(1)]int step) {
_curInt = start;
_step = step;
InnerEnumerator = IntYielder(this, start, step);
}
public count([DefaultParameterValue(0)]int start, BigInteger step) {
_curInt = start;
_step = step;
InnerEnumerator = IntYielder(this, start, step);
}
public count(BigInteger start, int step) {
_cur = start;
_step = step;
InnerEnumerator = BigIntYielder(this, start, step);
}
public count(BigInteger start, BigInteger step) {
_cur = start;
_step = step;
InnerEnumerator = BigIntYielder(this, start, step);
}
public count(CodeContext/*!*/ context, [DefaultParameterValue(0)]object start, [DefaultParameterValue(1)]object step) {
EnsureNumeric(context, start);
EnsureNumeric(context, step);
_cur = start;
_step = step;
InnerEnumerator = ObjectYielder(PythonContext.GetContext(context), this, start, step);
}
private static void EnsureNumeric(CodeContext/*!*/ context, object num) {
if (num is int || num is double || num is BigInteger || num is Complex) {
return;
}
if (num == null ||
!PythonOps.HasAttr(context, num, "__int__") &&
!PythonOps.HasAttr(context, num, "__float__")) {
throw PythonOps.TypeError("a number is required");
}
}
private static IEnumerator<object> IntYielder(count c, int start, int step) {
int prev;
for (; ; ) {
prev = c._curInt;
try {
start = checked(start + step);
} catch (OverflowException) {
break;
}
c._curInt = start;
yield return prev;
}
BigInteger startBig = (BigInteger)start + step;
c._cur = startBig;
yield return prev;
for (startBig += step; ; startBig += step) {
object prevObj = c._cur;
c._cur = startBig;
yield return prevObj;
}
}
private static IEnumerator<object> IntYielder(count c, int start, BigInteger step) {
BigInteger startBig = (BigInteger)start + step;
c._cur = startBig;
yield return start;
for (startBig += step; ; startBig += step) {
object prevObj = c._cur;
c._cur = startBig;
yield return prevObj;
}
}
private static IEnumerator<BigInteger> BigIntYielder(count c, BigInteger start, int step) {
for (start += step; ; start += step) {
BigInteger prev = (BigInteger)c._cur;
c._cur = start;
yield return prev;
}
}
private static IEnumerator<BigInteger> BigIntYielder(count c, BigInteger start, BigInteger step) {
for (start += step; ; start += step) {
BigInteger prev = (BigInteger)c._cur;
c._cur = start;
yield return prev;
}
}
private static IEnumerator<object> ObjectYielder(PythonContext context, count c, object start, object step) {
start = context.Operation(PythonOperationKind.Add, start, step);
for (; ; start = context.Operation(PythonOperationKind.Add, start, step)) {
object prev = c._cur;
c._cur = start;
yield return prev;
}
}
public PythonTuple __reduce__() {
PythonTuple args;
if (StepIsOne()) {
args = PythonOps.MakeTuple(_cur == null ? _curInt : _cur);
} else {
args = PythonOps.MakeTuple(_cur == null ? _curInt : _cur, _step);
}
return PythonOps.MakeTuple(DynamicHelpers.GetPythonType(this), args);
}
public PythonTuple __reduce_ex__([Optional]int protocol) {
return __reduce__();
}
private bool StepIsOne() {
if (_step is int) {
return (int)_step == 1;
}
Extensible<int> stepExt;
if ((stepExt = _step as Extensible<int>) != null) {
return stepExt.Value == 1;
}
return false;
}
#region ICodeFormattable Members
public string __repr__(CodeContext/*!*/ context) {
object cur = _cur == null ? _curInt : _cur;
if (StepIsOne()) {
return string.Format("count({0})", PythonOps.Repr(context, cur));
}
return string.Format(
"count({0}, {1})",
PythonOps.Repr(context, cur),
PythonOps.Repr(context, _step)
);
}
#endregion
}
[PythonType]
public class cycle : IterBase {
public cycle(object iterable) {
InnerEnumerator = Yielder(PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(IEnumerator iter) {
List result = new List();
while (MoveNextHelper(iter)) {
result.AddNoLock(iter.Current);
yield return iter.Current;
}
if (result.__len__() != 0) {
for (; ; ) {
for (int i = 0; i < result.__len__(); i++) {
yield return result[i];
}
}
}
}
}
[PythonType]
public class dropwhile : IterBase {
private readonly CodeContext/*!*/ _context;
public dropwhile(CodeContext/*!*/ context, object predicate, object iterable) {
_context = context;
InnerEnumerator = Yielder(predicate, PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(object predicate, IEnumerator iter) {
PythonContext pc = PythonContext.GetContext(_context);
while (MoveNextHelper(iter)) {
if (!Converter.ConvertToBoolean(pc.CallSplat(predicate, iter.Current))) {
yield return iter.Current;
break;
}
}
while (MoveNextHelper(iter)) {
yield return iter.Current;
}
}
}
[PythonType]
public class groupby : IterBase {
private static readonly object _starterKey = new object();
private bool _fFinished = false;
private object _key;
private readonly CodeContext/*!*/ _context;
public groupby(CodeContext/*!*/ context, object iterable) {
InnerEnumerator = Yielder(PythonOps.GetEnumerator(iterable));
_context = context;
}
public groupby(CodeContext/*!*/ context, object iterable, object key) {
InnerEnumerator = Yielder(PythonOps.GetEnumerator(iterable));
_context = context;
if (key != null) {
_key = key;
}
}
private IEnumerator<object> Yielder(IEnumerator iter) {
object curKey = _starterKey;
if (MoveNextHelper(iter)) {
while (!_fFinished) {
while (PythonContext.Equal(GetKey(iter.Current), curKey)) {
if (!MoveNextHelper(iter)) {
_fFinished = true;
yield break;
}
}
curKey = GetKey(iter.Current);
yield return PythonTuple.MakeTuple(curKey, Grouper(iter, curKey));
}
}
}
private IEnumerator<object> Grouper(IEnumerator iter, object curKey) {
while (PythonContext.Equal(GetKey(iter.Current), curKey)) {
yield return iter.Current;
if (!MoveNextHelper(iter)) {
_fFinished = true;
yield break;
}
}
}
private object GetKey(object val) {
if (_key == null) return val;
return PythonContext.GetContext(_context).CallSplat(_key, val);
}
}
[PythonType]
public class ifilter : IterBase {
private readonly CodeContext/*!*/ _context;
public ifilter(CodeContext/*!*/ context, object predicate, object iterable) {
_context = context;
InnerEnumerator = Yielder(predicate, PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(object predicate, IEnumerator iter) {
while (MoveNextHelper(iter)) {
if (ShouldYield(predicate, iter.Current)) {
yield return iter.Current;
}
}
}
private bool ShouldYield(object predicate, object current) {
if (predicate == null) return PythonOps.IsTrue(current);
return Converter.ConvertToBoolean(PythonContext.GetContext(_context).CallSplat(predicate, current));
}
}
[PythonType]
public class ifilterfalse : IterBase {
private readonly CodeContext/*!*/ _context;
public ifilterfalse(CodeContext/*!*/ context, object predicate, object iterable) {
_context = context;
InnerEnumerator = Yielder(predicate, PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(object predicate, IEnumerator iter) {
while (MoveNextHelper(iter)) {
if (ShouldYield(predicate, iter.Current)) {
yield return iter.Current;
}
}
}
private bool ShouldYield(object predicate, object current) {
if (predicate == null) return !PythonOps.IsTrue(current);
return !Converter.ConvertToBoolean(
PythonContext.GetContext(_context).CallSplat(predicate, current)
);
}
}
[PythonType]
public class imap : IEnumerator {
private object _function;
private IEnumerator[] _iterables;
private readonly CodeContext/*!*/ _context;
public imap(CodeContext/*!*/ context, object function, params object[] iterables) {
if (iterables.Length < 1) {
throw PythonOps.TypeError("imap() must have at least two arguments");
}
_function = function;
_context = context;
_iterables = new IEnumerator[iterables.Length];
for (int i = 0; i < iterables.Length; i++) {
_iterables[i] = PythonOps.GetEnumerator(iterables[i]);
}
}
#region IEnumerator Members
object IEnumerator.Current {
get {
object[] args = new object[_iterables.Length];
for (int i = 0; i < args.Length; i++) {
args[i] = _iterables[i].Current;
}
if (_function == null) {
return PythonTuple.MakeTuple(args);
} else {
return PythonContext.GetContext(_context).CallSplat(_function, args);
}
}
}
bool IEnumerator.MoveNext() {
for (int i = 0; i < _iterables.Length; i++) {
if (!MoveNextHelper(_iterables[i])) return false;
}
return true;
}
void IEnumerator.Reset() {
for (int i = 0; i < _iterables.Length; i++) {
_iterables[i].Reset();
}
}
public object __iter__() {
return this;
}
#endregion
}
[PythonType]
public class islice : IterBase {
public islice(object iterable, object stop)
: this(iterable, 0, stop, 1) {
}
public islice(object iterable, object start, object stop)
: this(iterable, start, stop, 1) {
}
public islice(object iterable, object start, object stop, object step) {
int startInt = 0, stopInt = -1;
if (start != null && !Converter.TryConvertToInt32(start, out startInt) || startInt < 0)
throw PythonOps.ValueError("start argument must be non-negative integer, ({0})", start);
if (stop != null) {
if (!Converter.TryConvertToInt32(stop, out stopInt) || stopInt < 0)
throw PythonOps.ValueError("stop argument must be non-negative integer ({0})", stop);
}
int stepInt = 1;
if (step != null && !Converter.TryConvertToInt32(step, out stepInt) || stepInt <= 0) {
throw PythonOps.ValueError("step must be 1 or greater for islice");
}
InnerEnumerator = Yielder(PythonOps.GetEnumerator(iterable), startInt, stopInt, stepInt);
}
private IEnumerator<object> Yielder(IEnumerator iter, int start, int stop, int step) {
if (!MoveNextHelper(iter)) yield break;
int cur = 0;
while (cur < start) {
if (!MoveNextHelper(iter)) yield break;
cur++;
}
while (cur < stop || stop == -1) {
yield return iter.Current;
if ((cur + step) < 0) yield break; // early out if we'll overflow.
for (int i = 0; i < step; i++) {
if ((stop != -1 && ++cur >= stop) || !MoveNextHelper(iter)) {
yield break;
}
}
}
}
}
[PythonType]
public class izip : IEnumerator {
private readonly IEnumerator[]/*!*/ _iters;
private PythonTuple _current;
public izip(params object[] iterables) {
_iters = new IEnumerator[iterables.Length];
for (int i = 0; i < iterables.Length; i++) {
_iters[i] = PythonOps.GetEnumerator(iterables[i]);
}
}
#region IEnumerator Members
object IEnumerator.Current {
get {
return _current;
}
}
bool IEnumerator.MoveNext() {
if (_iters.Length == 0) return false;
object[] current = new object[_iters.Length];
for (int i = 0; i < _iters.Length; i++) {
if (!MoveNextHelper(_iters[i])) return false;
// values need to be extraced and saved as we move incase
// the user passed the same iterable multiple times.
current[i] = _iters[i].Current;
}
_current = PythonTuple.MakeTuple(current);
return true;
}
void IEnumerator.Reset() {
throw new NotImplementedException("The method or operation is not implemented.");
}
public object __iter__() {
return this;
}
#endregion
}
[PythonType]
public class izip_longest : IEnumerator {
private readonly IEnumerator[]/*!*/ _iters;
private readonly object _fill;
private PythonTuple _current;
public izip_longest(params object[] iterables) {
_iters = new IEnumerator[iterables.Length];
for (int i = 0; i < iterables.Length; i++) {
_iters[i] = PythonOps.GetEnumerator(iterables[i]);
}
}
public izip_longest([ParamDictionary]IDictionary<object, object> paramDict, params object[] iterables) {
object fill;
if (paramDict.TryGetValue("fillvalue", out fill)) {
_fill = fill;
if (paramDict.Count != 1) {
paramDict.Remove("fillvalue");
throw UnexpectedKeywordArgument(paramDict);
}
} else if (paramDict.Count != 0) {
throw UnexpectedKeywordArgument(paramDict);
}
_iters = new IEnumerator[iterables.Length];
for (int i = 0; i < iterables.Length; i++) {
_iters[i] = PythonOps.GetEnumerator(iterables[i]);
}
}
#region IEnumerator Members
object IEnumerator.Current {
get {
return _current;
}
}
bool IEnumerator.MoveNext() {
if (_iters.Length == 0) return false;
object[] current = new object[_iters.Length];
bool gotValue = false;
for (int i = 0; i < _iters.Length; i++) {
if (!MoveNextHelper(_iters[i])) {
current[i] = _fill;
} else {
// values need to be extraced and saved as we move incase
// the user passed the same iterable multiple times.
gotValue = true;
current[i] = _iters[i].Current;
}
}
if (gotValue) {
_current = PythonTuple.MakeTuple(current);
return true;
}
return false;
}
void IEnumerator.Reset() {
throw new NotImplementedException("The method or operation is not implemented.");
}
public object __iter__() {
return this;
}
#endregion
}
private static Exception UnexpectedKeywordArgument(IDictionary<object, object> paramDict) {
foreach (object name in paramDict.Keys) {
return PythonOps.TypeError("got unexpected keyword argument {0}", name);
}
throw new InvalidOperationException();
}
[PythonType]
public class product : IterBase {
public product(params object[] iterables) {
InnerEnumerator = Yielder(ArrayUtils.ConvertAll(iterables, x => new List(PythonOps.GetEnumerator(x))));
}
public product([ParamDictionary]IDictionary<object, object> paramDict, params object[] iterables) {
object repeat;
int iRepeat = 1;
if (paramDict.TryGetValue("repeat", out repeat)) {
if (repeat is int) {
iRepeat = (int)repeat;
} else {
throw PythonOps.TypeError("an integer is required");
}
if (paramDict.Count != 1) {
paramDict.Remove("repeat");
throw UnexpectedKeywordArgument(paramDict);
}
} else if (paramDict.Count != 0) {
throw UnexpectedKeywordArgument(paramDict);
}
List[] finalIterables = new List[iterables.Length * iRepeat];
for (int i = 0; i < iRepeat; i++) {
for (int j = 0; j < iterables.Length; j++) {
finalIterables[i * iterables.Length + j] = new List(iterables[j]);
}
}
InnerEnumerator = Yielder(finalIterables);
}
private IEnumerator<object> Yielder(List[] iterables) {
if (iterables.Length > 0) {
IEnumerator[] enums = new IEnumerator[iterables.Length];
enums[0] = iterables[0].GetEnumerator();
int curDepth = 0;
do {
if (enums[curDepth].MoveNext()) {
if (curDepth == enums.Length - 1) {
// create a new array so we don't mutate previous tuples
object[] final = new object[enums.Length];
for (int j = 0; j < enums.Length; j++) {
final[j] = enums[j].Current;
}
yield return PythonTuple.MakeTuple(final);
} else {
// going to the next depth, get a new enumerator
curDepth++;
enums[curDepth] = iterables[curDepth].GetEnumerator();
}
} else {
// current depth exhausted, go to the previous iterator
curDepth--;
}
} while (curDepth != -1);
} else {
yield return PythonTuple.EMPTY;
}
}
}
[PythonType]
public class combinations : IterBase {
private readonly List _data;
public combinations(object iterable, object r) {
_data = new List(iterable);
InnerEnumerator = Yielder(GetR(r, _data));
}
private IEnumerator<object> Yielder(int r) {
IEnumerator[] enums = new IEnumerator[r];
if (r > 0) {
enums[0] = _data.GetEnumerator();
int curDepth = 0;
int[] curIndices = new int[enums.Length];
do {
if (enums[curDepth].MoveNext()) {
curIndices[curDepth]++;
bool shouldSkip = false;
for (int i = 0; i < curDepth; i++) {
if (curIndices[i] >= curIndices[curDepth]) {
// skip if we've already seen this index or a higher
// index elsewhere
shouldSkip = true;
break;
}
}
if (!shouldSkip) {
if (curDepth == enums.Length - 1) {
// create a new array so we don't mutate previous tuples
object[] final = new object[r];
for (int j = 0; j < enums.Length; j++) {
final[j] = enums[j].Current;
}
yield return PythonTuple.MakeTuple(final);
} else {
// going to the next depth, get a new enumerator
curDepth++;
enums[curDepth] = _data.GetEnumerator();
curIndices[curDepth] = 0;
}
}
} else {
// current depth exhausted, go to the previous iterator
curDepth--;
}
} while (curDepth != -1);
} else {
yield return PythonTuple.EMPTY;
}
}
}
[PythonType]
public class combinations_with_replacement : IterBase {
private readonly List _data;
public combinations_with_replacement(object iterable, object r) {
_data = new List(iterable);
InnerEnumerator = Yielder(GetR(r, _data));
}
private IEnumerator<object> Yielder(int r) {
IEnumerator[] enums = new IEnumerator[r];
if (r > 0) {
enums[0] = _data.GetEnumerator();
int curDepth = 0;
int[] curIndices = new int[enums.Length];
do {
if (enums[curDepth].MoveNext()) {
curIndices[curDepth]++;
bool shouldSkip = false;
for (int i = 0; i < curDepth; i++) {
if (curIndices[i] > curIndices[curDepth]) {
// skip if we've already seen a higher index elsewhere
shouldSkip = true;
break;
}
}
if (!shouldSkip) {
if (curDepth == enums.Length - 1) {
// create a new array so we don't mutate previous tuples
object[] final = new object[r];
for (int j = 0; j < enums.Length; j++) {
final[j] = enums[j].Current;
}
yield return PythonTuple.MakeTuple(final);
} else {
// going to the next depth, get a new enumerator
curDepth++;
enums[curDepth] = _data.GetEnumerator();
curIndices[curDepth] = 0;
}
}
} else {
// current depth exhausted, go to the previous iterator
curDepth--;
}
} while (curDepth != -1);
} else {
yield return PythonTuple.EMPTY;
}
}
}
[PythonType]
public class permutations : IterBase {
private readonly List _data;
public permutations(object iterable) {
_data = new List(iterable);
InnerEnumerator = Yielder(_data.Count);
}
public permutations(object iterable, object r) {
_data = new List(iterable);
InnerEnumerator = Yielder(GetR(r, _data));
}
private IEnumerator<object> Yielder(int r) {
if (r > 0) {
IEnumerator[] enums = new IEnumerator[r];
enums[0] = _data.GetEnumerator();
int curDepth = 0;
int[] curIndices = new int[enums.Length];
do {
if (enums[curDepth].MoveNext()) {
curIndices[curDepth]++;
bool shouldSkip = false;
for (int i = 0; i < curDepth; i++) {
if (curIndices[i] == curIndices[curDepth]) {
// skip if we're already using this index elsewhere
shouldSkip = true;
break;
}
}
if (!shouldSkip) {
if (curDepth == enums.Length - 1) {
// create a new array so we don't mutate previous tuples
object[] final = new object[r];
for (int j = 0; j < enums.Length; j++) {
final[j] = enums[j].Current;
}
yield return PythonTuple.MakeTuple(final);
} else {
// going to the next depth, get a new enumerator
curDepth++;
enums[curDepth] = _data.GetEnumerator();
curIndices[curDepth] = 0;
}
}
} else {
// current depth exhausted, go to the previous iterator
curDepth--;
}
} while (curDepth != -1);
} else {
yield return PythonTuple.EMPTY;
}
}
}
private static int GetR(object r, List data) {
int ri;
if (r != null) {
ri = Converter.ConvertToInt32(r);
if (ri < 0) {
throw PythonOps.ValueError("r cannot be negative");
}
} else {
ri = data.Count;
}
return ri;
}
[PythonType, DontMapICollectionToLen]
public class repeat : IterBase, ICodeFormattable, ICollection {
private int _remaining;
private bool _fInfinite;
private object _obj;
public repeat(object @object) {
_obj = @object;
InnerEnumerator = Yielder();
_fInfinite = true;
}
public repeat(object @object, int times) {
_obj = @object;
InnerEnumerator = Yielder();
_remaining = times;
}
private IEnumerator<object> Yielder() {
while (_fInfinite || _remaining > 0) {
_remaining--;
yield return _obj;
}
}
public int __length_hint__() {
if (_fInfinite) throw PythonOps.TypeError("len() of unsized object");
return Math.Max(_remaining, 0);
}
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
if (_fInfinite) {
return String.Format("{0}({1})", PythonOps.GetPythonTypeName(this), PythonOps.Repr(context, _obj));
}
return String.Format("{0}({1}, {2})", PythonOps.GetPythonTypeName(this), PythonOps.Repr(context, _obj), _remaining);
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
if (_fInfinite) throw new InvalidOperationException();
if (_remaining > array.Length - index) {
throw new IndexOutOfRangeException();
}
for (int i = 0; i < _remaining; i++) {
array.SetValue(_obj, index + i);
}
_remaining = 0;
}
int ICollection.Count {
get { return __length_hint__(); }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
while (_fInfinite || _remaining > 0) {
_remaining--;
yield return _obj;
}
}
#endregion
}
[PythonType]
public class starmap : IterBase {
public starmap(CodeContext context, object function, object iterable) {
InnerEnumerator = Yielder(context, function, PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(CodeContext context, object function, IEnumerator iter) {
PythonContext pc = PythonContext.GetContext(context);
while (MoveNextHelper(iter)) {
PythonTuple args = iter.Current as PythonTuple;
object[] objargs;
if (args != null) {
objargs = new object[args.__len__()];
for (int i = 0; i < objargs.Length; i++) {
objargs[i] = args[i];
}
} else {
List argsList = new List(PythonOps.GetEnumerator(iter.Current));
objargs = ArrayUtils.ToArray(argsList);
}
yield return pc.CallSplat(function, objargs);
}
}
}
[PythonType]
public class takewhile : IterBase {
private readonly CodeContext/*!*/ _context;
public takewhile(CodeContext/*!*/ context, object predicate, object iterable) {
_context = context;
InnerEnumerator = Yielder(predicate, PythonOps.GetEnumerator(iterable));
}
private IEnumerator<object> Yielder(object predicate, IEnumerator iter) {
while (MoveNextHelper(iter)) {
if(!Converter.ConvertToBoolean(
PythonContext.GetContext(_context).CallSplat(predicate, iter.Current)
)) {
break;
}
yield return iter.Current;
}
}
}
[PythonHidden]
public class TeeIterator : IEnumerator, IWeakReferenceable {
internal IEnumerator _iter;
internal List _data;
private int _curIndex = -1;
private WeakRefTracker _weakRef;
public TeeIterator(object iterable) {
TeeIterator other = iterable as TeeIterator;
if (other != null) {
this._iter = other._iter;
this._data = other._data;
} else {
this._iter = PythonOps.GetEnumerator(iterable);
_data = new List();
}
}
public TeeIterator(IEnumerator iter, List dataList) {
this._iter = iter;
this._data = dataList;
}
#region IEnumerator Members
object IEnumerator.Current {
get {
return _data[_curIndex];
}
}
bool IEnumerator.MoveNext() {
lock (_data) {
_curIndex++;
if (_curIndex >= _data.__len__() && MoveNextHelper(_iter)) {
_data.append(_iter.Current);
}
return _curIndex < _data.__len__();
}
}
void IEnumerator.Reset() {
throw new NotImplementedException("The method or operation is not implemented.");
}
public object __iter__() {
return this;
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return (_weakRef);
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_weakRef = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_weakRef = value;
}
#endregion
}
private static bool MoveNextHelper(IEnumerator move) {
try { return move.MoveNext(); } catch (IndexOutOfRangeException) { return false; } catch (StopIterationException) { return false; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JCG = J2N.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.
*/
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Term = Lucene.Net.Index.Term;
internal sealed class SloppyPhraseScorer : Scorer
{
private PhrasePositions min, max;
private float sloppyFreq; //phrase frequency in current doc as computed by phraseFreq().
private readonly Similarity.SimScorer docScorer;
private readonly int slop;
private readonly int numPostings;
private readonly PhraseQueue pq; // for advancing min position
private int end; // current largest phrase position
private bool hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private bool checkedRpts; // flag to only check for repetitions in first candidate doc
private bool hasMultiTermRpts;
private PhrasePositions[][] rptGroups; // in each group are PPs that repeats each other (i.e. same term), sorted by (query) offset
private PhrasePositions[] rptStack; // temporary stack for switching colliding repeating pps
private int numMatches;
private readonly long cost;
internal SloppyPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, int slop, Similarity.SimScorer docScorer)
: base(weight)
{
this.docScorer = docScorer;
this.slop = slop;
this.numPostings = postings == null ? 0 : postings.Length;
pq = new PhraseQueue(postings.Length);
// min(cost)
cost = postings[0].postings.GetCost();
// convert tps to a list of phrase positions.
// note: phrase-position differs from term-position in that its position
// reflects the phrase offset: pp.pos = tp.pos - offset.
// this allows to easily identify a matching (exact) phrase
// when all PhrasePositions have exactly the same position.
if (postings.Length > 0)
{
min = new PhrasePositions(postings[0].postings, postings[0].position, 0, postings[0].terms);
max = min;
max.doc = -1;
for (int i = 1; i < postings.Length; i++)
{
PhrasePositions pp = new PhrasePositions(postings[i].postings, postings[i].position, i, postings[i].terms);
max.next = pp;
max = pp;
max.doc = -1;
}
max.next = min; // make it cyclic for easier manipulation
}
}
/// <summary>
/// Score a candidate doc for all slop-valid position-combinations (matches)
/// encountered while traversing/hopping the PhrasePositions.
/// <para/> The score contribution of a match depends on the distance:
/// <para/> - highest score for distance=0 (exact match).
/// <para/> - score gets lower as distance gets higher.
/// <para/>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
/// once for "a b" (distance=0), and once for "b a" (distance=2).
/// <para/>Possibly not all valid combinations are encountered, because for efficiency
/// we always propagate the least PhrasePosition. This allows to base on
/// <see cref="Util.PriorityQueue{T}"/> and move forward faster.
/// As result, for example, document "a b c b a"
/// would score differently for queries "a b c"~4 and "c b a"~4, although
/// they really are equivalent.
/// Similarly, for doc "a b c b a f g", query "c b"~2
/// would get same score as "g f"~2, although "c b"~2 could be matched twice.
/// We may want to fix this in the future (currently not, for performance reasons).
/// </summary>
private float PhraseFreq()
{
if (!InitPhrasePositions())
{
return 0.0f;
}
float freq = 0.0f;
numMatches = 0;
PhrasePositions pp = pq.Pop();
int matchLength = end - pp.position;
int next = pq.Top.position;
while (AdvancePP(pp))
{
if (hasRpts && !AdvanceRpts(pp))
{
break; // pps exhausted
}
if (pp.position > next) // done minimizing current match-length
{
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
pq.Add(pp);
pp = pq.Pop();
next = pq.Top.position;
matchLength = end - pp.position;
}
else
{
int matchLength2 = end - pp.position;
if (matchLength2 < matchLength)
{
matchLength = matchLength2;
}
}
}
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
return freq;
}
/// <summary>
/// Advance a PhrasePosition and update 'end', return false if exhausted </summary>
private bool AdvancePP(PhrasePositions pp)
{
if (!pp.NextPosition())
{
return false;
}
if (pp.position > end)
{
end = pp.position;
}
return true;
}
/// <summary>
/// pp was just advanced. If that caused a repeater collision, resolve by advancing the lesser
/// of the two colliding pps. Note that there can only be one collision, as by the initialization
/// there were no collisions before pp was advanced.
/// </summary>
private bool AdvanceRpts(PhrasePositions pp)
{
if (pp.rptGroup < 0)
{
return true; // not a repeater
}
PhrasePositions[] rg = rptGroups[pp.rptGroup];
FixedBitSet bits = new FixedBitSet(rg.Length); // for re-queuing after collisions are resolved
int k0 = pp.rptInd;
int k;
while ((k = Collide(pp)) >= 0)
{
pp = Lesser(pp, rg[k]); // always advance the lesser of the (only) two colliding pps
if (!AdvancePP(pp))
{
return false; // exhausted
}
if (k != k0) // careful: mark only those currently in the queue
{
bits = FixedBitSet.EnsureCapacity(bits, k);
bits.Set(k); // mark that pp2 need to be re-queued
}
}
// collisions resolved, now re-queue
// empty (partially) the queue until seeing all pps advanced for resolving collisions
int n = 0;
// TODO would be good if we can avoid calling cardinality() in each iteration!
int numBits = bits.Length; // larges bit we set
while (bits.Cardinality() > 0)
{
PhrasePositions pp2 = pq.Pop();
rptStack[n++] = pp2;
if (pp2.rptGroup >= 0 && pp2.rptInd < numBits && bits.Get(pp2.rptInd)) // this bit may not have been set
{
bits.Clear(pp2.rptInd);
}
}
// add back to queue
for (int i = n - 1; i >= 0; i--)
{
pq.Add(rptStack[i]);
}
return true;
}
/// <summary>
/// Compare two pps, but only by position and offset </summary>
private PhrasePositions Lesser(PhrasePositions pp, PhrasePositions pp2)
{
if (pp.position < pp2.position || (pp.position == pp2.position && pp.offset < pp2.offset))
{
return pp;
}
return pp2;
}
/// <summary>
/// Index of a pp2 colliding with pp, or -1 if none </summary>
private int Collide(PhrasePositions pp)
{
int tpPos = TpPos(pp);
PhrasePositions[] rg = rptGroups[pp.rptGroup];
for (int i = 0; i < rg.Length; i++)
{
PhrasePositions pp2 = rg[i];
if (pp2 != pp && TpPos(pp2) == tpPos)
{
return pp2.rptInd;
}
}
return -1;
}
/// <summary>
/// Initialize <see cref="PhrasePositions"/> in place.
/// A one time initialization for this scorer (on first doc matching all terms):
/// <list type="bullet">
/// <item><description>Check if there are repetitions</description></item>
/// <item><description>If there are, find groups of repetitions.</description></item>
/// </list>
/// Examples:
/// <list type="number">
/// <item><description>no repetitions: <b>"ho my"~2</b></description></item>
/// <item><description>>repetitions: <b>"ho my my"~2</b></description></item>
/// <item><description>repetitions: <b>"my ho my"~2</b></description></item>
/// </list>
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted (and so current doc will not be a match) </returns>
private bool InitPhrasePositions()
{
end = int.MinValue;
if (!checkedRpts)
{
return InitFirstTime();
}
if (!hasRpts)
{
InitSimple();
return true; // PPs available
}
return InitComplex();
}
/// <summary>
/// No repeats: simplest case, and most common. It is important to keep this piece of the code simple and efficient </summary>
private void InitSimple()
{
//System.err.println("initSimple: doc: "+min.doc);
pq.Clear();
// position pps and build queue from list
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// With repeats: not so simple. </summary>
private bool InitComplex()
{
//System.err.println("initComplex: doc: "+min.doc);
PlaceFirstPositions();
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Move all PPs to their first position </summary>
private void PlaceFirstPositions()
{
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
}
}
/// <summary>
/// Fill the queue (all pps are already placed) </summary>
private void FillQueue()
{
pq.Clear();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// At initialization (each doc), each repetition group is sorted by (query) offset.
/// this provides the start condition: no collisions.
/// <para/>Case 1: no multi-term repeats
/// <para/>
/// It is sufficient to advance each pp in the group by one less than its group index.
/// So lesser pp is not advanced, 2nd one advance once, 3rd one advanced twice, etc.
/// <para/>Case 2: multi-term repeats
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted. </returns>
private bool AdvanceRepeatGroups()
{
foreach (PhrasePositions[] rg in rptGroups)
{
if (hasMultiTermRpts)
{
// more involved, some may not collide
int incr;
for (int i = 0; i < rg.Length; i += incr)
{
incr = 1;
PhrasePositions pp = rg[i];
int k;
while ((k = Collide(pp)) >= 0)
{
PhrasePositions pp2 = Lesser(pp, rg[k]);
if (!AdvancePP(pp2)) // at initialization always advance pp with higher offset
{
return false; // exhausted
}
if (pp2.rptInd < i) // should not happen?
{
incr = 0;
break;
}
}
}
}
else
{
// simpler, we know exactly how much to advance
for (int j = 1; j < rg.Length; j++)
{
for (int k = 0; k < j; k++)
{
if (!rg[j].NextPosition())
{
return false; // PPs exhausted
}
}
}
}
}
return true; // PPs available
}
/// <summary>
/// Initialize with checking for repeats. Heavy work, but done only for the first candidate doc.
/// <para/>
/// If there are repetitions, check if multi-term postings (MTP) are involved.
/// <para/>
/// Without MTP, once PPs are placed in the first candidate doc, repeats (and groups) are visible.
/// <para/>
/// With MTP, a more complex check is needed, up-front, as there may be "hidden collisions".
/// <para/>
/// For example P1 has {A,B}, P1 has {B,C}, and the first doc is: "A C B". At start, P1 would point
/// to "A", p2 to "C", and it will not be identified that P1 and P2 are repetitions of each other.
/// <para/>
/// The more complex initialization has two parts:
/// <para/>
/// (1) identification of repetition groups.
/// <para/>
/// (2) advancing repeat groups at the start of the doc.
/// <para/>
/// For (1), a possible solution is to just create a single repetition group,
/// made of all repeating pps. But this would slow down the check for collisions,
/// as all pps would need to be checked. Instead, we compute "connected regions"
/// on the bipartite graph of postings and terms.
/// </summary>
private bool InitFirstTime()
{
//System.err.println("initFirstTime: doc: "+min.doc);
checkedRpts = true;
PlaceFirstPositions();
var rptTerms = RepeatingTerms();
hasRpts = rptTerms.Count > 0;
if (hasRpts)
{
rptStack = new PhrasePositions[numPostings]; // needed with repetitions
IList<IList<PhrasePositions>> rgs = GatherRptGroups(rptTerms);
SortRptGroups(rgs);
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Sort each repetition group by (query) offset.
/// Done only once (at first doc) and allows to initialize faster for each doc.
/// </summary>
private void SortRptGroups(IList<IList<PhrasePositions>> rgs)
{
rptGroups = new PhrasePositions[rgs.Count][];
IComparer<PhrasePositions> cmprtr = Comparer<PhrasePositions>.Create((pp1, pp2) => pp1.offset - pp2.offset);
for (int i = 0; i < rptGroups.Length; i++)
{
PhrasePositions[] rg = rgs[i].ToArray();
Array.Sort(rg, cmprtr);
rptGroups[i] = rg;
for (int j = 0; j < rg.Length; j++)
{
rg[j].rptInd = j; // we use this index for efficient re-queuing
}
}
}
/// <summary>
/// Detect repetition groups. Done once - for first doc. </summary>
private IList<IList<PhrasePositions>> GatherRptGroups(JCG.LinkedDictionary<Term, int?> rptTerms)
{
PhrasePositions[] rpp = RepeatingPPs(rptTerms);
IList<IList<PhrasePositions>> res = new List<IList<PhrasePositions>>();
if (!hasMultiTermRpts)
{
// simpler - no multi-terms - can base on positions in first doc
for (int i = 0; i < rpp.Length; i++)
{
PhrasePositions pp = rpp[i];
if (pp.rptGroup >= 0) // already marked as a repetition
{
continue;
}
int tpPos = TpPos(pp);
for (int j = i + 1; j < rpp.Length; j++)
{
PhrasePositions pp2 = rpp[j];
if (pp2.rptGroup >= 0 || pp2.offset == pp.offset || TpPos(pp2) != tpPos) // not a repetition - not a repetition: two PPs are originally in same offset in the query! - already marked as a repetition
{
continue;
}
// a repetition
int g = pp.rptGroup;
if (g < 0)
{
g = res.Count;
pp.rptGroup = g;
List<PhrasePositions> rl = new List<PhrasePositions>(2);
rl.Add(pp);
res.Add(rl);
}
pp2.rptGroup = g;
res[g].Add(pp2);
}
}
}
else
{
// more involved - has multi-terms
IList<JCG.HashSet<PhrasePositions>> tmp = new List<JCG.HashSet<PhrasePositions>>();
IList<FixedBitSet> bb = PpTermsBitSets(rpp, rptTerms);
UnionTermGroups(bb);
IDictionary<Term, int> tg = TermGroups(rptTerms, bb);
JCG.HashSet<int> distinctGroupIDs = new JCG.HashSet<int>(tg.Values);
for (int i = 0; i < distinctGroupIDs.Count; i++)
{
tmp.Add(new JCG.HashSet<PhrasePositions>());
}
foreach (PhrasePositions pp in rpp)
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
int g = tg[t];
tmp[g].Add(pp);
Debug.Assert(pp.rptGroup == -1 || pp.rptGroup == g);
pp.rptGroup = g;
}
}
}
foreach (JCG.HashSet<PhrasePositions> hs in tmp)
{
res.Add(new List<PhrasePositions>(hs));
}
}
return res;
}
/// <summary>
/// Actual position in doc of a PhrasePosition, relies on that position = tpPos - offset) </summary>
private int TpPos(PhrasePositions pp)
{
return pp.position + pp.offset;
}
/// <summary>
/// Find repeating terms and assign them ordinal values </summary>
private JCG.LinkedDictionary<Term, int?> RepeatingTerms()
{
JCG.LinkedDictionary<Term, int?> tord = new JCG.LinkedDictionary<Term, int?>();
Dictionary<Term, int?> tcnt = new Dictionary<Term, int?>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
int? cnt0;
tcnt.TryGetValue(t, out cnt0);
int? cnt = cnt0 == null ? new int?(1) : new int?(1 + (int)cnt0);
tcnt[t] = cnt;
if (cnt == 2)
{
tord[t] = tord.Count;
}
}
}
return tord;
}
/// <summary>
/// Find repeating pps, and for each, if has multi-terms, update this.hasMultiTermRpts </summary>
private PhrasePositions[] RepeatingPPs(IDictionary<Term, int?> rptTerms)
{
List<PhrasePositions> rp = new List<PhrasePositions>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
rp.Add(pp);
hasMultiTermRpts |= (pp.terms.Length > 1);
break;
}
}
}
return rp.ToArray();
}
/// <summary>
/// bit-sets - for each repeating pp, for each of its repeating terms, the term ordinal values is set </summary>
private IList<FixedBitSet> PpTermsBitSets(PhrasePositions[] rpp, IDictionary<Term, int?> tord)
{
List<FixedBitSet> bb = new List<FixedBitSet>(rpp.Length);
foreach (PhrasePositions pp in rpp)
{
FixedBitSet b = new FixedBitSet(tord.Count);
var ord = new int?();
foreach (var t in pp.terms)
{
if (tord.TryGetValue(t, out ord) && ord != null)
b.Set((int)ord);
}
bb.Add(b);
}
return bb;
}
/// <summary>
/// Union (term group) bit-sets until they are disjoint (O(n^^2)), and each group have different terms </summary>
private void UnionTermGroups(IList<FixedBitSet> bb)
{
int incr;
for (int i = 0; i < bb.Count - 1; i += incr)
{
incr = 1;
int j = i + 1;
while (j < bb.Count)
{
if (bb[i].Intersects(bb[j]))
{
bb[i].Or(bb[j]);
bb.RemoveAt(j);
incr = 0;
}
else
{
++j;
}
}
}
}
/// <summary>
/// Map each term to the single group that contains it </summary>
private IDictionary<Term, int> TermGroups(JCG.LinkedDictionary<Term, int?> tord, IList<FixedBitSet> bb)
{
Dictionary<Term, int> tg = new Dictionary<Term, int>();
Term[] t = tord.Keys.ToArray(/*new Term[0]*/);
for (int i = 0; i < bb.Count; i++) // i is the group no.
{
DocIdSetIterator bits = bb[i].GetIterator();
int ord;
while ((ord = bits.NextDoc()) != NO_MORE_DOCS)
{
tg[t[ord]] = i;
}
}
return tg;
}
public override int Freq => numMatches;
internal float SloppyFreq => sloppyFreq;
// private void printQueue(PrintStream ps, PhrasePositions ext, String title) {
// //if (min.doc != ?) return;
// ps.println();
// ps.println("---- "+title);
// ps.println("EXT: "+ext);
// PhrasePositions[] t = new PhrasePositions[pq.size()];
// if (pq.size()>0) {
// t[0] = pq.pop();
// ps.println(" " + 0 + " " + t[0]);
// for (int i=1; i<t.length; i++) {
// t[i] = pq.pop();
// assert t[i-1].position <= t[i].position;
// ps.println(" " + i + " " + t[i]);
// }
// // add them back
// for (int i=t.length-1; i>=0; i--) {
// pq.add(t[i]);
// }
// }
// }
private bool AdvanceMin(int target)
{
if (!min.SkipTo(target))
{
max.doc = NO_MORE_DOCS; // for further calls to docID()
return false;
}
min = min.next; // cyclic
max = max.next; // cyclic
return true;
}
public override int DocID => max.doc;
public override int NextDoc()
{
return Advance(max.doc + 1); // advance to the next doc after #docID()
}
public override float GetScore()
{
return docScorer.Score(max.doc, sloppyFreq);
}
public override int Advance(int target)
{
Debug.Assert(target > DocID);
do
{
if (!AdvanceMin(target))
{
return NO_MORE_DOCS;
}
while (min.doc < max.doc)
{
if (!AdvanceMin(max.doc))
{
return NO_MORE_DOCS;
}
}
// found a doc with all of the terms
sloppyFreq = PhraseFreq(); // check for phrase
target = min.doc + 1; // next target in case sloppyFreq is still 0
} while (sloppyFreq == 0f);
// found a match
return max.doc;
}
public override long GetCost()
{
return cost;
}
public override string ToString()
{
return "scorer(" + m_weight + ")";
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.CortexM
{
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
//--//
// TODO: put right addresses, and fix code generation for LLVM that does not understand the attribute's constants
//[MemoryMappedPeripheral(Base = 0x40D00000U, Length = 0x000000D0U)]
public class SysTick
{
//////
////// From core_cm[x].h in mBed CMSIS support:
//////
////// /** \brief Structure type to access the System Timer (SysTick).
////// */
////// typedef struct
////// {
////// __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
////// __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
////// __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
////// __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
////// } SysTick_Type;
//////
////// ...
////// ...
////// ...
//////
////// #define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
//////
//--//
public const uint MaxCounterValue = 0x00FFFFFF;
//
// SYST_CSR @ address 0xE000E010
//
private const int SYST_CSR__MASK = 0x00010007;
private const int SYST_CSR__ENABLE___SHIFT = 0;
private const uint SYST_CSR__ENABLE___MASK = 0x00000001u << SYST_CSR__ENABLE___SHIFT;
private const uint SYST_CSR__ENABLE___ENABLED = 1u << SYST_CSR__ENABLE___SHIFT;
private const uint SYST_CSR__ENABLE___DISABLED = 0u << SYST_CSR__ENABLE___SHIFT;
private const int SYST_CSR__TICKINT___SHIFT = 1;
private const uint SYST_CSR__TICKINT___MASK = 0x00000001u << SYST_CSR__TICKINT___SHIFT;
private const uint SYST_CSR__TICKINT___ENABLED = 1u << SYST_CSR__TICKINT___SHIFT;
private const uint SYST_CSR__TICKINT___DISABLED = 0u << SYST_CSR__TICKINT___SHIFT;
private const int SYST_CSR__CLKSOURCE___SHIFT = 2;
private const uint SYST_CSR__CLKSOURCE___MASK = 0x00000001u << SYST_CSR__CLKSOURCE___SHIFT;
private const uint SYST_CSR__CLKSOURCE___PROCESSOR = 1u << SYST_CSR__CLKSOURCE___SHIFT;
private const uint SYST_CSR__CLKSOURCE___EXTERNAL = 0u << SYST_CSR__CLKSOURCE___SHIFT;
private const int SYST_CSR__COUNTFLAG___SHIFT = 16;
private const uint SYST_CSR__COUNTFLAG___MASK = 0x00000001u << SYST_CSR__COUNTFLAG___SHIFT;
private const uint SYST_CSR__COUNTFLAG___COUNTED = 1u << SYST_CSR__COUNTFLAG___SHIFT;
private const uint SYST_CSR__COUNTFLAG___DIDNOTCOUNT = 0u << SYST_CSR__COUNTFLAG___SHIFT;
//--//
private const uint SYST_CSR__STARTED = SYST_CSR__ENABLE___ENABLED | SYST_CSR__TICKINT___ENABLED | SYST_CSR__CLKSOURCE___PROCESSOR;
private const uint SYST_CSR__STOPPED = SYST_CSR__TICKINT___ENABLED | SYST_CSR__CLKSOURCE___PROCESSOR;
//
// SYST_CSR @ address 0xE000E014
//
private const int SYST_RVR__MASK = 0x00FFFFFF;
private const int SYST_RVR__RELOAD___MASK = 0x00FFFFFF;
private const int SYST_RVR__RELOAD___SHIFT = 0;
//
// SYST_CVR @ address 0xE000E018
//
private const int SYST_CVR__MASK = 0x00FFFFFF;
private const int SYST_CVR__CURRENT___MASK = 0x00FFFFFF;
private const int SYST_CVR__CURRENT___SHIFT = 0;
//
// SYST_CALIB @ address 0xE000E01C
//
private const uint SYST_CALIB__MASK = 0xC0FFFFFF;
private const int SYST_CALIB__TENMS___SHIFT = 0;
private const uint SYST_CALIB__TENMS___MASK = 0x00FFFFFFu << SYST_CALIB__TENMS___SHIFT;
private const int SYST_CALIB__SKEW__SHIFT = 30;
private const uint SYST_CALIB__SKEW__MASK = 1u << SYST_CALIB__SKEW__SHIFT;
private const uint SYST_CALIB__SKEW__PRECISE = 0u << SYST_CALIB__SKEW__SHIFT;
private const uint SYST_CALIB__SKEW__NOTPRECISE = 1u << SYST_CALIB__SKEW__SHIFT;
private const int SYST_CALIB__NOREF__SHIFT = 31;
private const uint SYST_CALIB__NOREF__MASK = 1u << SYST_CALIB__NOREF__SHIFT;
private const uint SYST_CALIB__NOREF__HASREF = 0u << SYST_CALIB__NOREF__SHIFT;
private const uint SYST_CALIB__NOREF__NOREF = 1u << SYST_CALIB__NOREF__SHIFT;
//--//
public uint Match
{
[RT.Inline]
get
{
return CMSIS_STUB_SysTick_GetLOAD( );
}
[RT.Inline]
set
{
RT.BugCheck.Assert( value <= 0x00FFFFFF, RT.BugCheck.StopCode.IncorrectArgument );
CMSIS_STUB_SysTick_SetLOAD( value );
}
}
public uint Calibration
{
[RT.Inline]
get
{
return CMSIS_STUB_SysTick_GetCALIB( );
}
}
public uint Counter
{
[RT.Inline]
get
{
return CMSIS_STUB_SysTick_GetVAL( );
}
[RT.Inline]
set
{
RT.BugCheck.Assert( value <= 0x00FFFFFF, RT.BugCheck.StopCode.IncorrectArgument );
//
// writing any value clear the register to zero, and also clears the count flag
//
CMSIS_STUB_SysTick_SetVAL( value );
}
}
public bool HasMatched
{
[RT.Inline]
get
{
uint ctrl = CMSIS_STUB_SysTick_GetCTRL( );
return (( ctrl & SYST_CSR__COUNTFLAG___MASK ) == SYST_CSR__COUNTFLAG___COUNTED);
}
}
[RT.Inline]
public void ResetAndClear()
{
// writing the counter value clear the COUNTFLAG
this.Counter = 0;
}
public bool Enabled
{
[RT.Inline]
set
{
if(value == true)
{
// enable SysTick with interrupts from processor clock
CMSIS_STUB_SysTick_SetCTRL( SYST_CSR__STARTED );
}
else
{
uint ctrl = CMSIS_STUB_SysTick_GetCTRL( );
ctrl &= ~SYST_CSR__ENABLE___ENABLED;
CMSIS_STUB_SysTick_SetCTRL( ctrl );
}
}
}
public uint TenMillisecondsCalibrationValue
{
get
{
return CMSIS_STUB_SysTick_GetCALIB( ) & SYST_CALIB__TENMS___MASK;
}
}
public bool HasRef
{
get
{
return ((CMSIS_STUB_SysTick_GetCALIB() & SYST_CALIB__NOREF__MASK) == SYST_CALIB__NOREF__HASREF);
}
}
public bool IsPrecise
{
get
{
return (CMSIS_STUB_SysTick_GetCALIB() & SYST_CALIB__SKEW__MASK) == SYST_CALIB__SKEW__PRECISE;
}
}
//
// Access Methods
//
public static extern SysTick Instance
{
[RT.SingletonFactory()]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
//--//
[DllImport( "C" )]
private static extern uint CMSIS_STUB_SysTick_GetCTRL( );
[DllImport( "C" )]
private static extern uint CMSIS_STUB_SysTick_GetLOAD( );
[DllImport( "C" )]
private static extern uint CMSIS_STUB_SysTick_GetVAL( );
[DllImport( "C" )]
private static extern uint CMSIS_STUB_SysTick_GetCALIB( );
[DllImport( "C" )]
private static extern void CMSIS_STUB_SysTick_SetCTRL( uint value );
[DllImport( "C" )]
private static extern void CMSIS_STUB_SysTick_SetLOAD( uint value );
[DllImport( "C" )]
private static extern void CMSIS_STUB_SysTick_SetVAL( uint value );
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
namespace System.Data.SqlClient
{
sealed internal class SqlConnectionFactory : DbConnectionFactory
{
private SqlConnectionFactory() : base() { }
public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory();
override public DbProviderFactory ProviderFactory
{
get
{
return SqlClientFactory.Instance;
}
}
override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
{
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null);
}
override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
{
SqlConnectionString opt = (SqlConnectionString)options;
SqlConnectionPoolKey key = (SqlConnectionPoolKey)poolKey;
SqlInternalConnection result = null;
SessionData recoverySessionData = null;
SqlConnection sqlOwningConnection = owningConnection as SqlConnection;
bool applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false;
SqlConnectionString userOpt = null;
if (userOptions != null)
{
userOpt = (SqlConnectionString)userOptions;
}
else if (owningConnection != null)
{
userOpt = (SqlConnectionString)(((SqlConnection)owningConnection).UserConnectionOptions);
}
if (owningConnection != null)
{
recoverySessionData = ((SqlConnection)owningConnection)._recoverySessionData;
}
bool redirectedUserInstance = false;
DbConnectionPoolIdentity identity = null;
// Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
// Used by notifications.
if (opt.IntegratedSecurity)
{
if (pool != null)
{
identity = pool.Identity;
}
else
{
identity = DbConnectionPoolIdentity.GetCurrent();
}
}
// FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
// If "user instance=true" is in the connection string, we're using SSE user instances
if (opt.UserInstance)
{
// opt.DataSource is used to create the SSE connection
redirectedUserInstance = true;
string instanceName;
if ((null == pool) ||
(null != pool && pool.Count <= 0))
{ // Non-pooled or pooled and no connections in the pool.
SqlInternalConnectionTds sseConnection = null;
try
{
// We throw an exception in case of a failure
// NOTE: Cloning connection option opt to set 'UserInstance=True' and 'Enlist=False'
// This first connection is established to SqlExpress to get the instance name
// of the UserInstance.
SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */);
sseConnection = new SqlInternalConnectionTds(identity, sseopt, null, false, applyTransientFaultHandling: applyTransientFaultHandling);
// NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
instanceName = sseConnection.InstanceName;
if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal))
{
throw SQL.NonLocalSSEInstance();
}
if (null != pool)
{ // Pooled connection - cache result
SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
// No lock since we are already in creation mutex
providerInfo.InstanceName = instanceName;
}
}
finally
{
if (null != sseConnection)
{
sseConnection.Dispose();
}
}
}
else
{ // Cached info from pool.
SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
// No lock since we are already in creation mutex
instanceName = providerInfo.InstanceName;
}
// NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
// retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
// options immutable - stored in global hash - don't modify
opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */);
poolGroupProviderInfo = null; // null so we do not pass to constructor below...
}
result = new SqlInternalConnectionTds(identity, opt, poolGroupProviderInfo, redirectedUserInstance, userOpt, recoverySessionData, applyTransientFaultHandling: applyTransientFaultHandling);
return result;
}
protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous)
{
Debug.Assert(!ADP.IsEmpty(connectionString), "empty connectionString");
SqlConnectionString result = new SqlConnectionString(connectionString);
return result;
}
override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
{
DbConnectionPoolProviderInfo providerInfo = null;
if (((SqlConnectionString)connectionOptions).UserInstance)
{
providerInfo = new SqlConnectionPoolProviderInfo();
}
return providerInfo;
}
override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions)
{
SqlConnectionString opt = (SqlConnectionString)connectionOptions;
DbConnectionPoolGroupOptions poolingOptions = null;
if (opt.Pooling)
{ // never pool context connections.
int connectionTimeout = opt.ConnectTimeout;
if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue / 1000))
connectionTimeout *= 1000;
else if (connectionTimeout >= Int32.MaxValue / 1000)
connectionTimeout = Int32.MaxValue;
poolingOptions = new DbConnectionPoolGroupOptions(
opt.IntegratedSecurity,
opt.MinPoolSize,
opt.MaxPoolSize,
connectionTimeout,
opt.LoadBalanceTimeout
);
}
return poolingOptions;
}
override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions);
}
internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key)
{
SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key);
if (null == connectionOptions)
{
connectionOptions = new SqlConnectionString(key.ConnectionString);
}
if (connectionOptions.IsEmpty)
{
throw ADP.NoConnectionString();
}
return connectionOptions;
}
override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection)
{
SqlConnection c = (connection as SqlConnection);
if (null != c)
{
return c.PoolGroup;
}
return null;
}
override internal DbConnectionInternal GetInnerConnection(DbConnection connection)
{
SqlConnection c = (connection as SqlConnection);
if (null != c)
{
return c.InnerConnection;
}
return null;
}
override internal void PermissionDemand(DbConnection outerConnection)
{
SqlConnection c = (outerConnection as SqlConnection);
if (null != c)
{
c.PermissionDemand();
}
}
override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup)
{
SqlConnection c = (outerConnection as SqlConnection);
if (null != c)
{
c.PoolGroup = poolGroup;
}
}
override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to)
{
SqlConnection c = (owningObject as SqlConnection);
if (null != c)
{
c.SetInnerConnectionEvent(to);
}
}
override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from)
{
SqlConnection c = (owningObject as SqlConnection);
if (null != c)
{
return c.SetInnerConnectionFrom(to, from);
}
return false;
}
override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to)
{
SqlConnection c = (owningObject as SqlConnection);
if (null != c)
{
c.SetInnerConnectionTo(to);
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * 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 System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
readonly CallInvocationDetails<TRequest, TResponse> details;
readonly INativeCall injectedNativeCall; // for testing
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Indicates that steaming call has finished.
TaskCompletionSource<object> streamingCallFinishedTcs = new TaskCompletionSource<object>();
// Response headers set here once received.
TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>();
// Set after status is received. Used for both unary and streaming response calls.
ClientSideStatus? finishedStatus;
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails)
: base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer, callDetails.Channel.Environment)
{
this.details = callDetails.WithOptions(callDetails.Options.Normalize());
this.initialMetadataSent = true; // we always send metadata at the very beginning of the call.
}
/// <summary>
/// This constructor should only be used for testing.
/// </summary>
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails)
{
this.injectedNativeCall = injectedNativeCall;
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(TRequest msg)
{
var profiler = Profilers.ForCurrentThread();
using (profiler.NewScope("AsyncCall.UnaryCall"))
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(cq);
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(ctx, payload, metadataArray, GetWriteFlagsForCall());
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch"))
{
HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata());
}
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
// Once the blocking call returns, the result should be available synchronously.
// Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException.
return unaryResponseTcs.Task.GetAwaiter().GetResult();
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartUnary(HandleUnaryResponse, payload, metadataArray, GetWriteFlagsForCall());
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
halfcloseRequested = true;
byte[] payload = UnsafeSerialize(msg);
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall());
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(environment.CompletionQueue);
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendMessage(TRequest msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate)
{
StartSendMessageInternal(msg, writeFlags, completionDelegate);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate)
{
StartReadMessageInternal(completionDelegate);
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendCloseFromClient(HandleHalfclosed);
halfcloseRequested = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise.
/// </summary>
public Task StreamingCallFinishedTask
{
get
{
return streamingCallFinishedTcs.Task;
}
}
/// <summary>
/// Get the task that completes once response headers are received.
/// </summary>
public Task<Metadata> ResponseHeadersAsync
{
get
{
return responseHeadersTcs.Task;
}
}
/// <summary>
/// Gets the resulting status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished.");
return finishedStatus.Value.Status;
}
}
/// <summary>
/// Gets the trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished.");
return finishedStatus.Value.Trailers;
}
}
public CallInvocationDetails<TRequest, TResponse> Details
{
get
{
return this.details;
}
}
protected override void OnAfterReleaseResources()
{
details.Channel.RemoveCallReference(this);
}
protected override bool IsClient
{
get { return true; }
}
private void Initialize(CompletionQueueSafeHandle cq)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCall.Initialize"))
{
var call = CreateNativeCall(cq);
details.Channel.AddCallReference(this);
InitializeInternal(call);
RegisterCancellationCallback();
}
}
private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCall.CreateNativeCall"))
{
if (injectedNativeCall != null)
{
return injectedNativeCall; // allows injecting a mock INativeCall in tests.
}
var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance;
var credentials = details.Options.Credentials;
using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null)
{
var result = details.Channel.Handle.CreateCall(environment.CompletionRegistry,
parentCall, ContextPropagationToken.DefaultMask, cq,
details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials);
return result;
}
}
}
// Make sure that once cancellationToken for this call is cancelled, Cancel() will be called.
private void RegisterCancellationCallback()
{
var token = details.Options.CancellationToken;
if (token.CanBeCanceled)
{
token.Register(() => this.Cancel());
}
}
/// <summary>
/// Gets WriteFlags set in callDetails.Options.WriteOptions
/// </summary>
private WriteFlags GetWriteFlagsForCall()
{
var writeOptions = details.Options.WriteOptions;
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders)
{
responseHeadersTcs.SetResult(responseHeaders);
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse"))
{
TResponse msg = default(TResponse);
var deserializeException = success ? TryDeserialize(receivedMessage, out msg) : null;
lock (myLock)
{
finished = true;
if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
{
receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
}
finishedStatus = receivedStatus;
ReleaseResourcesIfPossible();
}
responseHeadersTcs.SetResult(responseHeaders);
var status = receivedStatus.Status;
if (!success || status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status));
return;
}
unaryResponseTcs.SetResult(msg);
}
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, ClientSideStatus receivedStatus)
{
lock (myLock)
{
finished = true;
finishedStatus = receivedStatus;
ReleaseResourcesIfPossible();
}
var status = receivedStatus.Status;
if (!success || status.StatusCode != StatusCode.OK)
{
streamingCallFinishedTcs.SetException(new RpcException(status));
return;
}
streamingCallFinishedTcs.SetResult(null);
}
}
}
| |
using IL2CPU.API;
using IL2CPU.API.Attribs;
using XSharp;
using XSharp.Assembler;
namespace Cosmos.Debug.Kernel.Plugs.Asm
{
[Plug(Target = typeof(Debugger))]
public static class DebuggerAsm
{
[PlugMethod(Assembler = typeof(DebugBreak))]
public static void Break(Debugger aThis) { }
[PlugMethod(Assembler = typeof(DebugDoSend))]
public static void DoSend(string aText) { }
[PlugMethod(Assembler = typeof(DebugDoSendNumber))]
public static void DoSendNumber(int aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendNumber))]
public static void DoSendNumber(uint aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
public static void DoSendNumber(long aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendLongNumber))]
public static void DoSendNumber(ulong aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendComplexNumber))]
public static void DoSendNumber(float aNumber) { }
[PlugMethod(Assembler = typeof(DebugDoSendComplexLongNumber))]
public static void DoSendNumber(double aNumber) { }
[PlugMethod(Assembler = typeof(DebugSendMessageBox))]
public static unsafe void SendMessageBox(Debugger aThis, int aLength, char* aText) { }
[PlugMethod(Assembler = typeof(DebugSendPtr))]
public static unsafe void SendPtr(Debugger aThis, object aPtr) { }
[PlugMethod(Assembler = typeof(DebugSendChannelCommand))]
public static unsafe void SendChannelCommand(byte aChannel, byte aCommand, int aByteCount, byte* aData) { }
[PlugMethod(Assembler = typeof(DebugSendChannelCommandNoData))]
public static unsafe void SendChannelCommand(byte aChannel, byte aCommand) { }
[PlugMethod(Assembler = typeof(DoBochsBreak))]
public static void DoBochsBreak() { }
[Inline]
public static void SendKernelPanic(uint id)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendKernelPanic");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
[PlugMethod(Assembler = typeof(DoRealHalt))]
public static void DoRealHalt() { }
//[PlugMethod(Assembler = typeof(DebugTraceOff))]
//public static void TraceOff() { }
//[PlugMethod(Assembler = typeof(DebugTraceOn))]
//public static void TraceOn() { }
}
//TODO: Make a new plug attrib that assembly plug methods dont need
// an empty stub also, its just extra fluff - although they allow signature matching
// Maybe could merge this into the same unit as the plug
public class DebugTraceOff : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_TraceOff");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DebugTraceOn : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_TraceOn");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for SendChannelCommand
/// </summary>
/// <remarks>
/// AL contains channel
/// BL contains command
/// ECX contains number of bytes to send as command data
/// ESI contains data start pointer
/// </remarks>
public class DebugSendChannelCommand : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov AL, [EBP + 20]");
new LiteralAssemblerCode("mov BL, [EBP + 16]");
new LiteralAssemblerCode("mov ECX, [EBP + 12]");
new LiteralAssemblerCode("mov ESI, [EBP + 8]");
new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for SendChannelCommandNoData
/// </summary>
/// <remarks>
/// AL contains channel
/// BL contains command
/// ECX contains number of bytes to send as command data
/// ESI contains data start pointer
/// </remarks>
public class DebugSendChannelCommandNoData : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov AL, [EBP + 12]");
new LiteralAssemblerCode("mov BL, [EBP + 8]");
new LiteralAssemblerCode("mov ECX, 0");
new LiteralAssemblerCode("mov ESI, EBP");
new LiteralAssemblerCode("call DebugStub_SendCommandOnChannel");
new LiteralAssemblerCode("%endif");
}
}
public class DebugBreak : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("mov dword [DebugStub_DebugBreakOnNextTrace], 1");
new LiteralAssemblerCode("%endif");
}
}
/// <summary>
/// Assembler for DoSend
/// </summary>
/// <remarks>
/// EBP + 12 contains length
/// EBP + 8 contains first char pointer
/// </remarks>
public class DebugDoSend : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
XS.Label(".BeforeArgumentsPrepare");
new LiteralAssemblerCode("mov EBX, [EBP + 12]");
new LiteralAssemblerCode("push dword [EBX + 12]");
new LiteralAssemblerCode("add EBX, 16");
new LiteralAssemblerCode("push dword EBX");
XS.Label(".BeforeCall");
new LiteralAssemblerCode("Call DebugStub_SendText");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendSimpleNumber");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendLongNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 12]");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendSimpleLongNumber");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendComplexNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendComplexNumber");
new LiteralAssemblerCode("add ESP, 4");
new LiteralAssemblerCode("%endif");
}
}
public class DebugDoSendComplexLongNumber : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("push dword [EBP + 12]");
new LiteralAssemblerCode("push dword [EBP + 8]");
new LiteralAssemblerCode("Call DebugStub_SendComplexLongNumber");
new LiteralAssemblerCode("add ESP, 8");
new LiteralAssemblerCode("%endif");
}
}
public class DebugSendMessageBox : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_SendMessageBox");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DebugSendPtr : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
new LiteralAssemblerCode("%ifdef DEBUGSTUB");
new LiteralAssemblerCode("pushad");
new LiteralAssemblerCode("Call DebugStub_SendPtr");
new LiteralAssemblerCode("popad");
new LiteralAssemblerCode("%endif");
}
}
public class DoBochsBreak : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
XS.Exchange(XSRegisters.BX, XSRegisters.BX);
}
}
public class DoRealHalt : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
XS.DisableInterrupts();
// bochs magic break
//Exchange(BX, BX);
XS.Halt();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public class PresenceModule : IRegionModule, IPresenceModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private bool m_Gridmode = false;
// some default scene for doing things that aren't connected to a specific scene. Avoids locking.
private Scene m_initialScene;
private List<Scene> m_Scenes = new List<Scene>();
// we currently are only interested in root-agents. If the root isn't here, we don't know the region the
// user is in, so we have to ask the messaging server anyway.
private Dictionary<UUID, Scene> m_RootAgents =
new Dictionary<UUID, Scene>();
public event PresenceChange OnPresenceChange;
public event BulkPresenceData OnBulkPresenceData;
public void Initialise(Scene scene, IConfigSource config)
{
lock (m_Scenes)
{
// This is a shared module; Initialise will be called for every region on this server.
// Only check config once for the first region.
if (m_Scenes.Count == 0)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"PresenceModule", "PresenceModule") !=
"PresenceModule")
return;
cnf = config.Configs["Startup"];
if (cnf != null)
m_Gridmode = cnf.GetBoolean("gridmode", false);
m_Enabled = true;
m_initialScene = scene;
}
if (m_Gridmode)
NotifyMessageServerOfStartup(scene);
m_Scenes.Add(scene);
}
scene.RegisterModuleInterface<IPresenceModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
}
public void PostInitialise()
{
}
public void Close()
{
if (!m_Gridmode || !m_Enabled)
return;
if (OnPresenceChange != null)
{
lock (m_RootAgents)
{
// on shutdown, users are kicked, too
foreach (KeyValuePair<UUID, Scene> pair in m_RootAgents)
{
OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero));
}
}
}
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
NotifyMessageServerOfShutdown(scene);
}
}
public string Name
{
get { return "PresenceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// new client doesn't mean necessarily that user logged in, it just means it entered one of the
// the regions on this server
public void OnNewClient(IClientAPI client)
{
client.OnConnectionClosed += OnConnectionClosed;
client.OnLogout += OnLogout;
// KLUDGE: See handler for details.
client.OnEconomyDataRequest += OnEconomyDataRequest;
}
// connection closed just means *one* client connection has been closed. It doesn't mean that the
// user has logged off; it might have just TPed away.
public void OnConnectionClosed(IClientAPI client)
{
// TODO: Have to think what we have to do here...
// Should we just remove the root from the list (if scene matches)?
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
lock (m_RootAgents)
{
Scene rootScene;
if (!(m_RootAgents.TryGetValue(client.AgentId, out rootScene)) || scene != rootScene)
return;
m_RootAgents.Remove(client.AgentId);
}
// Should it have logged off, we'll do the logout part in OnLogout, even if no root is stored
// anymore. It logged off, after all...
}
// Triggered when the user logs off.
public void OnLogout(IClientAPI client)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
// On logout, we really remove the client from rootAgents, even if the scene doesn't match
lock (m_RootAgents)
{
if (m_RootAgents.ContainsKey(client.AgentId)) m_RootAgents.Remove(client.AgentId);
}
// now inform the messaging server and anyone who is interested
NotifyMessageServerOfAgentLeaving(client.AgentId, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(client.AgentId, UUID.Zero));
}
public void OnSetRootAgentScene(UUID agentID, Scene scene)
{
// OnSetRootAgentScene can be called from several threads at once (with different agentID).
// Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
// correct locking).
lock (m_RootAgents)
{
Scene rootScene;
if (m_RootAgents.TryGetValue(agentID, out rootScene) && scene == rootScene)
{
return;
}
m_RootAgents[agentID] = scene;
}
Util.FireAndForget(delegate(object obj)
{
// inform messaging server that agent changed the region
NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
});
}
private void OnEconomyDataRequest(IClientAPI client, UUID agentID)
{
// KLUDGE: This is the only way I found to get a message (only) after login was completed and the
// client is connected enough to receive UDP packets.
// This packet seems to be sent only once, just after connection was established to the first
// region after login.
// We use it here to trigger a presence update; the old update-on-login was never be heard by
// the freshly logged in viewer, as it wasn't connected to the region at that time.
// TODO: Feel free to replace this by a better solution if you find one.
// get the agent. This should work every time, as we just got a packet from it
ScenePresence agent = null;
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
agent = scene.GetScenePresence(agentID);
if (agent != null) break;
}
}
// just to be paranoid...
if (agent == null)
{
m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID);
return;
}
// we are a bit premature here, but the next packet will switch this child agent to root.
if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID));
}
public void OnMakeChildAgent(ScenePresence agent)
{
// OnMakeChildAgent can be called from several threads at once (with different agent).
// Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
// correct locking).
lock (m_RootAgents)
{
Scene rootScene;
if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene)
{
m_RootAgents.Remove(agent.UUID);
}
}
// don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded
// to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment,
// which will update the messaging-server, too.
}
private void NotifyMessageServerOfStartup(Scene scene)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "region_startup";
XmlRpcRequest UpRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = UpRequest.Send(Util.XmlRpcRequestURI(scene.CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
}
}
private void NotifyMessageServerOfShutdown(Scene scene)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "region_shutdown";
XmlRpcRequest DownRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = DownRequest.Send(Util.XmlRpcRequestURI(scene.CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
}
}
private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["AgentID"] = agentID.ToString();
xmlrpcdata["RegionUUID"] = region.ToString();
xmlrpcdata["RegionHandle"] = regionHandle.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "agent_location";
XmlRpcRequest LocationRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = LocationRequest.Send(Util.XmlRpcRequestURI(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
}
}
private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["AgentID"] = agentID.ToString();
xmlrpcdata["RegionUUID"] = region.ToString();
xmlrpcdata["RegionHandle"] = regionHandle.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "agent_leaving";
XmlRpcRequest LeavingRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = LeavingRequest.Send(Util.XmlRpcRequestURI(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
}
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using NUnit.Framework;
using ZXing.Common;
using ZXing.Common.Test;
namespace ZXing.PDF417.Test
{
/// <summary>
/// This class tests Macro PDF417 barcode specific functionality. It ensures that information, which is split into
/// several barcodes can be properly combined again to yield the original data content.
/// @author Guenther Grau
/// </summary>
[TestFixture]
public sealed class PDF417BlackBox4TestCase : AbstractBlackBoxTestCase
{
#if !SILVERLIGHT
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#else
private static readonly DanielVaughan.Logging.ILog log = DanielVaughan.Logging.LogManager.GetLog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endif
private static readonly Encoding UTF8 = Encoding.UTF8;
private static readonly Encoding ISO88591 = Encoding.GetEncoding("ISO8859-1");
private const String TEST_BASE_PATH_SUFFIX = "test/data/blackbox/pdf417-4";
private readonly PDF417Reader barcodeReader = new PDF417Reader();
private readonly List<TestResult> testResults = new List<TestResult>();
private String testBase;
public PDF417BlackBox4TestCase()
: base(TEST_BASE_PATH_SUFFIX, null, BarcodeFormat.PDF_417)
{
// A little workaround to prevent aggravation in my IDE
if (!Directory.Exists(TEST_BASE_PATH_SUFFIX))
{
// try starting with 'core' since the test base is often given as the project root
testBase = Path.Combine("..\\..\\..\\Source", TEST_BASE_PATH_SUFFIX);
}
else
{
testBase = TEST_BASE_PATH_SUFFIX;
}
testResults.Add(new TestResult(2, 2, 0, 0, 0.0f));
}
[Test]
public override void testBlackBox()
{
testPDF417BlackBoxCountingResults(true);
}
private void testPDF417BlackBoxCountingResults(bool assertOnFailure)
{
Assert.IsFalse(testResults.Count == 0);
IDictionary<String, List<String>> imageFiles = getImageFileLists();
int testCount = testResults.Count;
int[] passedCounts = new int[testCount];
int[] tryHarderCounts = new int[testCount];
foreach (KeyValuePair<String, List<String>> testImageGroup in imageFiles)
{
log.InfoFormat("Starting Image Group {0}", testImageGroup.Key);
String fileBaseName = testImageGroup.Key;
String expectedText;
String expectedTextFile = fileBaseName + ".txt";
if (File.Exists(expectedTextFile))
{
expectedText = File.ReadAllText(expectedTextFile, UTF8);
}
else
{
expectedTextFile = fileBaseName + ".bin";
Assert.IsTrue(File.Exists(expectedTextFile));
expectedText = File.ReadAllText(expectedTextFile, ISO88591);
}
for (int x = 0; x < testCount; x++)
{
List<Result> results = new List<Result>();
foreach (var imageFile in testImageGroup.Value)
{
#if !SILVERLIGHT
var image = new Bitmap(Image.FromFile(imageFile));
#else
var image = new WriteableBitmap(0, 0);
image.SetSource(File.OpenRead(testImage));
#endif
var rotation = testResults[x].Rotation;
var rotatedImage = rotateImage(image, rotation);
var source = new BitmapLuminanceSource(rotatedImage);
var bitmap = new BinaryBitmap(new HybridBinarizer(source));
try
{
results.AddRange(decode(bitmap, false));
}
catch (ReaderException )
{
// ignore
}
}
results.Sort((arg0, arg1) =>
{
PDF417ResultMetadata resultMetadata = getMeta(arg0);
PDF417ResultMetadata otherResultMetadata = getMeta(arg1);
return resultMetadata.SegmentIndex - otherResultMetadata.SegmentIndex;
});
var resultText = new StringBuilder();
String fileId = null;
foreach (Result result in results)
{
PDF417ResultMetadata resultMetadata = getMeta(result);
Assert.NotNull(resultMetadata, "resultMetadata");
if (fileId == null)
{
fileId = resultMetadata.FileId;
}
Assert.AreEqual(fileId, resultMetadata.FileId, "FileId");
resultText.Append(result.Text);
}
Assert.AreEqual(expectedText, resultText.ToString(), "ExpectedText");
passedCounts[x]++;
tryHarderCounts[x]++;
}
}
// Print the results of all tests first
int totalFound = 0;
int totalMustPass = 0;
int numberOfTests = imageFiles.Count;
for (int x = 0; x < testResults.Count; x++)
{
TestResult testResult = testResults[x];
log.InfoFormat("Rotation {0} degrees:", (int) testResult.Rotation);
log.InfoFormat(" {0} of {1} images passed ({2} required)", passedCounts[x], numberOfTests,
testResult.MustPassCount);
log.InfoFormat(" {0} of {1} images passed with try harder ({2} required)", tryHarderCounts[x],
numberOfTests, testResult.TryHarderCount);
totalFound += passedCounts[x] + tryHarderCounts[x];
totalMustPass += testResult.MustPassCount + testResult.TryHarderCount;
}
int totalTests = numberOfTests*testCount*2;
log.InfoFormat("Decoded {0} images out of {1} ({2}%, {3} required)", totalFound, totalTests, totalFound*
100/
totalTests, totalMustPass);
if (totalFound > totalMustPass)
{
log.WarnFormat("+++ Test too lax by {0} images", totalFound - totalMustPass);
}
else if (totalFound < totalMustPass)
{
log.WarnFormat("--- Test failed by {0} images", totalMustPass - totalFound);
}
// Then run through again and assert if any failed
if (assertOnFailure)
{
for (int x = 0; x < testCount; x++)
{
TestResult testResult = testResults[x];
String label = "Rotation " + testResult.Rotation + " degrees: Too many images failed";
Assert.IsTrue(passedCounts[x] >= testResult.MustPassCount, label);
Assert.IsTrue(tryHarderCounts[x] >= testResult.TryHarderCount, "Try harder, " + label);
}
}
}
private static PDF417ResultMetadata getMeta(Result result)
{
return result.ResultMetadata == null ? null : (PDF417ResultMetadata) result.ResultMetadata[ResultMetadataType.PDF417_EXTRA_METADATA];
}
private Result[] decode(BinaryBitmap source, bool tryHarder)
{
IDictionary<DecodeHintType, Object> hints = new Dictionary<DecodeHintType, object>();
if (tryHarder)
{
hints[DecodeHintType.TRY_HARDER] = true;
}
return barcodeReader.decodeMultiple(source, hints);
}
private IDictionary<String, List<String>> getImageFileLists()
{
IDictionary<String, List<String>> result = new Dictionary<string, List<String>>();
foreach (string fileName in getImageFiles())
{
String testImageFileName = fileName;
String fileBaseName = testImageFileName.Substring(0, testImageFileName.LastIndexOf('-'));
List<String> files;
if (!result.ContainsKey(fileBaseName))
{
files = new List<String>();
result[fileBaseName] = files;
}
else
{
files = result[fileBaseName];
}
files.Add(fileName);
}
return result;
}
}
}
| |
// 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 gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>AdGroupAd</c> resource.</summary>
public sealed partial class AdGroupAdName : gax::IResourceName, sys::IEquatable<AdGroupAdName>
{
/// <summary>The possible contents of <see cref="AdGroupAdName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </summary>
CustomerAdGroupAd = 1,
}
private static gax::PathTemplate s_customerAdGroupAd = new gax::PathTemplate("customers/{customer_id}/adGroupAds/{ad_group_id_ad_id}");
/// <summary>Creates a <see cref="AdGroupAdName"/> 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="AdGroupAdName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupAdName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupAdName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupAdName"/> with the pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupAdName"/> constructed from the provided ids.</returns>
public static AdGroupAdName FromCustomerAdGroupAd(string customerId, string adGroupId, string adId) =>
new AdGroupAdName(ResourceNameType.CustomerAdGroupAd, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdName"/> with pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdName"/> with pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string adId) =>
FormatCustomerAdGroupAd(customerId, adGroupId, adId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdName"/> with pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdName"/> with pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupAd(string customerId, string adGroupId, string adId) =>
s_customerAdGroupAd.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}");
/// <summary>Parses the given resource name string into a new <see cref="AdGroupAdName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupAdName"/> if successful.</returns>
public static AdGroupAdName Parse(string adGroupAdName) => Parse(adGroupAdName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdName"/> 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>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdName">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="AdGroupAdName"/> if successful.</returns>
public static AdGroupAdName Parse(string adGroupAdName, bool allowUnparsed) =>
TryParse(adGroupAdName, allowUnparsed, out AdGroupAdName 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="AdGroupAdName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdName"/>, 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 adGroupAdName, out AdGroupAdName result) => TryParse(adGroupAdName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdName"/> 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>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdName">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="AdGroupAdName"/>, 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 adGroupAdName, bool allowUnparsed, out AdGroupAdName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupAdName, nameof(adGroupAdName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupAd.TryParseName(adGroupAdName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupAd(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupAdName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupAdName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdId = adId;
AdGroupId = adGroupId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupAdName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupAdName(string customerId, string adGroupId, string adId) : this(ResourceNameType.CustomerAdGroupAd, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))
{
}
/// <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>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdId { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { 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.CustomerAdGroupAd: return s_customerAdGroupAd.Expand(CustomerId, $"{AdGroupId}~{AdId}");
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 AdGroupAdName);
/// <inheritdoc/>
public bool Equals(AdGroupAdName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupAdName a, AdGroupAdName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupAdName a, AdGroupAdName b) => !(a == b);
}
public partial class AdGroupAd
{
/// <summary>
/// <see cref="AdGroupAdName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupAdName ResourceNameAsAdGroupAdName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupAdLabelName"/>-typed view over the <see cref="Labels"/> resource name property.
/// </summary>
internal gax::ResourceNameList<AdGroupAdLabelName> LabelsAsAdGroupAdLabelNames
{
get => new gax::ResourceNameList<AdGroupAdLabelName>(Labels, s => string.IsNullOrEmpty(s) ? null : AdGroupAdLabelName.Parse(s, allowUnparsed: true));
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Linq;
using System.Text;
namespace UnrealBuildTool
{
public interface IntelliSenseGatherer
{
/// <summary>
/// Adds all of the specified preprocessor definitions to this VCProject's list of preprocessor definitions for all modules in the project
/// </summary>
/// <param name="NewPreprocessorDefinitions">List of preprocessor definitons to add</param>
void AddIntelliSensePreprocessorDefinitions( List<string> NewPreprocessorDefinitions );
/// <summary>
/// Adds all of the specified include paths to this VCProject's list of include paths for all modules in the project
/// </summary>
/// <param name="NewIncludePaths">List of include paths to add</param>
/// <param name="bAddingSystemIncludes">Are the include paths to add system include paths</param>
void AddInteliiSenseIncludePaths(HashSet<string> NewIncludePaths, bool bAddingSystemIncludes);
}
/// <summary>
/// A single target within a project. A project may have any number of targets within it, which are basically compilable projects
/// in themselves that the project wraps up.
/// </summary>
public class ProjectTarget
{
/// The target rules file path on disk, if we have one
public string TargetFilePath;
/// Optional target rules for this target. If the target came from a *.Target.cs file on disk, then it will have one of these.
/// For targets that are synthetic (like UnrealBuildTool or other manually added project files) we won't have a rules object for those.
public TargetRules TargetRules;
/// Extra supported build platforms. Normally the target rules determines these, but for synthetic targets we'll add them here.
public List<UnrealTargetPlatform> ExtraSupportedPlatforms = new List<UnrealTargetPlatform>();
/// Extra supported build configurations. Normally the target rules determines these, but for synthetic targets we'll add them here.
public List<UnrealTargetConfiguration> ExtraSupportedConfigurations = new List<UnrealTargetConfiguration>();
/// If true, forces Development configuration regardless of which configuration is set as the Solution Configuration
public bool ForceDevelopmentConfiguration = false;
/// Whether the project requires 'Deploy' option set (VC projects)
public bool ProjectDeploys = false;
public override string ToString()
{
return Path.GetFileNameWithoutExtension(TargetFilePath);
}
}
/// <summary>
/// Class that stores info about aliased file.
/// </summary>
public class AliasedFile
{
public AliasedFile(string FileSystemPath, string ProjectPath)
{
this.FileSystemPath = FileSystemPath;
this.ProjectPath = ProjectPath;
}
// File system path.
public string FileSystemPath { get; private set; }
// Project path.
public string ProjectPath { get; private set; }
}
public abstract class ProjectFile : IntelliSenseGatherer
{
/// <summary>
/// Represents a single source file (or other type of file) in a project
/// </summary>
public class SourceFile
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="InitFilePath">Path to the source file on disk</param>
/// <param name="InitRelativeBaseFolder">The directory on this the path within the project will be relative to</param>
public SourceFile( string InitFilePath, string InitRelativeBaseFolder )
{
FilePath = InitFilePath;
RelativeBaseFolder = InitRelativeBaseFolder;
}
public SourceFile()
{
}
/// <summary>
/// File path to file on disk
/// </summary>
public string FilePath
{
get;
private set;
}
/// <summary>
/// Optional directory that overrides where files in this project are relative to when displayed in the IDE. If null, will default to the project's RelativeBaseFolder.
/// </summary>
public string RelativeBaseFolder
{
get;
private set;
}
}
/// <summary>
/// Constructs a new project file object
/// </summary>
/// <param name="InitFilePath">The path to the project file, relative to the master project file</param>
protected ProjectFile( string InitRelativeFilePath )
{
RelativeProjectFilePath = InitRelativeFilePath;
ShouldBuildByDefaultForSolutionTargets = true;
}
/// Full path to the project file on disk
public string ProjectFilePath
{
get
{
return Path.Combine( ProjectFileGenerator.MasterProjectRelativePath, RelativeProjectFilePath );
}
}
/// Project file path, relative to the master project
public string RelativeProjectFilePath
{
get;
private set;
}
/// Returns true if this is a generated project (as opposed to an imported project)
public bool IsGeneratedProject
{
get;
set;
}
/// Returns true if this is a "stub" project. Stub projects function as dumb containers for source files
/// and are never actually "built" by the master project. Stub projects are always "generated" projects.
public bool IsStubProject
{
get;
set;
}
/// Returns true if this is a foreign project, and requires UBT to be passed the path to the .uproject file
/// on the command line.
public bool IsForeignProject
{
get;
set;
}
/// Whether this project should be built for all solution targets
public bool ShouldBuildForAllSolutionTargets
{
get;
set;
}
/// Whether this project should be built by default. Can still be built from the IDE through the context menu.
public bool ShouldBuildByDefaultForSolutionTargets
{
get;
set;
}
/// All of the targets in this project. All non-stub projects must have at least one target.
public readonly List<ProjectTarget> ProjectTargets = new List<ProjectTarget>();
/// <summary>
/// Adds a list of files to this project, ignoring dupes
/// </summary>
/// <param name="FilesToAdd">Files to add</param>
/// <param name="RelativeBaseFolder">The directory the path within the project will be relative to</param>
public void AddFilesToProject( List<string> FilesToAdd, string RelativeBaseFolder )
{
foreach( var CurFile in FilesToAdd )
{
AddFileToProject( CurFile, RelativeBaseFolder );
}
}
/// Aliased (i.e. files is custom filter tree) in this project
public readonly List<AliasedFile> AliasedFiles = new List<AliasedFile>();
/// <summary>
/// Adds aliased file to the project.
/// </summary>
/// <param name="File">Aliased file.</param>
public void AddAliasedFileToProject(AliasedFile File)
{
AliasedFiles.Add(File);
}
/// <summary>
/// Adds a file to this project, ignoring dupes
/// </summary>
/// <param name="FilePath">Path to the file on disk</param>
/// <param name="RelativeBaseFolder">The directory the path within the project will be relative to</param>
public void AddFileToProject( string FilePath, string RelativeBaseFolder )
{
// Don't add duplicates
SourceFile ExistingFile = null;
if (SourceFileMap.TryGetValue(FilePath, out ExistingFile))
{
if( ExistingFile.RelativeBaseFolder != RelativeBaseFolder )
{
if( ( ExistingFile.RelativeBaseFolder != null ) != ( RelativeBaseFolder != null ) ||
!ExistingFile.RelativeBaseFolder.Equals( RelativeBaseFolder, StringComparison.InvariantCultureIgnoreCase ) )
{
throw new BuildException( "Trying to add file '" + FilePath + "' to project '" + ProjectFilePath + "' when the file already exists, but with a different relative base folder '" + RelativeBaseFolder + "' is different than the current file's '" + ExistingFile.RelativeBaseFolder + "'!" );
}
else
{
throw new BuildException( "Trying to add file '" + FilePath + "' to project '" + ProjectFilePath + "' when the file already exists, but the specified project relative base folder is different than the current file's!" );
}
}
}
else
{
SourceFile File = AllocSourceFile( FilePath, RelativeBaseFolder );
if( File != null )
{
SourceFileMap[FilePath] = File;
SourceFiles.Add( File );
}
}
}
/// <summary>
/// Splits the definition text into macro name and value (if any).
/// </summary>
/// <param name="Definition">Definition text</param>
/// <param name="Key">Out: The definition name</param>
/// <param name="Value">Out: The definition value or null if it has none</param>
/// <returns>Pair representing macro name and value.</returns>
private void SplitDefinitionAndValue(string Definition, out String Key, out String Value)
{
int EqualsIndex = Definition.IndexOf('=');
if (EqualsIndex >= 0)
{
Key = Definition.Substring(0, EqualsIndex);
Value = Definition.Substring(EqualsIndex + 1);
}
else
{
Key = Definition;
Value = "";
}
}
/// <summary>
/// Adds all of the specified preprocessor definitions to this VCProject's list of preprocessor definitions for all modules in the project
/// </summary>
/// <param name="NewPreprocessorDefinitions">List of preprocessor definitons to add</param>
public void AddIntelliSensePreprocessorDefinitions( List<string> NewPreprocessorDefinitions )
{
if( ProjectFileGenerator.OnlyGenerateIntelliSenseDataForProject == null ||
ProjectFileGenerator.OnlyGenerateIntelliSenseDataForProject == this )
{
foreach( var CurDef in NewPreprocessorDefinitions )
{
// Don't add definitions and value combinations that have already been added for this project
if( KnownIntelliSensePreprocessorDefinitions.Add( CurDef ) )
{
// Go ahead and check to see if the definition already exists, but the value is different
var AlreadyExists = false;
string Def, Value;
SplitDefinitionAndValue(CurDef, out Def, out Value);
for (int DefineIndex = 0; DefineIndex < IntelliSensePreprocessorDefinitions.Count; ++DefineIndex)
{
string ExistingDef, ExistingValue;
SplitDefinitionAndValue(IntelliSensePreprocessorDefinitions[DefineIndex], out ExistingDef, out ExistingValue);
if (ExistingDef == Def)
{
// Already exists, but the value is changing. We don't bother clobbering values for existing defines for this project.
AlreadyExists = true;
break;
}
}
if( !AlreadyExists )
{
IntelliSensePreprocessorDefinitions.Add( CurDef );
}
}
}
}
}
/// <summary>
/// Adds all of the specified include paths to this VCProject's list of include paths for all modules in the project
/// </summary>
/// <param name="NewIncludePaths">List of include paths to add</param>
public void AddInteliiSenseIncludePaths(HashSet<string> NewIncludePaths, bool bAddingSystemIncludes)
{
if( ProjectFileGenerator.OnlyGenerateIntelliSenseDataForProject == null ||
ProjectFileGenerator.OnlyGenerateIntelliSenseDataForProject == this )
{
foreach( var CurPath in NewIncludePaths )
{
if( bAddingSystemIncludes ? KnownIntelliSenseSystemIncludeSearchPaths.Add( CurPath ) : KnownIntelliSenseIncludeSearchPaths.Add( CurPath ) )
{
string PathRelativeToProjectFile;
// If the include string is an environment variable (e.g. $(DXSDK_DIR)), then we never want to
// give it a relative path
if( CurPath.StartsWith( "$(" ) )
{
PathRelativeToProjectFile = CurPath;
}
else
{
// Incoming include paths are relative to the solution directory, but we need these paths to be
// relative to the project file's directory
PathRelativeToProjectFile = NormalizeProjectPath( CurPath );
}
// Trim any trailing slash
PathRelativeToProjectFile = PathRelativeToProjectFile.TrimEnd('/', '\\');
// Make sure that it doesn't exist already
var AlreadyExists = false;
List<string> SearchPaths = bAddingSystemIncludes ? IntelliSenseSystemIncludeSearchPaths : IntelliSenseIncludeSearchPaths;
foreach( var ExistingPath in SearchPaths )
{
if( PathRelativeToProjectFile == ExistingPath )
{
AlreadyExists = true;
break;
}
}
if( !AlreadyExists )
{
SearchPaths.Add( PathRelativeToProjectFile );
}
}
}
}
}
/// <summary>
/// Add the given project to the DepondsOn project list.
/// </summary>
/// <param name="InProjectFile">The project this project is dependent on</param>
public void AddDependsOnProject(ProjectFile InProjectFile)
{
// Make sure that it doesn't exist already
var AlreadyExists = false;
foreach (var ExistingDependentOn in DependsOnProjects)
{
if (ExistingDependentOn == InProjectFile)
{
AlreadyExists = true;
break;
}
}
if (AlreadyExists == false)
{
DependsOnProjects.Add(InProjectFile);
}
}
/// <summary>
/// Writes a project file to disk
/// </summary>
/// <param name="InPlatforms">The platforms to write the project files for</param>
/// <param name="InConfigurations">The configurations to add to the project files</param>
/// <returns>True on success</returns>
public virtual bool WriteProjectFile(List<UnrealTargetPlatform> InPlatforms, List<UnrealTargetConfiguration> InConfigurations)
{
throw new BuildException( "UnrealBuildTool cannot automatically generate this project type because WriteProjectFile() was not overridden." );
}
public virtual void LoadGUIDFromExistingProject()
{
}
/// <summary>
/// Allocates a generator-specific source file object
/// </summary>
/// <param name="InitFilePath">Path to the source file on disk</param>
/// <param name="InitProjectSubFolder">Optional sub-folder to put the file in. If empty, this will be determined automatically from the file's path relative to the project file</param>
/// <returns>The newly allocated source file object</returns>
public virtual SourceFile AllocSourceFile( string InitFilePath, string InitProjectSubFolder = null )
{
return new SourceFile( InitFilePath, InitProjectSubFolder );
}
/** Takes the given path and tries to rebase it relative to the project or solution directory variables. */
public string NormalizeProjectPath(string InputPath)
{
// If the path is rooted in an environment variable, leave it be.
if(InputPath.StartsWith("$("))
{
return InputPath;
}
// Otherwise make sure it's absolute
string FullInputPath = Utils.CleanDirectorySeparators(Path.GetFullPath(InputPath));
// Try to make it relative to the solution directory.
string FullSolutionPath = Utils.CleanDirectorySeparators(Path.GetFullPath(ProjectFileGenerator.MasterProjectRelativePath));
if (FullSolutionPath.Last() != Path.DirectorySeparatorChar)
{
FullSolutionPath += Path.DirectorySeparatorChar;
}
if (FullInputPath.StartsWith(FullSolutionPath))
{
FullInputPath = Utils.MakePathRelativeTo(Utils.CleanDirectorySeparators(FullInputPath), Path.GetDirectoryName(Path.GetFullPath(ProjectFilePath)));
}
else
{
FullInputPath = Utils.CleanDirectorySeparators(FullInputPath);
}
// Otherwise return the input
return FullInputPath;
}
/** Takes the given path, normalizes it, and quotes it if necessary. */
public string EscapePath(string InputPath)
{
string Result = InputPath;
if (Result.Contains(' '))
{
Result = "\"" + Result + "\"";
}
return Result;
}
/** Visualizer for the debugger */
public override string ToString()
{
return RelativeProjectFilePath;
}
/// Map of file paths to files in the project.
private readonly Dictionary<string, SourceFile> SourceFileMap = new Dictionary<string, SourceFile>(StringComparer.InvariantCultureIgnoreCase);
/// Files in this project
public readonly List<SourceFile> SourceFiles = new List<SourceFile>();
/// Include paths for every single module in the project file, merged together
public readonly List<string> IntelliSenseIncludeSearchPaths = new List<string>();
public readonly List<string> IntelliSenseSystemIncludeSearchPaths = new List<string>();
public readonly HashSet<string> KnownIntelliSenseIncludeSearchPaths = new HashSet<string>( StringComparer.InvariantCultureIgnoreCase );
public readonly HashSet<string> KnownIntelliSenseSystemIncludeSearchPaths = new HashSet<string>( StringComparer.InvariantCultureIgnoreCase );
/// Preprocessor definitions for every single module in the project file, merged together
public readonly List<string> IntelliSensePreprocessorDefinitions = new List<string>();
public readonly HashSet<string> KnownIntelliSensePreprocessorDefinitions = new HashSet<string>( StringComparer.InvariantCultureIgnoreCase );
/// Projects that this project is dependent on
public readonly List<ProjectFile> DependsOnProjects = new List<ProjectFile>();
}
}
| |
namespace T5Suite2
{
partial class frmMatrixSelection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMatrixSelection));
this.lookUpEdit1 = new DevExpress.XtraEditors.LookUpEdit();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.labelControl3 = new DevExpress.XtraEditors.LabelControl();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
this.lookUpEdit2 = new DevExpress.XtraEditors.LookUpEdit();
this.lookUpEdit3 = new DevExpress.XtraEditors.LookUpEdit();
this.groupControl1 = new DevExpress.XtraEditors.GroupControl();
this.comboBoxEdit1 = new DevExpress.XtraEditors.ComboBoxEdit();
this.labelControl4 = new DevExpress.XtraEditors.LabelControl();
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit1.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit();
this.groupControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).BeginInit();
this.SuspendLayout();
//
// lookUpEdit1
//
this.lookUpEdit1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lookUpEdit1.Location = new System.Drawing.Point(109, 27);
this.lookUpEdit1.Name = "lookUpEdit1";
this.lookUpEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.lookUpEdit1.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Varname", "Symbol", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.lookUpEdit1.Properties.NullText = "Select a symbol for X";
this.lookUpEdit1.Size = new System.Drawing.Size(246, 20);
this.lookUpEdit1.TabIndex = 0;
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(20, 34);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(28, 13);
this.labelControl1.TabIndex = 3;
this.labelControl1.Text = "x axis";
//
// labelControl2
//
this.labelControl2.Location = new System.Drawing.Point(20, 60);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(28, 13);
this.labelControl2.TabIndex = 4;
this.labelControl2.Text = "y axis";
//
// labelControl3
//
this.labelControl3.Location = new System.Drawing.Point(20, 86);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(64, 13);
this.labelControl3.TabIndex = 5;
this.labelControl3.Text = "z axis (value)";
//
// simpleButton1
//
this.simpleButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.simpleButton1.Location = new System.Drawing.Point(312, 156);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(75, 23);
this.simpleButton1.TabIndex = 6;
this.simpleButton1.Text = "Ok";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// simpleButton2
//
this.simpleButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.simpleButton2.Location = new System.Drawing.Point(231, 156);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(75, 23);
this.simpleButton2.TabIndex = 7;
this.simpleButton2.Text = "Cancel";
this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click);
//
// lookUpEdit2
//
this.lookUpEdit2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lookUpEdit2.Location = new System.Drawing.Point(109, 53);
this.lookUpEdit2.Name = "lookUpEdit2";
this.lookUpEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.lookUpEdit2.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Varname", "Symbol", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.lookUpEdit2.Properties.NullText = "Select a symbol for Y";
this.lookUpEdit2.Size = new System.Drawing.Size(246, 20);
this.lookUpEdit2.TabIndex = 8;
//
// lookUpEdit3
//
this.lookUpEdit3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lookUpEdit3.Location = new System.Drawing.Point(109, 79);
this.lookUpEdit3.Name = "lookUpEdit3";
this.lookUpEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.lookUpEdit3.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Varname", "Symbol", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.lookUpEdit3.Properties.NullText = "Select a symbol for Z";
this.lookUpEdit3.Size = new System.Drawing.Size(246, 20);
this.lookUpEdit3.TabIndex = 9;
//
// groupControl1
//
this.groupControl1.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.groupControl1.Controls.Add(this.comboBoxEdit1);
this.groupControl1.Controls.Add(this.labelControl4);
this.groupControl1.Controls.Add(this.lookUpEdit3);
this.groupControl1.Controls.Add(this.lookUpEdit1);
this.groupControl1.Controls.Add(this.labelControl1);
this.groupControl1.Controls.Add(this.labelControl2);
this.groupControl1.Controls.Add(this.lookUpEdit2);
this.groupControl1.Controls.Add(this.labelControl3);
this.groupControl1.Location = new System.Drawing.Point(12, 12);
this.groupControl1.Name = "groupControl1";
this.groupControl1.Size = new System.Drawing.Size(375, 138);
this.groupControl1.TabIndex = 10;
this.groupControl1.Text = "Matrix definition";
//
// comboBoxEdit1
//
this.comboBoxEdit1.EditValue = "Mean values";
this.comboBoxEdit1.Location = new System.Drawing.Point(109, 105);
this.comboBoxEdit1.Name = "comboBoxEdit1";
this.comboBoxEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.comboBoxEdit1.Properties.Items.AddRange(new object[] {
"Mean values",
"Minimum values",
"Maximum values"});
this.comboBoxEdit1.Size = new System.Drawing.Size(246, 20);
this.comboBoxEdit1.TabIndex = 13;
//
// labelControl4
//
this.labelControl4.Location = new System.Drawing.Point(20, 108);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(44, 13);
this.labelControl4.TabIndex = 12;
this.labelControl4.Text = "Viewtype";
//
// frmMatrixSelection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(399, 188);
this.Controls.Add(this.simpleButton2);
this.Controls.Add(this.groupControl1);
this.Controls.Add(this.simpleButton1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmMatrixSelection";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Select parameters for matrix";
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit1.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.lookUpEdit3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit();
this.groupControl1.ResumeLayout(false);
this.groupControl1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.LookUpEdit lookUpEdit1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.LabelControl labelControl2;
private DevExpress.XtraEditors.LabelControl labelControl3;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
private DevExpress.XtraEditors.LookUpEdit lookUpEdit2;
private DevExpress.XtraEditors.LookUpEdit lookUpEdit3;
private DevExpress.XtraEditors.GroupControl groupControl1;
private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit1;
private DevExpress.XtraEditors.LabelControl labelControl4;
}
}
| |
// 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.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Gallio.Icarus.Commands;
using Gallio.Icarus.Controllers;
using Gallio.Icarus.Controllers.Interfaces;
using Gallio.Icarus.Models;
using Gallio.Icarus.ProgressMonitoring;
using Gallio.Icarus.Utilities;
using Gallio.Icarus.WindowManager;
using Gallio.Model;
using Gallio.Runtime;
using Gallio.UI.Common.Synchronization;
using Gallio.UI.ControlPanel;
using Gallio.UI.ProgressMonitoring;
using WeifenLuo.WinFormsUI.Docking;
namespace Gallio.Icarus
{
public partial class Main : Form
{
private readonly IApplicationController applicationController;
private readonly IProgressController progressController;
private readonly IReportController reportController;
private readonly ITaskManager taskManager;
private readonly IOptionsController optionsController;
private readonly IWindowManager windowManager;
private readonly ITestTreeModel testTreeModel;
private readonly ITestStatistics testStatistics;
private readonly ICommandFactory commandFactory;
private readonly ITestFrameworkManager testFrameworkManager;
internal Main(IApplicationController applicationController)
{
this.applicationController = applicationController;
applicationController.RunStarted += (s, e) => SyncContext.Post(cb =>
{
// enable/disable buttons
startButton.Enabled = startTestsToolStripMenuItem.Enabled = false;
startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = false;
stopButton.Enabled = stopTestsToolStripMenuItem.Enabled = true;
}, null);
applicationController.RunFinished += (s, e) => SyncContext.Post(cb =>
{
// enable/disable buttons & menu items appropriately
stopButton.Enabled = stopTestsToolStripMenuItem.Enabled = false;
startButton.Enabled = startTestsToolStripMenuItem.Enabled = true;
startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = true;
}, null);
applicationController.ExploreFinished += (sender, e) => SyncContext.Post(cb =>
{
startButton.Enabled = startTestsToolStripMenuItem.Enabled = true;
startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = true;
}, null);
applicationController.TestsFailed += (s, e) => SyncContext.Post(cb => Activate(), null);
taskManager = RuntimeAccessor.ServiceLocator.Resolve<ITaskManager>();
optionsController = RuntimeAccessor.ServiceLocator.Resolve<IOptionsController>();
reportController = RuntimeAccessor.ServiceLocator.Resolve<IReportController>();
testTreeModel = RuntimeAccessor.ServiceLocator.Resolve<ITestTreeModel>();
testStatistics = RuntimeAccessor.ServiceLocator.Resolve<ITestStatistics>();
commandFactory = RuntimeAccessor.ServiceLocator.Resolve<ICommandFactory>();
testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve<ITestFrameworkManager>();
windowManager = RuntimeAccessor.ServiceLocator.Resolve<IWindowManager>();
// moved this below the service locator calls as the optionsController was being used _before_ it was initialised :(
// TODO: remove as many dependencies from the shell as possible
InitializeComponent();
SetupReportMenus();
SetupRecentProjects();
applicationController.PropertyChanged += (sender, e) =>
{
switch (e.PropertyName)
{
case "ProjectFileName":
Text = applicationController.Title;
break;
case "RecentProjects":
SetupRecentProjects();
break;
}
};
progressController = RuntimeAccessor.ServiceLocator.Resolve<IProgressController>();
progressController.Status.PropertyChanged += (s, e) =>
{
toolStripStatusLabel.Text = progressController.Status;
};
progressController.TotalWork.PropertyChanged += (s, e) =>
{
toolStripProgressBar.TotalWork = progressController.TotalWork;
};
progressController.CompletedWork.PropertyChanged += (s, e) =>
{
toolStripProgressBar.CompletedWork = progressController.CompletedWork;
};
progressController.DisplayProgressDialog += (s, e) => SyncContext.Post(cb =>
new ProgressMonitorDialog(e.ProgressMonitor).Show(this), null);
}
private static bool RunningOnWin7()
{
return (Environment.OSVersion.Version.Major > 6) ||
(Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 1);
}
private void SetupReportMenus()
{
// add a menu item for each report type (Report -> View As)
var reportTypes = new List<string>();
reportTypes.AddRange(reportController.ReportTypes);
reportTypes.Sort();
foreach (string reportType in reportTypes)
{
var menuItem = new ToolStripMenuItem { Text = reportType };
menuItem.Click += delegate
{
var command = commandFactory.CreateShowReportCommand(menuItem.Text);
taskManager.QueueTask(command);
};
viewAsToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
private void SetupRecentProjects()
{
recentProjectsToolStripMenuItem.DropDownItems.Clear();
recentProjectsToolStripMenuItem.DropDownItems.AddRange(applicationController.RecentProjects);
}
private IDockContent GetContentFromPersistString(string persistString)
{
return windowManager.Get(persistString);
}
private void Form_Load(object sender, EventArgs e)
{
// provide WindowsFormsSynchronizationContext for cross-thread databinding
SyncContext.Current = System.Threading.SynchronizationContext.Current;
Text = applicationController.Title;
// setup window manager
var manager = (WindowManager.WindowManager) windowManager;
manager.SetDockPanel(dockPanel);
var menuManager = (MenuManager)manager.MenuManager;
menuManager.SetToolstrip(menuStrip.Items);
// deal with arguments
applicationController.Load();
// try to load the dock state, if the file does not exist
// or loading fails then use defaults.
try
{
dockPanel.LoadFromXml(Paths.DockConfigFile, GetContentFromPersistString);
}
catch
{
DefaultDockState();
}
RestoreWindowSizeAndLocation();
if (RunningOnWin7())
new Win7TaskBar(Handle, (ITaskbarList4)new CTaskbarList(), testTreeModel, testStatistics);
}
private void RestoreWindowSizeAndLocation()
{
if (!optionsController.Size.Equals(Size.Empty))
Size = optionsController.Size;
if (optionsController.WindowState == FormWindowState.Minimized)
return;
WindowState = optionsController.WindowState;
if (optionsController.WindowState == FormWindowState.Maximized)
return;
var desktop = new Rectangle();
foreach (var screen in Screen.AllScreens)
desktop = Rectangle.Union(desktop, screen.WorkingArea);
if (desktop.Contains(optionsController.Location))
Location = optionsController.Location;
}
private void DefaultDockState()
{
// We show the test results, execution log, project explorer and annotations
// by default in order to draw the user's attention to these elements.
// I've seen users get lost trying to add/remove files when only presented
// with the test explorer. Likewise I've seen them confused when tests
// won't run due to an error that could be diagnosed in the annotation window
// or in the runtime log. Auto-hidden panels are less likely to be
// looked at than regular tabs.
// -- Jeff.
windowManager.ShowDefaults();
}
private void fileExit_Click(object sender, EventArgs e)
{
Close();
}
private void aboutMenuItem_Click(object sender, EventArgs e)
{
using (var aboutDialog = new AboutDialog(new AboutController(testFrameworkManager)))
aboutDialog.ShowDialog(this);
}
private void startButton_Click(object sender, EventArgs e)
{
StartTests(false);
}
private void StartTests(bool attachDebugger)
{
var command = commandFactory.CreateRunTestsCommand(attachDebugger);
taskManager.QueueTask(command);
}
private void reloadToolbarButton_Click(object sender, EventArgs e)
{
Reload();
}
private void Reload()
{
var command = commandFactory.CreateReloadCommand();
taskManager.QueueTask(command);
}
private void openProject_Click(object sender, EventArgs e)
{
using (var openProjectDialog = Dialogs.CreateOpenProjectDialog())
{
if (openProjectDialog.ShowDialog() != DialogResult.OK)
return;
applicationController.OpenProject(openProjectDialog.FileName);
}
}
private void saveProjectAsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (Dialogs.CreateSaveProjectDialog())
{
SaveProject(true);
}
}
private void SaveProject(Boolean saveAs)
{
if (saveAs || applicationController.DefaultProject )
{
using (var saveProjectDialog = Dialogs.CreateSaveProjectDialog())
{
if (saveProjectDialog.ShowDialog() != DialogResult.OK)
return;
applicationController.Title = saveProjectDialog.FileName;
}
}
applicationController.SaveProject(true);
}
private void addFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
AddFiles();
}
private void AddFiles()
{
using (var openFileDialog = Dialogs.CreateAddFilesDialog())
{
if (openFileDialog.ShowDialog(this) != DialogResult.OK)
return;
var command = commandFactory.CreateAddFilesCommand(openFileDialog.FileNames);
taskManager.QueueTask(command);
}
}
private void optionsMenuItem_Click(object sender, EventArgs e)
{
var presenter = RuntimeAccessor.ServiceLocator.Resolve<IControlPanelPresenter>();
presenter.Show(this);
}
private void removeAllFiles_Click(object sender, EventArgs e)
{
RemoveAllFiles();
}
private void RemoveAllFiles()
{
var command = commandFactory.CreateRemoveAllFilesCommand();
taskManager.QueueTask(command);
}
private void stopButton_Click(object sender, EventArgs e)
{
progressController.Cancel();
}
private void saveProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveProject(false);
}
private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateNewProject();
}
private void CreateNewProject()
{
applicationController.NewProject();
}
private void newProjectToolStripButton_Click(object sender, EventArgs e)
{
CreateNewProject();
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
progressController.Cancel();
}
private void startTestsToolStripMenuItem_Click(object sender, EventArgs e)
{
StartTests(false);
}
private void showOnlineHelpToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowOnlineHelp();
}
private static void ShowOnlineHelp()
{
Process.Start(ConfigurationManager.AppSettings["OnlineHelpURL"]);
}
private void resetToolStripMenuItem_Click(object sender, EventArgs e)
{
var command = commandFactory.CreateResetTestsCommand();
taskManager.QueueTask(command);
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)
return;
try
{
optionsController.Location = Location;
optionsController.WindowState = WindowState;
// shut down any running operations
progressController.Cancel();
applicationController.Shutdown();
// save dock panel config
dockPanel.SaveAsXml(Paths.DockConfigFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void startWithDebuggerToolStripMenuItem_Click(object sender, EventArgs e)
{
StartTests(true);
}
private void saveProjectToolStripButton_Click(object sender, EventArgs e)
{
SaveProject(false);
}
private void addFilesToolStripButton_Click(object sender, EventArgs e)
{
AddFiles();
}
private void Main_SizeChanged(object sender, EventArgs e)
{
optionsController.Size = Size;
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using ServiceStack.Text.Common;
using ServiceStack.Text.Support;
#if NETFX_CORE
using System.Threading.Tasks;
#endif
#if WINDOWS_PHONE
using System.IO.IsolatedStorage;
#if !WP8
using ServiceStack.Text.WP;
#endif
#endif
namespace ServiceStack.Text
{
public static class StringExtensions
{
public static T To<T>(this string value)
{
return TypeSerializer.DeserializeFromString<T>(value);
}
public static T To<T>(this string value, T defaultValue)
{
return String.IsNullOrEmpty(value) ? defaultValue : TypeSerializer.DeserializeFromString<T>(value);
}
public static T ToOrDefaultValue<T>(this string value)
{
return String.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString<T>(value);
}
public static object To(this string value, Type type)
{
return TypeSerializer.DeserializeFromString(value, type);
}
/// <summary>
/// Converts from base: 0 - 62
/// </summary>
/// <param name="source">The source.</param>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <returns></returns>
public static string BaseConvert(this string source, int from, int to)
{
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = "";
var length = source.Length;
var number = new int[length];
for (var i = 0; i < length; i++)
{
number[i] = chars.IndexOf(source[i]);
}
int newlen;
do
{
var divide = 0;
newlen = 0;
for (var i = 0; i < length; i++)
{
divide = divide * @from + number[i];
if (divide >= to)
{
number[newlen++] = divide / to;
divide = divide % to;
}
else if (newlen > 0)
{
number[newlen++] = 0;
}
}
length = newlen;
result = chars[divide] + result;
}
while (newlen != 0);
return result;
}
public static string EncodeXml(this string value)
{
return value.Replace("<", "<").Replace(">", ">").Replace("&", "&");
}
public static string EncodeJson(this string value)
{
return String.Concat
("\"",
value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "\\n"),
"\""
);
}
public static string EncodeJsv(this string value)
{
if (JsState.QueryStringMode)
{
return UrlEncode(value);
}
return String.IsNullOrEmpty(value) || !JsWriter.HasAnyEscapeChars(value)
? value
: String.Concat
(
JsWriter.QuoteString,
value.Replace(JsWriter.QuoteString, TypeSerializer.DoubleQuoteString),
JsWriter.QuoteString
);
}
public static string DecodeJsv(this string value)
{
const int startingQuotePos = 1;
const int endingQuotePos = 2;
return String.IsNullOrEmpty(value) || value[0] != JsWriter.QuoteChar
? value
: value.Substring(startingQuotePos, value.Length - endingQuotePos)
.Replace(TypeSerializer.DoubleQuoteString, JsWriter.QuoteString);
}
public static string UrlEncode(this string text)
{
if (String.IsNullOrEmpty(text)) return text;
var sb = new StringBuilder();
foreach (var charCode in Encoding.UTF8.GetBytes(text))
{
if (
charCode >= 65 && charCode <= 90 // A-Z
|| charCode >= 97 && charCode <= 122 // a-z
|| charCode >= 48 && charCode <= 57 // 0-9
|| charCode >= 44 && charCode <= 46 // ,-.
)
{
sb.Append((char)charCode);
}
else
{
sb.Append('%' + charCode.ToString("x2"));
}
}
return sb.ToString();
}
public static string UrlDecode(this string text)
{
if (String.IsNullOrEmpty(text)) return null;
var bytes = new List<byte>();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text[i];
if (c == '+')
{
bytes.Add(32);
}
else if (c == '%')
{
var hexNo = Convert.ToByte(text.Substring(i + 1, 2), 16);
bytes.Add(hexNo);
i += 2;
}
else
{
bytes.Add((byte)c);
}
}
#if SILVERLIGHT
byte[] byteArray = bytes.ToArray();
return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
#else
return Encoding.UTF8.GetString(bytes.ToArray());
#endif
}
#if !XBOX
public static string HexEscape(this string text, params char[] anyCharOf)
{
if (String.IsNullOrEmpty(text)) return text;
if (anyCharOf == null || anyCharOf.Length == 0) return text;
var encodeCharMap = new HashSet<char>(anyCharOf);
var sb = new StringBuilder();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text[i];
if (encodeCharMap.Contains(c))
{
sb.Append('%' + ((int)c).ToString("x"));
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
#endif
public static string HexUnescape(this string text, params char[] anyCharOf)
{
if (String.IsNullOrEmpty(text)) return null;
if (anyCharOf == null || anyCharOf.Length == 0) return text;
var sb = new StringBuilder();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text.Substring(i, 1);
if (c == "%")
{
var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16);
sb.Append((char)hexNo);
i += 2;
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
public static string UrlFormat(this string url, params string[] urlComponents)
{
var encodedUrlComponents = new string[urlComponents.Length];
for (var i = 0; i < urlComponents.Length; i++)
{
var x = urlComponents[i];
encodedUrlComponents[i] = x.UrlEncode();
}
return String.Format(url, encodedUrlComponents);
}
public static string ToRot13(this string value)
{
var array = value.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var number = (int)array[i];
if (number >= 'a' && number <= 'z')
number += (number > 'm') ? -13 : 13;
else if (number >= 'A' && number <= 'Z')
number += (number > 'M') ? -13 : 13;
array[i] = (char)number;
}
return new string(array);
}
public static string WithTrailingSlash(this string path)
{
if (String.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (path[path.Length - 1] != '/')
{
return path + "/";
}
return path;
}
public static string AppendPath(this string uri, params string[] uriComponents)
{
return AppendUrlPaths(uri, uriComponents);
}
public static string AppendUrlPaths(this string uri, params string[] uriComponents)
{
var sb = new StringBuilder(uri.WithTrailingSlash());
var i = 0;
foreach (var uriComponent in uriComponents)
{
if (i++ > 0) sb.Append('/');
sb.Append(uriComponent.UrlEncode());
}
return sb.ToString();
}
public static string AppendUrlPathsRaw(this string uri, params string[] uriComponents)
{
var sb = new StringBuilder(uri.WithTrailingSlash());
var i = 0;
foreach (var uriComponent in uriComponents)
{
if (i++ > 0) sb.Append('/');
sb.Append(uriComponent);
}
return sb.ToString();
}
#if !SILVERLIGHT
public static string FromAsciiBytes(this byte[] bytes)
{
return bytes == null ? null
: Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
public static byte[] ToAsciiBytes(this string value)
{
return Encoding.ASCII.GetBytes(value);
}
#endif
public static string FromUtf8Bytes(this byte[] bytes)
{
return bytes == null ? null
: Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
public static byte[] ToUtf8Bytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
public static byte[] ToUtf8Bytes(this int intVal)
{
return FastToUtf8Bytes(intVal.ToString());
}
public static byte[] ToUtf8Bytes(this long longVal)
{
return FastToUtf8Bytes(longVal.ToString());
}
public static byte[] ToUtf8Bytes(this double doubleVal)
{
var doubleStr = doubleVal.ToString(CultureInfo.InvariantCulture.NumberFormat);
if (doubleStr.IndexOf('E') != -1 || doubleStr.IndexOf('e') != -1)
doubleStr = DoubleConverter.ToExactString(doubleVal);
return FastToUtf8Bytes(doubleStr);
}
/// <summary>
/// Skip the encoding process for 'safe strings'
/// </summary>
/// <param name="strVal"></param>
/// <returns></returns>
private static byte[] FastToUtf8Bytes(string strVal)
{
var bytes = new byte[strVal.Length];
for (var i = 0; i < strVal.Length; i++)
bytes[i] = (byte)strVal[i];
return bytes;
}
public static string[] SplitOnFirst(this string strVal, char needle)
{
if (strVal == null) return new string[0];
var pos = strVal.IndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnFirst(this string strVal, string needle)
{
if (strVal == null) return new string[0];
var pos = strVal.IndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnLast(this string strVal, char needle)
{
if (strVal == null) return new string[0];
var pos = strVal.LastIndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnLast(this string strVal, string needle)
{
if (strVal == null) return new string[0];
var pos = strVal.LastIndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string WithoutExtension(this string filePath)
{
if (String.IsNullOrEmpty(filePath)) return null;
var extPos = filePath.LastIndexOf('.');
if (extPos == -1) return filePath;
var dirPos = filePath.LastIndexOfAny(DirSeps);
return extPos > dirPos ? filePath.Substring(0, extPos) : filePath;
}
#if NETFX_CORE
private static readonly char DirSep = '\\';//Path.DirectorySeparatorChar;
private static readonly char AltDirSep = '/';//Path.DirectorySeparatorChar == '/' ? '\\' : '/';
#else
private static readonly char DirSep = Path.DirectorySeparatorChar;
private static readonly char AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/';
#endif
static readonly char[] DirSeps = new[] { '\\', '/' };
public static string ParentDirectory(this string filePath)
{
if (String.IsNullOrEmpty(filePath)) return null;
var dirSep = filePath.IndexOf(DirSep) != -1
? DirSep
: filePath.IndexOf(AltDirSep) != -1 ? AltDirSep : (char)0;
return dirSep == 0 ? null : filePath.TrimEnd(dirSep).SplitOnLast(dirSep)[0];
}
public static string ToJsv<T>(this T obj)
{
return TypeSerializer.SerializeToString(obj);
}
public static T FromJsv<T>(this string jsv)
{
return TypeSerializer.DeserializeFromString<T>(jsv);
}
public static string ToJson<T>(this T obj) {
return JsConfig.PreferInterfaces
? JsonSerializer.SerializeToString(obj, AssemblyUtils.MainInterface<T>())
: JsonSerializer.SerializeToString(obj);
}
public static T FromJson<T>(this string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
public static string ToCsv<T>(this T obj)
{
return CsvSerializer.SerializeToString(obj);
}
#if !XBOX && !SILVERLIGHT && !MONOTOUCH
public static string ToXml<T>(this T obj)
{
return XmlSerializer.SerializeToString(obj);
}
#endif
#if !XBOX && !SILVERLIGHT && !MONOTOUCH
public static T FromXml<T>(this string json)
{
return XmlSerializer.DeserializeFromString<T>(json);
}
#endif
public static string FormatWith(this string text, params object[] args)
{
return String.Format(text, args);
}
public static string Fmt(this string text, params object[] args)
{
return String.Format(text, args);
}
public static bool StartsWithIgnoreCase(this string text, string startsWith)
{
#if NETFX_CORE
return text != null
&& text.StartsWith(startsWith, StringComparison.CurrentCultureIgnoreCase);
#else
return text != null
&& text.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase);
#endif
}
public static bool EndsWithIgnoreCase(this string text, string endsWith)
{
#if NETFX_CORE
return text != null
&& text.EndsWith(endsWith, StringComparison.CurrentCultureIgnoreCase);
#else
return text != null
&& text.EndsWith(endsWith, StringComparison.InvariantCultureIgnoreCase);
#endif
}
public static string ReadAllText(this string filePath)
{
#if XBOX && !SILVERLIGHT
using( var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read ) )
{
return new StreamReader( fileStream ).ReadToEnd( ) ;
}
#elif NETFX_CORE
var task = Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
task.AsTask().Wait();
var file = task.GetResults();
var streamTask = file.OpenStreamForReadAsync();
streamTask.Wait();
var fileStream = streamTask.Result;
return new StreamReader( fileStream ).ReadToEnd( ) ;
#elif WINDOWS_PHONE
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fileStream = isoStore.OpenFile(filePath, FileMode.Open))
{
return new StreamReader(fileStream).ReadToEnd();
}
}
#else
return File.ReadAllText(filePath);
#endif
}
public static int IndexOfAny(this string text, params string[] needles)
{
return IndexOfAny(text, 0, needles);
}
public static int IndexOfAny(this string text, int startIndex, params string[] needles)
{
if (text == null) return -1;
var firstPos = -1;
foreach (var needle in needles)
{
var pos = text.IndexOf(needle);
if (firstPos == -1 || pos < firstPos) firstPos = pos;
}
return firstPos;
}
public static string ExtractContents(this string fromText, string startAfter, string endAt)
{
return ExtractContents(fromText, startAfter, startAfter, endAt);
}
public static string ExtractContents(this string fromText, string uniqueMarker, string startAfter, string endAt)
{
if (String.IsNullOrEmpty(uniqueMarker))
throw new ArgumentNullException("uniqueMarker");
if (String.IsNullOrEmpty(startAfter))
throw new ArgumentNullException("startAfter");
if (String.IsNullOrEmpty(endAt))
throw new ArgumentNullException("endAt");
if (String.IsNullOrEmpty(fromText)) return null;
var markerPos = fromText.IndexOf(uniqueMarker);
if (markerPos == -1) return null;
var startPos = fromText.IndexOf(startAfter, markerPos);
if (startPos == -1) return null;
startPos += startAfter.Length;
var endPos = fromText.IndexOf(endAt, startPos);
if (endPos == -1) endPos = fromText.Length;
return fromText.Substring(startPos, endPos - startPos);
}
#if XBOX && !SILVERLIGHT
static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled);
#else
static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>");
#endif
public static string StripHtml(this string html)
{
return String.IsNullOrEmpty(html) ? null : StripHtmlRegEx.Replace(html, "");
}
#if XBOX && !SILVERLIGHT
static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]", RegexOptions.Compiled);
static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)", RegexOptions.Compiled);
#else
static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]");
static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)");
#endif
public static string StripMarkdownMarkup(this string markdown)
{
if (String.IsNullOrEmpty(markdown)) return null;
markdown = StripBracketsRegEx.Replace(markdown, "");
markdown = StripBracesRegEx.Replace(markdown, "");
markdown = markdown
.Replace("*", "")
.Replace("!", "")
.Replace("\r", "")
.Replace("\n", "")
.Replace("#", "");
return markdown;
}
private const int LowerCaseOffset = 'a' - 'A';
public static string ToCamelCase(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
var len = value.Length;
var newValue = new char[len];
var firstPart = true;
for (var i = 0; i < len; ++i) {
var c0 = value[i];
var c1 = i < len - 1 ? value[i + 1] : 'A';
var c0isUpper = c0 >= 'A' && c0 <= 'Z';
var c1isUpper = c1 >= 'A' && c1 <= 'Z';
if (firstPart && c0isUpper && (c1isUpper || i == 0))
c0 = (char)(c0 + LowerCaseOffset);
else
firstPart = false;
newValue[i] = c0;
}
return new string(newValue);
}
private static readonly TextInfo TextInfo = CultureInfo.InvariantCulture.TextInfo;
public static string ToTitleCase(this string value)
{
#if SILVERLIGHT || __MonoCS__
string[] words = value.Split('_');
for (int i = 0; i <= words.Length - 1; i++)
{
if ((!object.ReferenceEquals(words[i], string.Empty)))
{
string firstLetter = words[i].Substring(0, 1);
string rest = words[i].Substring(1);
string result = firstLetter.ToUpper() + rest.ToLower();
words[i] = result;
}
}
return String.Join("", words);
#else
return TextInfo.ToTitleCase(value).Replace("_", String.Empty);
#endif
}
public static string ToLowercaseUnderscore(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
value = value.ToCamelCase();
var sb = new StringBuilder(value.Length);
foreach (var t in value)
{
if (Char.IsDigit(t) || (Char.IsLetter(t) && Char.IsLower(t)) || t == '_')
{
sb.Append(t);
}
else
{
sb.Append("_");
sb.Append(Char.ToLowerInvariant(t));
}
}
return sb.ToString();
}
public static string SafeSubstring(this string value, int startIndex)
{
return SafeSubstring(value, startIndex, value.Length);
}
public static string SafeSubstring(this string value, int startIndex, int length)
{
if (String.IsNullOrEmpty(value)) return String.Empty;
if (value.Length >= (startIndex + length))
return value.Substring(startIndex, length);
return value.Length > startIndex ? value.Substring(startIndex) : String.Empty;
}
public static bool IsAnonymousType(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
// HACK: The only way to detect anonymous types right now.
#if NETFX_CORE
return type.IsGeneric() && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal));
#else
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGeneric() && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
#endif
}
public static int CompareIgnoreCase(this string strA, string strB)
{
return String.Compare(strA, strB, InvariantComparisonIgnoreCase());
}
public static bool EndsWithInvariant(this string str, string endsWith)
{
return str.EndsWith(endsWith, InvariantComparison());
}
#if NETFX_CORE
public static char DirSeparatorChar = '\\';
public static StringComparison InvariantComparison()
{
return StringComparison.CurrentCulture;
}
public static StringComparison InvariantComparisonIgnoreCase()
{
return StringComparison.CurrentCultureIgnoreCase;
}
public static StringComparer InvariantComparer()
{
return StringComparer.CurrentCulture;
}
public static StringComparer InvariantComparerIgnoreCase()
{
return StringComparer.CurrentCultureIgnoreCase;
}
#else
public static char DirSeparatorChar = Path.DirectorySeparatorChar;
public static StringComparison InvariantComparison()
{
return StringComparison.InvariantCulture;
}
public static StringComparison InvariantComparisonIgnoreCase()
{
return StringComparison.InvariantCultureIgnoreCase;
}
public static StringComparer InvariantComparer()
{
return StringComparer.InvariantCulture;
}
public static StringComparer InvariantComparerIgnoreCase()
{
return StringComparer.InvariantCultureIgnoreCase;
}
#endif
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// String.System.IConvertible.ToInt64(IFormatProvider provider)
/// This method supports the .NET Framework infrastructure and is
/// not intended to be used directly from your code.
/// Converts the value of the current String object to a 32-bit signed integer.
/// </summary>
class IConvertibleToInt64
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
public static int Main()
{
IConvertibleToInt64 iege = new IConvertibleToInt64();
TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToInt64(IFormatProvider)");
if (iege.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarioes
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Random numeric string";
const string c_TEST_ID = "P001";
string strSrc;
IFormatProvider provider;
Int64 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt64(-55);
strSrc = i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToInt64(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Positive sign";
const string c_TEST_ID = "P002";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
Int64 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt64(-55);
ni.PositiveSign = TestLibrary.Generator.GetString(-55, false,false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSrc = ni.PositiveSign + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (i == ((IConvertible)strSrc).ToInt64(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: string is Int64.MaxValue";
const string c_TEST_ID = "P003";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = Int64.MaxValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (Int64.MaxValue == ((IConvertible)strSrc).ToInt64(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: string is Int32.MinValue";
const string c_TEST_ID = "P004";
string strSrc;
IFormatProvider provider;
bool expectedValue = true;
bool actualValue = false;
strSrc = Int64.MinValue.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = (Int64.MinValue == ((IConvertible)strSrc).ToInt64(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Positive sign";
const string c_TEST_ID = "P005";
string strSrc;
IFormatProvider provider;
NumberFormatInfo ni = new NumberFormatInfo();
Int64 i;
bool expectedValue = true;
bool actualValue = false;
i = TestLibrary.Generator.GetInt64(-55);
ni.NegativeSign = TestLibrary.Generator.GetString(-55, false,false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSrc = ni.NegativeSign + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = ((-1 * i) == ((IConvertible)strSrc).ToInt64(provider));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, provider);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion // end for positive test scenarioes
#region Negative test scenarios
//FormatException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed";
const string c_TEST_ID = "N001";
string strSrc;
IFormatProvider provider;
strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN);
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToInt64(provider);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest2() //bug
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue";
const string c_TEST_ID = "N002";
string strSrc;
IFormatProvider provider;
Int64 i;
i = TestLibrary.Generator.GetInt64(-55);
strSrc = Int64.MaxValue.ToString() + i.ToString();
provider = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToInt64(provider);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
public bool NegTest3() //bug
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue";
const string c_TEST_ID = "N003";
string strSrc;
NumberFormatInfo ni = new NumberFormatInfo();
IFormatProvider provider;
Int64 i;
i = TestLibrary.Generator.GetInt64(-55);
strSrc = ni.NegativeSign + Int64.MaxValue + i.ToString();
provider = (IFormatProvider)ni;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IConvertible)strSrc).ToInt64(provider);
TestLibrary.TestFramework.LogError("015" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider));
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider));
retVal = false;
}
return retVal;
}
#endregion
private string GetDataString(string strSrc, IFormatProvider provider)
{
string str1, str2, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str2 = (null == provider) ? "null" : provider.ToString();
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Format provider string]\n {0}", str2);
return str;
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ServiceResponse.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the ServiceResponse class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;
/// <summary>
/// Represents the standard response to an Exchange Web Services operation.
/// </summary>
[Serializable]
public class ServiceResponse
{
private ServiceResult result;
private ServiceError errorCode;
private string errorMessage;
private Dictionary<string, string> errorDetails = new Dictionary<string, string>();
private Collection<PropertyDefinitionBase> errorProperties = new Collection<PropertyDefinitionBase>();
/// <summary>
/// Initializes a new instance of the <see cref="ServiceResponse"/> class.
/// </summary>
internal ServiceResponse()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceResponse"/> class.
/// </summary>
/// <param name="soapFaultDetails">The SOAP fault details.</param>
internal ServiceResponse(SoapFaultDetails soapFaultDetails)
{
this.result = ServiceResult.Error;
this.errorCode = soapFaultDetails.ResponseCode;
this.errorMessage = soapFaultDetails.FaultString;
this.errorDetails = soapFaultDetails.ErrorDetails;
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceResponse"/> class.
/// This is intended to be used by unit tests to create a fake service error response
/// </summary>
/// <param name="responseCode">Response code</param>
/// <param name="errorMessage">Detailed error message</param>
internal ServiceResponse(ServiceError responseCode, string errorMessage)
{
this.result = ServiceResult.Error;
this.errorCode = responseCode;
this.errorMessage = errorMessage;
this.errorDetails = null;
}
/// <summary>
/// Loads response from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
internal void LoadFromXml(EwsServiceXmlReader reader, string xmlElementName)
{
if (!reader.IsStartElement(XmlNamespace.Messages, xmlElementName))
{
reader.ReadStartElement(XmlNamespace.Messages, xmlElementName);
}
this.result = reader.ReadAttributeValue<ServiceResult>(XmlAttributeNames.ResponseClass);
if (this.result == ServiceResult.Success || this.result == ServiceResult.Warning)
{
if (this.result == ServiceResult.Warning)
{
this.errorMessage = reader.ReadElementValue(XmlNamespace.Messages, XmlElementNames.MessageText);
}
this.errorCode = reader.ReadElementValue<ServiceError>(XmlNamespace.Messages, XmlElementNames.ResponseCode);
if (this.result == ServiceResult.Warning)
{
reader.ReadElementValue<int>(XmlNamespace.Messages, XmlElementNames.DescriptiveLinkKey);
}
// If batch processing stopped, EWS returns an empty element. Skip over it.
if (this.BatchProcessingStopped)
{
do
{
reader.Read();
}
while (!reader.IsEndElement(XmlNamespace.Messages, xmlElementName));
}
else
{
this.ReadElementsFromXml(reader);
reader.ReadEndElementIfNecessary(XmlNamespace.Messages, xmlElementName);
}
}
else
{
this.errorMessage = reader.ReadElementValue(XmlNamespace.Messages, XmlElementNames.MessageText);
this.errorCode = reader.ReadElementValue<ServiceError>(XmlNamespace.Messages, XmlElementNames.ResponseCode);
reader.ReadElementValue<int>(XmlNamespace.Messages, XmlElementNames.DescriptiveLinkKey);
while (!reader.IsEndElement(XmlNamespace.Messages, xmlElementName))
{
reader.Read();
if (reader.IsStartElement())
{
if (!this.LoadExtraErrorDetailsFromXml(reader, reader.LocalName))
{
reader.SkipCurrentElement();
}
}
}
}
this.MapErrorCodeToErrorMessage();
this.Loaded();
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="responseObject">The response object.</param>
/// <param name="service">The service.</param>
internal void LoadFromJson(JsonObject responseObject, ExchangeService service)
{
this.result = (ServiceResult)Enum.Parse(typeof(ServiceResult), responseObject.ReadAsString(XmlAttributeNames.ResponseClass));
this.errorCode = (ServiceError)Enum.Parse(typeof(ServiceError), responseObject.ReadAsString(XmlElementNames.ResponseCode));
// TODO: Deal with a JSON version of "LoadExtraDetailsFromXml"
if (this.result == ServiceResult.Warning || this.result == ServiceResult.Error)
{
this.errorMessage = responseObject.ReadAsString(XmlElementNames.MessageText);
}
if (this.result == ServiceResult.Success || this.result == ServiceResult.Warning)
{
if (!this.BatchProcessingStopped)
{
this.ReadElementsFromJson(responseObject, service);
}
}
this.MapErrorCodeToErrorMessage();
this.Loaded();
}
/// <summary>
/// Parses the message XML.
/// </summary>
/// <param name="reader">The reader.</param>
private void ParseMessageXml(EwsServiceXmlReader reader)
{
do
{
reader.Read();
if (reader.IsStartElement())
{
switch (reader.LocalName)
{
case XmlElementNames.Value:
this.errorDetails.Add(reader.ReadAttributeValue(XmlAttributeNames.Name), reader.ReadElementValue());
break;
case XmlElementNames.FieldURI:
this.errorProperties.Add(ServiceObjectSchema.FindPropertyDefinition(reader.ReadAttributeValue(XmlAttributeNames.FieldURI)));
break;
case XmlElementNames.IndexedFieldURI:
this.errorProperties.Add(
new IndexedPropertyDefinition(
reader.ReadAttributeValue(XmlAttributeNames.FieldURI),
reader.ReadAttributeValue(XmlAttributeNames.FieldIndex)));
break;
case XmlElementNames.ExtendedFieldURI:
ExtendedPropertyDefinition extendedPropDef = new ExtendedPropertyDefinition();
extendedPropDef.LoadFromXml(reader);
this.errorProperties.Add(extendedPropDef);
break;
default:
break;
}
}
}
while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.MessageXml));
}
/// <summary>
/// Called when the response has been loaded from XML.
/// </summary>
internal virtual void Loaded()
{
}
/// <summary>
/// Called after the response has been loaded from XML in order to map error codes to "better" error messages.
/// </summary>
internal void MapErrorCodeToErrorMessage()
{
// Use a better error message when an item cannot be updated because its changeKey is old.
if (this.ErrorCode == ServiceError.ErrorIrresolvableConflict)
{
this.ErrorMessage = Strings.ItemIsOutOfDate;
}
}
/// <summary>
/// Reads response elements from XML.
/// </summary>
/// <param name="reader">The reader.</param>
internal virtual void ReadElementsFromXml(EwsServiceXmlReader reader)
{
}
/// <summary>
/// Reads the headers from a HTTP response
/// </summary>
/// <param name="responseHeaders">a collection of response headers</param>
internal virtual void ReadHeader(WebHeaderCollection responseHeaders)
{
}
/// <summary>
/// Reads response elements from Json.
/// </summary>
/// <param name="responseObject">The response object.</param>
/// <param name="service">The service.</param>
internal virtual void ReadElementsFromJson(JsonObject responseObject, ExchangeService service)
{
}
/// <summary>
/// Loads extra error details from XML
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="xmlElementName">The current element name of the extra error details.</param>
/// <returns>True if the expected extra details is loaded;
/// False if the element name does not match the expected element. </returns>
internal virtual bool LoadExtraErrorDetailsFromXml(EwsServiceXmlReader reader, string xmlElementName)
{
if (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.MessageXml) && !reader.IsEmptyElement)
{
this.ParseMessageXml(reader);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Throws a ServiceResponseException if this response has its Result property set to Error.
/// </summary>
internal void ThrowIfNecessary()
{
this.InternalThrowIfNecessary();
}
/// <summary>
/// Internal method that throws a ServiceResponseException if this response has its Result property set to Error.
/// </summary>
internal virtual void InternalThrowIfNecessary()
{
if (this.Result == ServiceResult.Error)
{
throw new ServiceResponseException(this);
}
}
/// <summary>
/// Gets a value indicating whether a batch request stopped processing before the end.
/// </summary>
internal bool BatchProcessingStopped
{
get { return (this.result == ServiceResult.Warning) && (this.errorCode == ServiceError.ErrorBatchProcessingStopped); }
}
/// <summary>
/// Gets the result associated with this response.
/// </summary>
public ServiceResult Result
{
get { return this.result; }
}
/// <summary>
/// Gets the error code associated with this response.
/// </summary>
public ServiceError ErrorCode
{
get { return this.errorCode; }
}
/// <summary>
/// Gets a detailed error message associated with the response. If Result is set to Success, ErrorMessage returns null.
/// ErrorMessage is localized according to the PreferredCulture property of the ExchangeService object that
/// was used to call the method that generated the response.
/// </summary>
public string ErrorMessage
{
get { return this.errorMessage; }
internal set { this.errorMessage = value; }
}
/// <summary>
/// Gets error details associated with the response. If Result is set to Success, ErrorDetailsDictionary returns null.
/// Error details will only available for some error codes. For example, when error code is ErrorRecurrenceHasNoOccurrence,
/// the ErrorDetailsDictionary will contain keys for EffectiveStartDate and EffectiveEndDate.
/// </summary>
/// <value>The error details dictionary.</value>
public IDictionary<string, string> ErrorDetails
{
get { return this.errorDetails; }
}
/// <summary>
/// Gets information about property errors associated with the response. If Result is set to Success, ErrorProperties returns null.
/// ErrorProperties is only available for some error codes. For example, when the error code is ErrorInvalidPropertyForOperation,
/// ErrorProperties will contain the definition of the property that was invalid for the request.
/// </summary>
/// <value>The error properties list.</value>
public Collection<PropertyDefinitionBase> ErrorProperties
{
get { return this.errorProperties; }
}
}
}
| |
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: filterHalfTone.cs
//
// composition toolkit filter
//
// Author Sergey Solokhin (Neill3d)
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
uniform vec2 outputSize; // stored in a format ( 1.0/w, 1.0/h )
layout(binding=0, rgba8) uniform writeonly image2D resultImage;
layout(binding=1) uniform sampler2D colorSampler;
#include "misc_masking.cs"
float uScale = 1.0; // For imperfect, isotropic anti-aliasing in
float uYrot = 1.0; // absence of dFdx() and dFdy() functions
uniform float frequency; // Needed globally for lame version of aastep()
/*
//T is any generic type (float,vec2, vec3 ...)
//I am assuming forward finite difference
T dFdx(T x) {
T x2 = getValueOf(x, gl_FragCoord.x+1);
T x1 = getValueOf(x, gl_FragCoord.x);
return x2-x1;
}
T dFdy(T y) {
T y2 = getValueOf(y, gl_FragCoord.y+1);
T y1 = getValueOf(y, gl_FragCoord.y);
return y2-y1;
}
*/
float dFdx(float value)
{
return 0.0;
}
float dFdx(vec2 value)
{
return 0.0;
}
float dFdy(float value)
{
return 0.0;
}
float dFdy(vec2 value)
{
return 0.0;
}
/*
// Anti-aliased step function. If the auto derivatives extension
// is supported, the AA is done in a fully general, anisotropic
// manner. If not, the expression for "afwidth" is a kludge for
// this particular shader and this particular view transform.
float aastep(float threshold, float value) {
//float afwidth = 0.7 * length(vec2(dFdx(value), dFdy(value)));
float afwidth = frequency * (1.0/200.0) / uScale / cos(uYrot);
return smoothstep(threshold-afwidth, threshold+afwidth, value);
}
*/
float aastep(float threshold, float value)
{
return step(threshold, value);
}
// Explicit bilinear texture lookup to circumvent bad hardware precision.
// The extra arguments specify the dimension of the texture. (GLSL 1.30
// introduced textureSize() to get that information from the sampler.)
// 'dims' is the width and height of the texture, 'one' is 1.0/dims.
// (Precomputing 'one' saves two divisions for each lookup.)
vec4 texture2D_bilinear(sampler2D tex, vec2 st, vec2 dims, vec2 one) {
vec2 uv = st * dims;
vec2 uv00 = floor(uv - vec2(0.5)); // Lower left corner of lower left texel
vec2 uvlerp = uv - uv00 - vec2(0.5); // Texel-local lerp blends [0,1]
vec2 st00 = (uv00 + vec2(0.5)) * one;
vec4 texel00 = texture(tex, st00);
vec4 texel10 = texture(tex, st00 + vec2(one.x, 0.0));
vec4 texel01 = texture(tex, st00 + vec2(0.0, one.y));
vec4 texel11 = texture(tex, st00 + one);
vec4 texel0 = mix(texel00, texel01, uvlerp.y);
vec4 texel1 = mix(texel10, texel11, uvlerp.y);
return mix(texel0, texel1, uvlerp.x);
}
// 2D simplex noise
// Description : Array- and textureless GLSL 2D simplex noise.
// Author : Ian McEwan, Ashima Arts. Version: 20110822
// Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289((( x * 34.0) + 1.0) * x); }
float snoise(vec2 v) {
const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439); // 1.0 / 41.0
// First corner
vec2 i = floor(v + dot(v, C.yy) );
vec2 x0 = v - i + dot(i, C.xx);
// Other corners
vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
+ i.x + vec3(0.0, i1.x, 1.0 ));
vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy),
dot(x12.zw,x12.zw)), 0.0);
m = m*m; m = m*m;
// Gradients
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 a0 = x - floor(x + 0.5);
// Normalise gradients implicitly by scaling m
m *= 1.792843 - 0.853735 * ( a0*a0 + h*h );
// Compute final noise value at P
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
void main (void)
{
ivec2 pixelPosition = ivec2(gl_GlobalInvocationID.xy);
vec2 texCoord = vec2(outputSize.x * (0.5 + pixelPosition.x), outputSize.y * (0.5 + pixelPosition.y));
#ifdef SAME_SIZE
vec4 srccolor = texelFetch(colorSampler, pixelPosition, 0);
#else
// do some scaling with bilinear filtering
vec4 srccolor = texture(colorSampler, texCoord );
#endif
vec2 uDims = outputSize;
vec2 vOne = vec2(1.0/outputSize.x, 1.0/outputSize.y);
// Use a texture to modulate the size of the dots, and
// use explicit bilinear interpolation for better precision
vec3 texcolor = texture2D_bilinear(colorSampler, texCoord, uDims, vOne).rgb;
float n = 0.1*snoise(texCoord*200.0); // Fractal noise
n += 0.05*snoise(texCoord*400.0); // with three
n += 0.025*snoise(texCoord*800.0); // octaves
vec3 white = vec3(n*0.2 + 0.97); // Paper color + noise
vec3 black = vec3(n + 0.1); // Ink density + noise
// Perform a crude RGB-to-CMYK conversion
vec4 cmyk;
cmyk.xyz = 1.0 - texcolor; // CMY = 1-RGB
// Black generation: K = min(C,M,Y)
cmyk.w = min(cmyk.x, min(cmyk.y, cmyk.z));
// Grey component replacement: subtract K from CMY
cmyk.xyz -= cmyk.w;
// Distances to nearest point in angled grids of
// (frequency x frequency) points over the unit square
// K component: 45 degrees screen angle
vec2 Kst = frequency*mat2(0.707, -0.707, 0.707, 0.707)*texCoord;
vec2 Kuv = 2.0*fract(Kst)-1.0;
float k = aastep(0.0, sqrt(cmyk.w)-length(Kuv)+n);
// C component: 15 degrees screen angle
vec2 Cst = frequency*mat2(0.966, -0.259, 0.259, 0.966)*texCoord;
vec2 Cuv = 2.0*fract(Cst)-1.0;
float c = aastep(0.0, sqrt(cmyk.x)-length(Cuv)+n);
// M component: -15 degrees screen angle
vec2 Mst = frequency*mat2(0.966, 0.259, -0.259, 0.966)*texCoord;
vec2 Muv = 2.0*fract(Mst)-1.0;
float m = aastep(0.0, sqrt(cmyk.y)-length(Muv)+n);
// Y component: 0 degrees screen angle
vec2 Yst = frequency*texCoord;
vec2 Yuv = 2.0*fract(Yst)-1.0;
float y = aastep(0.0, sqrt(cmyk.z)-length(Yuv)+n);
// CMY screen in RGB
vec3 rgbscreen = 1.0 - 0.9*vec3(c,m,y) + n;
// Blend in K for final color
rgbscreen = mix(rgbscreen, black, 0.85*k + 0.3*n);
/*
// Blend to plain RGB texture under extreme minification
// (handles any minification level by regular mipmapping)
float afwidth = 2.0 * frequency * max(length(dFdx(texCoord)), length(dFdy(texCoord)));
float blend = smoothstep(0.7, 1.4, afwidth);
vec4 outColor = vec4(mix(rgbscreen, texcolor, blend), 1.0);
*/
vec4 outColor = vec4(rgbscreen, 1.0);
outColor = ApplyMask(texCoord, srccolor, outColor);
imageStore(resultImage, pixelPosition, outColor);
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of Protection Container mapping operations for the Site
/// Recovery extension.
/// </summary>
public partial interface IProtectionContainerMappingOperations
{
/// <summary>
/// Configures protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Container mapping name.
/// </param>
/// <param name='input'>
/// Create mapping input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginConfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purges protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginPurgeProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Unconfigures protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Container mapping name.
/// </param>
/// <param name='input'>
/// Unconfigure protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginUnconfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Configures protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Container mapping name.
/// </param>
/// <param name='input'>
/// Create mapping input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> ConfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Get the protected container mapping by name.
/// </summary>
/// <param name='fabricName'>
/// Fabric Name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection Container Name.
/// </param>
/// <param name='mappingName'>
/// Container mapping name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Protection Container mapping object.
/// </returns>
Task<ProtectionContainerMappingResponse> GetAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for operation which change status of mapping for
/// protection container.
/// </returns>
Task<MappingOperationResponse> GetConfigureProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> GetPurgeProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for operation which change status of mapping for
/// protection container.
/// </returns>
Task<MappingOperationResponse> GetUnconfigureProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Get the list of all protection container mapping for the given
/// container under a fabric.
/// </summary>
/// <param name='fabricName'>
/// Fabric Unique name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection Container Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Protection Container mapping collection object.
/// </returns>
Task<ProtectionContainerMappingListResponse> ListAsync(string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purges protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Protection container mapping name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> PurgeProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Unconfigures protection for given protection container
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='mappingName'>
/// Container mapping name.
/// </param>
/// <param name='input'>
/// Unconfigure protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> UnconfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmSupplierDeposits
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmSupplierDeposits() : base()
{
KeyDown += frmSupplierDeposits_KeyDown;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Button cmdCancel;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.ColumnHeader _lvDeposit_ColumnHeader_1;
public System.Windows.Forms.ColumnHeader _lvDeposit_ColumnHeader_2;
public System.Windows.Forms.ColumnHeader _lvDeposit_ColumnHeader_3;
private System.Windows.Forms.ListView withEventsField_lvDeposit;
public System.Windows.Forms.ListView lvDeposit {
get { return withEventsField_lvDeposit; }
set {
if (withEventsField_lvDeposit != null) {
withEventsField_lvDeposit.ItemCheck -= lvDeposit_ItemCheck;
withEventsField_lvDeposit.KeyPress -= lvDeposit_KeyPress;
}
withEventsField_lvDeposit = value;
if (withEventsField_lvDeposit != null) {
withEventsField_lvDeposit.ItemCheck += lvDeposit_ItemCheck;
withEventsField_lvDeposit.KeyPress += lvDeposit_KeyPress;
}
}
}
public System.Windows.Forms.Label lblSupplier;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmSupplierDeposits));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.lvDeposit = new System.Windows.Forms.ListView();
this._lvDeposit_ColumnHeader_1 = new System.Windows.Forms.ColumnHeader();
this._lvDeposit_ColumnHeader_2 = new System.Windows.Forms.ColumnHeader();
this._lvDeposit_ColumnHeader_3 = new System.Windows.Forms.ColumnHeader();
this.lblSupplier = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.lvDeposit.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Text = "Supplier Deposits";
this.ClientSize = new System.Drawing.Size(450, 477);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmSupplierDeposits";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(450, 38);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 1;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(369, 3);
this.cmdClose.TabIndex = 3;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.TabIndex = 2;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
this.lvDeposit.Size = new System.Drawing.Size(442, 394);
this.lvDeposit.Location = new System.Drawing.Point(3, 72);
this.lvDeposit.TabIndex = 0;
this.lvDeposit.View = System.Windows.Forms.View.Details;
this.lvDeposit.LabelEdit = false;
this.lvDeposit.LabelWrap = true;
this.lvDeposit.HideSelection = true;
this.lvDeposit.AllowColumnReorder = -1;
this.lvDeposit.CheckBoxes = true;
this.lvDeposit.ForeColor = System.Drawing.SystemColors.WindowText;
this.lvDeposit.BackColor = System.Drawing.SystemColors.Window;
this.lvDeposit.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lvDeposit.Name = "lvDeposit";
this._lvDeposit_ColumnHeader_1.Text = "Deposit Name";
this._lvDeposit_ColumnHeader_1.Width = 236;
this._lvDeposit_ColumnHeader_2.Text = "Type";
this._lvDeposit_ColumnHeader_2.Width = 106;
this._lvDeposit_ColumnHeader_3.Text = "Suppliers Description";
this._lvDeposit_ColumnHeader_3.Width = 377;
this.lblSupplier.Text = "Label1";
this.lblSupplier.Size = new System.Drawing.Size(39, 13);
this.lblSupplier.Location = new System.Drawing.Point(9, 45);
this.lblSupplier.TabIndex = 4;
this.lblSupplier.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblSupplier.BackColor = System.Drawing.Color.Transparent;
this.lblSupplier.Enabled = true;
this.lblSupplier.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblSupplier.Cursor = System.Windows.Forms.Cursors.Default;
this.lblSupplier.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblSupplier.UseMnemonic = true;
this.lblSupplier.Visible = true;
this.lblSupplier.AutoSize = true;
this.lblSupplier.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblSupplier.Name = "lblSupplier";
this.Controls.Add(picButtons);
this.Controls.Add(lvDeposit);
this.Controls.Add(lblSupplier);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(cmdCancel);
this.lvDeposit.Columns.Add(_lvDeposit_ColumnHeader_1);
this.lvDeposit.Columns.Add(_lvDeposit_ColumnHeader_2);
this.lvDeposit.Columns.Add(_lvDeposit_ColumnHeader_3);
this.picButtons.ResumeLayout(false);
this.lvDeposit.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Common.Logging;
using Spring.Collections;
using Spring.Core;
using Spring.Core.TypeConversion;
using Spring.Core.TypeResolution;
using Spring.Objects.Factory.Config;
using Spring.Util;
using System.Linq;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Helper class for resolving constructors and factory methods.
/// Performs constructor resolution through argument matching.
/// </summary>
/// <remarks>
/// Operates on a <see cref="AbstractObjectFactory"/> and an <see cref="IInstantiationStrategy"/>.
/// Used by <see cref="AbstractAutowireCapableObjectFactory"/>.
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack</author>
public class ConstructorResolver
{
private readonly ILog log = LogManager.GetLogger(typeof(ConstructorResolver));
private readonly AbstractObjectFactory objectFactory;
private readonly IAutowireCapableObjectFactory autowireFactory;
private readonly IInstantiationStrategy instantiationStrategy;
private readonly ObjectDefinitionValueResolver valueResolver;
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorResolver"/> class for the given factory
/// and instantiation strategy.
/// </summary>
/// <param name="objectFactory">The object factory to work with.</param>
/// <param name="autowireFactory">The object factory as IAutowireCapableObjectFactory.</param>
/// <param name="instantiationStrategy">The instantiation strategy for creating objects.</param>
/// <param name="valueResolver">the resolver to resolve property value placeholders if any</param>
public ConstructorResolver(AbstractObjectFactory objectFactory, IAutowireCapableObjectFactory autowireFactory,
IInstantiationStrategy instantiationStrategy, ObjectDefinitionValueResolver valueResolver)
{
this.objectFactory = objectFactory;
this.autowireFactory = autowireFactory;
this.instantiationStrategy = instantiationStrategy;
this.valueResolver = valueResolver;
}
/// <summary>
/// "autowire constructor" (with constructor arguments by type) behavior.
/// Also applied if explicit constructor argument values are specified,
/// matching all remaining arguments with objects from the object factory.
/// </summary>
/// <para>
/// This corresponds to constructor injection: In this mode, a Spring
/// object factory is able to host components that expect constructor-based
/// dependency resolution.
/// </para>
/// <param name="objectName">Name of the object.</param>
/// <param name="rod">The merged object definition for the object.</param>
/// <param name="chosenCtors">The chosen chosen candidate constructors (or <code>null</code> if none).</param>
/// <param name="explicitArgs">The explicit argument values passed in programmatically via the getBean method,
/// or <code>null</code> if none (-> use constructor argument values from object definition)</param>
/// <returns>An IObjectWrapper for the new instance</returns>
public IObjectWrapper AutowireConstructor(string objectName, RootObjectDefinition rod,
ConstructorInfo[] chosenCtors, object[] explicitArgs)
{
ObjectWrapper wrapper = new ObjectWrapper();
ConstructorInstantiationInfo constructorInstantiationInfo = GetConstructorInstantiationInfo(
objectName, rod, chosenCtors, explicitArgs);
wrapper.WrappedInstance = instantiationStrategy.Instantiate(rod, objectName, this.objectFactory,
constructorInstantiationInfo.ConstructorInfo, constructorInstantiationInfo.ArgInstances);
#region Instrumentation
if (log.IsDebugEnabled)
{
log.Debug(string.Format(CultureInfo.InvariantCulture, "Object '{0}' instantiated via constructor [{1}].", objectName, constructorInstantiationInfo.ConstructorInfo));
}
#endregion
return wrapper;
}
/// <summary>
/// Gets the constructor instantiation info given the object definition.
/// </summary>
/// <param name="objectName">Name of the object.</param>
/// <param name="rod">The RootObjectDefinition</param>
/// <param name="chosenCtors">The explicitly chosen ctors.</param>
/// <param name="explicitArgs">The explicit chose ctor args.</param>
/// <returns>A ConstructorInstantiationInfo containg the specified constructor in the RootObjectDefinition or
/// one based on type matching.</returns>
public ConstructorInstantiationInfo GetConstructorInstantiationInfo(string objectName, RootObjectDefinition rod,
ConstructorInfo[] chosenCtors, object[] explicitArgs)
{
ObjectWrapper wrapper = new ObjectWrapper();
ConstructorInfo constructorToUse = null;
object[] argsToUse = null;
if (explicitArgs != null)
{
argsToUse = explicitArgs;
}
else
{
//TODO performance optmization on cached ctors.
}
// Need to resolve the constructor.
bool autowiring = (chosenCtors != null ||
rod.ResolvedAutowireMode == AutoWiringMode.Constructor);
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs = 0;
if (explicitArgs != null)
{
minNrOfArgs = explicitArgs.Length;
}
else
{
ConstructorArgumentValues cargs = rod.ConstructorArgumentValues;
resolvedValues = new ConstructorArgumentValues();
minNrOfArgs = ResolveConstructorArguments(objectName, rod, wrapper, cargs, resolvedValues);
}
// Take specified constructors, if any.
ConstructorInfo[] candidates = (chosenCtors != null
? chosenCtors
: AutowireUtils.GetConstructors(rod, 0));
AutowireUtils.SortConstructors(candidates);
int minTypeDiffWeight = Int32.MaxValue;
for (int i = 0; i < candidates.Length; i++)
{
ConstructorInfo candidate = candidates[i];
Type[] paramTypes = ReflectionUtils.GetParameterTypes(candidate.GetParameters());
if (constructorToUse != null && argsToUse.Length > paramTypes.Length)
{
// already found greedy constructor that can be satisfied, so
// don't look any further, there are only less greedy constructors left...
break;
}
if (paramTypes.Length < minNrOfArgs)
{
throw new ObjectCreationException(rod.ResourceDescription, objectName,
string.Format(CultureInfo.InvariantCulture,
"'{0}' constructor arguments specified but no matching constructor found "
+ "in object '{1}' (hint: specify argument indexes, names, or "
+ "types to avoid ambiguities).", minNrOfArgs, objectName));
}
ArgumentsHolder args = null;
if (resolvedValues != null)
{
UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData = null;
// Try to resolve arguments for current constructor
//need to check for null as indicator of no ctor arg match instead of using exceptions for flow
//control as in the Java implementation
args = CreateArgumentArray(objectName, rod, resolvedValues, wrapper, paramTypes, candidate,
autowiring, out unsatisfiedDependencyExceptionData);
if (args == null)
{
if (i == candidates.Length - 1 && constructorToUse == null)
{
throw new UnsatisfiedDependencyException(rod.ResourceDescription,
objectName,
unsatisfiedDependencyExceptionData.ParameterIndex,
unsatisfiedDependencyExceptionData.ParameterType,
unsatisfiedDependencyExceptionData.ErrorMessage);
}
// try next constructor...
continue;
}
}
else
{
// Explicit arguments given -> arguments length must match exactly
if (paramTypes.Length != explicitArgs.Length)
{
continue;
}
args = new ArgumentsHolder(explicitArgs);
}
int typeDiffWeight = args.GetTypeDifferenceWeight(paramTypes);
// Choose this constructor if it represents the closest match.
if (typeDiffWeight < minTypeDiffWeight)
{
constructorToUse = candidate;
argsToUse = args.arguments;
minTypeDiffWeight = typeDiffWeight;
}
}
if (constructorToUse == null)
{
throw new ObjectCreationException(rod.ResourceDescription, objectName, "Could not resolve matching constructor.");
}
return new ConstructorInstantiationInfo(constructorToUse, argsToUse);
}
/// <summary>
/// Instantiate an object instance using a named factory method.
/// </summary>
/// <remarks>
/// <p>
/// The method may be static, if the <paramref name="definition"/>
/// parameter specifies a class, rather than a
/// <see cref="Spring.Objects.Factory.IFactoryObject"/> instance, or an
/// instance variable on a factory object itself configured using Dependency
/// Injection.
/// </p>
/// <p>
/// Implementation requires iterating over the static or instance methods
/// with the name specified in the supplied <paramref name="definition"/>
/// (the method may be overloaded) and trying to match with the parameters.
/// We don't have the types attached to constructor args, so trial and error
/// is the only way to go here.
/// </p>
/// </remarks>
/// <param name="name">
/// The name associated with the supplied <paramref name="definition"/>.
/// </param>
/// <param name="definition">
/// The definition describing the instance that is to be instantiated.
/// </param>
/// <param name="arguments">
/// Any arguments to the factory method that is to be invoked.
/// </param>
/// <returns>
/// The result of the factory method invocation (the instance).
/// </returns>
public virtual IObjectWrapper InstantiateUsingFactoryMethod(string name, RootObjectDefinition definition, object[] arguments)
{
ObjectWrapper wrapper = new ObjectWrapper();
Type factoryClass = null;
bool isStatic = true;
ConstructorArgumentValues cargs = definition.ConstructorArgumentValues;
ConstructorArgumentValues resolvedValues = new ConstructorArgumentValues();
int expectedArgCount = 0;
// we don't have arguments passed in programmatically, so we need to resolve the
// arguments specified in the constructor arguments held in the object definition...
if (arguments == null || arguments.Length == 0)
{
expectedArgCount = cargs.ArgumentCount;
ResolveConstructorArguments(name, definition, wrapper, cargs, resolvedValues);
}
else
{
// if we have constructor args, don't need to resolve them...
expectedArgCount = arguments.Length;
}
if (StringUtils.HasText(definition.FactoryObjectName))
{
// it's an instance method on the factory object's class...
factoryClass = objectFactory.GetObject(definition.FactoryObjectName).GetType();
isStatic = false;
}
else
{
// it's a static factory method on the object class...
factoryClass = definition.ObjectType;
}
GenericArgumentsHolder genericArgsInfo = new GenericArgumentsHolder(definition.FactoryMethodName);
IList<MethodInfo> factoryMethodCandidates = FindMethods(genericArgsInfo.GenericMethodName, expectedArgCount, isStatic, factoryClass);
bool autowiring = (definition.AutowireMode == AutoWiringMode.Constructor);
// try all matching methods to see if they match the constructor arguments...
for (int i = 0; i < factoryMethodCandidates.Count; i++)
{
MethodInfo factoryMethodCandidate = factoryMethodCandidates[i];
if (genericArgsInfo.ContainsGenericArguments)
{
string[] unresolvedGenericArgs = genericArgsInfo.GetGenericArguments();
if (factoryMethodCandidate.GetGenericArguments().Length != unresolvedGenericArgs.Length)
continue;
Type[] paramTypes = new Type[unresolvedGenericArgs.Length];
for (int j = 0; j < unresolvedGenericArgs.Length; j++)
{
paramTypes[j] = TypeResolutionUtils.ResolveType(unresolvedGenericArgs[j]);
}
factoryMethodCandidate = factoryMethodCandidate.MakeGenericMethod(paramTypes);
}
if (arguments == null || arguments.Length == 0)
{
Type[] paramTypes = ReflectionUtils.GetParameterTypes(factoryMethodCandidate.GetParameters());
// try to create the required arguments...
UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData = null;
ArgumentsHolder args = CreateArgumentArray(name, definition, resolvedValues, wrapper, paramTypes,
factoryMethodCandidate, autowiring, out unsatisfiedDependencyExceptionData);
if (args == null)
{
arguments = null;
// if we failed to match this method, keep
// trying new overloaded factory methods...
continue;
}
else
{
arguments = args.arguments;
}
}
// if we get here, we found a usable candidate factory method - check, if arguments match
//arguments = (arguments.Length == 0 ? null : arguments);
if (ReflectionUtils.GetMethodByArgumentValues(new MethodInfo[] { factoryMethodCandidate }, arguments) == null)
{
continue;
}
object objectInstance = instantiationStrategy.Instantiate(definition, name, objectFactory, factoryMethodCandidate, arguments);
wrapper.WrappedInstance = objectInstance;
#region Instrumentation
if (log.IsDebugEnabled)
{
log.Debug(string.Format(CultureInfo.InvariantCulture, "Object '{0}' instantiated via factory method [{1}].", name, factoryMethodCandidate));
}
#endregion
return wrapper;
}
// if we get here, we didn't match any method...
throw new ObjectDefinitionStoreException(
string.Format(CultureInfo.InvariantCulture, "Cannot find matching factory method '{0} on Type [{1}].", definition.FactoryMethodName,
factoryClass));
}
/// <summary>
/// Create an array of arguments to invoke a constructor or static factory method,
/// given the resolved constructor arguments values.
/// </summary>
/// <remarks>When return value is null the out parameter UnsatisfiedDependencyExceptionData will contain
/// information for use in throwing a UnsatisfiedDependencyException by the caller. This avoids using
/// exceptions for flow control as in the original implementation.</remarks>
private ArgumentsHolder CreateArgumentArray(string objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, bool autowiring, out UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData)
{
string methodType = (methodOrCtorInfo is ConstructorInfo) ? "constructor" : "factory method";
unsatisfiedDependencyExceptionData = null;
ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length);
ISet usedValueHolders = new HybridSet();
IList autowiredObjectNames = new LinkedList();
bool resolveNecessary = false;
ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters();
for (int paramIndex = 0; paramIndex < paramTypes.Length; paramIndex++)
{
Type paramType = paramTypes[paramIndex];
string parameterName = argTypes[paramIndex].Name;
// If we couldn't find a direct match and are not supposed to autowire,
// let's try the next generic, untyped argument value as fallback:
// it could match after type conversion (for example, String -> int).
ConstructorArgumentValues.ValueHolder valueHolder = null;
if (resolvedValues.GetNamedArgumentValue(parameterName) != null)
{
valueHolder = resolvedValues.GetArgumentValue(parameterName, paramType, usedValueHolders);
}
else
{
valueHolder = resolvedValues.GetArgumentValue(paramIndex, paramType, usedValueHolders);
}
if (valueHolder == null && !autowiring)
{
valueHolder = resolvedValues.GetGenericArgumentValue(null, usedValueHolders);
}
if (valueHolder != null)
{
// We found a potential match - let's give it a try.
// Do not consider the same value definition multiple times!
usedValueHolders.Add(valueHolder);
args.rawArguments[paramIndex] = valueHolder.Value;
try
{
object originalValue = valueHolder.Value;
object convertedValue = TypeConversionUtils.ConvertValueIfNecessary(paramType, originalValue, null);
args.arguments[paramIndex] = convertedValue;
//?
args.preparedArguments[paramIndex] = convertedValue;
}
catch (TypeMismatchException ex)
{
//To avoid using exceptions for flow control, this is not a cost in Java as stack trace is lazily created.
string errorMessage = String.Format(CultureInfo.InvariantCulture,
"Could not convert {0} argument value [{1}] to required type [{2}] : {3}",
methodType, valueHolder.Value,
paramType, ex.Message);
unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage);
return null;
}
}
else
{
// No explicit match found: we're either supposed to autowire or
// have to fail creating an argument array for the given constructor.
if (!autowiring)
{
string errorMessage = String.Format(CultureInfo.InvariantCulture,
"Ambiguous {0} argument types - " +
"Did you specify the correct object references as {0} arguments?",
methodType);
unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage);
return null;
}
try
{
MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex);
object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames);
args.rawArguments[paramIndex] = autowiredArgument;
args.arguments[paramIndex] = autowiredArgument;
args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
resolveNecessary = true;
}
catch (ObjectsException ex)
{
unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, ex.Message);
return null;
}
}
}
foreach (string autowiredObjectName in autowiredObjectNames)
{
if (log.IsDebugEnabled)
{
log.Debug("Autowiring by type from object name '" + objectName +
"' via " + methodType + " to object named '" + autowiredObjectName + "'");
}
}
return args;
}
private class AutowiredArgumentMarker
{
}
private object ResolveAutoWiredArgument(MethodParameter methodParameter, string objectName, IList autowiredObjectNames)
{
return
this.autowireFactory.ResolveDependency(new DependencyDescriptor(methodParameter, true), objectName,
autowiredObjectNames);
}
/// <summary>
/// Resolves the <see cref="Spring.Objects.Factory.Config.ConstructorArgumentValues"/>
/// of the supplied <paramref name="definition"/>.
/// </summary>
/// <param name="objectName">The name of the object that is being resolved by this factory.</param>
/// <param name="definition">The rod.</param>
/// <param name="wrapper">The wrapper.</param>
/// <param name="cargs">The cargs.</param>
/// <param name="resolvedValues">Where the resolved constructor arguments will be placed.</param>
/// <returns>
/// The minimum number of arguments that any constructor for the supplied
/// <paramref name="definition"/> must have.
/// </returns>
/// <remarks>
/// <p>
/// 'Resolve' can be taken to mean that all of the <paramref name="definition"/>s
/// constructor arguments is resolved into a concrete object that can be plugged
/// into one of the <paramref name="definition"/>s constructors. Runtime object
/// references to other objects in this (or a parent) factory are resolved,
/// type conversion is performed, etc.
/// </p>
/// <p>
/// These resolved values are plugged into the supplied
/// <paramref name="resolvedValues"/> object, because we wouldn't want to touch
/// the <paramref name="definition"/>s constructor arguments in case it (or any of
/// its constructor arguments) is a prototype object definition.
/// </p>
/// <p>
/// This method is also used for handling invocations of static factory methods.
/// </p>
/// </remarks>
private int ResolveConstructorArguments(string objectName, RootObjectDefinition definition, ObjectWrapper wrapper,
ConstructorArgumentValues cargs,
ConstructorArgumentValues resolvedValues)
{
// ObjectDefinitionValueResolver valueResolver = new ObjectDefinitionValueResolver(objectFactory);
int minNrOfArgs = cargs.ArgumentCount;
foreach (KeyValuePair<int, ConstructorArgumentValues.ValueHolder> entry in cargs.IndexedArgumentValues)
{
int index = Convert.ToInt32(entry.Key);
if (index < 0)
{
throw new ObjectCreationException(definition.ResourceDescription, objectName,
"Invalid constructor agrument index: " + index);
}
if (index > minNrOfArgs)
{
minNrOfArgs = index + 1;
}
ConstructorArgumentValues.ValueHolder valueHolder = entry.Value;
string argName = "constructor argument with index " + index;
object resolvedValue =
valueResolver.ResolveValueIfNecessary(objectName, definition, argName, valueHolder.Value);
resolvedValues.AddIndexedArgumentValue(index, resolvedValue,
StringUtils.HasText(valueHolder.Type)
? TypeResolutionUtils.ResolveType(valueHolder.Type).
AssemblyQualifiedName
: null);
}
foreach (ConstructorArgumentValues.ValueHolder valueHolder in definition.ConstructorArgumentValues.GenericArgumentValues)
{
string argName = "constructor argument";
object resolvedValue =
valueResolver.ResolveValueIfNecessary(objectName, definition, argName, valueHolder.Value);
resolvedValues.AddGenericArgumentValue(resolvedValue,
StringUtils.HasText(valueHolder.Type)
? TypeResolutionUtils.ResolveType(valueHolder.Type).
AssemblyQualifiedName
: null);
}
foreach (KeyValuePair<string, object> namedArgumentEntry in definition.ConstructorArgumentValues.NamedArgumentValues)
{
string argumentName = namedArgumentEntry.Key;
string syntheticArgumentName = "constructor argument with name " + argumentName;
ConstructorArgumentValues.ValueHolder valueHolder =
(ConstructorArgumentValues.ValueHolder)namedArgumentEntry.Value;
object resolvedValue =
valueResolver.ResolveValueIfNecessary(objectName, definition, syntheticArgumentName, valueHolder.Value);
resolvedValues.AddNamedArgumentValue(argumentName, resolvedValue);
}
return minNrOfArgs;
}
/// <summary>
/// Returns an array of all of those
/// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the
/// <paramref name="searchType"/> that match the supplied criteria.
/// </summary>
/// <param name="methodName">
/// Methods that have this name (can be in the form of a regular expression).
/// </param>
/// <param name="expectedArgumentCount">
/// Methods that have exactly this many arguments.
/// </param>
/// <param name="isStatic">
/// Methods that are static / instance.
/// </param>
/// <param name="searchType">
/// The <see cref="System.Type"/> on which the methods (if any) are to be found.
/// </param>
/// <returns>
/// An array of all of those
/// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the
/// <paramref name="searchType"/> that match the supplied criteria.
/// </returns>
private static IList<MethodInfo> FindMethods(string methodName, int expectedArgumentCount, bool isStatic, Type searchType)
{
ComposedCriteria methodCriteria = new ComposedCriteria();
methodCriteria.Add(new MethodNameMatchCriteria(methodName));
methodCriteria.Add(new MethodParametersCountCriteria(expectedArgumentCount));
BindingFlags methodFlags = BindingFlags.Public | BindingFlags.IgnoreCase | (isStatic ? BindingFlags.Static : BindingFlags.Instance);
MemberInfo[] methods = searchType.FindMembers(MemberTypes.Method, methodFlags, new CriteriaMemberFilter().FilterMemberByCriteria, methodCriteria);
return methods.Cast<MethodInfo>().ToArray();
}
internal class ArgumentsHolder
{
public object[] rawArguments;
public object[] arguments;
public object[] preparedArguments;
public ArgumentsHolder(int size)
{
this.rawArguments = new object[size];
this.arguments = new object[size];
this.preparedArguments = new object[size];
}
public ArgumentsHolder(object[] args)
{
this.rawArguments = args;
this.arguments = args;
this.preparedArguments = args;
}
public int GetTypeDifferenceWeight(Type[] paramTypes)
{
// If valid arguments found, determine type difference weight.
// Try type difference weight on both the converted arguments and
// the raw arguments. If the raw weight is better, use it.
// Decrease raw weight by 1024 to prefer it over equal converted weight.
int typeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, this.arguments);
int rawTypeDiffWeight = AutowireUtils.GetTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024;
return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// LongRangePartitionerTests.cs - Tests for range partitioner for long integer range.
//
// PLEASE NOTE !! - For tests that need to iterate the elements inside the partitions more
// than once, we need to call GetPartitions for the second time. Iterating a second times
// over the first enumerable<tuples> / IList<IEnumerator<tuples> will yield no elements
//
// PLEASE NOTE!! - we use lazy evaluation wherever possible to allow for more than Int32.MaxValue
// elements. ToArray / toList will result in an OOM
//
// Taken from dev11 branch:
// \qa\clr\testsrc\pfx\Functional\Common\Partitioner\YetiTests\RangePartitioner\LongRangePartitionerTests.cs
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class LongRangePartitionerTests
{
/// <summary>
/// Ensure that the partitioner returned has properties set correctly
/// </summary>
[Fact]
public static void CheckKeyProperties()
{
var partitioner = Partitioner.Create(0, 9223372036854774807);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
partitioner = Partitioner.Create(0, 9223372036854774807, 90);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
[Fact]
public static void CheckGetPartitions()
{
CheckGetPartitions(0, 1, 1);
CheckGetPartitions(1, 1999, 3);
CheckGetPartitions(2147473647, 9999, 4);
CheckGetPartitions(2147484647, 1000, 8);
CheckGetPartitions(-2147484647, 1000, 16);
CheckGetPartitions(-1999, 5000, 63);
CheckGetPartitions(9223372036854774807, 999, 13); // close to Int64.Max
}
public static void CheckGetPartitions(long from, long count, int dop)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetPartitions element mismatch");
}
/// <summary>
/// CheckGetDynamicPartitions returns an IEnumerable<Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
[Fact]
public static void CheckGetDynamicPartitions()
{
CheckGetDynamicPartitions(0, 1);
CheckGetDynamicPartitions(1, 1999);
CheckGetDynamicPartitions(2147473647, 9999);
CheckGetDynamicPartitions(2147484647, 1000);
CheckGetDynamicPartitions(-2147484647, 1000);
CheckGetDynamicPartitions(-1999, 5000);
CheckGetDynamicPartitions(9223372036854774807, 999); // close to Int64.Max
}
public static void CheckGetDynamicPartitions(long from, long count)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<long, long>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
[Fact]
public static void CheckGetOrderablePartitions()
{
CheckGetOrderablePartitions(0, 1, 1);
CheckGetOrderablePartitions(1, 1999, 3);
CheckGetOrderablePartitions(2147473647, 9999, 4);
CheckGetOrderablePartitions(2147484647, 1000, 8);
CheckGetOrderablePartitions(-2147484647, 1000, 16);
CheckGetOrderablePartitions(-1999, 5000, 63);
CheckGetOrderablePartitions(9223372036854774807, 999, 13); // close to Int64.Max
}
public static void CheckGetOrderablePartitions(long from, long count, int dop)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
[Fact]
public static void GetOrderableDynamicPartitions()
{
GetOrderableDynamicPartitions(0, 1);
GetOrderableDynamicPartitions(1, 1999);
GetOrderableDynamicPartitions(2147473647, 9999);
GetOrderableDynamicPartitions(2147484647, 1000);
GetOrderableDynamicPartitions(-2147484647, 1000);
GetOrderableDynamicPartitions(-1999, 5000);
GetOrderableDynamicPartitions(9223372036854774807, 999); // close to Int64.Max
}
public static void GetOrderableDynamicPartitions(long from, long count)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetPartitionsWithRange()
{
CheckGetPartitionsWithRange(1999, 1000, 20, 1);
CheckGetPartitionsWithRange(-1999, 1000, 100, 2);
CheckGetPartitionsWithRange(1999, 1, 2000, 3);
CheckGetPartitionsWithRange(9223372036854774807, 999, 600, 4);
CheckGetPartitionsWithRange(-9223372036854774807, 1000, 19, 63);
}
public static void CheckGetPartitionsWithRange(long from, long count, long desiredRangeSize, int dop)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetPartitions element mismatch");
//var rangeSizes = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<long> rangeSizes = new List<long>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// CheckGetDynamicPartitionsWithRange returns an IEnumerable<Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetDynamicPartitionsWithRange()
{
CheckGetDynamicPartitionsWithRange(1999, 1000, 20);
CheckGetDynamicPartitionsWithRange(-1999, 1000, 100);
CheckGetDynamicPartitionsWithRange(1999, 1, 2000);
CheckGetDynamicPartitionsWithRange(9223372036854774807, 999, 600);
CheckGetDynamicPartitionsWithRange(-9223372036854774807, 1000, 19);
}
public static void CheckGetDynamicPartitionsWithRange(long from, long count, long desiredRangeSize)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
//var rangeSizes = partitioner.GetDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<long> rangeSizes = new List<long>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<long, long>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetOrderablePartitionsWithRange()
{
CheckGetOrderablePartitionsWithRange(1999, 1000, 20, 1);
CheckGetOrderablePartitionsWithRange(-1999, 1000, 100, 2);
CheckGetOrderablePartitionsWithRange(1999, 1, 2000, 3);
CheckGetOrderablePartitionsWithRange(9223372036854774807, 999, 600, 4);
CheckGetOrderablePartitionsWithRange(-9223372036854774807, 1000, 19, 63);
}
public static void CheckGetOrderablePartitionsWithRange(long from, long count, long desiredRangeSize, int dop)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<long> elements = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
//var rangeSizes = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<long> rangeSizes = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<long, long>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void GetOrderableDynamicPartitionsWithRange()
{
GetOrderableDynamicPartitionsWithRange(1999, 1000, 20);
GetOrderableDynamicPartitionsWithRange(-1999, 1000, 100);
GetOrderableDynamicPartitionsWithRange(1999, 1, 2000);
GetOrderableDynamicPartitionsWithRange(9223372036854774807, 999, 600);
GetOrderableDynamicPartitionsWithRange(-9223372036854774807, 1000, 19);
}
public static void GetOrderableDynamicPartitionsWithRange(long from, long count, long desiredRangeSize)
{
long to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<long> elements = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in tuple.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
//var rangeSizes = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<long> rangeSizes = new List<long>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// Helper function to validate the the range size of the partitioners match what the user specified
/// (desiredRangeSize).
/// The last range may have less than or equal to desiredRangeSize.
/// </summary>
/// <param name="desiredRangeSize"></param>
/// <param name="rangeSizes"></param>
/// <returns></returns>
public static void ValidateRangeSize(long desiredRangeSize, IList<long> rangeSizes)
{
//var rangesWithDifferentRangeSize = rangeSizes.Take(rangeSizes.Length - 1).Where(r => r != desiredRangeSize).ToArray();
IList<long> rangesWithDifferentRangeSize = new List<long>();
// ensuring that every range, size from the last one is the same.
int numToTake = rangeSizes.Count - 1;
for (int i = 0; i < numToTake; i++)
{
long range = rangeSizes[i];
if (range != desiredRangeSize)
rangesWithDifferentRangeSize.Add(range);
}
Assert.Equal(0, rangesWithDifferentRangeSize.Count);
Assert.InRange(rangeSizes[rangeSizes.Count - 1], 0, desiredRangeSize);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
[Fact]
public static void RangePartitionerChunking()
{
RangePartitionerChunking(2147473647, 9999, 4);
RangePartitionerChunking(2147484647, 1000, -1);
}
public static void RangePartitionerChunking(long from, long count, long rangeSize)
{
long to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetPartitions(2);
// Initialize the from / to values from the first element
if (!partitions[0].MoveNext()) return;
Assert.Equal(from, partitions[0].Current.Item1);
if (rangeSize == -1)
{
rangeSize = partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
long nextExpectedFrom = partitions[0].Current.Item2;
long nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
long actualCount = partitions[0].Current.Item2 - partitions[0].Current.Item1;
while (true)
{
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
[Fact]
public static void RangePartitionerDynamicChunking()
{
RangePartitionerDynamicChunking(2147473647, 9999, 4);
RangePartitionerDynamicChunking(2147484647, 1000, -1);
}
public static void RangePartitionerDynamicChunking(long from, long count, long rangeSize)
{
long to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetDynamicPartitions();
var partition1 = partitions.GetEnumerator();
var partition2 = partitions.GetEnumerator();
// Initialize the from / to values from the first element
if (!partition1.MoveNext()) return;
Assert.Equal(from, partition1.Current.Item1);
if (rangeSize == -1)
{
rangeSize = partition1.Current.Item2 - partition1.Current.Item1;
}
long nextExpectedFrom = partition1.Current.Item2;
long nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
long actualCount = partition1.Current.Item2 - partition1.Current.Item1;
while (true)
{
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UvsChess;
namespace StudentAI
{
public class StudentAI : IChessAI
{
const int pawnValue = 100;
const int knightValue = 320;
const int bishopValue = 333;
const int rookValue = 510;
const int queenValue = 880;
const int kingValue = 10000;
const int openMoveValue = 5;
const int checkValue = 500;
const int checkmateValue = 10000;
const int randomValue = 50;
//lower is higher here
private const int baselinePawnRankModifier = 20;
private const int dontDrawPawnRankModifier = 1;
public static int PawnRankModifier = baselinePawnRankModifier;
const int distKingModifier = 60;
public int HalfMoves = 0;
public string Name
{
get { return "ConnorAI (debug)"; }
}
private enum AIProfilerTags
{
GetNextMove,
IsValidMove
}
/// Evaluates the chess board and decided which move to make. This is the main method of the AI.
public ChessMove GetNextMove(ChessBoard board, ChessColor myColor)
{
#region profiler
//For more information about using the profiler, visit http://code.google.com/p/uvschess/wiki/ProfilerHowTo
// This is how you setup the profiler. This should be done in GetNextMove.
Profiler.TagNames = Enum.GetNames(typeof(AIProfilerTags));
// In order for the profiler to calculate the AI's nodes/sec value,
// I need to tell the profiler which method key's are for MiniMax.
// In this case our mini and max methods are the same,
// but usually they are not.
Profiler.MinisProfilerTag = (int)AIProfilerTags.GetNextMove;
Profiler.MaxsProfilerTag = (int)AIProfilerTags.GetNextMove;
// This increments the method call count by 1 for GetNextMove in the profiler
Profiler.IncrementTagCount((int)AIProfilerTags.GetNextMove);
#endregion
PawnRankModifier = HalfMoves > 30 ? dontDrawPawnRankModifier : baselinePawnRankModifier;
ChessMove myNextMove = null;
var allMoves = GetMyMoves(board, myColor);
allMoves = EvaluateMoves(allMoves);
allMoves.Sort();
allMoves.Reverse();
//while (!IsMyTurnOver())
//{
// if (myNextMove != null) continue;
myNextMove = allMoves.First().Move;
#region Logging
this.Log("value of move: "+allMoves.First().Move.ValueOfMove);
this.Log("half moves: " + HalfMoves);
this.Log(string.Empty);
#endregion
// break;
//}
#region Profiler
Profiler.SetDepthReachedDuringThisTurn(2);
#endregion
HalfMoves++;
var currentPiece = board[myNextMove.From.X, myNextMove.From.Y];
if (currentPiece == ChessPiece.BlackPawn || currentPiece == ChessPiece.WhitePawn)
HalfMoves = 0;
return myNextMove;
}
/// Validates a move. The framework uses this to validate the opponents move.
public bool IsValidMove(ChessBoard boardBeforeMove, ChessMove moveToCheck, ChessColor colorOfPlayerMoving)
{
#region Profiler
Profiler.IncrementTagCount((int)AIProfilerTags.IsValidMove);
#endregion
HalfMoves++;
var currentPiece = boardBeforeMove[moveToCheck.From.X, moveToCheck.From.Y];
if (currentPiece == ChessPiece.BlackPawn || currentPiece == ChessPiece.WhitePawn)
HalfMoves = 0;
var allMoves = GetMyMoves(boardBeforeMove,colorOfPlayerMoving);
allMoves = EvaluateMoves(allMoves);
return IsMovingRightColorPiece(boardBeforeMove, moveToCheck, colorOfPlayerMoving) && MoveDataListContains(allMoves, moveToCheck);
}
private void SetMoveFlagAndValue(ChessMoveData moveData)
{
var myMoves = StudentAI.GetMyMoves(moveData.NewBoard, moveData.Color);
//see if checking other player
bool any = false;
foreach (var move in myMoves)
{
var oldToTile = move.OldBoard[move.Move.To.X, move.Move.To.Y];
if ((moveData.Color == ChessColor.Black && oldToTile == ChessPiece.WhiteKing) || (moveData.Color == ChessColor.White && oldToTile == ChessPiece.BlackKing))
{
any = true;
break;
}
}
moveData.Move.Flag = any
? ChessFlag.Check : ChessFlag.NoFlag;
//see if in checkmate
if (moveData.Move.Flag == ChessFlag.Check)
if(InCheckmate(moveData))
moveData.Move.Flag = ChessFlag.Checkmate;
moveData.Move.ValueOfMove = GetBoardValue(moveData.NewBoard, moveData.Color);
var otherMoves = StudentAI.GetMyMoves(moveData.NewBoard, EnemyColor(moveData.Color));
foreach (var otherMove in otherMoves)
{
if (otherMove.Move.To.X != moveData.Move.To.X || otherMove.Move.To.Y != moveData.Move.To.Y)
continue;
var currentPiece = moveData.NewBoard[moveData.Move.To.X, moveData.Move.To.Y];
if (currentPiece == ChessPiece.Empty) continue;
var colorMulti = (GetChessPieceColor(currentPiece) == moveData.Color) ? 1 : -1;
var value = 0;
switch (currentPiece)
{
case ChessPiece.BlackPawn:
value += colorMulti * pawnValue;
value += colorMulti * (pawnValue / PawnRankModifier) * (moveData.Move.To.Y - 1);
break;
case ChessPiece.WhitePawn:
value += colorMulti * pawnValue;
value += colorMulti * (pawnValue / PawnRankModifier) * (6 - moveData.Move.To.Y);
break;
case ChessPiece.BlackRook:
case ChessPiece.WhiteRook:
value += colorMulti * rookValue;
break;
case ChessPiece.BlackKnight:
case ChessPiece.WhiteKnight:
value += colorMulti * knightValue;
break;
case ChessPiece.BlackBishop:
case ChessPiece.WhiteBishop:
value += colorMulti * bishopValue;
break;
case ChessPiece.BlackQueen:
case ChessPiece.WhiteQueen:
value += colorMulti * queenValue;
break;
case ChessPiece.BlackKing:
case ChessPiece.WhiteKing:
break;
default:
throw new Exception("Somehow not catching a specific piece? Empty?");
break;
}
value = (int)(value*1.5f);
moveData.Move.ValueOfMove -= value;
break;
}
var random = new Random();
moveData.Move.ValueOfMove += random.Next(randomValue*2) - randomValue;
if (moveData.Move.Flag == ChessFlag.Check)
moveData.Move.ValueOfMove += checkValue;
if (moveData.Move.Flag == ChessFlag.Checkmate)
moveData.Move.ValueOfMove += checkmateValue;
}
private static bool InCheckmate(ChessMoveData moveData)
{
//get all enemy moves
var enemyMoves = GetMyMoves(moveData.NewBoard, EnemyColor(moveData.Color));
//if any enemy move results in a board where i can't take the king, is not checkmate
var checkmate = true;
foreach (var enemyMove in enemyMoves)
{
var myCounterMoves = GetMyMoves(enemyMove.NewBoard, moveData.Color);
var canTakeKing = false;
foreach (var counterMove in myCounterMoves)
{
var toTile = counterMove.OldBoard[counterMove.Move.To.X, counterMove.Move.To.Y];
if ((moveData.Color == ChessColor.Black && toTile == ChessPiece.WhiteKing) ||
(moveData.Color == ChessColor.White && toTile == ChessPiece.BlackKing))
{
canTakeKing = true;
break;
}
}
if (!canTakeKing)
{
checkmate = false;
break;
}
}
return checkmate;
}
private static ChessLocation GetPiecePosition(ChessBoard board, ChessPiece piece)
{
for(var i=0;i<8;i++)
for (var j = 0; j < 8; j++)
{
if(board[i,j]==piece)
return new ChessLocation(i,j);
}
return null;
}
private bool MoveDataListContains(List<ChessMoveData> chessMoveData, ChessMove moveToCheck)
{
return chessMoveData.Any(m => m.Move == moveToCheck);
}
public static List<ChessMoveData> GetMyMoves(ChessBoard board, ChessColor myColor)
{
return GetAllMoves(board,false,myColor);
}
private static List<ChessMoveData> GetAllMoves(ChessBoard board, bool AllColorsAllowed = true, ChessColor onlyThisColor = ChessColor.Black)
{
var moveList = new List<ChessMoveData>();
for (var y = 0; y < ChessBoard.NumberOfRows; y++)
{
for (var x = 0; x < ChessBoard.NumberOfColumns; x++)
{
var currentPiece = board[x, y];
if (currentPiece == ChessPiece.Empty) continue;
if (!AllColorsAllowed && GetChessPieceColor(currentPiece) != onlyThisColor) continue;
switch (currentPiece)
{
case ChessPiece.BlackPawn:
case ChessPiece.WhitePawn:
AddPawnMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
case ChessPiece.BlackRook:
case ChessPiece.WhiteRook:
AddRookMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
case ChessPiece.BlackKnight:
case ChessPiece.WhiteKnight:
AddKnightMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
case ChessPiece.BlackBishop:
case ChessPiece.WhiteBishop:
AddBishopMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
case ChessPiece.BlackQueen:
case ChessPiece.WhiteQueen:
AddQueenMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
case ChessPiece.BlackKing:
case ChessPiece.WhiteKing:
AddKingMoves(moveList, board, x, y, GetChessPieceColor(currentPiece));
break;
default:
throw new Exception("Somehow not catching a specific piece? Empty?");
break;
}
}
}
return moveList;
}
public class ChessMoveData:IComparable<ChessMoveData>
{
public ChessMove Move { get; set; }
public ChessBoard OldBoard { get; set; }
public ChessBoard NewBoard { get; set; }
public ChessColor Color { get; set; }
public ChessMoveData(ChessBoard board, ChessMove move, ChessColor color)
{
OldBoard = board;
Move = move;
Color = color;
NewBoard = board.Clone();
NewBoard.MakeMove(move);
}
public int CompareTo(ChessMoveData other)
{
return Move.CompareTo(other.Move);
}
}
private static ChessMoveData NewChessMove(ChessBoard board, ChessLocation from, ChessLocation to, ChessColor color)
{
var move = new ChessMove(from, to);
return new ChessMoveData(board, move, color);
}
private static void AddPawnMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
var startLocation = new ChessLocation(x, y);
var canJump = (pieceColor==ChessColor.Black && y==1) || (pieceColor==ChessColor.White && y==6);
var yForward = (pieceColor == ChessColor.Black) ? 1 : -1;
if (TileIsValid(x, y + yForward) && TileIsFree(board, x, y + yForward))
{
moveList.Add(NewChessMove(board, startLocation, new ChessLocation(x, y + yForward), pieceColor));
if (canJump)
if (TileIsValid(x, y + yForward * 2) && TileIsFree(board, x, y + yForward * 2))
moveList.Add(NewChessMove(board, startLocation, new ChessLocation(x, y + yForward * 2), pieceColor));
}
if (TileIsValid(x + 1, y + yForward) && TileHasColor(board, x + 1, y + yForward, EnemyColor(pieceColor)))
moveList.Add(NewChessMove(board, startLocation, new ChessLocation(x + 1, y + yForward), pieceColor));
if (TileIsValid(x - 1, y + yForward) && TileHasColor(board, x - 1, y + yForward, EnemyColor(pieceColor)))
moveList.Add(NewChessMove(board, startLocation, new ChessLocation(x - 1, y + yForward), pieceColor));
}
private static void AddRookMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
AddRiderMoves(moveList, board, x, y, pieceColor, 1, 0);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, 0);
AddRiderMoves(moveList, board, x, y, pieceColor, 0, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, 0, -1);
}
private static void AddKnightMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
AddLeaperMoves(moveList, board, x, y, pieceColor, 1, 2);
AddLeaperMoves(moveList, board, x, y, pieceColor, 1, -2);
AddLeaperMoves(moveList, board, x, y, pieceColor, 2, 1);
AddLeaperMoves(moveList, board, x, y, pieceColor, 2, -1);
AddLeaperMoves(moveList, board, x, y, pieceColor, -1, 2);
AddLeaperMoves(moveList, board, x, y, pieceColor, -1, -2);
AddLeaperMoves(moveList, board, x, y, pieceColor, -2, 1);
AddLeaperMoves(moveList, board, x, y, pieceColor, -2, -1);
}
private static void AddBishopMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
AddRiderMoves(moveList, board, x, y, pieceColor, 1, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, -1);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, 1, -1);
}
private static void AddQueenMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
AddRiderMoves(moveList, board, x, y, pieceColor, 1, 0);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, 0);
AddRiderMoves(moveList, board, x, y, pieceColor, 0, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, 0, -1);
AddRiderMoves(moveList, board, x, y, pieceColor, 1, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, -1);
AddRiderMoves(moveList, board, x, y, pieceColor, -1, 1);
AddRiderMoves(moveList, board, x, y, pieceColor, 1, -1);
}
private static void AddRiderMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor, int modX, int modY)
{
var i = 1;
while (true)
{
var newX = x + modX * i;
var newY = y + modY * i;
if (TileIsValid(newX, newY))
{
if (TileHasColor(board, newX, newY, EnemyColor(pieceColor)))
{
moveList.Add(NewChessMove(board, new ChessLocation(x, y), new ChessLocation(newX, newY), pieceColor));
break;
}
if (TileIsFree(board, newX, newY))
{
moveList.Add(NewChessMove(board, new ChessLocation(x, y), new ChessLocation(newX, newY), pieceColor));
i++;
continue;
}
else
{
break;
}
}
else
{
break;
}
}
}
private static void AddKingMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y, ChessColor pieceColor)
{
AddLeaperMoves(moveList, board, x, y, pieceColor, 0, 1);
AddLeaperMoves(moveList, board, x, y, pieceColor, 0, -1);
AddLeaperMoves(moveList, board, x, y, pieceColor, 1, 0);
AddLeaperMoves(moveList, board, x, y, pieceColor, -1, 0);
AddLeaperMoves(moveList, board, x, y, pieceColor, 1, 1);
AddLeaperMoves(moveList, board, x, y, pieceColor, 1, -1);
AddLeaperMoves(moveList, board, x, y, pieceColor, -1, 1);
AddLeaperMoves(moveList, board, x, y, pieceColor, -1, -1);
}
private static void AddLeaperMoves(List<ChessMoveData> moveList, ChessBoard board, int x, int y,
ChessColor pieceColor, int modX, int modY)
{
var newX = x + modX;
var newY = y + modY;
if (TileIsValid(newX, newY) && (TileIsFree(board, newX, newY) || TileHasColor(board, newX, newY, EnemyColor(pieceColor))))
moveList.Add(NewChessMove(board, new ChessLocation(x, y), new ChessLocation(newX, newY), pieceColor));
}
private static bool TileIsValid(int x, int y)
{
return !(x < 0 || y < 0 || x > 7 || y > 7);
}
private static ChessColor GetChessPieceColor(ChessPiece piece)
{
if (piece < ChessPiece.Empty) return ChessColor.Black;
if (piece > ChessPiece.Empty) return ChessColor.White;
throw new Exception("You didn't check whether this was an empty tile before calling this method!");
}
private static ChessColor EnemyColor(ChessColor color)
{
return color == ChessColor.Black ? ChessColor.White : ChessColor.Black;
}
private static bool TileHasColor(ChessBoard board, int x, int y, ChessColor color)
{
var piece = board[x, y];
if (piece == ChessPiece.Empty) return false;
return (color == GetChessPieceColor(piece));
}
private static bool TileIsFree(ChessBoard board, int x, int y)
{
return board[x, y] == ChessPiece.Empty;
}
///TODO: seperate flags adding and value adding
/// value adding shouldn't happen when checking if IsValid
private List<ChessMoveData> EvaluateMoves(List<ChessMoveData> moveList)
{
var newList = new List<ChessMoveData>();
//remove moves that lead to check
foreach (var move in moveList)
{
var isInCheck = false;
var enemyMoves = GetMyMoves(move.NewBoard, EnemyColor(move.Color));
foreach (var enemyMove in enemyMoves)
{
var toTile = enemyMove.OldBoard[enemyMove.Move.To.X, enemyMove.Move.To.Y];
if ((enemyMove.Color == ChessColor.Black && toTile == ChessPiece.WhiteKing) ||
(enemyMove.Color == ChessColor.White && toTile == ChessPiece.BlackKing))
{
isInCheck = true;
break;
}
}
if (!isInCheck)
{
newList.Add(move);
continue;
}
}
moveList = newList;
//get value of move
foreach (var move in moveList)
{
SetMoveFlagAndValue(move);
}
//move pawns if half moves is too high (avoid stalemate)
if (HalfMoves > 30)
{
foreach (var move in moveList)
{
var currentPiece = move.OldBoard[move.Move.From.X, move.Move.From.Y];
if (currentPiece != ChessPiece.BlackPawn && currentPiece != ChessPiece.WhitePawn)
continue;
move.Move.ValueOfMove += 1000;
}
}
return moveList;
}
private static int GetBoardValue(ChessBoard board, ChessColor myColor)
{
var whiteKingLocation = GetPiecePosition(board, ChessPiece.WhiteKing);
var blackKingLocation = GetPiecePosition(board, ChessPiece.BlackKing);
var value = 0;
for (var y = 0; y < ChessBoard.NumberOfRows; y++)
{
for (var x = 0; x < ChessBoard.NumberOfColumns; x++)
{
var currentPiece = board[x, y];
if (currentPiece == ChessPiece.Empty) continue;
var colorMulti = (GetChessPieceColor(currentPiece) == myColor) ? 1 : -1;
int distToKing;
var kingLocation = (GetChessPieceColor(currentPiece) == ChessColor.Black)
? whiteKingLocation
: blackKingLocation;
if (kingLocation == null)
{
distToKing = 10;
}
else
{
var dis = Convert.ToInt32(Math.Sqrt(Math.Pow(x - kingLocation.X, 2) + Math.Pow(y - kingLocation.Y, 2)));
if (dis < 2) dis = 10;
distToKing = 10 - dis;
}
switch (currentPiece)
{
case ChessPiece.BlackPawn:
value += colorMulti*pawnValue;
value += colorMulti*(pawnValue/PawnRankModifier)*(y - 1);
break;
case ChessPiece.WhitePawn:
value += colorMulti * pawnValue;
value += colorMulti * (pawnValue / PawnRankModifier) * (6 - y);
break;
case ChessPiece.BlackRook:
case ChessPiece.WhiteRook:
value += colorMulti * rookValue;
value += colorMulti*(rookValue/distKingModifier)*distToKing;
break;
case ChessPiece.BlackKnight:
case ChessPiece.WhiteKnight:
value += colorMulti * knightValue;
value += colorMulti * (knightValue / distKingModifier) * distToKing;
break;
case ChessPiece.BlackBishop:
case ChessPiece.WhiteBishop:
value += colorMulti * bishopValue;
value += colorMulti * (bishopValue / distKingModifier) * distToKing;
break;
case ChessPiece.BlackQueen:
case ChessPiece.WhiteQueen:
value += colorMulti * queenValue;
value += colorMulti * (queenValue / distKingModifier) * distToKing;
break;
case ChessPiece.BlackKing:
case ChessPiece.WhiteKing:
value += colorMulti * kingValue;
break;
default:
throw new Exception("Somehow not catching a specific piece? Empty?");
break;
}
}
}
return value;
}
private static bool IsMovingRightColorPiece(ChessBoard board, ChessMove moveToCheck, ChessColor colorOfPlayerMoving)
{
return (GetChessPieceColor(board[moveToCheck.From.X, moveToCheck.From.Y]) == colorOfPlayerMoving);
}
#region IChessAI Members that should be implemented as automatic properties and should NEVER be touched by students.
/// <summary>
/// This will return false when the framework starts running your AI. When the AI's time has run out,
/// then this method will return true. Once this method returns true, your AI should return a
/// move immediately.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
public AIIsMyTurnOverCallback IsMyTurnOver { get; set; }
/// <summary>
/// Call this method to print out debug information. The framework subscribes to this event
/// and will provide a log window for your debug messages.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AILoggerCallback Log { get; set; }
/// <summary>
/// Call this method to catch profiling information. The framework subscribes to this event
/// and will print out the profiling stats in your log window.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="key"></param>
public AIProfiler Profiler { get; set; }
/// <summary>
/// Call this method to tell the framework what decision print out debug information. The framework subscribes to this event
/// and will provide a debug window for your decision tree.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AISetDecisionTreeCallback SetDecisionTree { get; set; }
#endregion
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reflection;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Web;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.DependencyInjection;
using Umbraco.Cms.Tests.Integration.Testing;
using Umbraco.Cms.Web.BackOffice.Controllers;
using Umbraco.Cms.Web.Common.Controllers;
using Umbraco.Cms.Web.Website.Controllers;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.Integration.TestServerTest
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, Logger = UmbracoTestOptions.Logger.Console, Boot = true)]
public abstract class UmbracoTestServerTestBase : UmbracoIntegrationTest
{
[SetUp]
public override void Setup()
{
InMemoryConfiguration["ConnectionStrings:" + Constants.System.UmbracoConnectionName] = null;
InMemoryConfiguration["Umbraco:CMS:Hosting:Debug"] = "true";
/*
* It's worth noting that our usage of WebApplicationFactory is non-standard,
* the intent is that your Startup.ConfigureServices is called just like
* when the app starts up, then replacements are registered in this class with
* builder.ConfigureServices (builder.ConfigureTestServices has hung around from before the
* generic host switchover).
*
* This is currently a pain to refactor towards due to UmbracoBuilder+TypeFinder+TypeLoader setup but
* we should get there one day.
*
* See https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests
*/
var factory = new UmbracoWebApplicationFactory<UmbracoTestServerTestBase>(CreateHostBuilder, BeforeHostStart);
// additional host configuration for web server integration tests
Factory = factory.WithWebHostBuilder(builder =>
{
// Otherwise inferred as $(SolutionDir)/Umbraco.Tests.Integration (note lack of src/tests)
builder.UseContentRoot(Assembly.GetExecutingAssembly().GetRootDirectorySafe());
// Executes after the standard ConfigureServices method
builder.ConfigureTestServices(services =>
// Add a test auth scheme with a test auth handler to authn and assign the user
services.AddAuthentication(TestAuthHandler.TestAuthenticationScheme)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.TestAuthenticationScheme, options => { }));
});
Client = Factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
LinkGenerator = Factory.Services.GetRequiredService<LinkGenerator>();
}
public override IHostBuilder CreateHostBuilder()
{
IHostBuilder builder = base.CreateHostBuilder();
builder.ConfigureWebHost(builder =>
{
// need to configure the IWebHostEnvironment too
builder.ConfigureServices((c, s) => c.HostingEnvironment = TestHelper.GetWebHostEnvironment());
// call startup
builder.Configure(app => Configure(app));
})
.UseDefaultServiceProvider(cfg =>
{
// These default to true *if* WebHostEnvironment.EnvironmentName == Development
// When running tests, EnvironmentName used to be null on the mock that we register into services.
// Enable opt in for tests so that validation occurs regardless of environment name.
// Would be nice to have this on for UmbracoIntegrationTest also but requires a lot more effort to resolve issues.
cfg.ValidateOnBuild = true;
cfg.ValidateScopes = true;
});
return builder;
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareApiControllerUrl<T>(Expression<Func<T, object>> methodSelector)
where T : UmbracoApiController
{
string url = LinkGenerator.GetUmbracoApiService(methodSelector);
return PrepareUrl(url);
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareSurfaceControllerUrl<T>(Expression<Func<T, object>> methodSelector)
where T : SurfaceController
{
string url = LinkGenerator.GetUmbracoSurfaceUrl(methodSelector);
return PrepareUrl(url);
}
/// <summary>
/// Prepare a url before using <see cref="Client"/>.
/// This returns the url but also sets the HttpContext.request into to use this url.
/// </summary>
/// <returns>The string URL of the controller action.</returns>
protected string PrepareUrl(string url)
{
IUmbracoContextFactory umbracoContextFactory = GetRequiredService<IUmbracoContextFactory>();
IHttpContextAccessor httpContextAccessor = GetRequiredService<IHttpContextAccessor>();
httpContextAccessor.HttpContext = new DefaultHttpContext
{
Request =
{
Scheme = "https",
Host = new HostString("localhost", 80),
Path = url,
QueryString = new QueryString(string.Empty)
}
};
umbracoContextFactory.EnsureUmbracoContext();
return url;
}
protected HttpClient Client { get; private set; }
protected LinkGenerator LinkGenerator { get; private set; }
protected WebApplicationFactory<UmbracoTestServerTestBase> Factory { get; private set; }
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<TestUmbracoDatabaseFactoryProvider>();
Core.Hosting.IHostingEnvironment hostingEnvironment = TestHelper.GetHostingEnvironment();
TypeLoader typeLoader = services.AddTypeLoader(
GetType().Assembly,
hostingEnvironment,
TestHelper.ConsoleLoggerFactory,
AppCaches.NoCache,
Configuration,
TestHelper.Profiler);
var builder = new UmbracoBuilder(services, Configuration, typeLoader, TestHelper.ConsoleLoggerFactory, TestHelper.Profiler, AppCaches.NoCache, hostingEnvironment);
builder
.AddConfiguration()
.AddUmbracoCore()
.AddWebComponents()
.AddNuCache()
.AddRuntimeMinifier()
.AddBackOfficeCore()
.AddBackOfficeAuthentication()
.AddBackOfficeIdentity()
.AddMembersIdentity()
.AddBackOfficeAuthorizationPolicies(TestAuthHandler.TestAuthenticationScheme)
.AddPreviewSupport()
.AddMvcAndRazor(mvcBuilding: mvcBuilder =>
{
// Adds Umbraco.Web.BackOffice
mvcBuilder.AddApplicationPart(typeof(ContentController).Assembly);
// Adds Umbraco.Web.Common
mvcBuilder.AddApplicationPart(typeof(RenderController).Assembly);
// Adds Umbraco.Web.Website
mvcBuilder.AddApplicationPart(typeof(SurfaceController).Assembly);
// Adds Umbraco.Tests.Integration
mvcBuilder.AddApplicationPart(typeof(UmbracoTestServerTestBase).Assembly);
})
.AddWebServer()
.AddWebsite()
.AddTestServices(TestHelper) // This is the important one!
.Build();
}
public override void Configure(IApplicationBuilder app)
{
app.UseUmbraco()
.WithMiddleware(u =>
{
u.UseBackOffice();
u.UseWebsite();
})
.WithEndpoints(u =>
{
u.UseBackOfficeEndpoints();
u.UseWebsiteEndpoints();
});
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for LoadBalancersOperations.
/// </summary>
public static partial class LoadBalancersOperationsExtensions
{
/// <summary>
/// The delete LoadBalancer operation deletes the specified load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
public static void Delete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName)
{
Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).DeleteAsync(resourceGroupName, loadBalancerName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete LoadBalancer operation deletes the specified load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The delete LoadBalancer operation deletes the specified load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
public static void BeginDelete(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName)
{
Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).BeginDeleteAsync(resourceGroupName, loadBalancerName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete LoadBalancer operation deletes the specified load balancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The Get LoadBalancer operation retrieves information about the specified
/// LoadBalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
public static LoadBalancer Get(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string))
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).GetAsync(resourceGroupName, loadBalancerName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get LoadBalancer operation retrieves information about the specified
/// LoadBalancer.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='expand'>
/// expand references resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> GetAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, loadBalancerName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
public static LoadBalancer CreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).CreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> CreateOrUpdateAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
public static LoadBalancer BeginCreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LoadBalancer operation creates/updates a LoadBalancer
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the loadBalancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete LoadBalancer operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LoadBalancer> BeginCreateOrUpdateAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<LoadBalancer> ListAll(this ILoadBalancersOperations operations)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAllAsync(this ILoadBalancersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<LoadBalancer> List(this ILoadBalancersOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAsync(this ILoadBalancersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LoadBalancer> ListAllNext(this ILoadBalancersOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListAllNextAsync(this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<LoadBalancer> ListNext(this ILoadBalancersOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((ILoadBalancersOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List loadBalancer operation retrieves all the load balancers in a
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<LoadBalancer>> ListNextAsync(this ILoadBalancersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using GitHubSharp.Utils;
using GitHubSharp.Controllers;
using System.Threading.Tasks;
using GitHubSharp.Models;
using System.Net.Http;
using System.Text;
using System.Linq;
namespace GitHubSharp
{
public class Client
{
public const string DefaultApi = "https://api.github.com";
public const string AccessTokenUri = "https://github.com";
public static Func<HttpClient> ClientConstructor = () => new HttpClient();
public static IJsonSerializer Serializer = new SimpleJsonSerializer();
private readonly HttpClient _client;
public string ApiUri { get; private set; }
public AuthenticatedUserController AuthenticatedUser
{
get { return new AuthenticatedUserController(this); }
}
public UsersController Users
{
get { return new UsersController(this); }
}
public NotificationsController Notifications
{
get { return new NotificationsController(this); }
}
public ExploreRepositoriesController Repositories
{
get { return new ExploreRepositoriesController(this); }
}
public MarkdownController Markdown
{
get { return new MarkdownController(this); }
}
public TeamsController Teams
{
get { return new TeamsController(this); }
}
public OrganizationsController Organizations
{
get { return new OrganizationsController(this); }
}
public GistsController Gists
{
get { return new GistsController(this); }
}
public AuthorizationsController Authorizations
{
get { return new AuthorizationsController(this); }
}
/// <summary>
/// Gets the username for this client
/// </summary>
public string Username { get; set; }
/// <summary>
/// Gets or sets the timeout.
/// </summary>
/// <value>
/// The timeout.
/// </value>
public TimeSpan Timeout
{
get { return _client.Timeout; }
set { _client.Timeout = value; }
}
/// <summary>
/// Constructor
/// </summary>
private Client()
{
_client = ClientConstructor();
_client.DefaultRequestHeaders.UserAgent.ParseAdd("GithubSharp");
Timeout = new TimeSpan(0, 0, 20);
}
/// <summary>
/// Create a BASIC Auth Client
/// </summary>
public static Client Basic(string username, string password, string apiUri = DefaultApi)
{
if (string.IsNullOrEmpty(apiUri))
apiUri = DefaultApi;
if (string.IsNullOrEmpty(username))
throw new ArgumentException("Username must be valid!");
if (string.IsNullOrEmpty(password))
throw new ArgumentException("Password must be valid!");
Uri apiOut;
if (!Uri.TryCreate(apiUri, UriKind.Absolute, out apiOut))
throw new ArgumentException("The URL, " + apiUri + ", is not valid!");
var c = new Client();
c.Username = username;
c.ApiUri = apiOut.AbsoluteUri.TrimEnd('/');
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
c._client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", token);
return c;
}
/// <summary>
/// Create a TwoFactor(BASIC + X-GitHub-OTP) Auth Client
/// </summary>
public static Client BasicTwoFactorAuthentication(string username, string password, string twoFactor, string apiUri = DefaultApi)
{
var c = Basic(username, password, apiUri);
c._client.DefaultRequestHeaders.Add("X-GitHub-OTP", twoFactor);
return c;
}
/// <summary>
/// Create a BASIC OAuth client
/// </summary>
public static Client BasicOAuth(string oauth, string apiUri = DefaultApi)
{
if (string.IsNullOrEmpty(apiUri))
apiUri = DefaultApi;
Uri apiOut;
if (!Uri.TryCreate(apiUri, UriKind.Absolute, out apiOut))
throw new ArgumentException("The URL, " + apiUri + ", is not valid!");
var c = new Client();
c.ApiUri = apiOut.AbsoluteUri.TrimEnd('/');
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", oauth, "x-oauth-basic")));
c._client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", token);
return c;
}
/// <summary>
/// Request an access token
/// </summary>
public static async Task<AccessTokenModel> RequestAccessToken(string clientId, string clientSecret, string code, string redirectUri, string domainUri = AccessTokenUri)
{
if (string.IsNullOrEmpty(domainUri))
domainUri = AccessTokenUri;
if (!domainUri.EndsWith("/", StringComparison.Ordinal))
domainUri += "/";
domainUri += "login/oauth/access_token";
var c = new Client();
using (var r = new HttpRequestMessage(HttpMethod.Post, domainUri))
{
var args = new { client_id = clientId, client_secret = clientSecret, code, redirect_uri = redirectUri };
var serialized = Serializer.Serialize(args);
r.Content = new StringContent(serialized, Encoding.UTF8, "application/json");
r.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
using (var response = await c.ExecuteRequest(r).ConfigureAwait(false))
return (await ParseResponse<AccessTokenModel>(response).ConfigureAwait(false)).Data;
}
}
private static string ToQueryString(IEnumerable<KeyValuePair<string, string>> nvc)
{
var array = (from key in nvc
select string.Format("{0}={1}", Uri.EscapeDataString(key.Key), Uri.EscapeDataString(key.Value)))
.ToArray();
return "?" + string.Join("&", array);
}
/// <summary>
/// Makes a 'GET' request to the server using a URI
/// </summary>
/// <typeparam name="T">The type of object the response should be deserialized ot</typeparam>
/// <returns>An object with response data</returns>
private async Task<GitHubResponse<T>> Get<T>(GitHubRequest githubRequest) where T : new()
{
var url = new StringBuilder().Append(githubRequest.Url);
if (githubRequest.Args != null)
url.Append(ToQueryString(ObjectToDictionaryConverter.Convert(githubRequest.Args).ToArray()));
var absoluteUrl = url.ToString();
// If there is no cache, just directly execute and parse. Nothing more
using (var request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl))
{
using (var requestResponse = await ExecuteRequest(request).ConfigureAwait(false))
{
return await ParseResponse<T>(requestResponse).ConfigureAwait(false);
}
}
}
private static HttpRequestMessage CreatePutRequest(GitHubRequest request)
{
var r = new HttpRequestMessage(HttpMethod.Put, request.Url);
if (request.Args != null)
{
var serialized = Serializer.Serialize(request.Args);
r.Content = new StringContent(serialized, Encoding.UTF8, "application/json");
}
else
{
r.Content = new StringContent("");
r.Content.Headers.ContentLength = 0;
}
return r;
}
/// <summary>
/// Makes a 'PUT' request to the server
/// </summary>
private async Task<GitHubResponse<T>> Put<T>(GitHubRequest gitHubRequest) where T : new()
{
using (var request = CreatePutRequest(gitHubRequest))
{
using (var response = await ExecuteRequest(request).ConfigureAwait(false))
{
return await ParseResponse<T>(response).ConfigureAwait(false);
}
}
}
/// <summary>
/// Makes a 'PUT' request to the server
/// </summary>
private async Task<GitHubResponse> Put(GitHubRequest gitHubRequest)
{
using (var request = CreatePutRequest(gitHubRequest))
{
using (var response = await ExecuteRequest(request).ConfigureAwait(false))
{
return await ParseResponse(response).ConfigureAwait(false);
}
}
}
/// <summary>
/// Makes a 'POST' request to the server
/// </summary>
private async Task<GitHubResponse<T>> Post<T>(GitHubRequest request) where T : new()
{
using (var r = new HttpRequestMessage(HttpMethod.Post, request.Url))
{
if (request.Args != null)
{
var serialized = Serializer.Serialize(request.Args);
r.Content = new StringContent(serialized, Encoding.UTF8, "application/json");
}
using (var response = await ExecuteRequest(r).ConfigureAwait(false))
{
return await ParseResponse<T>(response).ConfigureAwait(false);
}
}
}
/// <summary>
/// Makes a 'DELETE' request to the server
/// </summary>
private async Task<GitHubResponse> Delete(GitHubRequest request)
{
using (var r = new HttpRequestMessage(HttpMethod.Delete, request.Url))
{
using (var response = await ExecuteRequest(r).ConfigureAwait(false))
{
return await ParseResponse(response).ConfigureAwait(false);
}
}
}
private static HttpRequestMessage CreatePatchRequest(GitHubRequest request)
{
using (var r = new HttpRequestMessage(new HttpMethod("PATCH"), request.Url))
{
if (request.Args != null)
{
var serialized = Serializer.Serialize(request.Args);
r.Content = new StringContent(serialized, Encoding.UTF8, "application/json");
}
return r;
}
}
private async Task<GitHubResponse<T>> Patch<T>(GitHubRequest gitHubRequest) where T : new()
{
using (var request = CreatePatchRequest(gitHubRequest))
{
using (var response = await ExecuteRequest(request).ConfigureAwait(false))
{
return await ParseResponse<T>(response).ConfigureAwait(false);
}
}
}
private async Task<GitHubResponse> Patch(GitHubRequest gitHubRequest)
{
using (var request = CreatePatchRequest(gitHubRequest))
{
using (var response = await ExecuteRequest(request).ConfigureAwait(false))
{
return await ParseResponse(response).ConfigureAwait(false);
}
}
}
private static async Task<GitHubResponse<T>> ParseResponse<T>(HttpResponseMessage response) where T : new()
{
var ghr = new GitHubResponse<T> { StatusCode = (int)response.StatusCode };
foreach (var h in response.Headers)
{
if (h.Key.Equals("X-RateLimit-Limit"))
ghr.RateLimitLimit = Convert.ToInt32(h.Value.First());
else if (h.Key.Equals("X-RateLimit-Remaining"))
ghr.RateLimitRemaining = Convert.ToInt32(h.Value.First());
else if (h.Key.Equals("ETag"))
ghr.ETag = h.Value.First().Replace("\"", "").Trim();
else if (h.Key.Equals("Link"))
{
var s = h.Value.First().Split(',');
foreach (var link in s)
{
var splitted = link.Split(';');
var url = splitted[0].Trim();
var what = splitted[1].Trim();
what = what.Substring(5);
what = what.Substring(0, what.Length - 1);
url = url.Substring(1);
url = url.Substring(0, url.Length - 1);
if (what.Equals("next"))
{
ghr.More = GitHubRequest.Get<T>(url);
}
}
}
}
// Booleans have a special definition in the github responses.
// They typically represent a status code Not Found = false
// or 204 = true and 205 (reset content)
if (typeof(T) == typeof(bool) && (ghr.StatusCode == 204 || ghr.StatusCode == 205 || ghr.StatusCode == 404))
{
var b = ghr.StatusCode == 204 || ghr.StatusCode == 205;
ghr.Data = (T)(object)(b);
return ghr;
}
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (response.StatusCode < (HttpStatusCode)200 || response.StatusCode >= (HttpStatusCode)300)
throw StatusCodeException.FactoryCreate(response, content);
ghr.Data = Serializer.Deserialize<T>(content);
return ghr;
}
private static async Task<GitHubResponse> ParseResponse(HttpResponseMessage response)
{
var ghr = new GitHubResponse { StatusCode = (int)response.StatusCode };
foreach (var h in response.Headers)
{
if (h.Key.Equals("X-RateLimit-Limit"))
ghr.RateLimitLimit = Convert.ToInt32(h.Value.First());
else if (h.Key.Equals("X-RateLimit-Remaining"))
ghr.RateLimitRemaining = Convert.ToInt32(h.Value.First());
else if (h.Key.Equals("ETag"))
ghr.ETag = h.Value.First().Replace("\"", "");
}
var content = await response.Content.ReadAsStringAsync();
if (response.StatusCode < (HttpStatusCode)200 || response.StatusCode >= (HttpStatusCode)300)
throw StatusCodeException.FactoryCreate(response, content);
return ghr;
}
/// <summary>
/// Executes a request to the server
/// </summary>
internal async Task<HttpResponseMessage> ExecuteRequest(HttpRequestMessage request)
{
try
{
if (request.Headers.Accept.Count == 0)
request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.github.v3.full+json"));
return await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
}
catch (TaskCanceledException e)
{
// Provide a better error message
throw new TaskCanceledException("Timeout waiting for GitHub to respond. Check your connection and try again.", e);
}
catch(WebException e)
{
// Provide a better error message
throw new WebException("Unable to communicate with GitHub. Please check your connection and try again.", e);
}
}
public Task<GitHubResponse> ExecuteAsync(GitHubRequest request)
{
switch (request.RequestMethod)
{
case RequestMethod.DELETE:
return Delete(request);
case RequestMethod.PUT:
return Put(request);
case RequestMethod.PATCH:
return Patch(request);
default:
return null;
}
}
public Task<GitHubResponse<T>> ExecuteAsync<T>(GitHubRequest<T> request) where T : new()
{
switch (request.RequestMethod)
{
case RequestMethod.GET:
return Get<T>(request);
case RequestMethod.POST:
return Post<T>(request);
case RequestMethod.PUT:
return Put<T>(request);
case RequestMethod.PATCH:
return Patch<T>(request);
default:
return null;
}
}
// public bool IsCached(GitHubRequest request)
// {
// if (Cache == null || request.RequestMethod != RequestMethod.GET)
// return false;
//
// var req = new RestRequest(request.Url, Method.GET);
// if (request.Args != null)
// foreach (var arg in ObjectToDictionaryConverter.Convert(request.Args))
// req.AddParameter(arg.Key, arg.Value);
//
// return Cache.Exists(_client.BuildUri(req).AbsoluteUri);
// }
public async Task<string> DownloadRawResource(string rawUrl, System.IO.Stream downloadSream)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, rawUrl))
{
using (var response = await ExecuteRequest(request))
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
stream.CopyTo(downloadSream);
return "" + response.Content.Headers.ContentType;
}
}
}
}
public async Task<string> DownloadRawResource2(string rawUrl, System.IO.Stream downloadSream)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, rawUrl))
{
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.github.raw"));
using (var response = await ExecuteRequest(request))
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
stream.CopyTo(downloadSream);
return "" + response.Content.Headers.ContentType;
}
}
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using PlayFab.PfEditor.Json;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public static partial class PlayFabEditorHelper
{
#region EDITOR_STRINGS
public static string EDEX_NAME = "PlayFab_EditorExtensions";
public static string EDEX_ROOT = Application.dataPath + "/PlayFabEditorExtensions/Editor";
public static string DEV_API_ENDPOINT = "https://editor.playfabapi.com";
public static string TITLE_ENDPOINT = ".playfabapi.com";
public static string GAMEMANAGER_URL = "https://developer.playfab.com";
public static string PLAYFAB_SETTINGS_TYPENAME = "PlayFabSettings";
public static string PLAYFAB_EDEX_MAINFILE = "PlayFabEditor.cs";
public static string SDK_DOWNLOAD_PATH = "/Resources/PlayFabUnitySdk.unitypackage";
public static string EDEX_UPGRADE_PATH = "/Resources/PlayFabUnityEditorExtensions.unitypackage";
public static string EDEX_PACKAGES_PATH = "/Resources/MostRecentPackage.unitypackage";
public static string CLOUDSCRIPT_FILENAME = ".CloudScript.js"; //prefixed with a '.' to exclude this code from Unity's compiler
public static string CLOUDSCRIPT_PATH = EDEX_ROOT + "/Resources/" + CLOUDSCRIPT_FILENAME;
public static string ADMIN_API = "ENABLE_PLAYFABADMIN_API";
public static string CLIENT_API = "DISABLE_PLAYFABCLIENT_API";
public static string ENTITY_API = "DISABLE_PLAYFABENTITY_API";
public static string SERVER_API = "ENABLE_PLAYFABSERVER_API";
public static string DEBUG_REQUEST_TIMING = "PLAYFAB_REQUEST_TIMING";
public static string ENABLE_PLAYFABPLAYSTREAM_API = "ENABLE_PLAYFABPLAYSTREAM_API";
public static string ENABLE_BETA_FETURES = "ENABLE_PLAYFAB_BETA";
public static string ENABLE_PLAYFABPUBSUB_API = "ENABLE_PLAYFABPUBSUB_API";
public static Dictionary<string, PfDefineFlag> FLAG_LABELS = new Dictionary<string, PfDefineFlag> {
{ ADMIN_API, new PfDefineFlag { Flag = ADMIN_API, Label = "ENABLE ADMIN API", Category = PfDefineFlag.FlagCategory.Api, isInverted = false, isSafe = true } },
{ CLIENT_API, new PfDefineFlag { Flag = CLIENT_API, Label = "ENABLE CLIENT API", Category = PfDefineFlag.FlagCategory.Api, isInverted = true, isSafe = true } },
{ ENTITY_API, new PfDefineFlag { Flag = ENTITY_API, Label = "ENABLE ENTITY API", Category = PfDefineFlag.FlagCategory.Api, isInverted = true, isSafe = true } },
{ SERVER_API, new PfDefineFlag { Flag = SERVER_API, Label = "ENABLE SERVER API", Category = PfDefineFlag.FlagCategory.Api, isInverted = false, isSafe = true } },
{ DEBUG_REQUEST_TIMING, new PfDefineFlag { Flag = DEBUG_REQUEST_TIMING, Label = "ENABLE REQUEST TIMES", Category = PfDefineFlag.FlagCategory.Feature, isInverted = false, isSafe = true } },
{ ENABLE_BETA_FETURES, new PfDefineFlag { Flag = ENABLE_BETA_FETURES, Label = "ENABLE UNSTABLE FEATURES", Category = PfDefineFlag.FlagCategory.Feature, isInverted = false, isSafe = true } },
{ ENABLE_PLAYFABPUBSUB_API, new PfDefineFlag { Flag = ENABLE_PLAYFABPUBSUB_API, Label = "ENABLE PubSub", Category = PfDefineFlag.FlagCategory.Feature, isInverted = false, isSafe = false } },
};
public static string DEFAULT_SDK_LOCATION = "Assets/PlayFabSdk";
public static string STUDIO_OVERRIDE = "_OVERRIDE_";
public static string MSG_SPIN_BLOCK = "{\"useSpinner\":true, \"blockUi\":true }";
#endregion
private static GUISkin _uiStyle;
public static GUISkin uiStyle
{
get
{
if (_uiStyle != null)
return _uiStyle;
_uiStyle = GetUiStyle();
return _uiStyle;
}
}
static PlayFabEditorHelper()
{
// scan for changes to the editor folder / structure.
if (uiStyle == null)
{
string[] rootFiles = new string[0];
bool relocatedEdEx = false;
_uiStyle = null;
try
{
if (!string.IsNullOrEmpty(PlayFabEditorPrefsSO.Instance.EdExPath))
EDEX_ROOT = PlayFabEditorPrefsSO.Instance.EdExPath;
rootFiles = Directory.GetDirectories(EDEX_ROOT);
}
catch
{
if (rootFiles.Length == 0)
{
// this probably means the editor folder was moved.
// see if we can locate the moved root and reload the assets
var movedRootFiles = Directory.GetFiles(Application.dataPath, PLAYFAB_EDEX_MAINFILE, SearchOption.AllDirectories);
if (movedRootFiles.Length > 0)
{
relocatedEdEx = true;
EDEX_ROOT = movedRootFiles[0].Substring(0, movedRootFiles[0].LastIndexOf(PLAYFAB_EDEX_MAINFILE) - 1);
PlayFabEditorPrefsSO.Instance.EdExPath = EDEX_ROOT;
PlayFabEditorDataService.SaveEnvDetails();
}
}
}
finally
{
if (relocatedEdEx && rootFiles.Length == 0)
{
Debug.Log("Found new EdEx root: " + EDEX_ROOT);
}
else if (rootFiles.Length == 0)
{
Debug.Log("Could not relocate the PlayFab Editor Extension");
EDEX_ROOT = string.Empty;
}
}
}
}
private static GUISkin GetUiStyle()
{
var searchRootAssetFolder = Application.dataPath;
var pfGuiPaths = Directory.GetFiles(searchRootAssetFolder, "PlayFabStyles.guiskin", SearchOption.AllDirectories);
foreach (var eachPath in pfGuiPaths)
{
var loadPath = eachPath.Substring(eachPath.LastIndexOf("Assets"));
return (GUISkin)AssetDatabase.LoadAssetAtPath(loadPath, typeof(GUISkin));
}
return null;
}
public static void SharedErrorCallback(EditorModels.PlayFabError error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error.GenerateErrorReport());
}
public static void SharedErrorCallback(string error)
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "SharedErrorCallback" + error);
}
public static EditorModels.PlayFabError GeneratePlayFabError(string json, object customData = null)
{
JsonObject errorDict = null;
Dictionary<string, List<string>> errorDetails = null;
try
{
//deserialize the error
errorDict = JsonWrapper.DeserializeObject<JsonObject>(json, PlayFabEditorUtil.ApiSerializerStrategy);
if (errorDict.ContainsKey("errorDetails"))
{
var ed = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString());
errorDetails = ed;
}
}
catch (Exception e)
{
return new EditorModels.PlayFabError()
{
ErrorMessage = e.Message
};
}
//create new error object
return new EditorModels.PlayFabError
{
HttpCode = errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400,
HttpStatus = errorDict.ContainsKey("status")
? (string)errorDict["status"]
: "BadRequest",
Error = errorDict.ContainsKey("errorCode")
? (EditorModels.PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"])
: EditorModels.PlayFabErrorCode.ServiceUnavailable,
ErrorMessage = errorDict.ContainsKey("errorMessage")
? (string)errorDict["errorMessage"]
: string.Empty,
ErrorDetails = errorDetails,
CustomData = customData ?? new object()
};
}
#region unused, but could be useful
/// <summary>
/// Tool to create a color background texture
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="col"></param>
/// <returns>Texture2D</returns>
public static Texture2D MakeTex(int width, int height, Color col)
{
var pix = new Color[width * height];
for (var i = 0; i < pix.Length; i++)
pix[i] = col;
var result = new Texture2D(width, height);
result.SetPixels(pix);
result.Apply();
return result;
}
public static Vector3 GetColorVector(int colorValue)
{
return new Vector3((colorValue / 255f), (colorValue / 255f), (colorValue / 255f));
}
#endregion
}
public class PfDefineFlag
{
public enum FlagCategory
{
Api,
Feature,
Other,
}
public string Flag; // Also doubles as the dictionary key
public string Label;
public FlagCategory Category;
public bool isInverted;
public bool isSafe;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Albedo;
using Albedo.Refraction;
using AutoFixture.Kernel;
namespace AutoFixture.Idioms
{
/// <summary>
/// Encapsulates a unit test that verifies that a member (property or field) is correctly initialized
/// by the constructor.
/// </summary>
public class ConstructorInitializedMemberAssertion : IdiomaticAssertion
{
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorInitializedMemberAssertion"/> class.
/// </summary>
/// <param name="builder">
/// A composer which can create instances required to implement the idiomatic unit test,
/// such as the owner of the property, as well as the value to be assigned and read from
/// the member.
/// </param>
/// <param name="comparer"> An <see cref="IEqualityComparer"/> instance, which is used
/// to determine if each member has the same value which was passed to the matching
/// constructor parameter.
/// </param>
/// <param name="parameterMemberMatcher">Provides a way to customize the way parameters
/// are matched to members. The boolean value returned from
/// <see cref="IEqualityComparer{T}.Equals(T,T)"/> indicates if the parameter and member
/// are matched.
/// </param>
/// <remarks>
/// <para>
/// <paramref name="builder" /> will typically be a <see cref="Fixture" /> instance.
/// </para>
/// </remarks>
public ConstructorInitializedMemberAssertion(
ISpecimenBuilder builder,
IEqualityComparer comparer,
IEqualityComparer<IReflectionElement> parameterMemberMatcher)
{
this.Builder = builder ?? throw new ArgumentNullException(nameof(builder));
this.Comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));
this.ParameterMemberMatcher = parameterMemberMatcher ??
throw new ArgumentNullException(nameof(parameterMemberMatcher));
}
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorInitializedMemberAssertion"/> class.
/// </summary>
/// <param name="builder">
/// A composer which can create instances required to implement the idiomatic unit test,
/// such as the owner of the property, as well as the value to be assigned and read from
/// the member.
/// </param>
/// <remarks>
/// <para>
/// <paramref name="builder" /> will typically be a <see cref="Fixture" /> instance.
/// </para>
/// </remarks>
public ConstructorInitializedMemberAssertion(ISpecimenBuilder builder)
: this(
builder,
EqualityComparer<object>.Default,
new DefaultParameterMemberMatcher())
{
}
/// <summary>
/// Gets the builder supplied by the constructor.
/// </summary>
public ISpecimenBuilder Builder { get; }
/// <summary>
/// Gets the comparer supplied to the constructor.
/// </summary>
/// <remarks>
/// This comparer instance is used to determine if all of the value retrieved from
/// the members are equal to their corresponding 'matched' constructor parameter.
/// </remarks>
public IEqualityComparer Comparer { get; }
/// <summary>
/// Gets the <see cref="IEqualityComparer{IReflectionElement}"/> instance which is
/// used to determine if a constructor parameter matches a given member (property
/// or field).
/// </summary>
/// <remarks>
/// If the parameter and member are matched, the member is expected to be initialized
/// from the value passed into the matching constructor parameter.
/// </remarks>
public IEqualityComparer<IReflectionElement> ParameterMemberMatcher { get; }
/// <summary>
/// Verifies that all constructor arguments are properly exposed as either fields
/// or properties.
/// </summary>
/// <param name="constructorInfo">The constructor.</param>
public override void Verify(ConstructorInfo constructorInfo)
{
if (constructorInfo == null) throw new ArgumentNullException(nameof(constructorInfo));
var parameters = constructorInfo.GetParameters();
if (parameters.Length == 0)
return;
var publicPropertiesAndFields = GetPublicPropertiesAndFields(constructorInfo.DeclaringType).ToArray();
// Handle backwards-compatibility by replacing the default
// matcher with one that behaves the similar to the previous
// behaviour
IEqualityComparer<IReflectionElement> matcher =
this.ParameterMemberMatcher is DefaultParameterMemberMatcher
? new DefaultParameterMemberMatcher(
new DefaultParameterMemberMatcher.NameIgnoreCaseAndTypeEqualComparer())
: this.ParameterMemberMatcher;
var firstParameterNotExposed = parameters.FirstOrDefault(
p => !publicPropertiesAndFields.Any(m =>
matcher.Equals(p.ToReflectionElement(), m.ToReflectionElement())));
if (firstParameterNotExposed != null)
{
throw new ConstructorInitializedMemberException(constructorInfo, firstParameterNotExposed);
}
}
/// <summary>
/// Verifies that a property is correctly initialized by the constructor.
/// </summary>
/// <param name="propertyInfo">The property.</param>
/// <remarks>
/// <para>
/// This method verifies that the <paramref name="propertyInfo" /> is correctly initialized with
/// the value given to the same-named constructor parameter. It uses the <see cref="Builder" /> to
/// supply values to the constructor(s) of the Type on which the field is implemented, and then
/// reads from the field. The assertion passes if the value read from the property is the same as
/// the value passed to the constructor. If more than one constructor has an argument with the
/// same name and type, all constructors are checked. If any constructor (with a matching argument)
/// does not initialise the property with the correct value, a
/// <see cref="ConstructorInitializedMemberException" /> is thrown.
/// </para>
/// </remarks>
/// <exception cref="WritablePropertyException">The verification fails.</exception>
public override void Verify(PropertyInfo propertyInfo)
{
if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo));
var matchingConstructors = this.GetConstructorsWithInitializerForMember(propertyInfo).ToArray();
if (!matchingConstructors.Any())
{
if (RequiresConstructorInitialization(propertyInfo))
{
throw new ConstructorInitializedMemberException(propertyInfo, string.Format(
CultureInfo.CurrentCulture,
"No constructors with an argument that matches the read-only property '{0}' were found",
propertyInfo.Name));
}
// For writable properties or fields, having no constructor parameter that initializes
// the member is perfectly fine.
return;
}
if (CouldLeadToFalsePositive(propertyInfo.PropertyType))
{
throw BuildExceptionDueToPotentialFalsePositive(propertyInfo);
}
var expectedAndActual = matchingConstructors
.Select(ctor => this.BuildSpecimenFromConstructor(ctor, propertyInfo));
// Compare the value passed into the constructor with the value returned from the property
if (expectedAndActual.Any(s => !this.Comparer.Equals(s.Expected, s.Actual)))
{
throw new ConstructorInitializedMemberException(propertyInfo);
}
}
/// <summary>
/// Verifies that a field is correctly initialized by the constructor.
/// </summary>
/// <param name="fieldInfo">The field.</param>
/// <remarks>
/// <para>
/// This method verifies that <paramref name="fieldInfo" /> is correctly initialized with the
/// value given to the same-named constructor parameter. It uses the <see cref="Builder" /> to
/// supply values to the constructor(s) of the Type on which the field is implemented, and then
/// reads from the field. The assertion passes if the value read from the field is the same as
/// the value passed to the constructor. If more than one constructor has an argument with the
/// same name and type, all constructors are checked. If any constructor does not initialise
/// the field with the correct value, a <see cref="ConstructorInitializedMemberException" />
/// is thrown.
/// </para>
/// </remarks>
/// <exception cref="ConstructorInitializedMemberException">The verification fails.</exception>
public override void Verify(FieldInfo fieldInfo)
{
if (fieldInfo == null) throw new ArgumentNullException(nameof(fieldInfo));
var matchingConstructors = this.GetConstructorsWithInitializerForMember(fieldInfo).ToArray();
if (!matchingConstructors.Any())
{
if (RequiresConstructorInitialization(fieldInfo))
{
throw new ConstructorInitializedMemberException(fieldInfo, string.Format(CultureInfo.CurrentCulture,
"No constructors with an argument that matches the read-only field '{0}' were found",
fieldInfo.Name));
}
// For writable properties or fields, having no constructor parameter that initializes
// the member is perfectly fine.
return;
}
if (CouldLeadToFalsePositive(fieldInfo.FieldType))
{
throw BuildExceptionDueToPotentialFalsePositive(fieldInfo);
}
var expectedAndActual = matchingConstructors
.Select(ctor => this.BuildSpecimenFromConstructor(ctor, fieldInfo));
// Compare the value passed into the constructor with the value returned from the property
if (expectedAndActual.Any(s => !this.Comparer.Equals(s.Expected, s.Actual)))
{
throw new ConstructorInitializedMemberException(fieldInfo);
}
}
private static bool CouldLeadToFalsePositive(Type type)
{
if (!type.IsEnum) return false;
// Check for a default value only enum
var values = Enum.GetValues(type);
return values.Length == 1 && values.GetValue(0).Equals(Activator.CreateInstance(type));
}
private static ConstructorInitializedMemberException BuildExceptionDueToPotentialFalsePositive(
MemberInfo propertyOrField)
{
var message = string.Format(
CultureInfo.CurrentCulture,
"Unable to properly detect a successful initialization due to {0} being of type enum having " +
"a single default value.{3}Declaring type: {1}{3}Reflected type: {2}{3}",
propertyOrField.Name,
propertyOrField.DeclaringType?.AssemblyQualifiedName,
propertyOrField.ReflectedType?.AssemblyQualifiedName,
Environment.NewLine);
return propertyOrField switch
{
FieldInfo fi => new ConstructorInitializedMemberException(fi, message),
PropertyInfo pi => new ConstructorInitializedMemberException(pi, message),
_ => throw new ArgumentException("Must be a property or field", nameof(propertyOrField))
};
}
private ExpectedAndActual BuildSpecimenFromConstructor(
ConstructorInfo ci, MemberInfo propertyOrField)
{
var parametersAndValues = ci.GetParameters()
.Select(pi => new
{
Parameter = pi,
Value = this.GetParameterValue(pi)
})
.ToArray();
// Get the value expected to be assigned to the matching member
var expectedValueForMember = parametersAndValues
.Single(p => this.IsMatchingParameterAndMember(p.Parameter, propertyOrField))
.Value;
// Construct an instance of the specimen class
var specimen = ci.Invoke(parametersAndValues.Select(pv => pv.Value).ToArray());
// Get the value from the specimen field/property
object actual = propertyOrField switch
{
FieldInfo fi => fi.GetValue(specimen),
PropertyInfo pi => pi.CanRead ? pi.GetValue(specimen, null) : expectedValueForMember,
_ => throw new ArgumentException("Must be a property or field", nameof(propertyOrField))
};
return new ExpectedAndActual(expectedValueForMember, actual);
}
private object GetParameterValue(ParameterInfo parameterInfo)
=> parameterInfo.ParameterType switch
{
{ } t when t == typeof(bool) => true,
{ IsEnum: true } => this.GetEnumParameterValue(parameterInfo),
_ => this.Builder.CreateAnonymous(parameterInfo)
};
private object GetEnumParameterValue(ParameterInfo parameterInfo)
{
var value = this.Builder.CreateAnonymous(parameterInfo);
// Ensure enum isn't getting the default value, otherwise
// we won't be able to determine whether initialization
// occurred.
object defaultValue = parameterInfo.ParameterType.GetDefaultValue();
if (!value.Equals(defaultValue)) return value;
// If the second consecutive attempt does not yield a non-default result,
// then the value must have been frozen, so no point trying again.
return this.Builder.CreateAnonymous(parameterInfo);
}
private class ExpectedAndActual
{
public ExpectedAndActual(object expected, object actual)
{
this.Expected = expected;
this.Actual = actual;
}
public object Expected { get; }
public object Actual { get; }
}
private IEnumerable<ConstructorInfo> GetConstructorsWithInitializerForMember(MemberInfo member)
{
return member.ReflectedType?.GetConstructors()
.Where(ci => this.IsConstructorWithMatchingArgument(ci, member));
}
private bool IsMatchingParameterAndMember(ParameterInfo parameter, MemberInfo fieldOrProperty)
{
return this.ParameterMemberMatcher.Equals(
fieldOrProperty.ToReflectionElement(), parameter.ToReflectionElement());
}
private bool IsConstructorWithMatchingArgument(ConstructorInfo ci, MemberInfo memberInfo)
{
return ci.GetParameters().Any(parameterElement =>
this.IsMatchingParameterAndMember(parameterElement, memberInfo));
}
private static IEnumerable<MemberInfo> GetPublicPropertiesAndFields(Type t)
{
return t.GetMembers(BindingFlags.Instance | BindingFlags.Public)
.Where(m => m.MemberType.HasFlag(MemberTypes.Field)
|| m.MemberType.HasFlag(MemberTypes.Property));
}
private static bool RequiresConstructorInitialization(PropertyInfo propertyInfo)
{
MethodInfo setterMethod = propertyInfo.GetSetMethod();
bool isReadOnly = propertyInfo.CanRead
&& (setterMethod == null
|| setterMethod.IsPrivate
|| setterMethod.IsFamilyOrAssembly
|| setterMethod.IsFamilyAndAssembly);
MethodInfo getterMethod = propertyInfo.GetGetMethod();
bool isStatic = getterMethod.IsStatic;
return isReadOnly && !isStatic;
}
private static bool RequiresConstructorInitialization(FieldInfo fieldInfo)
{
bool isReadOnly = fieldInfo.Attributes.HasFlag(FieldAttributes.InitOnly);
bool isStatic = fieldInfo.Attributes.HasFlag(FieldAttributes.Static);
return isReadOnly && !isStatic;
}
private class DefaultParameterMemberMatcher : ReflectionVisitorElementComparer<NameAndType>
{
public class NameIgnoreCaseAndTypeEqualComparer : IEqualityComparer<NameAndType>
{
public bool Equals(NameAndType x, NameAndType y)
{
if (x == null) throw new ArgumentNullException(nameof(x));
if (y == null) throw new ArgumentNullException(nameof(y));
return x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase)
&& x.Type == y.Type;
}
public int GetHashCode(NameAndType obj)
{
// Forces methods like Distinct() to use the Equals method, because
// the hash codes will all be equal.
return 0;
}
}
public DefaultParameterMemberMatcher(
IEqualityComparer<NameAndType> comparer)
: base(new NameAndTypeCollectingVisitor(), comparer)
{
}
public DefaultParameterMemberMatcher()
: this(null)
{
}
}
}
}
| |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.CodeDom.Compiler;
namespace Concur.Sample.ClientLibrary
{
[Register ("MainViewController")]
partial class MainViewController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField AmountTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField ClientIdTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton CreateReportButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField CurrencyTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField DateTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton ExpenseTypeCollapseButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton ExpenseTypeExpandButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIPickerView ExpenseTypePicker { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton ImageButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton LoginButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField LoginIdTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIView MyMainView { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField PasswordTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton PaymentTypeCollapseButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton PaymentTypeExpandButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIPickerView PaymentTypePicker { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField ReceiptImageTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UILabel ReportNameLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField ReportNameTextField { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UILabel StatusLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UILabel VendorLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UITextField VendorTextField { get; set; }
[Action ("CreateReportButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void CreateReportButton_TouchUpInside (UIButton sender);
[Action ("ExpenseTypeCollapseButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void ExpenseTypeCollapseButton_TouchUpInside (UIButton sender);
[Action ("ExpenseTypeExpandButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void ExpenseTypeExpandButton_TouchUpInside (UIButton sender);
[Action ("ImageButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void ImageButton_TouchUpInside (UIButton sender);
[Action ("LoginButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void LoginButton_TouchUpInside (UIButton sender);
[Action ("PaymentTypeCollapseButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void PaymentTypeCollapseButton_TouchUpInside (UIButton sender);
[Action ("PaymentTypeExpandButton_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void PaymentTypeExpandButton_TouchUpInside (UIButton sender);
void ReleaseDesignerOutlets ()
{
if (AmountTextField != null) {
AmountTextField.Dispose ();
AmountTextField = null;
}
if (ClientIdTextField != null) {
ClientIdTextField.Dispose ();
ClientIdTextField = null;
}
if (CreateReportButton != null) {
CreateReportButton.Dispose ();
CreateReportButton = null;
}
if (CurrencyTextField != null) {
CurrencyTextField.Dispose ();
CurrencyTextField = null;
}
if (DateTextField != null) {
DateTextField.Dispose ();
DateTextField = null;
}
if (ExpenseTypeCollapseButton != null) {
ExpenseTypeCollapseButton.Dispose ();
ExpenseTypeCollapseButton = null;
}
if (ExpenseTypeExpandButton != null) {
ExpenseTypeExpandButton.Dispose ();
ExpenseTypeExpandButton = null;
}
if (ExpenseTypePicker != null) {
ExpenseTypePicker.Dispose ();
ExpenseTypePicker = null;
}
if (ImageButton != null) {
ImageButton.Dispose ();
ImageButton = null;
}
if (LoginButton != null) {
LoginButton.Dispose ();
LoginButton = null;
}
if (LoginIdTextField != null) {
LoginIdTextField.Dispose ();
LoginIdTextField = null;
}
if (MyMainView != null) {
MyMainView.Dispose ();
MyMainView = null;
}
if (PasswordTextField != null) {
PasswordTextField.Dispose ();
PasswordTextField = null;
}
if (PaymentTypeCollapseButton != null) {
PaymentTypeCollapseButton.Dispose ();
PaymentTypeCollapseButton = null;
}
if (PaymentTypeExpandButton != null) {
PaymentTypeExpandButton.Dispose ();
PaymentTypeExpandButton = null;
}
if (PaymentTypePicker != null) {
PaymentTypePicker.Dispose ();
PaymentTypePicker = null;
}
if (ReceiptImageTextField != null) {
ReceiptImageTextField.Dispose ();
ReceiptImageTextField = null;
}
if (ReportNameLabel != null) {
ReportNameLabel.Dispose ();
ReportNameLabel = null;
}
if (ReportNameTextField != null) {
ReportNameTextField.Dispose ();
ReportNameTextField = null;
}
if (StatusLabel != null) {
StatusLabel.Dispose ();
StatusLabel = null;
}
if (VendorLabel != null) {
VendorLabel.Dispose ();
VendorLabel = null;
}
if (VendorTextField != null) {
VendorTextField.Dispose ();
VendorTextField = null;
}
}
}
}
| |
using System;
using System.Globalization;
using System.Web;
namespace Subtext.Akismet
{
/// <summary>
/// The client class used to communicate with the
/// <see href="http://akismet.com/">Akismet</see> service.
/// </summary>
public class AkismetClient
{
private HttpClient httpClient;
static readonly string version = typeof(HttpClient).Assembly.GetName().Version.ToString();
static readonly Uri verifyUrl = new Uri("http://rest.akismet.com/1.1/verify-key");
const string checkUrlFormat = "http://{0}.rest.akismet.com/1.1/comment-check";
const string submitSpamUrlFormat = "http://{0}.rest.akismet.com/1.1/submit-spam";
const string submitHamUrlFormat = "http://{0}.rest.akismet.com/1.1/submit-ham";
Uri submitSpamUrl;
Uri submitHamUrl;
Uri checkUrl;
/// <summary>
/// Initializes a new instance of the <see cref="AkismetClient"/> class.
/// </summary>
/// <remarks>
/// This constructor takes in all the dependencies to allow for
/// dependency injection and unit testing. Seems like overkill,
/// but it's worth it.
/// </remarks>
/// <param name="apiKey">The Akismet API key.</param>
/// <param name="blogUrl">The root url of the blog.</param>
/// <param name="httpClient">Client class used to make the underlying requests.</param>
public AkismetClient(string apiKey, Uri blogUrl, HttpClient httpClient)
{
if(apiKey == null)
throw new ArgumentNullException("The akismet Api Key must be specified");
if (blogUrl == null)
throw new ArgumentNullException("The blog's url must be specified");
if (httpClient == null)
throw new ArgumentNullException("Must supply an http client");
this.apiKey = apiKey;
this.blogUrl = blogUrl;
this.httpClient = httpClient;
SetServiceUrls();
}
/// <summary>
/// Initializes a new instance of the <see cref="AkismetClient"/> class.
/// </summary>
/// <param name="apiKey">The Akismet API key.</param>
/// <param name="blogUrl">The root url of the blog.</param>
public AkismetClient(string apiKey, Uri blogUrl) : this(apiKey, blogUrl, new HttpClient())
{
}
void SetServiceUrls()
{
this.submitHamUrl = new Uri(String.Format(submitHamUrlFormat, this.apiKey));
this.submitSpamUrl = new Uri(String.Format(submitSpamUrlFormat, this.apiKey));
this.checkUrl = new Uri(String.Format(checkUrlFormat, this.apiKey));
}
/// <summary>
/// Gets or sets the Akismet API key.
/// </summary>
/// <value>The API key.</value>
public string ApiKey
{
get { return (this.apiKey == null) ? string.Empty : this.apiKey; }
set
{
this.apiKey = (value == null) ? string.Empty : value;
SetServiceUrls();
}
}
string apiKey;
/// <summary>
/// Gets or sets the Usera Agent for the Akismet Client.
/// Do not confuse this with the user agent for the comment
/// being checked.
/// </summary>
/// <value>The API key.</value>
public string UserAgent
{
get { return (this.userAgent == null) ? BuildUserAgent("DasBlog", version) : this.userAgent; }
set { this.userAgent = value; }
}
string userAgent = null;
/// <summary>
/// Helper method for building a user agent string in the format
/// preferred by Akismet.
/// </summary>
/// <param name="applicationName">Name of the application.</param>
/// <param name="appVersion">The version of the app.</param>
/// <returns></returns>
public static string BuildUserAgent(string applicationName, string appVersion)
{
return string.Format("{0}/{1} | Akismet/1.11", applicationName, version);
}
/// <summary>
/// Gets or sets the timeout in milliseconds for the http request to Akismet.
/// By default 5000 (5 seconds).
/// </summary>
/// <value>The timeout.</value>
public int Timeout
{
get { return this.timeout; }
set { this.timeout = value; }
}
int timeout = 5000;
/// <summary>
/// Gets or sets the root URL to the blog.
/// </summary>
/// <value>The blog URL.</value>
public Uri BlogUrl
{
get { return this.blogUrl; }
set { this.blogUrl = value; }
}
Uri blogUrl;
/// <summary>
/// Verifies the API key. You really only need to
/// call this once, perhaps at startup.
/// </summary>
/// <returns></returns>
public bool VerifyApiKey()
{
string parameters = "key=" + HttpUtility.UrlEncode(this.ApiKey) + "&blog=" + HttpUtility.UrlEncode(this.BlogUrl.ToString());
string result = this.httpClient.PostRequest(verifyUrl, this.UserAgent, this.Timeout, parameters);
if (String.IsNullOrEmpty(result))
throw new InvalidResponseException("Akismet returned an empty response");
return (System.String.Compare("valid", result, true) == 0);
}
/// <summary>
/// Checks the comment and returns true if it is spam, otherwise false.
/// </summary>
/// <param name="comment"></param>
/// <returns></returns>
public bool CheckCommentForSpam(IComment comment)
{
string result = SubmitComment(comment, this.checkUrl);
if (String.IsNullOrEmpty(result))
throw new InvalidResponseException("Akismet returned an empty response");
if (result != "true" && result != "false")
throw new InvalidResponseException(string.Format("Received the response '{0}' from Akismet. Probably a bad API key.", result));
return bool.Parse(result);
}
/// <summary>
/// Submits a comment to Akismet that should have been
/// flagged as SPAM, but was not flagged by Akismet.
/// </summary>
/// <param name="comment"></param>
/// <returns></returns>
public void SubmitSpam(IComment comment)
{
SubmitComment(comment, this.submitSpamUrl);
}
/// <summary>
/// Submits a comment to Akismet that should not have been
/// flagged as SPAM (a false positive).
/// </summary>
/// <param name="comment"></param>
/// <returns></returns>
public void SubmitHam(IComment comment)
{
SubmitComment(comment, this.submitHamUrl);
}
string SubmitComment(IComment comment, Uri url)
{
//Not too many concatenations. Might not need a string builder.
string parameters = "blog=" + HttpUtility.UrlEncode(this.blogUrl.ToString())
+ "&user_ip=" + comment.IpAddress.ToString()
+ "&user_agent=" + HttpUtility.UrlEncode(comment.UserAgent);
if (!String.IsNullOrEmpty(comment.Referer))
parameters += "&referer=" + HttpUtility.UrlEncode(comment.Referer);
if (comment.Permalink != null)
parameters += "&permalink=" + HttpUtility.UrlEncode(comment.Permalink.ToString());
if (!String.IsNullOrEmpty(comment.CommentType))
parameters += "&comment_type=" + HttpUtility.UrlEncode(comment.CommentType);
if (!String.IsNullOrEmpty(comment.Author))
parameters += "&comment_author=" + HttpUtility.UrlEncode(comment.Author);
if (!String.IsNullOrEmpty(comment.AuthorEmail))
parameters += "&comment_author_email=" + HttpUtility.UrlEncode(comment.AuthorEmail);
if (comment.AuthorUrl != null)
parameters += "&comment_author_url=" + HttpUtility.UrlEncode(comment.AuthorUrl.ToString());
if (!String.IsNullOrEmpty(comment.Content))
parameters += "&comment_content=" + HttpUtility.UrlEncode(comment.Content);
if (comment.ServerEnvironmentVariables != null)
{
foreach (string key in comment.ServerEnvironmentVariables)
{
parameters += "&" + key + "=" + HttpUtility.UrlEncode(comment.ServerEnvironmentVariables[key]);
}
}
return this.httpClient.PostRequest(url, this.UserAgent, this.Timeout, parameters).ToLower(CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Provides .NET 2.0 System.String features
/// </summary>
/// <remarks>
/// The idea is to reduce the differences between our version of the library and Subtext's version.
/// The fewer differences in the codebase, the easier it will be to merge in new features they add (in theory)
/// </remarks>
internal class String
{
public static bool IsNullOrEmpty(string stringToCheck)
{
if (stringToCheck == null) return true;
return (stringToCheck.Length == 0);
}
public static string Format(string format, params object[] args)
{
return System.String.Format(format, args);
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Core.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Core\Start-Job command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class StartJob : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public StartJob()
{
this.DisplayName = "Start-Job";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\Start-Job"; } }
// Arguments
/// <summary>
/// Provides access to the DefinitionName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> DefinitionName { get; set; }
/// <summary>
/// Provides access to the DefinitionPath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> DefinitionPath { get; set; }
/// <summary>
/// Provides access to the Type parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Type { get; set; }
/// <summary>
/// Provides access to the Name parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Name { get; set; }
/// <summary>
/// Provides access to the ScriptBlock parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.ScriptBlock> ScriptBlock { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the FilePath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> FilePath { get; set; }
/// <summary>
/// Provides access to the LiteralPath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> LiteralPath { get; set; }
/// <summary>
/// Provides access to the Authentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.Runspaces.AuthenticationMechanism> Authentication { get; set; }
/// <summary>
/// Provides access to the InitializationScript parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.ScriptBlock> InitializationScript { get; set; }
/// <summary>
/// Provides access to the RunAs32 parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> RunAs32 { get; set; }
/// <summary>
/// Provides access to the PSVersion parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Version> PSVersion { get; set; }
/// <summary>
/// Provides access to the InputObject parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSObject> InputObject { get; set; }
/// <summary>
/// Provides access to the ArgumentList parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Object[]> ArgumentList { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(DefinitionName.Expression != null)
{
targetCommand.AddParameter("DefinitionName", DefinitionName.Get(context));
}
if(DefinitionPath.Expression != null)
{
targetCommand.AddParameter("DefinitionPath", DefinitionPath.Get(context));
}
if(Type.Expression != null)
{
targetCommand.AddParameter("Type", Type.Get(context));
}
if(Name.Expression != null)
{
targetCommand.AddParameter("Name", Name.Get(context));
}
if(ScriptBlock.Expression != null)
{
targetCommand.AddParameter("ScriptBlock", ScriptBlock.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(FilePath.Expression != null)
{
targetCommand.AddParameter("FilePath", FilePath.Get(context));
}
if(LiteralPath.Expression != null)
{
targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
}
if(Authentication.Expression != null)
{
targetCommand.AddParameter("Authentication", Authentication.Get(context));
}
if(InitializationScript.Expression != null)
{
targetCommand.AddParameter("InitializationScript", InitializationScript.Get(context));
}
if(RunAs32.Expression != null)
{
targetCommand.AddParameter("RunAs32", RunAs32.Get(context));
}
if(PSVersion.Expression != null)
{
targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
}
if(InputObject.Expression != null)
{
targetCommand.AddParameter("InputObject", InputObject.Get(context));
}
if(ArgumentList.Expression != null)
{
targetCommand.AddParameter("ArgumentList", ArgumentList.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
/// <summary> <p>Abstract class representing the result of decoding a barcode, as more than
/// a String -- as some type of structured data. This might be a subclass which represents
/// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
/// decoded string into the most appropriate type of structured representation.</p>
///
/// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
/// on exception-based mechanisms during parsing.</p>
/// </summary>
/// <author>Sean Owen</author>
internal abstract class ResultParser
{
private static readonly ResultParser[] PARSERS = {
new BookmarkDoCoMoResultParser(),
new AddressBookDoCoMoResultParser(),
new EmailDoCoMoResultParser(),
new AddressBookAUResultParser(),
new VCardResultParser(),
new BizcardResultParser(),
new VEventResultParser(),
new EmailAddressResultParser(),
new SMTPResultParser(),
new TelResultParser(),
new SMSMMSResultParser(),
new SMSTOMMSTOResultParser(),
new GeoResultParser(),
new WifiResultParser(),
new URLTOResultParser(),
new URIResultParser(),
new ISBNResultParser(),
new ProductResultParser(),
new ExpandedProductResultParser(),
new VINResultParser(),
};
#if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z");
private static readonly Regex AMPERSAND = new Regex("&");
private static readonly Regex EQUALS = new Regex("=");
#else
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z", RegexOptions.Compiled);
private static readonly Regex AMPERSAND = new Regex("&", RegexOptions.Compiled);
private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled);
#endif
/// <summary>
/// Attempts to parse the raw {@link Result}'s contents as a particular type
/// of information (email, URL, etc.) and return a {@link ParsedResult} encapsulating
/// the result of parsing.
/// </summary>
/// <param name="theResult">The result.</param>
/// <returns></returns>
public abstract ParsedResult parse(ZXing.Result theResult);
public static ParsedResult parseResult(ZXing.Result theResult)
{
foreach (var parser in PARSERS)
{
var result = parser.parse(theResult);
if (result != null)
{
return result;
}
}
return new TextParsedResult(theResult.Text, null);
}
protected static void maybeAppend(String value, System.Text.StringBuilder result)
{
if (value != null)
{
result.Append('\n');
result.Append(value);
}
}
protected static void maybeAppend(String[] value, System.Text.StringBuilder result)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
result.Append('\n');
result.Append(value[i]);
}
}
}
protected static String[] maybeWrap(System.String value_Renamed)
{
return value_Renamed == null ? null : new System.String[] { value_Renamed };
}
protected static String unescapeBackslash(System.String escaped)
{
if (escaped != null)
{
int backslash = escaped.IndexOf('\\');
if (backslash >= 0)
{
int max = escaped.Length;
var unescaped = new System.Text.StringBuilder(max - 1);
unescaped.Append(escaped.ToCharArray(), 0, backslash);
bool nextIsEscaped = false;
for (int i = backslash; i < max; i++)
{
char c = escaped[i];
if (nextIsEscaped || c != '\\')
{
unescaped.Append(c);
nextIsEscaped = false;
}
else
{
nextIsEscaped = true;
}
}
return unescaped.ToString();
}
}
return escaped;
}
protected static int parseHexDigit(char c)
{
if (c >= 'a')
{
if (c <= 'f')
{
return 10 + (c - 'a');
}
}
else if (c >= 'A')
{
if (c <= 'F')
{
return 10 + (c - 'A');
}
}
else if (c >= '0')
{
if (c <= '9')
{
return c - '0';
}
}
return -1;
}
internal static bool isStringOfDigits(String value, int length)
{
return value != null && length > 0 && length == value.Length && DIGITS.Match(value).Success;
}
internal static bool isSubstringOfDigits(String value, int offset, int length)
{
if (value == null || length <= 0)
{
return false;
}
int max = offset + length;
return value.Length >= max && DIGITS.Match(value, offset, length).Success;
}
internal static IDictionary<string, string> parseNameValuePairs(String uri)
{
int paramStart = uri.IndexOf('?');
if (paramStart < 0)
{
return null;
}
var result = new Dictionary<String, String>(3);
foreach (var keyValue in AMPERSAND.Split(uri.Substring(paramStart + 1)))
{
appendKeyValue(keyValue, result);
}
return result;
}
private static void appendKeyValue(String keyValue, IDictionary<String, String> result)
{
String[] keyValueTokens = EQUALS.Split(keyValue, 2);
if (keyValueTokens.Length == 2)
{
String key = keyValueTokens[0];
String value = keyValueTokens[1];
try
{
//value = URLDecoder.decode(value, "UTF-8");
value = urlDecode(value);
result[key] = value;
}
catch (Exception uee)
{
throw new InvalidOperationException("url decoding failed", uee); // can't happen
}
result[key] = value;
}
}
internal static String[] matchPrefixedField(String prefix, String rawText, char endChar, bool trim)
{
IList<string> matches = null;
int i = 0;
int max = rawText.Length;
while (i < max)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(prefix, i);
if (i < 0)
{
break;
}
i += prefix.Length; // Skip past this prefix we found to start
int start = i; // Found the start of a match here
bool done = false;
while (!done)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(endChar, i);
if (i < 0)
{
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.Length;
done = true;
}
else if (rawText[i - 1] == '\\')
{
// semicolon was escaped so continue
i++;
}
else
{
// found a match
if (matches == null)
{
matches = new List<string>();
}
String element = unescapeBackslash(rawText.Substring(start, (i) - (start)));
if (trim)
{
element = element.Trim();
}
if (!String.IsNullOrEmpty(element))
{
matches.Add(element);
}
i++;
done = true;
}
}
}
if (matches == null || (matches.Count == 0))
{
return null;
}
return SupportClass.toStringArray(matches);
}
internal static String matchSinglePrefixedField(String prefix, String rawText, char endChar, bool trim)
{
String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
return matches == null ? null : matches[0];
}
protected static String urlDecode(String escaped)
{
// Should we better use HttpUtility.UrlDecode?
// Is HttpUtility.UrlDecode available for all platforms?
// What about encoding like UTF8?
if (escaped == null)
{
return null;
}
char[] escapedArray = escaped.ToCharArray();
int first = findFirstEscape(escapedArray);
if (first < 0)
{
return escaped;
}
int max = escapedArray.Length;
// final length is at most 2 less than original due to at least 1 unescaping
var unescaped = new System.Text.StringBuilder(max - 2);
// Can append everything up to first escape character
unescaped.Append(escapedArray, 0, first);
for (int i = first; i < max; i++)
{
char c = escapedArray[i];
if (c == '+')
{
// + is translated directly into a space
unescaped.Append(' ');
}
else if (c == '%')
{
// Are there even two more chars? if not we will just copy the escaped sequence and be done
if (i >= max - 2)
{
unescaped.Append('%'); // append that % and move on
}
else
{
int firstDigitValue = parseHexDigit(escapedArray[++i]);
int secondDigitValue = parseHexDigit(escapedArray[++i]);
if (firstDigitValue < 0 || secondDigitValue < 0)
{
// bad digit, just move on
unescaped.Append('%');
unescaped.Append(escapedArray[i - 1]);
unescaped.Append(escapedArray[i]);
}
unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue));
}
}
else
{
unescaped.Append(c);
}
}
return unescaped.ToString();
}
private static int findFirstEscape(char[] escapedArray)
{
int max = escapedArray.Length;
for (int i = 0; i < max; i++)
{
char c = escapedArray[i];
if (c == '+' || c == '%')
{
return i;
}
}
return -1;
}
}
}
| |
/*!
@file GameController.cs
@author Zoe Hardisty. <www.zoehardistydesign.com>
<https://github.com/zoebear/Radia/GameController.cs>
@date June 2015
@version 0.9.1
@section LICENSE
The MIT License (MIT)
Copyright (c) 2015 Zoe Hardisty
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.
@section DESCRIPTION
Main initialization of the graph and UI.
*/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System.Collections;
using System.IO;
using System.Threading;
using SimpleJSON;
using EpForceDirectedGraph.cs;
public class GameController : MonoBehaviour {
// Prefabs
public Function defaultPrefab;
public Function systemPrefab;
public Function heapPrefab;
public Function filePrefab;
public Function socketPrefab;
public Function stringPrefab;
public Function cryptoPrefab;
public Function dangerPrefab;
public markHalo markPrefab;
public Link linkPrefab;
// For force directed graph
private Graph graph;
private ForceDirected3D physics;
private FDRenderer render;
private Thread renderThread;
public float stiffness = 10.0f;
public float repulsion = 1.0f;
public float damping = 0.5f;
public bool runFDG = true;
// For tracking instantiated objects
public Hashtable nodes;
public Hashtable links;
// GUI Elements
private GUIText statusText;
public Texture2D crosshair;
// References
public UIController ui;
public SelectionController selection;
public LookInputModule look;
public GameObject legend;
public GameObject mark;
public GameObject mark_list;
public GameObject quit_dialog;
// UI State Control
private bool suspendInput = false;
private Function selectedFunction;
// Method for loading the JSON data from the API controller
private IEnumerator LoadLayout(){
graph = new Graph();
statusText.text = "Loading radia.json...";
string rawJson = null;
//var req = new WWW(apiUrl + "/functions");
string path_prefix;
if (SystemInfo.operatingSystem.StartsWith ("Win")) {
path_prefix = "\\";
} else {
path_prefix = "/../../";
}
//local app path for finding the JSON files
var req = new WWW ("file://" + Application.dataPath + path_prefix + "radia.json");
yield return req;
if (req.error != null) {
statusText.text = "Error reading radia.json";
return false;
}
rawJson = req.text;
statusText.text = "Processing Data";
var j = JSON.Parse(rawJson);
j = j["functions"];
for(int i = 0; i < j.Count; i++) {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
int category = 0;
if (j[i]["category"] != null) {
category = int.Parse(j[i]["category"]);
}
// (danger << 6) + (string << 5) + (fileio << 4) + (crypto << 3) + (socket << 2) + (heap << 1) + system
// 64 32 16 8 4 2 1
Function nodeObject;
float scale = 1.0f;
if ((category & 64) == 64) {
nodeObject = Instantiate(dangerPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
else if ((category & 8) == 8) {
nodeObject = Instantiate(cryptoPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
else if ((category & 4) == 4) {
nodeObject = Instantiate(socketPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
else if ((category & 32) == 32) {
nodeObject = Instantiate(stringPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
else if ((category & 16) == 16) {
nodeObject = Instantiate(filePrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
scale = 1.5f;
}
else if ((category & 1) == 1) {
nodeObject = Instantiate(systemPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
else if ((category & 2) == 2) {
nodeObject = Instantiate(heapPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
scale = 2.0f;
} else {
nodeObject = Instantiate(defaultPrefab, new Vector3(x, y, z), Quaternion.identity) as Function;
}
nodeObject.funcname = j[i]["name"];
nodeObject.address = ulong.Parse(j[i]["address"]);
nodeObject.attributes = category;
if (j[i]["size"] != null) {
nodeObject.size = int.Parse(j[i]["size"]);
} else {
nodeObject.size = 0;
}
nodeObject.module_name = j[i]["module_name"];
nodeObject.functag = j[i]["tag"];
nodeObject.comment = j[i]["comment"];
nodeObject.longname = j[i]["long_name"];
nodeObject.basic_blk_cnt = int.Parse(j[i]["basic_blk_cnt"]);
if (j[i]["dangerous_list"] != null) {
nodeObject.dangerous_calls = new string[j[i]["dangerous_list"].Count];
for (int c = 0; c < j[i]["dangerous_list"].Count; c++) {
nodeObject.dangerous_calls[c] = j[i]["dangerous_list"][c];
}
}
if (j[i]["strings"] != null) {
nodeObject.strings = new string[j[i]["strings"].Count];
for (int c = 0; c < j[i]["strings"].Count; c++) {
nodeObject.strings[c] = j[i]["strings"][c];
}
}
nodeObject.transform.localScale += new Vector3(scale, scale, scale);
nodes.Add(nodeObject.address, nodeObject);
// For force directed graph
NodeData data = new NodeData();
data.label = nodeObject.address.ToString();
data.mass = (float)nodeObject.size / 50.0f + 10.0f;
graph.CreateNode(data);
statusText.text = "Loading Functions: Function " + nodeObject.funcname;
if(i % 100 == 0)
yield return true;
}
j = JSON.Parse(rawJson);
j = j["callgraph"];
for(int i = 0; i < j.Count; i++) {
ulong srcid = ulong.Parse(j[i]["source"]);
ulong dstid = ulong.Parse(j[i]["target"]);
if (FindDupLink (srcid, dstid)) {
continue;
}
Link linkObject = Instantiate(linkPrefab, new Vector3(0, 0, 0), Quaternion.identity) as Link;
linkObject.id = i+1;
linkObject.sourceId = srcid;
linkObject.targetId = dstid;
links.Add(linkObject.id, linkObject);
// For force directed graph
Node node1 = graph.GetNode(linkObject.sourceId.ToString());
Node node2 = graph.GetNode(linkObject.targetId.ToString());
EdgeData data = new EdgeData();
data.label = linkObject.sourceId.ToString()+"-"+linkObject.targetId.ToString();
data.length = 1.0f;
graph.CreateEdge(node1, node2, data);
statusText.text = "Loading Callgraph: Call " + linkObject.id.ToString();
if(i % 100 == 0)
yield return true;
}
// Map node edges
MapLinkFunctions();
// For force directed graph
physics = new ForceDirected3D(graph, // instance of Graph
stiffness, // stiffness of the spring
repulsion, // node repulsion rate
damping // damping rate
);
render = new FDRenderer(physics);
render.setController(this);
statusText.text = "";
Camera.main.transform.LookAt (new Vector3 (0f, 0f, 0f));
renderThread = new Thread(new ThreadStart(FDRenderThread));
renderThread.Start ();
}
// Method for stripping out duplicate links -- too much overhead
private bool FindDupLink(ulong srcid, ulong dstid) {
foreach (int key in links.Keys) {
Link link = links [key] as Link;
if (srcid == link.sourceId && dstid == link.targetId) {
return true;
}
}
return false;
}
// Method for mapping links to nodes
private void MapLinkFunctions(){
foreach(int key in links.Keys){
Link link = links[key] as Link;
link.source = nodes[link.sourceId] as Function;
link.target = nodes[link.targetId] as Function;
if (link.source != null) {
link.source.egress_calls += 1;
link.source.egress_links.Add (link);
}
if (link.target != null) {
link.target.ingress_calls += 1;
link.target.ingress_links.Add(link);
}
}
}
void Start () {
Cursor.visible = false;
ui = GameObject.Find ("NodeUIOverlay").GetComponent<UIController> ();
selection = GameObject.Find ("SelectionCanvas").GetComponent<SelectionController> ();
look = GameObject.Find ("EventSystem").GetComponent<LookInputModule> ();
legend = GameObject.Find ("LegendCanvas");
mark = GameObject.Find ("MarkCanvas");
mark_list = GameObject.Find ("MarklistCanvas");
quit_dialog = GameObject.Find ("QuitDialogCanvas");
//HideLegend ();
ui.Startup ();
quit_dialog.SetActive (false);
ui.gameObject.SetActive (false);
selection.gameObject.SetActive (false);
mark.SetActive (false);
mark_list.SetActive (false);
nodes = new Hashtable();
links = new Hashtable();
statusText = GameObject.Find("StatusText").GetComponent<GUIText>();
statusText.text = "";
StartCoroutine( LoadLayout() );
//GameObject.Find ("SelectionCanvas").SetActive (false);
}
// This thread is used to periodically recalc the force directed graph
void FDRenderThread() {
while(runFDG) {
render.Draw (0.1f);
}
}
// Draw the cross hair
void OnGUI() {
float xMin = (Screen.width / 2) - (crosshair.width / 2);
float yMin = (Screen.height / 2) - (crosshair.height / 2);
GUI.DrawTexture(new Rect(xMin, yMin, crosshair.width, crosshair.height), crosshair);
}
// Kill the threat used to render the FDG... this is ~99% reliable for some reason
void OnApplicationQuit() {
Cleanup ();
}
public void Cleanup() {
runFDG = false;
Thread.Sleep (500);
if (renderThread != null && renderThread.IsAlive) {
renderThread.Abort ();
}
Cursor.visible = true;
}
public void ToggleFDGCalc() {
if (runFDG == true) {
runFDG = false;
} else {
runFDG = true;
}
}
public void SelectFunction(GameObject selected) {
Debug.Log (selected);
Function sel_func = selected.transform.root.GetComponent<Function> ();
if (sel_func != null) {
SetUIActive (true);
SetSelectedFunction (sel_func);
}
}
public bool InputActive() {
return !(suspendInput);
}
public void SetInputActive(bool state) {
suspendInput = !(state);
}
public void SetUIActive(bool state) {
if (state) {
ui.gameObject.SetActive (true);
selection.gameObject.SetActive (true);
} else {
if (selectedFunction != null) {
selectedFunction.resetState ();
}
selectedFunction = null;
selection.SetFunction(null);
ui.gameObject.SetActive(false);
selection.gameObject.SetActive(false);
mark.SetActive (false);
}
}
public bool GetUIActive() {
return ui.gameObject.activeSelf;
}
public void SetSelectedFunction(Function func) {
if (selectedFunction != null) {
selectedFunction.resetState ();
}
selectedFunction = func;
ui.SetFunction (func);
selection.SetFunction (func);
selectedFunction.updateState ();
}
public Function GetSelectedFunction() {
return selectedFunction;
}
public void EditComment() {
SetInputActive (false);
ui.SelectCommentInput ();
}
public void EditMark() {
Debug.Log ("EditMark(): disabled key input");
SetInputActive (false);
ShowMark ();
Debug.Log ("EditMark(): selecting input box");
ui.SelectMarkInput ();
}
public void EditFunctionName() {
SetInputActive (false);
ui.SelectFunctionNameInput ();
}
public void HideLegend() {
legend.SetActive (false);
}
public void ShowLegend() {
legend.SetActive (true);
}
public void ToggleLegend() {
if (legend.activeSelf) {
HideLegend();
} else {
ShowLegend();
}
}
public void ShowMark() {
mark.SetActive (true);
ui.SetMark ();
}
public void HideMark() {
mark.SetActive (false);
}
public void ShowMarkList() {
SetInputActive (false);
mark_list.SetActive (true);
ui.SetMarkList ();
ui.SelectMarkList ();
}
public void HideMarkList() {
MarkedController [] items = mark_list.GetComponentsInChildren<MarkedController> ();
foreach (MarkedController item in items) {
GameObject.Destroy(item.gameObject);
}
mark_list.SetActive (false);
SetInputActive (true);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using NUnit.Framework;
namespace MongoDB.UnitTests
{
[TestFixture]
public class TestDocument
{
private static void AreEqual(Document d1, Document d2)
{
if(!d1.Equals(d2))
Assert.Fail(string.Format("Documents don't match\r\nExpected: {0}\r\nActual: {1}", d1, d2));
}
private static void AreNotEqual(Document d1, Document d2)
{
if(d1.Equals(d2))
Assert.Fail(string.Format("Documents match\r\nExpected: not {0}\r\nActual: {1}", d1, d2));
}
private class ReverseComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return y.CompareTo(x);
}
}
[Test]
public void TestClearRemovesAll()
{
var d = new Document();
d["one"] = 1;
d.Add("two", 2);
d["three"] = 3;
Assert.AreEqual(3, d.Count);
d.Clear();
Assert.AreEqual(0, d.Count);
Assert.IsNull(d["one"]);
Assert.IsFalse(d.ContainsKey("one"));
}
[Test]
public void TestCopyToCopiesAndOverwritesKeys()
{
var d = new Document();
var dest = new Document();
dest["two"] = 200;
d["one"] = 1;
d.Add("two", 2);
d["three"] = 3;
d.CopyTo(dest);
Assert.AreEqual(2, dest["two"]);
}
[Test]
public void TestCopyToCopiesAndPreservesKeyOrderToEmptyDoc()
{
var d = new Document();
var dest = new Document();
d["one"] = 1;
d.Add("two", 2);
d["three"] = 3;
d.CopyTo(dest);
var cnt = 1;
foreach(var key in dest.Keys)
{
Assert.AreEqual(cnt, d[key]);
cnt++;
}
}
[Test]
public void TestDocumentCanCreatedFromDictionary()
{
var dictionary = new Dictionary<string, object> {{"value1", "test"}, {"value2", 10}};
var document = new Document(dictionary);
Assert.AreEqual(2, document.Count);
Assert.AreEqual("test", document["value1"]);
Assert.AreEqual(10, document["value2"]);
}
[Test]
public void TestDocumentIsSerializable()
{
var src = new Document().Add("test", 2);
using(var mem = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(mem, src);
mem.Position = 0;
var dest = (Document)formatter.Deserialize(mem);
AreEqual(src, dest);
}
}
[Test]
public void TestIdReturnsNullIfNotSet()
{
var document = new Document();
Assert.IsNull(document.Id);
}
[Test]
public void TestIdSets_IdField()
{
var document = new Document {Id = 10};
Assert.AreEqual(10, document.Id);
}
[Test]
public void TestInsertMaintainsKeyOrder()
{
var d = new Document();
d["one"] = 1;
d.Insert("zero", 0, 0);
var keysList = d.Keys as IEnumerable<string>;
foreach(var k in d.Keys)
{
Assert.AreEqual("zero", k);
break;
}
}
[Test]
[ExpectedException(ExceptionType = typeof(ArgumentException),
MatchType = MessageMatch.Contains)]
public void TestInsertWillThrowArgumentExceptionIfKeyAlreadyExists()
{
var d = new Document();
d["one"] = 1;
d.Insert("one", 1, 0);
}
[Test]
public void TestKeyOrderIsPreserved()
{
var d = new Document();
d["one"] = 1;
d.Add("two", 2);
d["three"] = 3;
var cnt = 1;
foreach(var key in d.Keys)
{
Assert.AreEqual(cnt, d[key]);
cnt++;
}
}
[Test]
public void TestKeyOrderPreservedOnRemove()
{
var d = new Document();
d["one"] = 1;
d["onepointfive"] = 1.5;
d.Add("two", 2);
d.Add("two.5", 2.5);
d.Remove("two.5");
d["three"] = 3;
d.Remove("onepointfive");
var cnt = 1;
foreach(var key in d.Keys)
{
Assert.AreEqual(cnt, d[key]);
cnt++;
}
}
[Test]
public void TestMaintainsOrderUsingMultipleMethods()
{
var d = new Document(new ReverseComparer());
d["one"] = 1;
var test = d["one"];
d["zero"] = 0;
var keysList = d.Keys as IEnumerable<string>;
Assert.AreEqual(keysList.First(), "zero");
}
[Test]
public void TestRemove()
{
var d = new Document();
d["one"] = 1;
d.Remove("one");
Assert.IsFalse(d.ContainsKey("one"));
}
[Test]
public void TestSetNullValue()
{
var document = new Document();
document.Add("value", null);
Assert.AreEqual(1, document.Count);
Assert.IsNull(document["value"]);
}
[Test]
public void TestTwoDocumentsWithDifferentDocumentChildTreeAreNotEqual()
{
var d1 = new Document().Add("k1", new Document().Add("k2", new Document().Add("k3", "foo")));
var d2 = new Document().Add("k1", new Document().Add("k2", new Document().Add("k3", "bar")));
AreNotEqual(d1, d2);
}
[Test]
public void TestTwoDocumentsWithMisorderedArrayContentAreNotEqual()
{
var d1 = new Document().Add("k1", new[] {"v1", "v2"});
var d2 = new Document().Add("k1", new[] {"v2", "v1"});
AreNotEqual(d1, d2);
}
[Test]
public void TestTwoDocumentsWithSameArrayContentAreEqual()
{
var d1 = new Document().Add("k1", new[] {"v1", "v2"});
var d2 = new Document().Add("k1", new[] {"v1", "v2"});
AreEqual(d1, d2);
}
[Test]
public void TestTwoDocumentsWithSameContentInDifferentOrderAreNotEqual()
{
var d1 = new Document().Add("k1", "v1").Add("k2", "v2");
var d2 = new Document().Add("k2", "v2").Add("k1", "v1");
AreNotEqual(d1, d2);
}
[Test]
public void TestTwoDocumentsWithSameContentInSameOrderAreEqual()
{
var d1 = new Document().Add("k1", "v1").Add("k2", "v2");
var d2 = new Document().Add("k1", "v1").Add("k2", "v2");
AreEqual(d1, d2);
}
[Test]
public void TestTwoDocumentsWithSameDocumentChildTreeAreEqual()
{
var d1 = new Document().Add("k1", new Document().Add("k2", new Document().Add("k3", "foo")));
var d2 = new Document().Add("k1", new Document().Add("k2", new Document().Add("k3", "foo")));
AreEqual(d1, d2);
}
[Test]
public void TestUseOfIComparerForKeys()
{
var doc = new Document(new ReverseComparer());
doc.Append("a", 3);
doc.Append("b", 2);
doc.Append("c", 1);
Assert.AreEqual("c", doc.Keys.First());
}
[Test]
public void TestValues()
{
var d = new Document();
d["one"] = 1;
d.Add("two", 2);
d["three"] = 3;
var vals = d.Values;
Assert.AreEqual(3, vals.Count);
}
[Test]
public void TestValuesAdded()
{
var d = new Document();
d["test"] = 1;
Assert.AreEqual(1, d["test"]);
}
[Test]
public void CanBeBinarySerialized()
{
var source = new Document("key1", "value1").Add("key2", 10);
var formatter = new BinaryFormatter();
var mem = new MemoryStream();
formatter.Serialize(mem, source);
mem.Position = 0;
var dest = (Document)formatter.Deserialize(mem);
Assert.AreEqual(2,dest.Count);
Assert.AreEqual(source["key1"], dest["key1"]);
Assert.AreEqual(source["key2"], dest["key2"]);
}
[Test]
public void CanBeXmlSerialized()
{
var source = new Document("key1", "value1").Add("key2", new Document("key", "value").Add("key2", null));
var serializer = new XmlSerializer(typeof(Document));
var writer = new StringWriter();
serializer.Serialize(writer, source);
var dest = (Document)serializer.Deserialize(new StringReader(writer.ToString()));
Assert.AreEqual(2, dest.Count);
Assert.AreEqual(source["key1"], dest["key1"]);
Assert.AreEqual(source["key2"], dest["key2"]);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// 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.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace NUnit.UiKit.Controls
{
/// <summary>
/// A special type of label which can display a tooltip-like
/// window to show the full extent of any text which doesn't
/// fit. The window may be placed directly over the label
/// or immediately beneath it and will expand to fit in
/// a horizontal, vertical or both directions as needed.
/// </summary>
public class ExpandingLabel : System.Windows.Forms.Label
{
#region Instance Variables
/// <summary>
/// Our window for displaying expanded text
/// </summary>
private TipWindow tipWindow;
/// <summary>
/// Direction of expansion
/// </summary>
private TipWindow.ExpansionStyle expansion = TipWindow.ExpansionStyle.Horizontal;
/// <summary>
/// True if tipWindow may overlay the label
/// </summary>
private bool overlay = true;
/// <summary>
/// Time in milliseconds that the tip window
/// will remain displayed.
/// </summary>
private int autoCloseDelay = 0;
/// <summary>
/// Time in milliseconds that the window stays
/// open after the mouse leaves the control.
/// </summary>
private int mouseLeaveDelay = 300;
/// <summary>
/// If true, a context menu with Copy is displayed which
/// allows copying contents to the clipboard.
/// </summary>
private bool copySupported = false;
#endregion
#region Properties
[Browsable( false )]
public bool Expanded
{
get { return tipWindow != null && tipWindow.Visible; }
}
[Category ( "Behavior" ), DefaultValue( TipWindow.ExpansionStyle.Horizontal )]
public TipWindow.ExpansionStyle Expansion
{
get { return expansion; }
set { expansion = value; }
}
[Category( "Behavior" ), DefaultValue( true )]
[Description("Indicates whether the tip window should overlay the label")]
public bool Overlay
{
get { return overlay; }
set { overlay = value; }
}
/// <summary>
/// Time in milliseconds that the tip window
/// will remain displayed.
/// </summary>
[Category( "Behavior" ), DefaultValue( 0 )]
[Description("Time in milliseconds that the tip is displayed. Zero indicates no automatic timeout.")]
public int AutoCloseDelay
{
get { return autoCloseDelay; }
set { autoCloseDelay = value; }
}
/// <summary>
/// Time in milliseconds that the window stays
/// open after the mouse leaves the control.
/// Reentering the control resets this.
/// </summary>
[Category( "Behavior" ), DefaultValue( 300 )]
[Description("Time in milliseconds that the tip is displayed after the mouse levaes the control")]
public int MouseLeaveDelay
{
get { return mouseLeaveDelay; }
set { mouseLeaveDelay = value; }
}
[Category( "Behavior"), DefaultValue( false )]
[Description("If true, displays a context menu with Copy")]
public bool CopySupported
{
get { return copySupported; }
set
{
copySupported = value;
if ( copySupported )
base.ContextMenu = null;
}
}
/// <summary>
/// Override Text property to set up copy menu if
/// the val is non-empty.
/// </summary>
public override string Text
{
get { return base.Text; }
set
{
base.Text = value;
if ( copySupported )
{
if ( value == null || value == string.Empty )
{
if ( this.ContextMenu != null )
{
this.ContextMenu.Dispose();
this.ContextMenu = null;
}
}
else
{
this.ContextMenu = new System.Windows.Forms.ContextMenu();
MenuItem copyMenuItem = new MenuItem( "Copy", new EventHandler( CopyToClipboard ) );
this.ContextMenu.MenuItems.Add( copyMenuItem );
}
}
}
}
#endregion
#region Public Methods
public void Expand()
{
if ( !Expanded )
{
tipWindow = new TipWindow( this );
tipWindow.Closed += new EventHandler( tipWindow_Closed );
tipWindow.Expansion = this.Expansion;
tipWindow.Overlay = this.Overlay;
tipWindow.AutoCloseDelay = this.AutoCloseDelay;
tipWindow.MouseLeaveDelay = this.MouseLeaveDelay;
tipWindow.WantClicks = this.CopySupported;
tipWindow.Show();
}
}
public void Unexpand()
{
if ( Expanded )
{
tipWindow.Close();
}
}
#endregion
#region Event Handlers
private void tipWindow_Closed( object sender, EventArgs e )
{
tipWindow = null;
}
protected override void OnMouseHover(System.EventArgs e)
{
Graphics g = Graphics.FromHwnd( Handle );
SizeF sizeNeeded = g.MeasureString( Text, Font );
bool expansionNeeded =
Width < (int)sizeNeeded.Width ||
Height < (int)sizeNeeded.Height;
if ( expansionNeeded ) Expand();
}
/// <summary>
/// Copy contents to clipboard
/// </summary>
private void CopyToClipboard( object sender, EventArgs e )
{
Clipboard.SetDataObject( this.Text );
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Communication.Identity;
using Azure.Communication.Pipeline;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Communication.Chat
{
/// <summary>
/// The Azure Communication Services Chat client.
/// </summary>
public class ChatClient
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly ChatRestClient _chatRestClient;
private readonly Uri _endpointUrl;
private readonly CommunicationUserCredential _communicationUserCredential;
private readonly ChatClientOptions _chatClientOptions;
private const string MultiStatusThreadResourceType = "THREAD";
/// <summary> Initializes a new instance of <see cref="ChatClient"/>.</summary>
/// <param name="endpointUrl">The uri for the Azure Communication Services Chat.</param>
/// <param name="communicationUserCredential">Instance of <see cref="CommunicationUserCredential"/>.</param>
/// <param name="options">Chat client options exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public ChatClient(Uri endpointUrl, CommunicationUserCredential communicationUserCredential, ChatClientOptions? options = default)
{
Argument.AssertNotNull(communicationUserCredential, nameof(communicationUserCredential));
Argument.AssertNotNull(endpointUrl, nameof(endpointUrl));
_chatClientOptions = options ?? new ChatClientOptions();
_communicationUserCredential = communicationUserCredential;
_endpointUrl = endpointUrl;
_clientDiagnostics = new ClientDiagnostics(_chatClientOptions);
HttpPipeline pipeline = CreatePipelineFromOptions(_chatClientOptions, communicationUserCredential);
_chatRestClient = new ChatRestClient(_clientDiagnostics, pipeline, endpointUrl.AbsoluteUri, _chatClientOptions.ApiVersion);
}
/// <summary>Initializes a new instance of <see cref="ChatClient"/> for mocking.</summary>
protected ChatClient()
{
_clientDiagnostics = null!;
_chatRestClient = null!;
_endpointUrl = null!;
_communicationUserCredential = null!;
_chatClientOptions = null!;
}
#region Thread Operations
/// <summary>Creates a ChatThreadClient asynchronously. <see cref="ChatThreadClient"/>.</summary>
/// <param name="topic">Topic for the chat thread</param>
/// <param name="members">Members to be included in the chat thread</param>
/// <param name="cancellationToken">The cancellation token for the task.</param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "AZC0015:Unexpected client method return type.", Justification = "ChatThreadClient needs to be created by the ChatClient parent object")]
public virtual async Task<ChatThreadClient> CreateChatThreadAsync(string topic, IEnumerable<ChatThreadMember> members, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(CreateChatThread)}");
scope.Start();
try
{
Response<MultiStatusResponse> threadResponse = await _chatRestClient.CreateChatThreadAsync(topic, members.Select(x => x.ToChatThreadMemberInternal()), cancellationToken).ConfigureAwait(false);
string threadId = threadResponse.Value.MultipleStatus.First(x => x.Type.ToUpperInvariant() == MultiStatusThreadResourceType).Id;
return new ChatThreadClient(threadId, _endpointUrl, _communicationUserCredential, _chatClientOptions);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>Creates a ChatThreadClient synchronously.<see cref="ChatThreadClient"/>.</summary>
/// <param name="topic">Topic for the chat thread</param>
/// <param name="members">Members to be included in the chat thread</param>
/// <param name="cancellationToken">The cancellation token for the task.</param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual ChatThreadClient CreateChatThread(string topic, IEnumerable<ChatThreadMember> members, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(CreateChatThread)}");
scope.Start();
try
{
Response<MultiStatusResponse> threadResponse = _chatRestClient.CreateChatThread(topic, members.Select(x=>x.ToChatThreadMemberInternal()), cancellationToken);
string threadId = threadResponse.Value.MultipleStatus.First(x => x.Type.ToUpperInvariant() == MultiStatusThreadResourceType).Id;
return new ChatThreadClient(threadId, _endpointUrl, _communicationUserCredential, _chatClientOptions);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Initializes a new instance of ChatThreadClient. <see cref="ChatThreadClient"/>.</summary>
/// <param name="threadId"> The thread id for the ChatThreadClient instance. </param>
public virtual ChatThreadClient GetChatThreadClient(string threadId)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThreadClient)}");
scope.Start();
try
{
return new ChatThreadClient(threadId, _endpointUrl, _communicationUserCredential, _chatClientOptions);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets a chat thread asynchronously. </summary>
/// <param name="threadId"> Thread id of the chat thread. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual async Task<Response<ChatThread>> GetChatThreadAsync(string threadId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThread)}");
scope.Start();
try
{
Response<ChatThreadInternal> chatThreadInternal = await _chatRestClient.GetChatThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ChatThread(chatThreadInternal.Value), chatThreadInternal.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets a chat thread. </summary>
/// <param name="threadId"> Thread id of the chat thread. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual Response<ChatThread> GetChatThread(string threadId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThread)}");
scope.Start();
try
{
Response<ChatThreadInternal> chatThreadInternal = _chatRestClient.GetChatThread(threadId, cancellationToken);
return Response.FromValue(new ChatThread(chatThreadInternal.Value), chatThreadInternal.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Gets the list of chat threads of a user<see cref="ChatThreadInfo"/> asynchronously.</summary>
/// <param name="startTime"> The earliest point in time to get chat threads up to. The timestamp should be in ISO8601 format: `yyyy-MM-ddTHH:mm:ssZ`. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual AsyncPageable<ChatThreadInfo> GetChatThreadsInfoAsync(DateTimeOffset? startTime = null, CancellationToken cancellationToken = default)
{
async Task<Page<ChatThreadInfo>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThreadsInfo)}");
scope.Start();
try
{
Response<ChatThreadsInfoCollection> response = await _chatRestClient.ListChatThreadsAsync(pageSizeHint, startTime, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ChatThreadInfo>> NextPageFunc(string? nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThreadsInfo)}");
scope.Start();
try
{
Response<ChatThreadsInfoCollection> response = await _chatRestClient.ListChatThreadsNextPageAsync(nextLink, pageSizeHint, startTime, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets the list of chat threads of a user<see cref="ChatThreadInfo"/>.</summary>
/// <param name="startTime"> The earliest point in time to get chat threads up to. The timestamp should be in ISO8601 format: `yyyy-MM-ddTHH:mm:ssZ`. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual Pageable<ChatThreadInfo> GetChatThreadsInfo(DateTimeOffset? startTime = null, CancellationToken cancellationToken = default)
{
Page<ChatThreadInfo> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThreadsInfo)}");
scope.Start();
try
{
Response<ChatThreadsInfoCollection> response = _chatRestClient.ListChatThreads(pageSizeHint, startTime, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ChatThreadInfo> NextPageFunc(string? nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(GetChatThreadsInfo)}");
scope.Start();
try
{
Response<ChatThreadsInfoCollection> response = _chatRestClient.ListChatThreadsNextPage(nextLink, pageSizeHint, startTime, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Deletes a thread asynchronously. </summary>
/// <param name="threadId"> Thread id to delete. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual async Task<Response> DeleteChatThreadAsync(string threadId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(DeleteChatThread)}");
scope.Start();
try
{
return await _chatRestClient.DeleteChatThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Deletes a thread. </summary>
/// <param name="threadId"> Thread id to delete. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
public virtual Response DeleteChatThread(string threadId, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatClient)}.{nameof(DeleteChatThread)}");
scope.Start();
try
{
return _chatRestClient.DeleteChatThread(threadId, cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
#endregion
private static HttpPipeline CreatePipelineFromOptions(ChatClientOptions options, CommunicationUserCredential communicationUserCredential)
{
var httpPipelinePolicy = new CommunicationUserAuthenticationPolicy(communicationUserCredential);
HttpPipeline httpPipeline = HttpPipelineBuilder.Build(options, httpPipelinePolicy);
return httpPipeline;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
namespace Microsoft.Practices.Prism.PubSubEvents.Tests
{
[TestClass]
public class EventSubscriptionFixture
{
[TestInitialize]
public void Setup()
{
}
[TestMethod]
public void NullTargetInActionThrows()
{
Assert.ThrowsException<ArgumentException>(() =>
{
var actionDelegateReference = new MockDelegateReference()
{
Target = null
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<object>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
filterDelegateReference);
});
}
[TestMethod]
public void DifferentTargetTypeInActionThrows()
{
Assert.ThrowsException<ArgumentException>(() =>
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<int>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<string>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<string>(actionDelegateReference,
filterDelegateReference);
});
}
[TestMethod]
public void NullActionThrows()
{
Assert.ThrowsException<ArgumentNullException>(() =>
{
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<object>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<object>(null,
filterDelegateReference);
});
}
[TestMethod]
public void NullTargetInFilterThrows()
{
Assert.ThrowsException<ArgumentException>(() =>
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<object>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = null
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
filterDelegateReference);
});
}
[TestMethod]
public void DifferentTargetTypeInFilterThrows()
{
Assert.ThrowsException<ArgumentException>(() =>
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<string>)delegate { }
};
var filterDelegateReference = new MockDelegateReference()
{
Target = (Predicate<int>)(arg =>
{
return true;
})
};
var eventSubscription = new EventSubscription<string>(actionDelegateReference,
filterDelegateReference);
});
}
[TestMethod]
public void NullFilterThrows()
{
Assert.ThrowsException<ArgumentNullException>(() =>
{
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<object>)delegate { }
};
var eventSubscription = new EventSubscription<object>(actionDelegateReference,
null);
});
}
[TestMethod]
public void CanInitEventSubscription()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var subscriptionToken = new SubscriptionToken(t => { });
eventSubscription.SubscriptionToken = subscriptionToken;
Assert.AreSame(actionDelegateReference.Target, eventSubscription.Action);
Assert.AreSame(filterDelegateReference.Target, eventSubscription.Filter);
Assert.AreSame(subscriptionToken, eventSubscription.SubscriptionToken);
}
[TestMethod]
public void GetPublishActionReturnsDelegateThatExecutesTheFilterAndThenTheAction()
{
var executedDelegates = new List<string>();
var actionDelegateReference =
new MockDelegateReference((Action<object>)delegate { executedDelegates.Add("Action"); });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate
{
executedDelegates.Add(
"Filter");
return true;
});
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
publishAction.Invoke(null);
Assert.AreEqual(2, executedDelegates.Count);
Assert.AreEqual("Filter", executedDelegates[0]);
Assert.AreEqual("Action", executedDelegates[1]);
}
[TestMethod]
public void GetPublishActionReturnsNullIfActionIsNull()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
actionDelegateReference.Target = null;
publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNull(publishAction);
}
[TestMethod]
public void GetPublishActionReturnsNullIfFilterIsNull()
{
var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNotNull(publishAction);
filterDelegateReference.Target = null;
publishAction = eventSubscription.GetExecutionStrategy();
Assert.IsNull(publishAction);
}
[TestMethod]
public void GetPublishActionDoesNotExecuteActionIfFilterReturnsFalse()
{
bool actionExecuted = false;
var actionDelegateReference = new MockDelegateReference()
{
Target = (Action<int>)delegate { actionExecuted = true; }
};
var filterDelegateReference = new MockDelegateReference((Predicate<int>)delegate
{
return false;
});
var eventSubscription = new EventSubscription<int>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
publishAction.Invoke(new object[] { null });
Assert.IsFalse(actionExecuted);
}
[TestMethod]
public void StrategyPassesArgumentToDelegates()
{
string passedArgumentToAction = null;
string passedArgumentToFilter = null;
var actionDelegateReference = new MockDelegateReference((Action<string>)(obj => passedArgumentToAction = obj));
var filterDelegateReference = new MockDelegateReference((Predicate<string>)(obj =>
{
passedArgumentToFilter = obj;
return true;
}));
var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference);
var publishAction = eventSubscription.GetExecutionStrategy();
publishAction.Invoke(new[] { "TestString" });
Assert.AreEqual("TestString", passedArgumentToAction);
Assert.AreEqual("TestString", passedArgumentToFilter);
}
}
}
| |
/* ====================================================================
Licensed To the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file To You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed To in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.Collections;
using NPOI.HPSF.Wellknown;
using System.Text;
using NPOI.Util;
/// <summary>
/// Maintains the instances of {@link CustomProperty} that belong To a
/// {@link DocumentSummaryInformation}. The class maintains the names of the
/// custom properties in a dictionary. It implements the {@link Map} interface
/// and by this provides a simplified view on custom properties: A property's
/// name is the key that maps To a typed value. This implementation hides
/// property IDs from the developer and regards the property names as keys To
/// typed values.
/// While this class provides a simple API To custom properties, it ignores
/// the fact that not names, but IDs are the real keys To properties. Under the
/// hood this class maintains a 1:1 relationship between IDs and names. Therefore
/// you should not use this class To process property Sets with several IDs
/// mapping To the same name or with properties without a name: the result will
/// contain only a subSet of the original properties. If you really need To deal
/// such property Sets, use HPSF's low-level access methods.
/// An application can call the {@link #isPure} method To check whether a
/// property Set parsed by {@link CustomProperties} is still pure (i.e.
/// unmodified) or whether one or more properties have been dropped.
/// This class is not thRead-safe; concurrent access To instances of this
/// class must be syncronized.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @since 2006-02-09
/// </summary>
public class CustomProperties : Hashtable
{
/**
* Maps property IDs To property names.
*/
private Hashtable dictionaryIDToName = new Hashtable();
/**
* Maps property names To property IDs.
*/
private Hashtable dictionaryNameToID = new Hashtable();
/**
* Tells whether this object is pure or not.
*/
private bool isPure = true;
/// <summary>
/// Puts a {@link CustomProperty} into this map. It is assumed that the
/// {@link CustomProperty} alReady has a valid ID. Otherwise use
/// {@link #Put(CustomProperty)}.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="cp">The custom property.</param>
/// <returns></returns>
public CustomProperty Put(string name, CustomProperty cp)
{
if (string.IsNullOrEmpty((string)name)) //tony qu changed the code
{
/* Ignoring a property without a name. */
isPure = false;
return null;
}
if (!(name is String))
throw new ArgumentException("The name of a custom property must " +
"be a String, but it is a " +
name.GetType().Name);
if (!(name.Equals(cp.Name)))
throw new ArgumentException("Parameter \"name\" (" + name +
") and custom property's name (" + cp.Name +
") do not match.");
/* Register name and ID in the dictionary. Mapping in both directions is possible. If there is alReady a */
long idKey = cp.ID;
Object oldID = dictionaryNameToID[name];
if(oldID!=null)
dictionaryIDToName.Remove(oldID);
dictionaryNameToID[name]=idKey;
dictionaryIDToName[idKey]= name;
/* Put the custom property into this map. */
if (oldID != null)
base.Remove(oldID);
base[idKey]= cp;
return cp;
}
/**
* Returns a set of all the names of our
* custom properties. Equivalent to
* {@link #nameSet()}
*/
public ICollection KeySet()
{
return dictionaryNameToID.Keys;
}
/**
* Returns a set of all the names of our
* custom properties
*/
public ICollection NameSet()
{
return dictionaryNameToID.Keys;
}
/**
* Returns a set of all the IDs of our
* custom properties
*/
public ICollection IdSet()
{
return dictionaryNameToID.Keys;
}
/// <summary>
/// Puts a {@link CustomProperty} that has not yet a valid ID into this
/// map. The method will allocate a suitable ID for the custom property:
/// <ul>
/// <li>If there is alReady a property with the same name, take the ID
/// of that property.</li>
/// <li>Otherwise Find the highest ID and use its value plus one.</li>
/// </ul>
/// </summary>
/// <param name="customProperty">The custom property.</param>
/// <returns>If the was alReady a property with the same name, the</returns>
private Object Put(CustomProperty customProperty)
{
String name = customProperty.Name;
/* Check whether a property with this name is in the map alReady. */
object oldId = dictionaryNameToID[(name)];
if (oldId!=null)
{
customProperty.ID = (long)oldId;
}
else
{
long max = 1;
for (IEnumerator i = dictionaryIDToName.Keys.GetEnumerator(); i.MoveNext(); )
{
long id = (long)i.Current;
if (id > max)
max = id;
}
customProperty.ID = max + 1;
}
return this.Put(name, customProperty);
}
/// <summary>
/// Removes a custom property.
/// </summary>
/// <param name="name">The name of the custom property To Remove</param>
/// <returns>The Removed property or
/// <c>null</c>
/// if the specified property was not found.</returns>
public object Remove(String name)
{
if (dictionaryNameToID[name] == null)
return null;
long id = (long)dictionaryNameToID[name];
dictionaryIDToName.Remove(id);
dictionaryNameToID.Remove(name);
CustomProperty tmp = (CustomProperty)this[id];
this.Remove(id);
return tmp;
}
/// <summary>
/// Adds a named string property.
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name, String value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_LPWSTR;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Adds a named long property
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name, long value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_I8;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Adds a named double property.
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name, Double value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_R8;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Adds a named integer property.
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name, int value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_I4;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Adds a named bool property.
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name, bool value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_BOOL;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Adds a named date property.
/// </summary>
/// <param name="name">The property's name.</param>
/// <param name="value">The property's value.</param>
/// <returns>the property that was stored under the specified name before, or
/// <c>null</c>
/// if there was no such property before.</returns>
public Object Put(String name,DateTime value)
{
MutableProperty p = new MutableProperty();
p.ID=-1;
p.Type=Variant.VT_FILETIME;
p.Value=value;
CustomProperty cp = new CustomProperty(p, name);
return Put(cp);
}
/// <summary>
/// Gets the <see cref="System.Object"/> with the specified name.
/// </summary>
/// <value>the value or
/// <c>null</c>
/// if a value with the specified
/// name is not found in the custom properties.</value>
public Object this[string name]
{
get
{
object x = dictionaryNameToID[name];
//string.Equals seems not support Unicode string
if (x == null)
{
IEnumerator dic = dictionaryNameToID.GetEnumerator();
while (dic.MoveNext())
{
string key = ((DictionaryEntry)dic.Current).Key as string;
int codepage = this.Codepage;
if (codepage < 0)
codepage = (int)CodePageUtil.CP_UNICODE;
byte[] a= Encoding.GetEncoding(codepage).GetBytes(key);
byte[] b = Encoding.UTF8.GetBytes(name);
if (NPOI.Util.Arrays.Equals(a, b))
x = ((DictionaryEntry)dic.Current).Value;
}
if (x == null)
{
return null;
}
}
long id = (long)x;
CustomProperty cp = (CustomProperty)base[id];
return cp != null ? cp.Value : null;
}
}
/**
* Checks against both String Name and Long ID
*/
public override bool ContainsKey(Object key)
{
if (key is long)
{
return base.ContainsKey((long)key);
}
if (key is String)
{
return base.ContainsKey((long)dictionaryNameToID[(key)]);
}
return false;
}
/**
* Checks against both the property, and its values.
*/
public override bool ContainsValue(Object value)
{
if (value is CustomProperty)
{
return base.ContainsValue(value);
}
else
{
foreach (object cp in base.Values)
{
if ((cp as CustomProperty).Value == value)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Gets the dictionary which Contains IDs and names of the named custom
/// properties.
/// </summary>
/// <value>The dictionary.</value>
public IDictionary Dictionary
{
get { return dictionaryIDToName; }
}
/// <summary>
/// Gets or sets the codepage.
/// </summary>
/// <value>The codepage.</value>
public int Codepage
{
get
{
int codepage = -1;
for (IEnumerator i = this.Values.GetEnumerator(); codepage == -1 && i.MoveNext(); )
{
CustomProperty cp = (CustomProperty)i.Current;
if (cp.ID == PropertyIDMap.PID_CODEPAGE)
codepage = (int)cp.Value;
}
return codepage;
}
set
{
MutableProperty p = new MutableProperty();
p.ID=PropertyIDMap.PID_CODEPAGE;
p.Type=Variant.VT_I2;
p.Value=value;
Put(new CustomProperty(p));
}
}
/// <summary>
/// Tells whether this {@link CustomProperties} instance is pure or one or
/// more properties of the underlying low-level property Set has been
/// dropped.
/// </summary>
/// <value><c>true</c> if this instance is pure; otherwise, <c>false</c>.</value>
public bool IsPure
{
get { return isPure; }
set { this.isPure = value; }
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
// #??? Clean up
using System;
using System.Diagnostics;
using System.Globalization;
using System.ComponentModel;
#if CORE || GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using GdiFontFamily = System.Drawing.FontFamily;
using GdiFont = System.Drawing.Font;
using GdiFontStyle = System.Drawing.FontStyle;
#endif
#if WPF
using System.Windows.Markup;
using WpfFontFamily = System.Windows.Media.FontFamily;
using WpfTypeface = System.Windows.Media.Typeface;
using WpfGlyphTypeface = System.Windows.Media.GlyphTypeface;
#endif
#if UWP
using UwpFontFamily = Windows.UI.Xaml.Media.FontFamily;
#endif
using PdfSharp.Fonts;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Internal;
using PdfSharp.Pdf;
#if SILVERLIGHT
#pragma warning disable 649
#endif
// ReSharper disable ConvertToAutoProperty
namespace PdfSharp.Drawing
{
/// <summary>
/// Defines an object used to draw text.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay}")]
public sealed class XFont
{
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
public XFont(string familyName, double emSize)
: this(familyName, emSize, XFontStyle.Regular, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
public XFont(string familyName, double emSize, XFontStyle style)
: this(familyName, emSize, style, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class.
/// </summary>
/// <param name="familyName">Name of the font family.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(string familyName, double emSize, XFontStyle style, XPdfFontOptions pdfOptions)
{
_familyName = familyName;
_emSize = emSize;
_style = style;
_pdfOptions = pdfOptions;
Initialize();
}
internal XFont(string familyName, double emSize, XFontStyle style, XPdfFontOptions pdfOptions, XStyleSimulations styleSimulations)
{
_familyName = familyName;
_emSize = emSize;
_style = style;
_pdfOptions = pdfOptions;
OverrideStyleSimulations = true;
StyleSimulations = styleSimulations;
Initialize();
}
#if CORE || GDI
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Drawing.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
public XFont(GdiFontFamily fontFamily, double emSize, XFontStyle style)
: this(fontFamily, emSize, style, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Drawing.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(GdiFontFamily fontFamily, double emSize, XFontStyle style, XPdfFontOptions pdfOptions)
{
_familyName = fontFamily.Name;
_gdiFontFamily = fontFamily;
_emSize = emSize;
_style = style;
_pdfOptions = pdfOptions;
InitializeFromGdi();
}
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.Font.
/// </summary>
/// <param name="font">The System.Drawing.Font.</param>
public XFont(GdiFont font)
: this(font, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.Font.
/// </summary>
/// <param name="font">The System.Drawing.Font.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(GdiFont font, XPdfFontOptions pdfOptions)
{
if (font.Unit != GraphicsUnit.World)
throw new ArgumentException("Font must use GraphicsUnit.World.");
_gdiFont = font;
Debug.Assert(font.Name == font.FontFamily.Name);
_familyName = font.Name;
_emSize = font.Size;
_style = FontStyleFrom(font);
_pdfOptions = pdfOptions;
InitializeFromGdi();
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Windows.Media.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Windows.Media.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
public XFont(WpfFontFamily fontFamily, double emSize, XFontStyle style)
: this(fontFamily, emSize, style, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Windows.Media.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(WpfFontFamily fontFamily, double emSize, XFontStyle style, XPdfFontOptions pdfOptions)
{
#if !SILVERLIGHT
_familyName = fontFamily.FamilyNames[XmlLanguage.GetLanguage("en-US")];
#else
// Best we can do in Silverlight.
_familyName = fontFamily.Source;
#endif
_wpfFontFamily = fontFamily;
_emSize = emSize;
_style = style;
_pdfOptions = pdfOptions;
InitializeFromWpf();
}
/// <summary>
/// Initializes a new instance of the <see cref="XFont" /> class from a System.Windows.Media.Typeface.
/// </summary>
/// <param name="typeface">The System.Windows.Media.Typeface.</param>
/// <param name="emSize">The em size.</param>
public XFont(WpfTypeface typeface, double emSize)
: this(typeface, emSize, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Windows.Media.Typeface.
/// </summary>
/// <param name="typeface">The System.Windows.Media.Typeface.</param>
/// <param name="emSize">The em size.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(WpfTypeface typeface, double emSize, XPdfFontOptions pdfOptions)
{
_wpfTypeface = typeface;
//Debug.Assert(font.Name == font.FontFamily.Name);
//_familyName = font.Name;
_emSize = emSize;
_pdfOptions = pdfOptions;
InitializeFromWpf();
}
#endif
#if UWP_
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Drawing.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
public XFont(UwpFontFamily fontFamily, double emSize, XFontStyle style)
: this(fontFamily, emSize, style, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.FontFamily.
/// </summary>
/// <param name="fontFamily">The System.Drawing.FontFamily.</param>
/// <param name="emSize">The em size.</param>
/// <param name="style">The font style.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(UwpFontFamily fontFamily, double emSize, XFontStyle style, XPdfFontOptions pdfOptions)
{
_familyName = fontFamily.Source;
_gdiFontFamily = fontFamily;
_emSize = emSize;
_style = style;
_pdfOptions = pdfOptions;
InitializeFromGdi();
}
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.Font.
/// </summary>
/// <param name="font">The System.Drawing.Font.</param>
public XFont(GdiFont font)
: this(font, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="XFont"/> class from a System.Drawing.Font.
/// </summary>
/// <param name="font">The System.Drawing.Font.</param>
/// <param name="pdfOptions">Additional PDF options.</param>
public XFont(GdiFont font, XPdfFontOptions pdfOptions)
{
if (font.Unit != GraphicsUnit.World)
throw new ArgumentException("Font must use GraphicsUnit.World.");
_gdiFont = font;
Debug.Assert(font.Name == font.FontFamily.Name);
_familyName = font.Name;
_emSize = font.Size;
_style = FontStyleFrom(font);
_pdfOptions = pdfOptions;
InitializeFromGdi();
}
#endif
//// Methods
//public Font(Font prototype, FontStyle newStyle);
//public Font(FontFamily family, float emSize);
//public Font(string familyName, float emSize);
//public Font(FontFamily family, float emSize, FontStyle style);
//public Font(FontFamily family, float emSize, GraphicsUnit unit);
//public Font(string familyName, float emSize, FontStyle style);
//public Font(string familyName, float emSize, GraphicsUnit unit);
//public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit);
//public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit);
////public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet);
////public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet);
////public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont);
////public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont);
//public object Clone();
//private static FontFamily CreateFontFamilyWithFallback(string familyName);
//private void Dispose(bool disposing);
//public override bool Equals(object obj);
//protected override void Finalize();
//public static Font FromHdc(IntPtr hdc);
//public static Font FromHfont(IntPtr hfont);
//public static Font FromLogFont(object lf);
//public static Font FromLogFont(object lf, IntPtr hdc);
//public override int GetHashCode();
/// <summary>
/// Initializes this instance by computing the glyph typeface, font family, font source and TrueType fontface.
/// (PDFsharp currently only deals with TrueType fonts.)
/// </summary>
void Initialize()
{
#if DEBUG
if (_familyName == "Segoe UI Semilight" && (_style & XFontStyle.BoldItalic) == XFontStyle.Italic)
GetType();
#endif
FontResolvingOptions fontResolvingOptions = OverrideStyleSimulations
? new FontResolvingOptions(_style, StyleSimulations)
: new FontResolvingOptions(_style);
// HACK: 'PlatformDefault' is used in unit test code.
if (StringComparer.OrdinalIgnoreCase.Compare(_familyName, GlobalFontSettings.DefaultFontName) == 0)
{
#if CORE || GDI || WPF
_familyName = "Calibri";
#endif
}
// In principle an XFont is an XGlyphTypeface plus an em-size.
_glyphTypeface = XGlyphTypeface.GetOrCreateFrom(_familyName, fontResolvingOptions);
#if GDI // TODO: In CORE build it is not necessary to create a GDI font at all
// Create font by using font family.
XFontSource fontSource; // Not needed here.
_gdiFont = FontHelper.CreateFont(_familyName, (float)_emSize, (GdiFontStyle)(_style & XFontStyle.BoldItalic), out fontSource);
#endif
#if WPF && !SILVERLIGHT // Pure WPF
_wpfFontFamily = _glyphTypeface.FontFamily.WpfFamily;
_wpfTypeface = _glyphTypeface.WpfTypeface;
if (_wpfFontFamily == null)
_wpfFontFamily = new WpfFontFamily(Name);
if (_wpfTypeface == null)
_wpfTypeface = FontHelper.CreateTypeface(WpfFontFamily, _style);
#endif
#if WPF && SILVERLIGHT_ // Pure Silverlight 5
if (GlyphTypeface == null)
{
//Debug.Assert(Typeface == null);
// #P F C
//GlyphTypeface = XPrivateFontCollection.TryGetXGlyphTypeface(Name, _style);
//if (GlyphTypeface == null)
//{
// // HACK: Just make it work...
// GlyphTypeface = GlobalFontSettings.TryGetXGlyphTypeface(Name, _style, out Data);
//}
#if DEBUG
if (GlyphTypeface == null)
throw new Exception("No font: " + Name);
#endif
_wpfFamily = GlyphTypeface.FontFamily;
}
//if (Family == null)
// Family = new System.Windows.Media.FontFamily(Name);
//if (Typeface == null)
// Typeface = FontHelper.CreateTypeface(Family, _style);
#endif
CreateDescriptorAndInitializeFontMetrics();
}
#if CORE || GDI
/// <summary>
/// A GDI+ font object is used to setup the internal font objects.
/// </summary>
void InitializeFromGdi()
{
try
{
Lock.EnterFontFactory();
if (_gdiFontFamily != null)
{
// Create font based on its family.
_gdiFont = new Font(_gdiFontFamily, (float)_emSize, (GdiFontStyle)_style, GraphicsUnit.World);
}
if (_gdiFont != null)
{
#if DEBUG_
string name1 = _gdiFont.Name;
string name2 = _gdiFont.OriginalFontName;
string name3 = _gdiFont.SystemFontName;
#endif
_familyName = _gdiFont.FontFamily.Name;
// TODO: _glyphTypeface = XGlyphTypeface.GetOrCreateFrom(_gdiFont);
}
else
{
Debug.Assert(false);
}
if (_glyphTypeface == null)
_glyphTypeface = XGlyphTypeface.GetOrCreateFromGdi(_gdiFont);
CreateDescriptorAndInitializeFontMetrics();
}
finally { Lock.ExitFontFactory(); }
}
#endif
#if WPF && !SILVERLIGHT
void InitializeFromWpf()
{
if (_wpfFontFamily != null)
{
_wpfTypeface = FontHelper.CreateTypeface(_wpfFontFamily, _style);
}
if (_wpfTypeface != null)
{
_familyName = _wpfTypeface.FontFamily.FamilyNames[XmlLanguage.GetLanguage("en-US")];
_glyphTypeface = XGlyphTypeface.GetOrCreateFromWpf(_wpfTypeface);
}
else
{
Debug.Assert(false);
}
if (_glyphTypeface == null)
_glyphTypeface = XGlyphTypeface.GetOrCreateFrom(_familyName, new FontResolvingOptions(_style));
CreateDescriptorAndInitializeFontMetrics();
}
#endif
/// <summary>
/// Code separated from Metric getter to make code easier to debug.
/// (Setup properties in their getters caused side effects during debugging because Visual Studio calls a getter
/// to early to show its value in a debugger window.)
/// </summary>
void CreateDescriptorAndInitializeFontMetrics() // TODO: refactor
{
Debug.Assert(_fontMetrics == null, "InitializeFontMetrics() was already called.");
_descriptor = (OpenTypeDescriptor)FontDescriptorCache.GetOrCreateDescriptorFor(this); //_familyName, _style, _glyphTypeface.Fontface);
_fontMetrics = new XFontMetrics(_descriptor.FontName, _descriptor.UnitsPerEm, _descriptor.Ascender, _descriptor.Descender,
_descriptor.Leading, _descriptor.LineSpacing, _descriptor.CapHeight, _descriptor.XHeight, _descriptor.StemV, 0, 0, 0,
_descriptor.UnderlinePosition, _descriptor.UnderlineThickness, _descriptor.StrikeoutPosition, _descriptor.StrikeoutSize);
XFontMetrics fm = Metrics;
// Already done in CreateDescriptorAndInitializeFontMetrics.
//if (_descriptor == null)
// _descriptor = (OpenTypeDescriptor)FontDescriptorStock.Global.CreateDescriptor(this); //(Name, (XGdiFontStyle)Font.Style);
UnitsPerEm = _descriptor.UnitsPerEm;
CellAscent = _descriptor.Ascender;
CellDescent = _descriptor.Descender;
CellSpace = _descriptor.LineSpacing;
#if DEBUG_ && GDI
int gdiValueUnitsPerEm = Font.FontFamily.GetEmHeight(Font.Style);
Debug.Assert(gdiValueUnitsPerEm == UnitsPerEm);
int gdiValueAscent = Font.FontFamily.GetCellAscent(Font.Style);
Debug.Assert(gdiValueAscent == CellAscent);
int gdiValueDescent = Font.FontFamily.GetCellDescent(Font.Style);
Debug.Assert(gdiValueDescent == CellDescent);
int gdiValueLineSpacing = Font.FontFamily.GetLineSpacing(Font.Style);
Debug.Assert(gdiValueLineSpacing == CellSpace);
#endif
#if DEBUG_ && WPF && !SILVERLIGHT
int wpfValueLineSpacing = (int)Math.Round(Family.LineSpacing * _descriptor.UnitsPerEm);
Debug.Assert(wpfValueLineSpacing == CellSpace);
#endif
Debug.Assert(fm.UnitsPerEm == _descriptor.UnitsPerEm);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the XFontFamily object associated with this XFont object.
/// </summary>
[Browsable(false)]
public XFontFamily FontFamily
{
get { return _glyphTypeface.FontFamily; }
}
/// <summary>
/// WRONG: Gets the face name of this Font object.
/// Indeed it returns the font family name.
/// </summary>
// [Obsolete("This function returns the font family name, not the face name. Use xxx.FontFamily.Name or xxx.FaceName")]
public string Name
{
get { return _glyphTypeface.FontFamily.Name; }
}
internal string FaceName
{
get { return _glyphTypeface.FaceName; }
}
/// <summary>
/// Gets the em-size of this font measured in the unit of this font object.
/// </summary>
public double Size
{
get { return _emSize; }
}
readonly double _emSize;
/// <summary>
/// Gets style information for this Font object.
/// </summary>
[Browsable(false)]
public XFontStyle Style
{
get { return _style; }
}
readonly XFontStyle _style;
/// <summary>
/// Indicates whether this XFont object is bold.
/// </summary>
public bool Bold
{
get { return (_style & XFontStyle.Bold) == XFontStyle.Bold; }
}
/// <summary>
/// Indicates whether this XFont object is italic.
/// </summary>
public bool Italic
{
get { return (_style & XFontStyle.Italic) == XFontStyle.Italic; }
}
/// <summary>
/// Indicates whether this XFont object is stroke out.
/// </summary>
public bool Strikeout
{
get { return (_style & XFontStyle.Strikeout) == XFontStyle.Strikeout; }
}
/// <summary>
/// Indicates whether this XFont object is underlined.
/// </summary>
public bool Underline
{
get { return (_style & XFontStyle.Underline) == XFontStyle.Underline; }
}
/// <summary>
/// Temporary HACK for XPS to PDF converter.
/// </summary>
internal bool IsVertical
{
get { return _isVertical; }
set { _isVertical = value; }
}
bool _isVertical;
/// <summary>
/// Gets the PDF options of the font.
/// </summary>
public XPdfFontOptions PdfOptions
{
get { return _pdfOptions ?? (_pdfOptions = new XPdfFontOptions()); }
}
XPdfFontOptions _pdfOptions;
/// <summary>
/// Indicates whether this XFont is encoded as Unicode.
/// </summary>
internal bool Unicode
{
get { return _pdfOptions != null && _pdfOptions.FontEncoding == PdfFontEncoding.Unicode; }
}
/// <summary>
/// Gets the cell space for the font. The CellSpace is the line spacing, the sum of CellAscent and CellDescent and optionally some extra space.
/// </summary>
public int CellSpace
{
get { return _cellSpace; }
internal set { _cellSpace = value; }
}
int _cellSpace;
/// <summary>
/// Gets the cell ascent, the area above the base line that is used by the font.
/// </summary>
public int CellAscent
{
get { return _cellAscent; }
internal set { _cellAscent = value; }
}
int _cellAscent;
/// <summary>
/// Gets the cell descent, the area below the base line that is used by the font.
/// </summary>
public int CellDescent
{
get { return _cellDescent; }
internal set { _cellDescent = value; }
}
int _cellDescent;
/// <summary>
/// Gets the font metrics.
/// </summary>
/// <value>The metrics.</value>
public XFontMetrics Metrics
{
get
{
// Code moved to InitializeFontMetrics().
//if (_fontMetrics == null)
//{
// FontDescriptor descriptor = FontDescriptorStock.Global.CreateDescriptor(this);
// _fontMetrics = new XFontMetrics(descriptor.FontName, descriptor.UnitsPerEm, descriptor.Ascender, descriptor.Descender,
// descriptor.Leading, descriptor.LineSpacing, descriptor.CapHeight, descriptor.XHeight, descriptor.StemV, 0, 0, 0);
//}
Debug.Assert(_fontMetrics != null, "InitializeFontMetrics() not yet called.");
return _fontMetrics;
}
}
XFontMetrics _fontMetrics;
/// <summary>
/// Returns the line spacing, in pixels, of this font. The line spacing is the vertical distance
/// between the base lines of two consecutive lines of text. Thus, the line spacing includes the
/// blank space between lines along with the height of the character itself.
/// </summary>
public double GetHeight()
{
double value = CellSpace * _emSize / UnitsPerEm;
#if CORE || NETFX_CORE || UWP
return value;
#endif
#if GDI && !WPF
#if DEBUG_
double gdiValue = Font.GetHeight();
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiValue, value, 5));
#endif
return value;
#endif
#if WPF && !GDI
return value;
#endif
#if WPF && GDI // Testing only
return value;
#endif
}
/// <summary>
/// Returns the line spacing, in the current unit of a specified Graphics object, of this font.
/// The line spacing is the vertical distance between the base lines of two consecutive lines of
/// text. Thus, the line spacing includes the blank space between lines along with the height of
/// </summary>
[Obsolete("Use GetHeight() without parameter.")]
public double GetHeight(XGraphics graphics)
{
#if true
throw new InvalidOperationException("Honestly: Use GetHeight() without parameter!");
#else
#if CORE || NETFX_CORE
double value = CellSpace * _emSize / UnitsPerEm;
return value;
#endif
#if GDI && !WPF
if (graphics._gfx != null) // #MediumTrust
{
double value = Font.GetHeight(graphics._gfx);
Debug.Assert(value == Font.GetHeight(graphics._gfx.DpiY));
double value2 = CellSpace * _emSize / UnitsPerEm;
Debug.Assert(value - value2 < 1e-3, "??");
return Font.GetHeight(graphics._gfx);
}
return CellSpace * _emSize / UnitsPerEm;
#endif
#if WPF && !GDI
double value = CellSpace * _emSize / UnitsPerEm;
return value;
#endif
#if GDI && WPF // Testing only
if (graphics.TargetContext == XGraphicTargetContext.GDI)
{
#if DEBUG
double value = Font.GetHeight(graphics._gfx);
// 2355*(0.3/2048)*96 = 33.11719
double myValue = CellSpace * (_emSize / (96 * UnitsPerEm)) * 96;
myValue = CellSpace * _emSize / UnitsPerEm;
//Debug.Assert(value == myValue, "??");
//Debug.Assert(value - myValue < 1e-3, "??");
#endif
return Font.GetHeight(graphics._gfx);
}
if (graphics.TargetContext == XGraphicTargetContext.WPF)
{
double value = CellSpace * _emSize / UnitsPerEm;
return value;
}
// ReSharper disable HeuristicUnreachableCode
Debug.Fail("Either GDI or WPF.");
return 0;
// ReSharper restore HeuristicUnreachableCode
#endif
#endif
}
/// <summary>
/// Gets the line spacing of this font.
/// </summary>
[Browsable(false)]
public int Height
{
// Implementation from System.Drawing.Font.cs
get { return (int)Math.Ceiling(GetHeight()); }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
internal XGlyphTypeface GlyphTypeface
{
get { return _glyphTypeface; }
}
XGlyphTypeface _glyphTypeface;
internal OpenTypeDescriptor Descriptor
{
get { return _descriptor; }
private set { _descriptor = value; }
}
OpenTypeDescriptor _descriptor;
internal string FamilyName
{
get { return _familyName; }
}
string _familyName;
internal int UnitsPerEm
{
get { return _unitsPerEm; }
private set { _unitsPerEm = value; }
}
internal int _unitsPerEm;
/// <summary>
/// Override style simulations by using the value of StyleSimulations.
/// </summary>
internal bool OverrideStyleSimulations;
/// <summary>
/// Used to enforce style simulations by renderer. For development purposes only.
/// </summary>
internal XStyleSimulations StyleSimulations;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if CORE || GDI
/// <summary>
/// Gets the GDI family.
/// </summary>
/// <value>The GDI family.</value>
public GdiFontFamily GdiFontFamily
{
get { return _gdiFontFamily; }
}
readonly GdiFontFamily _gdiFontFamily;
internal GdiFont GdiFont
{
get { return _gdiFont; }
}
Font _gdiFont;
internal static XFontStyle FontStyleFrom(GdiFont font)
{
return
(font.Bold ? XFontStyle.Bold : 0) |
(font.Italic ? XFontStyle.Italic : 0) |
(font.Strikeout ? XFontStyle.Strikeout : 0) |
(font.Underline ? XFontStyle.Underline : 0);
}
#if true || UseGdiObjects
/// <summary>
/// Implicit conversion form Font to XFont
/// </summary>
public static implicit operator XFont(GdiFont font)
{
return new XFont(font);
}
#endif
#endif
#if WPF
/// <summary>
/// Gets the WPF font family.
/// Can be null.
/// </summary>
internal WpfFontFamily WpfFontFamily
{
get { return _wpfFontFamily; }
}
WpfFontFamily _wpfFontFamily;
internal WpfTypeface WpfTypeface
{
get { return _wpfTypeface; }
}
WpfTypeface _wpfTypeface;
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Cache PdfFontTable.FontSelector to speed up finding the right PdfFont
/// if this font is used more than once.
/// </summary>
internal string Selector
{
get { return _selector; }
set { _selector = value; }
}
string _selector;
/// <summary>
/// Gets the DebuggerDisplayAttribute text.
/// </summary>
// ReSharper disable UnusedMember.Local
string DebuggerDisplay
// ReSharper restore UnusedMember.Local
{
get { return String.Format(CultureInfo.InvariantCulture, "font=('{0}' {1:0.##})", Name, Size); }
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
{
return string.IsNullOrEmpty(value);
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0)
{
return format.FormatWith(provider, new object?[] { arg0 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1)
{
return format.FormatWith(provider, new object?[] { arg0, arg1 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2)
{
return format.FormatWith(provider, new object?[] { arg0, arg1, arg2 });
}
public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2, object? arg3)
{
return format.FormatWith(provider, new object?[] { arg0, arg1, arg2, arg3 });
}
private static string FormatWith(this string format, IFormatProvider provider, params object?[] args)
{
// leave this a private to force code to use an explicit overload
// avoids stack memory being reserved for the object array
ValidationUtils.ArgumentNotNull(format, nameof(format));
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return <c>false</c>.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (s.Length == 0)
{
return false;
}
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
{
return false;
}
}
return true;
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static void ToCharAsUnicode(char c, char[] buffer)
{
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f');
buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f');
buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f');
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (valueSelector == null)
{
throw new ArgumentNullException(nameof(valueSelector));
}
IEnumerable<TSource> caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase));
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
IEnumerable<TSource> caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
return caseSensitiveResults.SingleOrDefault();
}
}
public static string ToCamelCase(string s)
{
if (StringUtils.IsNullOrEmpty(s) || !char.IsUpper(s[0]))
{
return s;
}
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (i == 1 && !char.IsUpper(chars[i]))
{
break;
}
bool hasNext = (i + 1 < chars.Length);
if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
{
// if the next character is a space, which is not considered uppercase
// (otherwise we wouldn't be here...)
// we want to ensure that the following:
// 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
// The code was written in such a way that the first word in uppercase
// ends when if finds an uppercase letter followed by a lowercase letter.
// now a ' ' (space, (char)32) is considered not upper
// but in that case we still want our current character to become lowercase
if (char.IsSeparator(chars[i + 1]))
{
chars[i] = ToLower(chars[i]);
}
break;
}
chars[i] = ToLower(chars[i]);
}
return new string(chars);
}
private static char ToLower(char c)
{
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
c = char.ToLower(c, CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(c);
#endif
return c;
}
public static string ToSnakeCase(string s) => ToSeparatedCase(s, '_');
public static string ToKebabCase(string s) => ToSeparatedCase(s, '-');
private enum SeparatedCaseState
{
Start,
Lower,
Upper,
NewWord
}
private static string ToSeparatedCase(string s, char separator)
{
if (StringUtils.IsNullOrEmpty(s))
{
return s;
}
StringBuilder sb = new StringBuilder();
SeparatedCaseState state = SeparatedCaseState.Start;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
{
if (state != SeparatedCaseState.Start)
{
state = SeparatedCaseState.NewWord;
}
}
else if (char.IsUpper(s[i]))
{
switch (state)
{
case SeparatedCaseState.Upper:
bool hasNext = (i + 1 < s.Length);
if (i > 0 && hasNext)
{
char nextChar = s[i + 1];
if (!char.IsUpper(nextChar) && nextChar != separator)
{
sb.Append(separator);
}
}
break;
case SeparatedCaseState.Lower:
case SeparatedCaseState.NewWord:
sb.Append(separator);
break;
}
char c;
#if HAVE_CHAR_TO_LOWER_WITH_CULTURE
c = char.ToLower(s[i], CultureInfo.InvariantCulture);
#else
c = char.ToLowerInvariant(s[i]);
#endif
sb.Append(c);
state = SeparatedCaseState.Upper;
}
else if (s[i] == separator)
{
sb.Append(separator);
state = SeparatedCaseState.Start;
}
else
{
if (state == SeparatedCaseState.NewWord)
{
sb.Append(separator);
}
sb.Append(s[i]);
state = SeparatedCaseState.Lower;
}
}
return sb.ToString();
}
public static bool IsHighSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsHighSurrogate(c);
#else
return (c >= 55296 && c <= 56319);
#endif
}
public static bool IsLowSurrogate(char c)
{
#if HAVE_UNICODE_SURROGATE_DETECTION
return char.IsLowSurrogate(c);
#else
return (c >= 56320 && c <= 57343);
#endif
}
public static bool StartsWith(this string source, char value)
{
return (source.Length > 0 && source[0] == value);
}
public static bool EndsWith(this string source, char value)
{
return (source.Length > 0 && source[source.Length - 1] == value);
}
public static string Trim(this string s, int start, int length)
{
// References: https://referencesource.microsoft.com/#mscorlib/system/string.cs,2691
// https://referencesource.microsoft.com/#mscorlib/system/string.cs,1226
if (s == null)
{
throw new ArgumentNullException();
}
if (start < 0)
{
throw new ArgumentOutOfRangeException(nameof(start));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
int end = start + length - 1;
if (end >= s.Length)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
for (; start < end; start++)
{
if (!char.IsWhiteSpace(s[start]))
{
break;
}
}
for (; end >= start; end--)
{
if (!char.IsWhiteSpace(s[end]))
{
break;
}
}
return s.Substring(start, end - start + 1);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule
{
public class XmlRpcInfo
{
public UUID item;
public UUID channel;
public string uri;
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XmlRpcGridRouter")]
public class XmlRpcGridRouter : INonSharedRegionModule, IXmlRpcRouter
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, UUID> m_Channels =
new Dictionary<UUID, UUID>();
private bool m_Enabled = false;
private string m_ServerURI = String.Empty;
#region INonSharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig startupConfig = config.Configs["XMLRPC"];
if (startupConfig == null)
return;
if (startupConfig.GetString("XmlRpcRouterModule",
"XmlRpcRouterModule") == "XmlRpcGridRouterModule")
{
m_ServerURI = startupConfig.GetString("XmlRpcHubURI", String.Empty);
if (m_ServerURI == String.Empty)
{
m_log.Error("[XMLRPC GRID ROUTER] Module configured but no URI given. Disabling");
return;
}
m_Enabled = true;
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IXmlRpcRouter>(this);
IScriptModule scriptEngine = scene.RequestModuleInterface<IScriptModule>();
if ( scriptEngine != null )
{
scriptEngine.OnScriptRemoved += this.ScriptRemoved;
scriptEngine.OnObjectRemoved += this.ObjectRemoved;
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<IXmlRpcRouter>(this);
}
public void Close()
{
}
public string Name
{
get { return "XmlRpcGridRouterModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
public void RegisterNewReceiver(IScriptModule scriptEngine, UUID channel, UUID objectID, UUID itemID, string uri)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[XMLRPC GRID ROUTER]: New receiver Obj: {0} Ch: {1} ID: {2} URI: {3}",
objectID.ToString(), channel.ToString(), itemID.ToString(), uri);
XmlRpcInfo info = new XmlRpcInfo();
info.channel = channel;
info.uri = uri;
info.item = itemID;
bool success = SynchronousRestObjectRequester.MakeRequest<XmlRpcInfo, bool>(
"POST", m_ServerURI+"/RegisterChannel/", info);
if (!success)
{
m_log.Error("[XMLRPC GRID ROUTER] Error contacting server");
}
m_Channels[itemID] = channel;
}
public void UnRegisterReceiver(string channelID, UUID itemID)
{
if (!m_Enabled)
return;
RemoveChannel(itemID);
}
public void ScriptRemoved(UUID itemID)
{
if (!m_Enabled)
return;
RemoveChannel(itemID);
}
public void ObjectRemoved(UUID objectID)
{
// m_log.InfoFormat("[XMLRPC GRID ROUTER]: Object Removed {0}",objectID.ToString());
}
private bool RemoveChannel(UUID itemID)
{
if(!m_Channels.ContainsKey(itemID))
{
m_log.InfoFormat("[XMLRPC GRID ROUTER]: Attempted to unregister non-existing Item: {0}", itemID.ToString());
return false;
}
XmlRpcInfo info = new XmlRpcInfo();
info.channel = m_Channels[itemID];
info.item = itemID;
info.uri = "http://0.0.0.0:00";
if (info != null)
{
bool success = SynchronousRestObjectRequester.MakeRequest<XmlRpcInfo, bool>(
"POST", m_ServerURI+"/RemoveChannel/", info);
if (!success)
{
m_log.Error("[XMLRPC GRID ROUTER] Error contacting server");
}
m_Channels.Remove(itemID);
return true;
}
return 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 System.Diagnostics;
using System.Globalization;
using System.Security.Principal;
using System.Security.Permissions;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
namespace System.DirectoryServices.AccountManagement
{
[System.Diagnostics.DebuggerDisplay("Name ( {Name} )")]
abstract public class Principal : IDisposable
{
//
// Public properties
//
public override string ToString()
{
return Name;
}
// Context property
public PrincipalContext Context
{
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
return _ctx;
}
}
// ContextType property
public ContextType ContextType
{
get
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// The only way we can't have a PrincipalContext is if we're unpersisted
Debug.Assert(_ctx != null || this.unpersisted == true);
if (_ctx == null)
throw new InvalidOperationException(SR.PrincipalMustSetContextForProperty);
return _ctx.ContextType;
}
}
// Description property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _description = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _descriptionChanged = LoadState.NotSet; // change-tracking
public string Description
{
get
{
return HandleGet<string>(ref _description, PropertyNames.PrincipalDescription, ref _descriptionChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDescription))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _description, value, ref _descriptionChanged, PropertyNames.PrincipalDescription);
}
}
// DisplayName property
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _displayName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _displayNameChanged = LoadState.NotSet; // change-tracking
public string DisplayName
{
get
{
return HandleGet<string>(ref _displayName, PropertyNames.PrincipalDisplayName, ref _displayNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalDisplayName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _displayName, value, ref _displayNameChanged, PropertyNames.PrincipalDisplayName);
}
}
//
// Convenience wrappers for the IdentityClaims property
// SAM Account Name
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _samName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _samNameChanged = LoadState.NotSet; // change-tracking
public string SamAccountName
{
get
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, PropertyNames.PrincipalSamAccountName));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
}
// UPN
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _userPrincipalName = null; // the actual property value
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _userPrincipalNameChanged = LoadState.NotSet; // change-tracking
public string UserPrincipalName
{
get
{
return HandleGet<string>(ref _userPrincipalName, PropertyNames.PrincipalUserPrincipalName, ref _userPrincipalNameChanged);
}
set
{
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalUserPrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
HandleSet<string>(ref _userPrincipalName, value, ref _userPrincipalNameChanged, PropertyNames.PrincipalUserPrincipalName);
}
}
// SID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private SecurityIdentifier _sid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _sidChanged = LoadState.NotSet;
public SecurityIdentifier Sid
{
get
{
return HandleGet<SecurityIdentifier>(ref _sid, PropertyNames.PrincipalSid, ref _sidChanged);
}
}
// GUID
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Nullable<Guid> _guid = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _guidChanged = LoadState.NotSet;
public Nullable<Guid> Guid
{
get
{
return HandleGet<Nullable<Guid>>(ref _guid, PropertyNames.PrincipalGuid, ref _guidChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _distinguishedName = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _distinguishedNameChanged = LoadState.NotSet;
public string DistinguishedName
{
get
{
return HandleGet<string>(ref _distinguishedName, PropertyNames.PrincipalDistinguishedName, ref _distinguishedNameChanged);
}
}
// DistinguishedName
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _structuralObjectClass = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _structuralObjectClassChanged = LoadState.NotSet;
public string StructuralObjectClass
{
get
{
return HandleGet<string>(ref _structuralObjectClass, PropertyNames.PrincipalStructuralObjectClass, ref _structuralObjectClassChanged);
}
}
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _name = null;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
private LoadState _nameChanged = LoadState.NotSet;
public string Name
{
get
{
// TODO Store should be mapping both to the same property already....
// TQ Special case to map name and SamAccountNAme to same cache variable.
// This should be removed in the future.
// Context type could be null for an unpersisted user.
// Default to the original domain behavior if a context is not set.
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
return HandleGet<string>(ref _samName, PropertyNames.PrincipalSamAccountName, ref _samNameChanged);
}
else
{
return HandleGet<string>(ref _name, PropertyNames.PrincipalName, ref _nameChanged);
}
}
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(String.Format(CultureInfo.CurrentCulture, SR.InvalidNullArgument, PropertyNames.PrincipalName));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
ContextType ct = (_ctx == null) ? ContextType.Domain : _ctx.ContextType;
if (ct == ContextType.Machine)
{
HandleSet<string>(ref _samName, value, ref _samNameChanged, PropertyNames.PrincipalSamAccountName);
}
else
{
HandleSet<string>(ref _name, value, ref _nameChanged, PropertyNames.PrincipalName);
}
}
}
private ExtensionHelper _extensionHelper;
[System.Diagnostics.DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal ExtensionHelper ExtensionHelper
{
get
{
if (null == _extensionHelper)
_extensionHelper = new ExtensionHelper(this);
return _extensionHelper;
}
}
//
// Public methods
//
public static Principal FindByIdentity(PrincipalContext context, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityValue);
}
public static Principal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return FindByIdentityWithType(context, typeof(Principal), identityType, identityValue);
}
public void Save()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.PrincipalMustSetContextForSave);
}
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx storeCtxToUse = GetStoreCtxToUse();
Debug.Assert(storeCtxToUse != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: inserting principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.ContextForType(this.GetType()));
storeCtxToUse.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save: updating principal of type {0} using {1}", this.GetType(), storeCtxToUse.GetType());
Debug.Assert(storeCtxToUse == _ctx.QueryCtx);
storeCtxToUse.Update(this);
}
}
public void Save(PrincipalContext context)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save(Context)");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (context.ContextType == ContextType.Machine || _ctx.ContextType == ContextType.Machine)
{
throw new InvalidOperationException(SR.SaveToNotSupportedAgainstMachineStore);
}
// We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted
// and they never set a PrincipalContext.
if (context == null)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.NullArguments);
}
// If the user is trying to save to the same context we are already set to then just save the changes
if (context == _ctx)
{
Save();
return;
}
// If we already have a context set on this object then make sure the new
// context is of the same type.
if (context.ContextType != _ctx.ContextType)
{
Debug.Assert(this.unpersisted == true);
throw new InvalidOperationException(SR.SaveToMustHaveSamecontextType);
}
StoreCtx originalStoreCtx = GetStoreCtxToUse();
_ctx = context;
// Call the appropriate operation depending on whether this is an insert or update
StoreCtx newStoreCtx = GetStoreCtxToUse();
Debug.Assert(newStoreCtx != null); // since we know this.ctx isn't null
Debug.Assert(originalStoreCtx != null); // since we know this.ctx isn't null
if (this.unpersisted)
{
// We have an unpersisted principal so we just want to create a principal in the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): inserting new principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
Debug.Assert(newStoreCtx == _ctx.ContextForType(this.GetType()));
newStoreCtx.Insert(this);
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
}
else
{
// We have a principal that already exists. We need to move it to the new store.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): Moving principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType());
// we are now saving to a new store so this principal is unpersisted.
this.unpersisted = true;
// If the user has modified the name save away the current name so
// if the move succeeds and the update fails we will move the item back to the original
// store with the original name.
bool nameModified = _nameChanged == LoadState.Changed;
string previousName = null;
if (nameModified)
{
string newName = _name;
_ctx.QueryCtx.Load(this, PropertyNames.PrincipalName);
previousName = _name;
this.Name = newName;
}
newStoreCtx.Move(originalStoreCtx, this);
try
{
this.unpersisted = false; // once we persist, we're no longer in the unpersisted state
newStoreCtx.Update(this);
}
catch (System.SystemException e)
{
try
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Update Failed (attempting to move back) Exception {0} ", e.Message);
if (nameModified)
this.Name = previousName;
originalStoreCtx.Move(newStoreCtx, this);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Move back succeeded");
}
catch (System.SystemException deleteFail)
{
// The move back failed. Just continue we will throw the original exception below.
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Move back Failed {0} ", deleteFail.Message);
}
if (e is System.Runtime.InteropServices.COMException)
throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e);
else
throw e;
}
}
_ctx.QueryCtx = newStoreCtx; // so Updates go to the right StoreCtx
}
public void Delete()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Delete");
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
// If we're unpersisted, nothing to delete
if (this.unpersisted)
throw new InvalidOperationException(SR.PrincipalCantDeleteUnpersisted);
// Since we're not unpersisted, we must have come back from a query, and the query logic would
// have filled in a PrincipalContext on us.
Debug.Assert(_ctx != null);
_ctx.QueryCtx.Delete(this);
_isDeleted = true;
}
public override bool Equals(object o)
{
Principal that = o as Principal;
if (that == null)
return false;
if (Object.ReferenceEquals(this, that))
return true;
if ((_key != null) && (that._key != null) && (_key.Equals(that._key)))
return true;
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public object GetUnderlyingObject()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.UnderlyingObject == null)
{
throw new InvalidOperationException(SR.PrincipalMustPersistFirst);
}
return this.UnderlyingObject;
}
public Type GetUnderlyingObjectType()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Make sure we're not a fake principal
CheckFakePrincipal();
if (this.unpersisted)
{
// If we're unpersisted, we can't determine the native type until our PrincipalContext has been set.
if (_ctx != null)
{
return _ctx.ContextForType(this.GetType()).NativeType(this);
}
else
{
throw new InvalidOperationException(SR.PrincipalMustSetContextForNative);
}
}
else
{
Debug.Assert(_ctx != null);
return _ctx.QueryCtx.NativeType(this);
}
}
public PrincipalSearchResult<Principal> GetGroups()
{
return new PrincipalSearchResult<Principal>(GetGroupsHelper());
}
public PrincipalSearchResult<Principal> GetGroups(PrincipalContext contextToQuery)
{
if (contextToQuery == null)
throw new ArgumentNullException("contextToQuery");
return new PrincipalSearchResult<Principal>(GetGroupsHelper(contextToQuery));
}
public bool IsMemberOf(GroupPrincipal group)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (group == null)
throw new ArgumentNullException("group");
return group.Members.Contains(this);
}
public bool IsMemberOf(PrincipalContext context, IdentityType identityType, string identityValue)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
GroupPrincipal g = GroupPrincipal.FindByIdentity(context, identityType, identityValue);
if (g != null)
{
return IsMemberOf(g);
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "IsMemberOf(urn/urn): no matching principal");
throw new NoMatchingPrincipalException(SR.NoMatchingGroupExceptionText);
}
}
//
// IDisposable
//
public virtual void Dispose()
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing");
if ((this.UnderlyingObject != null) && (this.UnderlyingObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying object");
((IDisposable)this.UnderlyingObject).Dispose();
}
if ((this.UnderlyingSearchObject != null) && (this.UnderlyingSearchObject is IDisposable))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Dispose: disposing underlying search object");
((IDisposable)this.UnderlyingSearchObject).Dispose();
}
_disposed = true;
GC.SuppressFinalize(this);
}
}
//
//
//
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected Principal()
{
}
//------------------------------------------------
// Protected functions for use by derived classes.
//------------------------------------------------
// Stores all values from derived classes for use at attributes or search filter.
private ExtensionCache _extensionCache = new ExtensionCache();
private LoadState _extensionCacheChanged = LoadState.NotSet;
protected object[] ExtensionGet(string attribute)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ExtensionCacheValue val;
if (_extensionCache.TryGetValue(attribute, out val))
{
if (val.Filter)
{
return null;
}
return val.Value;
}
else if (this.unpersisted)
{
return Array.Empty<object>();
}
else
{
Debug.Assert(this.GetUnderlyingObjectType() == typeof(DirectoryEntry));
DirectoryEntry de = (DirectoryEntry)this.GetUnderlyingObject();
int valCount = de.Properties[attribute].Count;
if (valCount == 0)
return Array.Empty<object>();
else
{
object[] objectArray = new object[valCount];
de.Properties[attribute].CopyTo(objectArray, 0);
return objectArray;
}
}
}
private void ValidateExtensionObject(object value)
{
if (value is object[])
{
if (((object[])value).Length == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in (object[])value)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
if (value is byte[])
{
if (((byte[])value).Length == 0)
{
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
else
{
if (value != null && value is ICollection)
{
ICollection collection = (ICollection)value;
if (collection.Count == 0)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
foreach (object o in collection)
{
if (o is ICollection)
throw new ArgumentException(SR.InvalidExtensionCollectionType);
}
}
}
}
protected void ExtensionSet(string attribute, object value)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value });
_extensionCacheChanged = LoadState.Changed;
}
internal void AdvancedFilterSet(string attribute, object value, Type objectType, MatchType mt)
{
if (null == attribute)
throw new ArgumentException(SR.NullArguments);
ValidateExtensionObject(value);
if (value is object[])
_extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value, objectType, mt);
else
_extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value }, objectType, mt);
_extensionCacheChanged = LoadState.Changed; ;
}
//
// Internal implementation
//
// True indicates this is a new Principal object that has not yet been persisted to the store
internal bool unpersisted = false;
// True means our store object has been deleted
private bool _isDeleted = false;
// True means that StoreCtx.Load() has been called on this Principal to load in the values
// of all the delay-loaded properties.
private bool _loaded = false;
// True means this principal corresponds to one of the well-known SIDs that do not have a
// corresponding store object (e.g., NT AUTHORITY\NETWORK SERVICE). Such principals
// should be treated as read-only.
internal bool fakePrincipal = false;
// Directly corresponds to the Principal.PrincipalContext public property
private PrincipalContext _ctx = null;
internal bool Loaded
{
set
{
_loaded = value;
}
get
{
return _loaded;
}
}
// A low-level way for derived classes to access the ctx field. Note this is intended for internal use only,
// hence the LinkDemand.
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal protected PrincipalContext ContextRaw
{
get
{ return _ctx; }
set
{
// Verify that the passed context is not disposed.
if (value != null)
value.CheckDisposed();
_ctx = value;
}
}
static internal Principal MakePrincipal(PrincipalContext ctx, Type principalType)
{
Principal p = null;
System.Reflection.ConstructorInfo CI = principalType.GetConstructor(new Type[] { typeof(PrincipalContext) });
if (null == CI)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p = (Principal)CI.Invoke(new object[] { ctx });
if (null == p)
{
throw new NotSupportedException(SR.ExtensionInvalidClassDefinitionConstructor);
}
p.unpersisted = false;
return p;
}
// Depending on whether we're to-be-inserted or were retrieved from a query,
// returns the appropriate StoreCtx from the PrincipalContext that we should use for
// all StoreCtx-related operations.
// Returns null if no context has been set yet.
internal StoreCtx GetStoreCtxToUse()
{
if (_ctx == null)
{
Debug.Assert(this.unpersisted == true);
return null;
}
if (this.unpersisted)
{
return _ctx.ContextForType(this.GetType());
}
else
{
return _ctx.QueryCtx;
}
}
// The underlying object (e.g., DirectoryEntry, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this is a unpersisted principal and StoreCtx.PushChangesToNative()
// has not yet been called on it
private object _underlyingObject = null;
internal object UnderlyingObject
{
get
{
if (_underlyingObject != null)
return _underlyingObject;
return null;
}
set
{
_underlyingObject = value;
}
}
// The underlying search object (e.g., SearcResult, Item) corresponding to this Principal.
// Set by StoreCtx.GetAsPrincipal when this Principal was instantiated by it.
// If not set, this object was not created from a search. We need to store the searchresult until the object is persisted because
// we may need to load properties from it.
private object _underlyingSearchObject = null;
internal object UnderlyingSearchObject
{
get
{
if (_underlyingSearchObject != null)
return _underlyingSearchObject;
return null;
}
set
{
_underlyingSearchObject = value;
}
}
// Optional. This property exists entirely for the use of the StoreCtxs. When UnderlyingObject
// can correspond to more than one possible principal in the store (e.g., WinFS's "multiple principals
// per contact" model), the StoreCtx can use this to track and discern which principal in the
// UnderlyingObject this Principal object corresponds to. Set by GetAsPrincipal(), if set at all.
private object _discriminant = null;
internal object Discriminant
{
get { return _discriminant; }
set { _discriminant = value; }
}
// A store-specific key, used to determine if two CLR Principal objects represent the same store principal.
// Set by GetAsPrincipal when Principal is created from a query, or when a unpersisted Principal is persisted.
private StoreKey _key = null;
internal StoreKey Key
{
get { return _key; }
set { _key = value; }
}
private bool _disposed = false;
// Checks if the principal has been disposed or deleted, and throws an appropriate exception if it has.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected void CheckDisposedOrDeleted()
{
if (_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing disposed object");
throw new ObjectDisposedException(this.GetType().ToString());
}
if (_isDeleted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckDisposedOrDeleted: accessing deleted object");
throw new InvalidOperationException(SR.PrincipalDeleted);
}
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, string identityValue)
{
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
return FindByIdentityWithTypeHelper(context, principalType, null, identityValue, DateTime.UtcNow);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
protected static Principal FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, string identityValue)
{
if (context == null)
throw new ArgumentNullException("context");
if (identityValue == null)
throw new ArgumentNullException("identityValue");
if ((identityType < IdentityType.SamAccountName) || (identityType > IdentityType.Guid))
throw new InvalidEnumArgumentException("identityType", (int)identityType, typeof(IdentityType));
return FindByIdentityWithTypeHelper(context, principalType, identityType, identityValue, DateTime.UtcNow);
}
private static Principal FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable<IdentityType> identityType, string identityValue, DateTime refDate)
{
// Ask the store to find a Principal based on this IdentityReference info.
Principal p = context.QueryCtx.FindPrincipalByIdentRef(principalType, (identityType == null) ? null : (string)IdentMap.StringMap[(int)identityType, 1], identityValue, refDate);
// Did we find a match?
if (p != null)
{
// Given the native object, ask the StoreCtx to construct a Principal object for us.
return p;
}
else
{
// No match.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "FindByIdentityWithTypeHelper: no match");
return null;
}
}
private ResultSet GetGroupsHelper()
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Unpersisted principals are not members of any group
if (this.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: returning empty set");
return new EmptySet();
}
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetGroupsHelper: querying");
ResultSet resultSet = storeCtx.GetGroupsMemberOf(this);
return resultSet;
}
private ResultSet GetGroupsHelper(PrincipalContext contextToQuery)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
if (_ctx == null)
throw new InvalidOperationException(SR.UserMustSetContextForMethod);
StoreCtx storeCtx = GetStoreCtxToUse();
Debug.Assert(storeCtx != null);
return contextToQuery.QueryCtx.GetGroupsMemberOf(this, storeCtx);
}
// If we're the result of a query and our properties haven't been loaded yet, do so now
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void LoadIfNeeded(string principalPropertyName)
{
// Fake principals have nothing to load, since they have no store object.
// Just set the loaded flag.
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: not needed, fake principal");
Debug.Assert(this.unpersisted == false);
}
else if (!this.unpersisted)
{
// We came back from a query --> our PrincipalContext must be filled in
Debug.Assert(_ctx != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadIfNeeded: loading");
// Just load the requested property...
_ctx.QueryCtx.Load(this, principalPropertyName);
}
}
// Checks if this is a fake principal, and throws an appropriate exception if so.
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void CheckFakePrincipal()
{
if (this.fakePrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Principal", "CheckFakePrincipal: fake principal");
throw new InvalidOperationException(SR.PrincipalNotSupportedOnFakePrincipal);
}
}
// These methods implement the logic shared by all the get/set accessors for the public properties.
// We pass currentValue by ref, even though we don't directly modify it, because if the LoadIfNeeded()
// call causes the data to be loaded, we need to pick up the post-load value, not the (empty) value at the point
// HandleGet<T> was called.
//
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal T HandleGet<T>(ref T currentValue, string name, ref LoadState state)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
if (state == LoadState.NotSet)
{
// Load in the value, if not yet done so
LoadIfNeeded(name);
state = LoadState.Loaded;
}
return currentValue;
}
// We'd like this to be marked protected AND internal, but that's not possible, so we'll settle for
// internal and treat it as if it were also protected.
internal void HandleSet<T>(ref T currentValue, T newValue, ref LoadState state, string name)
{
// Make sure we're not disposed or deleted.
CheckDisposedOrDeleted();
// Check that we actually support this propery in our store
//CheckSupportedProperty(name);
// Need to do this now so that newly-set value doesn't get overwritten by later load
// LoadIfNeeded(name);
currentValue = newValue;
state = LoadState.Changed;
}
//
// Load/Store implementation
//
//
// Loading with query results
//
// Given a property name like "Principal.DisplayName",
// writes the value into the internal field backing that property and
// resets the change-tracking for that property to "unchanged".
//
// If the property is a scalar property, then value is simply an object of the property type
// (e.g., a string for a string-valued property).
// If the property is an IdentityClaimCollection property, then value must be a List<IdentityClaim>.
// If the property is a ValueCollection<T>, then value must be a List<T>.
// If the property is a X509Certificate2Collection, then value must be a List<byte[]>, where
// each byte[] is a certificate.
// (The property can never be a PrincipalCollection, since such properties
// are not loaded by StoreCtx.Load()).
// ExtensionCache is never directly loaded by the store hence it does not exist in the switch
internal virtual void LoadValueIntoProperty(string propertyName, object value)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value == null ? "null" : value.ToString()));
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
_displayName = (string)value;
_displayNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDescription:
_description = (string)value;
_descriptionChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSamAccountName:
_samName = (string)value;
_samNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalUserPrincipalName:
_userPrincipalName = (string)value;
_userPrincipalNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalSid:
SecurityIdentifier SID = (SecurityIdentifier)value;
_sid = SID;
_sidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalGuid:
Guid PrincipalGuid = (Guid)value;
_guid = PrincipalGuid;
_guidChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalDistinguishedName:
_distinguishedName = (string)value;
_distinguishedNameChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalStructuralObjectClass:
_structuralObjectClass = (string)value;
_structuralObjectClassChanged = LoadState.Loaded;
break;
case PropertyNames.PrincipalName:
_name = (string)value;
_nameChanged = LoadState.Loaded;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a Group, and they asked for PropertyNames.UserEmailAddress).
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal virtual bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetChangeStatusForProperty: name=" + propertyName);
LoadState currentPropState;
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
currentPropState = _displayNameChanged;
break;
case PropertyNames.PrincipalDescription:
currentPropState = _descriptionChanged;
break;
case PropertyNames.PrincipalSamAccountName:
currentPropState = _samNameChanged;
break;
case PropertyNames.PrincipalUserPrincipalName:
currentPropState = _userPrincipalNameChanged;
break;
case PropertyNames.PrincipalSid:
currentPropState = _sidChanged;
break;
case PropertyNames.PrincipalGuid:
currentPropState = _guidChanged;
break;
case PropertyNames.PrincipalDistinguishedName:
currentPropState = _distinguishedNameChanged;
break;
case PropertyNames.PrincipalStructuralObjectClass:
currentPropState = _structuralObjectClassChanged;
break;
case PropertyNames.PrincipalName:
currentPropState = _nameChanged;
break;
case PropertyNames.PrincipalExtensionCache:
currentPropState = _extensionCacheChanged;
break;
default:
// If we're here, we didn't find the property. They probably asked for a property we don't
// support (e.g., we're a User, and they asked for PropertyNames.GroupMembers). Since we don't
// have it, it didn't change.
currentPropState = LoadState.NotSet;
break;
}
return (currentPropState == LoadState.Changed);
}
// Given a property name, returns the current value for the property.
// Generally, this method is called only if GetChangeStatusForProperty indicates there are changes on the
// property specified.
//
// If the property is a scalar property, the return value is an object of the property type.
// If the property is an IdentityClaimCollection property, the return value is the IdentityClaimCollection
// itself.
// If the property is a ValueCollection<T>, the return value is the ValueCollection<T> itself.
// If the property is a X509Certificate2Collection, the return value is the X509Certificate2Collection itself.
// If the property is a PrincipalCollection, the return value is the PrincipalCollection itself.
internal virtual object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case PropertyNames.PrincipalDisplayName:
return _displayName;
case PropertyNames.PrincipalDescription:
return _description;
case PropertyNames.PrincipalSamAccountName:
return _samName;
case PropertyNames.PrincipalUserPrincipalName:
return _userPrincipalName;
case PropertyNames.PrincipalSid:
return _sid;
case PropertyNames.PrincipalGuid:
return _guid;
case PropertyNames.PrincipalDistinguishedName:
return _distinguishedName;
case PropertyNames.PrincipalStructuralObjectClass:
return _structuralObjectClass;
case PropertyNames.PrincipalName:
return _name;
case PropertyNames.PrincipalExtensionCache:
return _extensionCache;
default:
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "Principal.GetValueForProperty: Ran off end of list looking for {0}", propertyName));
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
// This is used by StoreCtx.Insert() and StoreCtx.Update() to reset the change-tracking after they
// have persisted all current changes to the store.
internal virtual void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "ResetAllChangeStatus");
_displayNameChanged = (_displayNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_descriptionChanged = (_descriptionChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_samNameChanged = (_samNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_userPrincipalNameChanged = (_userPrincipalNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_sidChanged = (_sidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_guidChanged = (_guidChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_distinguishedNameChanged = (_distinguishedNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_nameChanged = (_nameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_extensionCacheChanged = (_extensionCacheChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
/*******************************************************************************
* The MIT License (MIT)
* Copyright (c) 2015 Frank Benoit, Stuttgart, Germany <fr@nk-benoit.de>
*
* See the LICENSE.md or the online documentation:
* https://docs.google.com/document/d/1Wqa8rDi0QYcqcf0oecD8GW53nMVXj3ZFSmcF81zAa8g/edit#heading=h.2kvlhpr5zi2u
*
* Contributors:
* Frank Benoit - initial API and implementation
*******************************************************************************/
using System;
using System.Diagnostics;
using Org.Chabu.Prot.V1;
namespace Org.Chabu.Prot.V1.Internal
{
using global::System;
using ByteBuffer = Org.Chabu.Prot.Util.ByteBuffer;
using PrintWriter = global::System.IO.TextWriter;
/**
*
* @author Frank Benoit
*/
internal sealed class ChabuChannelImpl : ChabuChannel {
private int channelId = -1;
private ChabuImpl chabu;
private readonly ChabuRecvByteTarget recvTarget;
private readonly ChabuXmitByteSource xmitSource;
private int xmitSeq = 0;
private int xmitArm = 0;
private bool recvArmShouldBeXmit = false;
private int recvSeq = 0;
private int recvArm = 0;
private int priority = 0;
private ByteBuffer recvTargetBuffer;
private long xmitLimit;
private long xmitPosition;
private long recvLimit;
private long recvPosition;
public ChabuChannelImpl(int priority, ChabuRecvByteTarget recvTarget, ChabuXmitByteSource xmitSource) {
this.recvTarget = recvTarget;
this.xmitSource = xmitSource;
Utils.ensure(priority >= 0, ChabuErrorCode.CONFIGURATION_CH_PRIO, "priority must be >= 0, but is {0}", priority);
Utils.ensure(recvTarget != null, ChabuErrorCode.CONFIGURATION_CH_USER, "IChabuChannelUser must be non null");
Utils.ensure(xmitSource != null, ChabuErrorCode.CONFIGURATION_CH_USER, "IChabuChannelUser must be non null");
this.recvArmShouldBeXmit = true;
this.priority = priority;
}
internal void activate(ChabuImpl chabu, int channelId) {
this.chabu = chabu;
this.channelId = channelId;
chabu.channelXmitRequestArm(channelId);
recvTarget.SetChannel(this);
if (recvTarget != xmitSource) {
xmitSource.SetChannel(this);
}
}
internal void verifySeq(int packetSeq) {
Utils.ensure(this.recvSeq == packetSeq, ChabuErrorCode.PROTOCOL_DATA_OVERFLOW,
"Channel[{0}] received more seq but expected ({1} :: {2}). Violation of the SEQ value.\n >> {3}",
channelId, packetSeq, this.recvSeq, this);
}
internal int handleRecvSeq(ByteChannel byteChannel, int recvByteCount) {
int allowedRecv = this.recvArm - this.recvSeq;
int remainingBytes = recvByteCount;
Utils.ensure(remainingBytes <= allowedRecv, ChabuErrorCode.PROTOCOL_DATA_OVERFLOW,
"Channel[{0}] received more data ({1}) as it can take ({2}). Violation of the ARM value.", channelId, remainingBytes, allowedRecv);
int summedReadBytes = 0;
while (remainingBytes > 0) {
if (recvTargetBuffer == null) {
recvTargetBuffer = recvTarget.GetRecvBuffer(remainingBytes);
Utils.ensure(recvTargetBuffer != null, ChabuErrorCode.ASSERT,
"Channel[{0}] recvTargetBuffer is null.", channelId);
Utils.ensure(recvTargetBuffer.remaining() <= remainingBytes, ChabuErrorCode.ASSERT,
"Channel[{0}] recvTargetBuffer has more remaining ({1}) as requested ({2}).",
channelId, recvTargetBuffer.remaining(), remainingBytes);
Utils.ensure(recvTargetBuffer.remaining() > 0, ChabuErrorCode.ASSERT,
"Channel[{0}] recvTargetBuffer cannot take data.",
channelId);
}
int readBytes = byteChannel.read(recvTargetBuffer);
summedReadBytes += readBytes;
remainingBytes -= readBytes;
recvSeq += readBytes;
recvPosition += readBytes;
if (!recvTargetBuffer.hasRemaining()) {
recvTargetBuffer = null;
recvTarget.RecvCompleted();
}
if (readBytes == 0) {
// could not read => try next time
break;
}
}
return summedReadBytes;
}
/**
* Receive the ARM from the partner. This may make the channel to prepare new data to send.
* @param arm the value to update this.xmitArm to.
*/
internal void handleRecvArm(int arm) {
if (this.xmitArm != arm) {
// was blocked by receiver
// now the arm is updated
// --> try to send new data
if (XmitRemaining > 0) {
chabu.channelXmitRequestData(channelId);
}
}
this.xmitArm = arm;
}
internal void handleXmitCtrl(ChabuXmitterNormal xmitter, ByteBuffer xmitBuf) {
if (recvArmShouldBeXmit) {
recvArmShouldBeXmit = false;
xmitter.ProcessXmitArm(channelId, recvArm);
}
}
internal ByteBuffer handleXmitData(ChabuXmitterNormal xmitter, ByteBuffer xmitBuf, int maxSize) {
int davail = Math.Min(getXmitRemainingByRemote(), XmitRemaining);
if (davail == 0) {
//System.out.println("ChabuChannelImpl.handleXmitData() : called by no data available");
return null;
}
int pls = Math.Min(davail, maxSize);
ByteBuffer seqBuffer = xmitSource.GetXmitBuffer(pls);
int realPls = seqBuffer.remaining();
Utils.ensure(realPls > 0, ChabuErrorCode.ASSERT, "XmitSource gave buffer with no space");
Utils.ensure(realPls <= pls, ChabuErrorCode.ASSERT, "XmitSource gave buffer with more data than was requested");
xmitter.ProcessXmitSeq(channelId, xmitSeq, realPls);
xmitSeq += realPls;
xmitPosition += realPls;
return seqBuffer;
}
public String toString() {
return String.Format("Channel[{0} recvS:{1} recvA:{2} recvPostion:{3} recvLimit:{4} xmitS:{5} xmitA:{6} xmitPostion:{7} xmitLimit:{8}]", channelId, this.recvSeq, this.recvArm, this.recvPosition, this.recvLimit, this.xmitSeq, this.xmitArm, this.xmitPosition, this.xmitLimit);
}
public int ChannelId {
get
{
return channelId;
}
}
public int Priority {
get
{
return priority;
}
}
public long XmitLimit {
set {
int added = Utils.safePosInt(value - this.xmitLimit);
AddXmitLimit(added);
}
get {
return xmitLimit;
}
}
public long AddXmitLimit(int added) {
if( added > 0 ){
this.xmitLimit += added;
chabu.channelXmitRequestData(channelId);
}
return xmitLimit;
}
public int XmitRemaining {
get
{
return Utils.safePosInt( xmitLimit - xmitPosition );
}
}
public int getXmitRemainingByRemote() {
return xmitArm - xmitSeq;
}
public long XmitPosition
{
get
{
return xmitPosition;
}
}
/**
* Called from Chabu, when the SEQ packet was transmitted.
*/
public void seqPacketCompleted() {
xmitSource.XmitCompleted();
}
public long RecvLimit
{
set
{
int added = Utils.safePosInt(value - this.recvLimit);
AddRecvLimit(added);
}
get
{
return recvLimit;
}
}
public long AddRecvLimit(int added) {
recvLimit += added;
recvArm += added;
recvArmShouldBeXmit = true;
chabu.channelXmitRequestArm(channelId);
return recvLimit;
}
public long RecvPosition {
get
{
return recvPosition;
}
}
public long RecvRemaining {
get
{
return Utils.safePosInt(recvLimit - recvPosition);
}
}
}
}
| |
//
// System.Web.UI.DataBinderTests
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (c) 2002 Ximian, Inc. (http://www.ximian.com)
//
//#define NUNIT // Comment out this one if you wanna play with the test without using NUnit
#if NUNIT
using NUnit.Framework;
#else
using System.Reflection;
#endif
using System.IO;
using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Runtime.CompilerServices;
namespace MonoTests.System.Web.UI
{
#if NUNIT
public class DataBinderTests : TestCase
{
#else
public class DataBinderTests
{
#endif
#if NUNIT
public static ITest Suite
{
get {
return new TestSuite (typeof (PathTest));
}
}
public DataBinderTests () : base ("MonoTests.System.Web.UI.DataBinderTests testcase") { }
public DataBinderTests (string name) : base (name) { }
protected override void SetUp ()
{
#else
static DataBinderTests ()
{
#endif
instance = new ClassInstance ("instance");
instance.another = new ClassInstance ("another");
echo = new StringEcho();
}
static ClassInstance instance;
static StringEcho echo;
public void TestEval1 ()
{
try {
DataBinder.Eval (instance, "hello");
Fail ("Eval1 #1 didn't throw exception");
} catch (HttpException) {
}
object o = instance.Prop1;
AssertEquals ("Eval1 #2", DataBinder.Eval (instance, "Prop1"), o);
o = instance.Prop2;
AssertEquals ("Eval1 #3", DataBinder.Eval (instance, "Prop2"), o);
o = instance [0];
AssertEquals ("Eval1 #4", DataBinder.Eval (instance, "[0]"), o);
o = instance ["hi there!"];
AssertEquals ("Eval1 #4", DataBinder.Eval (instance, "[\"hi there!\"]"), o);
}
public void TestEval2 ()
{
try {
DataBinder.Eval (instance, "Another.hello");
Fail ("Eval2 #1 didn't throw exception");
} catch (HttpException) {
}
object o = instance.Another.Prop1;
AssertEquals ("Eval2 #2", DataBinder.Eval (instance, "Another.Prop1"), o);
o = instance.Another.Prop2;
AssertEquals ("Eval2 #3", DataBinder.Eval (instance, "Another.Prop2"), o);
o = instance.Another [0];
AssertEquals ("Eval2 #4", DataBinder.Eval (instance, "Another[0]"), o);
o = instance.Another ["hi there!"];
AssertEquals ("Eval2 #4", DataBinder.Eval (instance, "Another[\"hi there!\"]"), o);
AssertEquals ("Eval2 #5", DataBinder.Eval (instance,
"Another[\"hi there!\"] MS ignores this]"), o);
// MS gets fooled with this!!!
//AssertEquals ("Eval2 #4", DataBinder.Eval (instance, "Another[\"hi] there!\"]"), o);
}
public void TestEval3 ()
{
try {
DataBinder.Eval (echo, "[0]");
Fail ("Eval3 #1 didn't throw exception");
} catch (ArgumentException) {
}
AssertEquals ("Eval3 #2", DataBinder.Eval (echo, "[test]"), "test");
AssertEquals ("Eval3 #3", DataBinder.Eval (echo, "[\"test\"]"), "test");
AssertEquals ("Eval3 #4", DataBinder.Eval (echo, "['test']"), "test");
AssertEquals ("Eval3 #5", DataBinder.Eval (echo, "['test\"]"), "'test\"");
AssertEquals ("Eval3 #6", DataBinder.Eval (echo, "[\"test']"), "\"test'");
}
#if !NUNIT
void Assert (string msg, bool result)
{
if (!result)
Console.WriteLine (msg);
}
void AssertEquals (string msg, object expected, object real)
{
if (expected == null && real == null)
return;
if (expected != null && expected.Equals (real))
return;
Console.WriteLine ("{0}: expected: '{1}', got: '{2}'", msg, expected, real);
}
void Fail (string msg)
{
Console.WriteLine ("Failed: {0}", msg);
}
static void Main ()
{
DataBinderTests dbt = new DataBinderTests ();
Type t = typeof (DataBinderTests);
MethodInfo [] methods = t.GetMethods ();
foreach (MethodInfo m in methods) {
if (m.Name.Substring (0, 4) == "Test")
m.Invoke (dbt, null);
}
}
#endif
}
class ClassInstance
{
public string hello = "Hello";
public ClassInstance another;
string prefix;
public ClassInstance (string prefix)
{
this.prefix = prefix;
}
public object Prop1
{
get {
return prefix + "This is Prop1";
}
}
public object Prop2
{
get {
return prefix + "This is Prop2";
}
}
public object this [int index]
{
get {
return prefix + "This is the indexer for int. Index: " + index;
}
}
public object this [string index]
{
get {
return prefix + "This is the indexer for string. Index: " + index;
}
}
public ClassInstance Another
{
get {
return another;
}
}
}
class StringEcho
{
public object this [string msg] {
get { return msg; }
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Files.Core;
using ASC.Files.Core.Security;
using ASC.Security.Cryptography;
using ASC.Web.Files.Classes;
using Microsoft.OneDrive.Sdk;
using File = ASC.Files.Core.File;
using Folder = ASC.Files.Core.Folder;
namespace ASC.Files.Thirdparty.OneDrive
{
internal abstract class OneDriveDaoBase
{
protected readonly OneDriveDaoSelector OneDriveDaoSelector;
public int TenantID { get; private set; }
public OneDriveProviderInfo OneDriveProviderInfo { get; private set; }
public string PathPrefix { get; private set; }
protected OneDriveDaoBase(OneDriveDaoSelector.OneDriveInfo onedriveInfo, OneDriveDaoSelector onedriveDaoSelector)
{
OneDriveProviderInfo = onedriveInfo.OneDriveProviderInfo;
PathPrefix = onedriveInfo.PathPrefix;
OneDriveDaoSelector = onedriveDaoSelector;
TenantID = CoreContext.TenantManager.GetCurrentTenant().TenantId;
}
public void Dispose()
{
OneDriveProviderInfo.Dispose();
}
protected IDbManager GetDb()
{
return DbManager.FromHttpContext(FileConstant.DatabaseId);
}
protected object MappingID(object id, bool saveIfNotExist = false)
{
if (id == null) return null;
int n;
var isNumeric = int.TryParse(id.ToString(), out n);
if (isNumeric) return n;
object result;
using (var db = GetDb())
{
if (id.ToString().StartsWith("onedrive"))
{
result = Regex.Replace(BitConverter.ToString(Hasher.Hash(id.ToString(), HashAlg.MD5)), "-", "").ToLower();
}
else
{
result = db.ExecuteScalar<String>(Query("files_thirdparty_id_mapping")
.Select("id")
.Where(Exp.Eq("hash_id", id)));
}
if (saveIfNotExist)
{
db.ExecuteNonQuery(Insert("files_thirdparty_id_mapping")
.InColumnValue("id", id)
.InColumnValue("hash_id", result));
}
}
return result;
}
protected SqlQuery Query(string table)
{
return new SqlQuery(table).Where(GetTenantColumnName(table), TenantID);
}
protected SqlDelete Delete(string table)
{
return new SqlDelete(table).Where(GetTenantColumnName(table), TenantID);
}
protected SqlInsert Insert(string table)
{
return new SqlInsert(table, true).InColumns(GetTenantColumnName(table)).Values(TenantID);
}
private static string GetTenantColumnName(string table)
{
const string tenant = "tenant_id";
if (!table.Contains(" ")) return tenant;
return table.Substring(table.IndexOf(" ", StringComparison.InvariantCulture)).Trim() + "." + tenant;
}
protected static string MakeOneDriveId(object entryId)
{
var id = Convert.ToString(entryId, CultureInfo.InvariantCulture);
return string.IsNullOrEmpty(id)
? string.Empty
: id.TrimStart('/');
}
protected static string GetParentFolderId(Item onedriveItem)
{
return onedriveItem == null || IsRoot(onedriveItem)
? null
: (onedriveItem.ParentReference.Path.Equals(OneDriveStorage.RootPath, StringComparison.InvariantCultureIgnoreCase)
? String.Empty
: onedriveItem.ParentReference.Id);
}
protected string MakeId(Item onedriveItem)
{
var id = string.Empty;
if (onedriveItem != null)
{
id = onedriveItem.Id;
}
return MakeId(id);
}
protected string MakeId(string id = null)
{
return string.Format("{0}{1}", PathPrefix,
string.IsNullOrEmpty(id) || id == ""
? "" : ("-|" + id.TrimStart('/')));
}
public string MakeOneDrivePath(Item onedriveItem)
{
return onedriveItem == null || IsRoot(onedriveItem)
? string.Empty
: (OneDriveStorage.MakeOneDrivePath(
new Regex("^" + OneDriveStorage.RootPath).Replace(onedriveItem.ParentReference.Path, ""),
onedriveItem.Name));
}
protected String MakeItemTitle(Item onedriveItem)
{
if (onedriveItem == null || IsRoot(onedriveItem))
{
return OneDriveProviderInfo.CustomerTitle;
}
return Global.ReplaceInvalidCharsAndTruncate(onedriveItem.Name);
}
protected Folder ToFolder(Item onedriveFolder)
{
if (onedriveFolder == null) return null;
if (onedriveFolder is ErrorItem)
{
//Return error entry
return ToErrorFolder(onedriveFolder as ErrorItem);
}
if (onedriveFolder.Folder == null) return null;
var isRoot = IsRoot(onedriveFolder);
var folder = new Folder
{
ID = MakeId(isRoot ? string.Empty : onedriveFolder.Id),
ParentFolderID = isRoot ? null : MakeId(GetParentFolderId(onedriveFolder)),
CreateBy = OneDriveProviderInfo.Owner,
CreateOn = isRoot ? OneDriveProviderInfo.CreateOn : (onedriveFolder.CreatedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFolder.CreatedDateTime.Value.DateTime) : default(DateTime)),
FolderType = FolderType.DEFAULT,
ModifiedBy = OneDriveProviderInfo.Owner,
ModifiedOn = isRoot ? OneDriveProviderInfo.CreateOn : (onedriveFolder.LastModifiedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFolder.LastModifiedDateTime.Value.DateTime) : default(DateTime)),
ProviderId = OneDriveProviderInfo.ID,
ProviderKey = OneDriveProviderInfo.ProviderKey,
RootFolderCreator = OneDriveProviderInfo.Owner,
RootFolderId = MakeId(),
RootFolderType = OneDriveProviderInfo.RootFolderType,
Shareable = false,
Title = MakeItemTitle(onedriveFolder),
TotalFiles = 0,
TotalSubFolders = 0
};
return folder;
}
protected static bool IsRoot(Item onedriveFolder)
{
return onedriveFolder.ParentReference == null || onedriveFolder.ParentReference.Id == null;
}
private File ToErrorFile(ErrorItem onedriveFile)
{
if (onedriveFile == null) return null;
return new File
{
ID = MakeId(onedriveFile.ErrorId),
CreateBy = OneDriveProviderInfo.Owner,
CreateOn = TenantUtil.DateTimeNow(),
ModifiedBy = OneDriveProviderInfo.Owner,
ModifiedOn = TenantUtil.DateTimeNow(),
ProviderId = OneDriveProviderInfo.ID,
ProviderKey = OneDriveProviderInfo.ProviderKey,
RootFolderCreator = OneDriveProviderInfo.Owner,
RootFolderId = MakeId(),
RootFolderType = OneDriveProviderInfo.RootFolderType,
Title = MakeItemTitle(onedriveFile),
Error = onedriveFile.Error
};
}
private Folder ToErrorFolder(ErrorItem onedriveFolder)
{
if (onedriveFolder == null) return null;
return new Folder
{
ID = MakeId(onedriveFolder.ErrorId),
ParentFolderID = null,
CreateBy = OneDriveProviderInfo.Owner,
CreateOn = TenantUtil.DateTimeNow(),
FolderType = FolderType.DEFAULT,
ModifiedBy = OneDriveProviderInfo.Owner,
ModifiedOn = TenantUtil.DateTimeNow(),
ProviderId = OneDriveProviderInfo.ID,
ProviderKey = OneDriveProviderInfo.ProviderKey,
RootFolderCreator = OneDriveProviderInfo.Owner,
RootFolderId = MakeId(),
RootFolderType = OneDriveProviderInfo.RootFolderType,
Shareable = false,
Title = MakeItemTitle(onedriveFolder),
TotalFiles = 0,
TotalSubFolders = 0,
Error = onedriveFolder.Error
};
}
public File ToFile(Item onedriveFile)
{
if (onedriveFile == null) return null;
if (onedriveFile is ErrorItem)
{
//Return error entry
return ToErrorFile(onedriveFile as ErrorItem);
}
if (onedriveFile.File == null) return null;
return new File
{
ID = MakeId(onedriveFile.Id),
Access = FileShare.None,
ContentLength = onedriveFile.Size.HasValue ? (long)onedriveFile.Size : 0,
CreateBy = OneDriveProviderInfo.Owner,
CreateOn = onedriveFile.CreatedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFile.CreatedDateTime.Value.DateTime) : default(DateTime),
FileStatus = FileStatus.None,
FolderID = MakeId(GetParentFolderId(onedriveFile)),
ModifiedBy = OneDriveProviderInfo.Owner,
ModifiedOn = onedriveFile.LastModifiedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFile.LastModifiedDateTime.Value.DateTime) : default(DateTime),
NativeAccessor = onedriveFile,
ProviderId = OneDriveProviderInfo.ID,
ProviderKey = OneDriveProviderInfo.ProviderKey,
Title = MakeItemTitle(onedriveFile),
RootFolderId = MakeId(),
RootFolderType = OneDriveProviderInfo.RootFolderType,
RootFolderCreator = OneDriveProviderInfo.Owner,
Shared = false,
Version = 1
};
}
public Folder GetRootFolder(object folderId)
{
return ToFolder(GetOneDriveItem(""));
}
protected Item GetOneDriveItem(object itemId)
{
var onedriveId = MakeOneDriveId(itemId);
try
{
return OneDriveProviderInfo.GetOneDriveItem(onedriveId);
}
catch (Exception ex)
{
return new ErrorItem(ex, onedriveId);
}
}
protected IEnumerable<string> GetChildren(object folderId)
{
return GetOneDriveItems(folderId).Select(entry => MakeId(entry.Id));
}
protected List<Item> GetOneDriveItems(object parentId, bool? folder = null)
{
var onedriveFolderId = MakeOneDriveId(parentId);
var items = OneDriveProviderInfo.GetOneDriveItems(onedriveFolderId);
if (folder.HasValue)
{
if (folder.Value)
{
return items.Where(i => i.Folder != null).ToList();
}
return items.Where(i => i.File != null).ToList();
}
return items;
}
protected sealed class ErrorItem : Item
{
public string Error { get; set; }
public string ErrorId { get; private set; }
public ErrorItem(Exception e, object id)
{
ErrorId = id.ToString();
if (e != null)
{
Error = e.Message;
}
}
}
protected String GetAvailableTitle(String requestTitle, string parentFolderId, Func<string, string, bool> isExist)
{
requestTitle = new Regex("\\.$").Replace(requestTitle, "_");
if (!isExist(requestTitle, parentFolderId)) return requestTitle;
var re = new Regex(@"( \(((?<index>[0-9])+)\)(\.[^\.]*)?)$");
var match = re.Match(requestTitle);
if (!match.Success)
{
var insertIndex = requestTitle.Length;
if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1)
{
insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture);
}
requestTitle = requestTitle.Insert(insertIndex, " (1)");
}
while (isExist(requestTitle, parentFolderId))
{
requestTitle = re.Replace(requestTitle, MatchEvaluator);
}
return requestTitle;
}
private static String MatchEvaluator(Match match)
{
var index = Convert.ToInt32(match.Groups[2].Value);
var staticText = match.Value.Substring(String.Format(" ({0})", index).Length);
return String.Format(" ({0}){1}", index + 1, staticText);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Nest;
using Tests.Framework;
using System.Xml.Linq;
namespace Tests.Framework.Integration
{
public class ElasticsearchNode : IDisposable
{
private static readonly object _lock = new object();
// <installpath> <> <plugin folder prefix>
private readonly Dictionary<string, Func<string, string>> SupportedPlugins = new Dictionary<string, Func<string, string>>
{
//{ "delete-by-query", _ => "delete-by-query" },
//{ "cloud-azure", _ => "cloud-azure" },
//{ "mapper-attachments", MapperAttachmentPlugin.GetVersion },
//{ "mapper-murmur3", _ => "mapper-murmur3" },
};
private readonly bool _doNotSpawnIfAlreadyRunning;
private ObservableProcess _process;
private IDisposable _processListener;
public ElasticsearchVersionInfo VersionInfo { get; }
public string Binary { get; }
private string RoamingFolder { get; }
private string RoamingClusterFolder { get; }
public bool Started { get; private set; }
public bool RunningIntegrations { get; private set; }
public string Prefix { get; set; }
public string ClusterName { get; }
public string NodeName { get; }
public string RepositoryPath { get; private set; }
public ElasticsearchNodeInfo Info { get; private set; }
public int Port { get; private set; }
#if DOTNETCORE
// Investigate problem with ManualResetEvent on CoreClr
// Maybe due to .WaitOne() not taking exitContext?
public class Signal
{
private readonly object _lock = new object();
private bool _notified;
public Signal(bool initialState)
{
_notified = initialState;
}
public void Set()
{
lock (_lock)
{
if (!_notified)
{
_notified = true;
Monitor.Pulse(_lock);
}
}
}
public bool WaitOne(TimeSpan timeout, bool exitContext)
{
lock (_lock)
{
bool exit = true;
if (!_notified)
exit = Monitor.Wait(_lock, timeout);
return exit;
}
}
}
private readonly Subject<Signal> _blockingSubject = new Subject<Signal>();
public IObservable<Signal> BootstrapWork { get; }
#else
private readonly Subject<ManualResetEvent> _blockingSubject = new Subject<ManualResetEvent>();
public IObservable<ManualResetEvent> BootstrapWork { get; }
#endif
public ElasticsearchNode(
string elasticsearchVersion,
bool runningIntegrations,
bool doNotSpawnIfAlreadyRunning,
string prefix
)
{
_doNotSpawnIfAlreadyRunning = doNotSpawnIfAlreadyRunning;
this.VersionInfo = new ElasticsearchVersionInfo(runningIntegrations ? elasticsearchVersion : "0.0.0-unittest");
this.RunningIntegrations = runningIntegrations;
this.Prefix = prefix.ToLowerInvariant();
var suffix = Guid.NewGuid().ToString("N").Substring(0, 6);
this.ClusterName = $"{this.Prefix}-cluster-{suffix}";
this.NodeName = $"{this.Prefix}-node-{suffix}";
this.BootstrapWork = _blockingSubject;
var appData = GetApplicationDataDirectory();
this.RoamingFolder = Path.Combine(appData, "NEST", this.VersionInfo.Version + (this.VersionInfo.IsSnapshot ? $"-{VersionInfo.SnapshotIdentifier}" : string.Empty));
this.RoamingClusterFolder = Path.Combine(this.RoamingFolder, "elasticsearch-" + this.VersionInfo.Version);
this.RepositoryPath = Path.Combine(RoamingFolder, "repositories");
this.Binary = Path.Combine(this.RoamingClusterFolder, "bin", "elasticsearch") + ".bat";
if (!runningIntegrations)
{
this.Port = 9200;
return;
}
Console.WriteLine("========> {0}", this.RoamingFolder);
this.DownloadAndExtractElasticsearch();
}
private string GetApplicationDataDirectory()
{
#if DOTNETCORE
return Environment.GetEnvironmentVariable("APPDATA");
#else
return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
#endif
}
public IObservable<ElasticsearchMessage> Start(string[] additionalSettings = null)
{
if (!this.RunningIntegrations) return Observable.Empty<ElasticsearchMessage>();
this.Stop();
var timeout = TimeSpan.FromMinutes(1);
#if DOTNETCORE
var handle = new Signal(false);
#else
var handle = new ManualResetEvent(false);
#endif
if (_doNotSpawnIfAlreadyRunning)
{
var client = TestClient.GetClient();
var alreadyUp = client.RootNodeInfo();
if (alreadyUp.IsValid)
{
var checkPlugins = client.CatPlugins();
if (checkPlugins.IsValid)
{
foreach (var supportedPlugin in SupportedPlugins)
{
if (!checkPlugins.Records.Any(r => r.Component.Equals(supportedPlugin.Key)))
throw new Exception($"Already running elasticsearch does not have supported plugin {supportedPlugin.Key} installed.");
}
this.Started = true;
this.Port = 9200;
this.Info = new ElasticsearchNodeInfo(alreadyUp.Version.Number, null, alreadyUp.Version.LuceneVersion);
this._blockingSubject.OnNext(handle);
if (!handle.WaitOne(timeout, true))
throw new Exception($"Could not launch tests on already running elasticsearch within {timeout}");
return Observable.Empty<ElasticsearchMessage>();
}
}
}
var settingMarker = this.VersionInfo.ParsedVersion.Major >= 5 ? "-E " : "-D";
var settings = new []
{
$"es.cluster.name=\"{this.ClusterName}\"",
$"es.node.name={this.NodeName}",
$"es.path.repo=\"{this.RepositoryPath}\"",
$"es.script.inline=true",
$"es.script.indexed=true"
}.Concat(additionalSettings ?? Enumerable.Empty<string>())
.Select(s=> $"{settingMarker}{s}");
this._process = new ObservableProcess(this.Binary, settings.ToArray());
var observable = Observable.Using(() => this._process, process => process.Start())
.Select(consoleLine => new ElasticsearchMessage(consoleLine));
this._processListener = observable.Subscribe(onNext: s => HandleConsoleMessage(s, handle));
if (!handle.WaitOne(timeout, true))
{
this.Stop();
throw new Exception($"Could not start elasticsearch within {timeout}");
}
return observable;
}
#if DOTNETCORE
private void HandleConsoleMessage(ElasticsearchMessage s, Signal handle)
#else
private void HandleConsoleMessage(ElasticsearchMessage s, ManualResetEvent handle)
#endif
{
//no need to snoop for metadata if we already started
if (!this.RunningIntegrations || this.Started) return;
ElasticsearchNodeInfo info;
int port;
if (s.TryParseNodeInfo(out info))
{
this.Info = info;
}
else if (s.TryGetStartedConfirmation())
{
var healthyCluster = this.Client().ClusterHealth(g => g.WaitForStatus(WaitForStatus.Yellow).Timeout(TimeSpan.FromSeconds(30)));
if (healthyCluster.IsValid)
{
this._blockingSubject.OnNext(handle);
this.Started = true;
}
else
{
this._blockingSubject.OnError(new Exception("Did not see a healthy cluster after the node started for 30 seconds"));
handle.Set();
this.Stop();
}
}
else if (s.TryGetPortNumber(out port))
{
this.Port = port;
}
}
private void DownloadAndExtractElasticsearch()
{
lock (_lock)
{
var localZip = Path.Combine(this.RoamingFolder, this.VersionInfo.Zip);
Directory.CreateDirectory(this.RoamingFolder);
if (!File.Exists(localZip))
{
Console.WriteLine($"Download elasticsearch: {this.VersionInfo.Version} from {this.VersionInfo.DownloadUrl}");
new WebClient().DownloadFile(this.VersionInfo.DownloadUrl, localZip);
Console.WriteLine($"Downloaded elasticsearch: {this.VersionInfo.Version}");
}
if (!Directory.Exists(this.RoamingClusterFolder))
{
Console.WriteLine($"Unzipping elasticsearch: {this.VersionInfo.Version} ...");
ZipFile.ExtractToDirectory(localZip, this.RoamingFolder);
}
InstallPlugins();
//hunspell config
var hunspellFolder = Path.Combine(this.RoamingClusterFolder, "config", "hunspell", "en_US");
var hunspellPrefix = Path.Combine(hunspellFolder, "en_US");
if (!File.Exists(hunspellPrefix + ".dic"))
{
Directory.CreateDirectory(hunspellFolder);
//File.Create(hunspellPrefix + ".dic");
File.WriteAllText(hunspellPrefix + ".dic", "1\r\nabcdegf");
//File.Create(hunspellPrefix + ".aff");
File.WriteAllText(hunspellPrefix + ".aff", "SET UTF8\r\nSFX P Y 1\r\nSFX P 0 s");
}
var analysFolder = Path.Combine(this.RoamingClusterFolder, "config", "analysis");
if (!Directory.Exists(analysFolder)) Directory.CreateDirectory(analysFolder);
var fopXml = Path.Combine(analysFolder, "fop") + ".xml";
if (!File.Exists(fopXml)) File.WriteAllText(fopXml, "<languages-info />");
var customStems = Path.Combine(analysFolder, "custom_stems") + ".txt";
if (!File.Exists(customStems)) File.WriteAllText(customStems, "");
var stopwords = Path.Combine(analysFolder, "stopwords") + ".txt";
if (!File.Exists(stopwords)) File.WriteAllText(stopwords, "");
}
}
private void InstallPlugins()
{
var pluginCommand = "plugin";
if (this.VersionInfo.ParsedVersion.Major >= 5) pluginCommand = "elasticsearch-plugin";
var pluginBat = Path.Combine(this.RoamingClusterFolder, "bin", pluginCommand) + ".bat";
foreach (var plugin in SupportedPlugins)
{
var installPath = plugin.Key;
var command = plugin.Value(this.VersionInfo.Version);
var pluginFolder = Path.Combine(this.RoamingClusterFolder, "plugins", installPath);
if (!Directory.Exists(this.RoamingClusterFolder)) continue;
// assume plugin already installed
if (Directory.Exists(pluginFolder)) continue;
Console.WriteLine($"Installing elasticsearch plugin: {installPath} ...");
var timeout = TimeSpan.FromSeconds(120);
var handle = new ManualResetEvent(false);
Task.Run(() =>
{
using (var p = new ObservableProcess(pluginBat, "install", command))
{
var o = p.Start();
Console.WriteLine($"Calling: {pluginBat} install {command}");
o.Subscribe(e => Console.WriteLine(e),
(e) =>
{
Console.WriteLine($"Failed installing elasticsearch plugin: {command}");
handle.Set();
throw e;
},
() =>
{
Console.WriteLine($"Finished installing elasticsearch plugin: {installPath} exit code: {p.ExitCode}");
handle.Set();
});
if (!handle.WaitOne(timeout, true))
throw new Exception($"Could not install {command} within {timeout}");
}
});
if (!handle.WaitOne(timeout, true))
throw new Exception($"Could not install {command} within {timeout}");
}
}
public IElasticClient Client(Func<Uri, IConnectionPool> createPool, Func<ConnectionSettings, ConnectionSettings> settings)
{
var port = this.Started ? this.Port : 9200;
settings = settings ?? (s => s);
var client = TestClient.GetClient(s => AppendClusterNameToHttpHeaders(settings(s)), port, createPool);
return client;
}
public IElasticClient Client(Func<ConnectionSettings, ConnectionSettings> settings = null)
{
var port = this.Started ? this.Port : 9200;
settings = settings ?? (s => s);
var client = TestClient.GetClient(s => AppendClusterNameToHttpHeaders(settings(s)), port);
return client;
}
private ConnectionSettings AppendClusterNameToHttpHeaders(ConnectionSettings settings)
{
IConnectionConfigurationValues values = settings;
var headers = values.Headers ?? new NameValueCollection();
headers.Add("ClusterName", this.ClusterName);
return settings;
}
public void Stop()
{
if (!this.RunningIntegrations || !this.Started) return;
this.Started = false;
Console.WriteLine($"Stopping... ran integrations: {this.RunningIntegrations}");
Console.WriteLine($"Node started: {this.Started} on port: {this.Port} using PID: {this.Info?.Pid}");
this._process?.Dispose();
this._processListener?.Dispose();
if (this.Info?.Pid != null)
{
var esProcess = Process.GetProcessById(this.Info.Pid.Value);
Console.WriteLine($"Killing elasticsearch PID {this.Info.Pid}");
esProcess.Kill();
esProcess.WaitForExit(5000);
esProcess.Close();
}
if (this._doNotSpawnIfAlreadyRunning) return;
var dataFolder = Path.Combine(this.RoamingClusterFolder, "data", this.ClusterName);
if (Directory.Exists(dataFolder))
{
Console.WriteLine($"attempting to delete cluster data: {dataFolder}");
Directory.Delete(dataFolder, true);
}
//var logPath = Path.Combine(this.RoamingClusterFolder, "logs");
//var files = Directory.GetFiles(logPath, this.ClusterName + "*.log");
//foreach (var f in files)
//{
// Console.WriteLine($"attempting to delete log file: {f}");
// File.Delete(f);
//}
if (Directory.Exists(this.RepositoryPath))
{
Console.WriteLine("attempting to delete repositories");
Directory.Delete(this.RepositoryPath, true);
}
}
public void Dispose()
{
this.Stop();
}
}
public class ElasticsearchMessage
{
/*
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] version[1.5.2], pid[7704], build[62ff986/2015-04-27T09:21:06Z]
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] initializing ...
[2015-05-26 20:05:07,681][INFO ][plugins ] [Nick Fury] loaded [], sites []
[2015-05-26 20:05:10,790][INFO ][node ] [Nick Fury] initialized
[2015-05-26 20:05:10,821][INFO ][node ] [Nick Fury] starting ...
[2015-05-26 20:05:11,041][INFO ][transport ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/192.168.194.146:9300]}
[2015-05-26 20:05:11,056][INFO ][discovery ] [Nick Fury] elasticsearch-martijnl/yuiyXva3Si6sQE5tY_9CHg
[2015-05-26 20:05:14,103][INFO ][cluster.service ] [Nick Fury] new_master [Nick Fury][yuiyXva3Si6sQE5tY_9CHg][WIN-DK60SLEMH8C][inet[/192.168.194.146:9300]], reason: zen-disco-join (elected_as_master)
[2015-05-26 20:05:14,134][INFO ][gateway ] [Nick Fury] recovered [0] indices into cluster_state
[2015-05-26 20:05:14,150][INFO ][http ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/192.168.194.146:9200]}
[2015-05-26 20:05:14,150][INFO ][node ] [Nick Fury] started
*/
public DateTime Date { get; }
public string Level { get; }
public string Section { get; }
public string Node { get; }
public string Message { get; }
private static readonly Regex ConsoleLineParser =
new Regex(@"\[(?<date>.*?)\]\[(?<level>.*?)\]\[(?<section>.*?)\] \[(?<node>.*?)\] (?<message>.+)");
public ElasticsearchMessage(string consoleLine)
{
Console.WriteLine(consoleLine);
if (string.IsNullOrEmpty(consoleLine)) return;
var match = ConsoleLineParser.Match(consoleLine);
if (!match.Success) return;
var dateString = match.Groups["date"].Value.Trim();
Date = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss,fff", CultureInfo.CurrentCulture);
Level = match.Groups["level"].Value.Trim();
Section = match.Groups["section"].Value.Trim().Replace("org.elasticsearch.", "");
Node = match.Groups["node"].Value.Trim();
Message = match.Groups["message"].Value.Trim();
}
private static readonly Regex InfoParser =
new Regex(@"version\[(?<version>.*)\], pid\[(?<pid>.*)\], build\[(?<build>.+)\]");
public bool TryParseNodeInfo(out ElasticsearchNodeInfo nodeInfo)
{
nodeInfo = null;
if (this.Section != "node") return false;
var match = InfoParser.Match(this.Message);
if (!match.Success) return false;
var version = match.Groups["version"].Value.Trim();
var pid = match.Groups["pid"].Value.Trim();
var build = match.Groups["build"].Value.Trim();
nodeInfo = new ElasticsearchNodeInfo(version, pid, build);
return true;
}
public bool TryGetStartedConfirmation()
{
if (this.Section != "node") return false;
return this.Message == "started";
}
private static readonly Regex PortParser =
new Regex(@"bound_address(es)? {.+\:(?<port>\d+)}");
public bool TryGetPortNumber(out int port)
{
port = 0;
if (this.Section != "http") return false;
var match = PortParser.Match(this.Message);
if (!match.Success) return false;
var portString = match.Groups["port"].Value.Trim();
port = int.Parse(portString);
return true;
}
}
public class ElasticsearchNodeInfo
{
public string Version { get; }
public int? Pid { get; }
public string Build { get; }
public ElasticsearchNodeInfo(string version, string pid, string build)
{
this.Version = version;
if (!string.IsNullOrEmpty(pid))
Pid = int.Parse(pid);
Build = build;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Globalization;
using System.Linq;
using Dbg = System.Management.Automation.Diagnostics;
using System.Collections;
using System.Reflection;
namespace System.Management.Automation
{
/// <summary>
/// This is used for automatic conversions to be performed in shell variables.
/// </summary>
internal sealed class ArgumentTypeConverterAttribute : ArgumentTransformationAttribute
{
/// <summary>
/// This ctor form is used to initialize shell variables
/// whose type is not permitted to change.
/// </summary>
/// <param name="types"></param>
internal ArgumentTypeConverterAttribute(params Type[] types)
{
_convertTypes = types;
}
private Type[] _convertTypes;
internal Type TargetType
{
get
{
return _convertTypes == null
? null
: _convertTypes.LastOrDefault();
}
}
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
return Transform(engineIntrinsics, inputData, false, false);
}
internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
{
if (_convertTypes == null)
return inputData;
object result = inputData;
try
{
for (int i = 0; i < _convertTypes.Length; i++)
{
if (bindingParameters)
{
// We should not be doing a conversion here if [ref] is the last type.
// When [ref] appears in an argument list, it is used for checking only.
// No Conversion should be done.
if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
{
object temp;
PSObject mshObject = result as PSObject;
if (mshObject != null)
temp = mshObject.BaseObject;
else
temp = result;
PSReference reference = temp as PSReference;
if (reference == null)
{
throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
ExtendedTypeSystem.ReferenceTypeExpected);
}
}
else
{
object temp;
PSObject mshObject = result as PSObject;
if (mshObject != null)
temp = mshObject.BaseObject;
else
temp = result;
// If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
PSReference reference = temp as PSReference;
if (reference != null)
{
result = reference.Value;
}
if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
{
// Don't allow conversion from array to string in script w/ cmdlet binding. Allow
// the conversion for ordinary script parameter binding for V1 compatibility.
temp = PSObject.Base(result);
if (temp != null && temp.GetType().IsArray)
{
throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
ExtendedTypeSystem.InvalidCastCannotRetrieveString);
}
}
}
}
//BUGBUG
//NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
//handling special case for boolean, switchparameter and Nullable<bool>
//These parameter types will not be converted if the incoming value types are not
//one of the accepted categories - $true/$false or numbers (0 or otherwise)
if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
{
CheckBoolValue(result, _convertTypes[i]);
}
if (bindingScriptCmdlet)
{
// Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
// to stay compatible with V1.
ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection
&& LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
{
IList currentValueAsIList = ParameterBinderBase.GetIList(result);
if (currentValueAsIList != null)
{
foreach (object val in currentValueAsIList)
{
CheckBoolValue(val, collectionTypeInfo.ElementType);
}
}
else
{
CheckBoolValue(result, collectionTypeInfo.ElementType);
}
}
}
result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);
// Do validation of invalid direct variable assignments which are allowed to
// be used for parameters.
//
// Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
if ((!bindingScriptCmdlet) && (!bindingParameters))
{
// ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
// during variable assignment (here) - "Ignore" is blocked during variable retrieval.
if (_convertTypes[i] == typeof(ActionPreference))
{
ActionPreference resultPreference = (ActionPreference)result;
if (resultPreference == ActionPreference.Suspend)
{
throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
}
}
}
}
}
catch (PSInvalidCastException e)
{
throw new ArgumentTransformationMetadataException(e.Message, e);
}
return result;
}
private static void CheckBoolValue(object value, Type boolType)
{
if (value != null)
{
Type resultType = value.GetType();
if (resultType == typeof(PSObject))
resultType = ((PSObject)value).BaseObject.GetType();
if (!(LanguagePrimitives.IsNumeric(resultType.GetTypeCode()) ||
LanguagePrimitives.IsBoolOrSwitchParameterType(resultType)))
{
ThrowPSInvalidBooleanArgumentCastException(resultType, boolType);
}
}
else
{
bool isNullable = boolType.GetTypeInfo().IsGenericType &&
boolType.GetGenericTypeDefinition() == typeof(Nullable<>);
if (!isNullable && LanguagePrimitives.IsBooleanType(boolType))
{
ThrowPSInvalidBooleanArgumentCastException(null, boolType);
}
}
}
internal static void ThrowPSInvalidBooleanArgumentCastException(Type resultType, Type convertType)
{
throw new PSInvalidCastException("InvalidCastExceptionUnsupportedParameterType", null,
ExtendedTypeSystem.InvalidCastExceptionForBooleanArgumentValue,
resultType, convertType);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Threading;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2.
/// </summary>
#if !CORECLR
[SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")]
[Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210611")]
#endif
[OutputType(typeof(Job))]
public class ResumeJobCommand : JobCmdletBase, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Jobs objects which need to be
/// suspended.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = JobParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Job[] Job
{
get
{
return _jobs;
}
set
{
_jobs = value;
}
}
private Job[] _jobs;
/// <summary>
/// </summary>
public override string[] Command
{
get
{
return null;
}
}
/// <summary>
/// Specifies whether to delay returning from the cmdlet until all jobs reach a running state.
/// This could take significant time due to workflow throttling.
/// </summary>
[Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)]
public SwitchParameter Wait { get; set; }
#endregion Parameters
#region Overrides
/// <summary>
/// Resume the Job.
/// </summary>
protected override void ProcessRecord()
{
// List of jobs to resume
List<Job> jobsToResume = null;
switch (ParameterSetName)
{
case NameParameterSet:
{
jobsToResume = FindJobsMatchingByName(true, false, true, false);
}
break;
case InstanceIdParameterSet:
{
jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false);
}
break;
case SessionIdParameterSet:
{
jobsToResume = FindJobsMatchingBySessionId(true, false, true, false);
}
break;
case StateParameterSet:
{
jobsToResume = FindJobsMatchingByState(false);
}
break;
case FilterParameterSet:
{
jobsToResume = FindJobsMatchingByFilter(false);
}
break;
default:
{
jobsToResume = CopyJobsToList(_jobs, false, false);
}
break;
}
_allJobsToResume.AddRange(jobsToResume);
// Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state
// Setting Wait to true so that this cmdlet will wait for the running job state.
if (_allJobsToResume.Count == 1)
Wait = true;
foreach (Job job in jobsToResume)
{
var job2 = job as Job2;
// If the job is not Job2, the resume operation is not supported.
if (job2 == null)
{
WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
continue;
}
string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id);
if (ShouldProcess(targetString, VerbsLifecycle.Resume))
{
_cleanUpActions.Add(job2, HandleResumeJobCompleted);
job2.ResumeJobCompleted += HandleResumeJobCompleted;
lock (_syncObject)
{
if (!_pendingJobs.Contains(job2.InstanceId))
{
_pendingJobs.Add(job2.InstanceId);
}
}
job2.ResumeJobAsync();
}
}
}
private bool _warnInvalidState = false;
private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>();
private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false);
private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions =
new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>();
private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>();
private readonly List<Job> _allJobsToResume = new List<Job>();
private readonly object _syncObject = new object();
private bool _needToCheckForWaitingJobs;
private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
{
Job job = sender as Job;
if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException)
{
_warnInvalidState = true;
}
var parentJob = job as ContainerParentJob;
if (parentJob != null && parentJob.ExecutionError.Count > 0)
{
foreach (
var e in
parentJob.ExecutionError.Where(static e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError")
)
{
if (e.Exception is InvalidJobStateException)
{
// if any errors were invalid job state exceptions, warn the user.
// This is to support Get-Job | Resume-Job scenarios when many jobs
// are Completed, etc.
_warnInvalidState = true;
}
else
{
_errorsToWrite.Add(e);
}
}
parentJob.ExecutionError.Clear();
}
bool releaseWait = false;
lock (_syncObject)
{
if (_pendingJobs.Contains(job.InstanceId))
{
_pendingJobs.Remove(job.InstanceId);
}
if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0)
releaseWait = true;
}
// end processing has been called
// set waithandle if this is the last one
if (releaseWait)
_waitForJobs.Set();
}
/// <summary>
/// End Processing.
/// </summary>
protected override void EndProcessing()
{
bool jobsPending = false;
lock (_syncObject)
{
_needToCheckForWaitingJobs = true;
if (_pendingJobs.Count > 0)
jobsPending = true;
}
if (Wait && jobsPending)
_waitForJobs.WaitOne();
if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState);
foreach (var e in _errorsToWrite) WriteError(e);
foreach (var j in _allJobsToResume) WriteObject(j);
base.EndProcessing();
}
/// <summary>
/// </summary>
protected override void StopProcessing()
{
_waitForJobs.Set();
}
#endregion Overrides
#region Dispose
/// <summary>
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// </summary>
/// <param name="disposing"></param>
protected void Dispose(bool disposing)
{
if (!disposing) return;
foreach (var pair in _cleanUpActions)
{
pair.Key.ResumeJobCompleted -= pair.Value;
}
_waitForJobs.Dispose();
}
#endregion Dispose
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary.IO
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
/// <summary>
/// Binary onheap stream.
/// </summary>
internal unsafe class BinaryHeapStream : BinaryStreamBase
{
/** Data array. */
private byte[] _data;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cap">Initial capacity.</param>
public BinaryHeapStream(int cap)
{
Debug.Assert(cap >= 0);
_data = new byte[cap];
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="data">Data array.</param>
public BinaryHeapStream(byte[] data)
{
Debug.Assert(data != null);
_data = data;
}
/** <inheritdoc /> */
public override void WriteByte(byte val)
{
int pos0 = EnsureWriteCapacityAndShift(1);
_data[pos0] = val;
}
/** <inheritdoc /> */
public override byte ReadByte()
{
int pos0 = EnsureReadCapacityAndShift(1);
return _data[pos0];
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteByteArray(byte[] val)
{
int pos0 = EnsureWriteCapacityAndShift(val.Length);
fixed (byte* data0 = _data)
{
WriteByteArray0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override byte[] ReadByteArray(int cnt)
{
int pos0 = EnsureReadCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
return ReadByteArray0(cnt, data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteBoolArray(bool[] val)
{
int pos0 = EnsureWriteCapacityAndShift(val.Length);
fixed (byte* data0 = _data)
{
WriteBoolArray0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override bool[] ReadBoolArray(int cnt)
{
int pos0 = EnsureReadCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
return ReadBoolArray0(cnt, data0 + pos0);
}
}
/** <inheritdoc /> */
public override void WriteShort(short val)
{
int pos0 = EnsureWriteCapacityAndShift(2);
fixed (byte* data0 = _data)
{
WriteShort0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override short ReadShort()
{
int pos0 = EnsureReadCapacityAndShift(2);
fixed (byte* data0 = _data)
{
return ReadShort0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteShortArray(short[] val)
{
int cnt = val.Length << 1;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteShortArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override short[] ReadShortArray(int cnt)
{
int cnt0 = cnt << 1;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadShortArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteCharArray(char[] val)
{
int cnt = val.Length << 1;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteCharArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override char[] ReadCharArray(int cnt)
{
int cnt0 = cnt << 1;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadCharArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override void WriteInt(int val)
{
int pos0 = EnsureWriteCapacityAndShift(4);
fixed (byte* data0 = _data)
{
WriteInt0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override void WriteInt(int writePos, int val)
{
EnsureWriteCapacity(writePos + 4);
fixed (byte* data0 = _data)
{
WriteInt0(val, data0 + writePos);
}
}
/** <inheritdoc /> */
public override int ReadInt()
{
int pos0 = EnsureReadCapacityAndShift(4);
fixed (byte* data0 = _data)
{
return ReadInt0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteIntArray(int[] val)
{
int cnt = val.Length << 2;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteIntArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override int[] ReadIntArray(int cnt)
{
int cnt0 = cnt << 2;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadIntArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteFloatArray(float[] val)
{
int cnt = val.Length << 2;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteFloatArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override float[] ReadFloatArray(int cnt)
{
int cnt0 = cnt << 2;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadFloatArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override void WriteLong(long val)
{
int pos0 = EnsureWriteCapacityAndShift(8);
fixed (byte* data0 = _data)
{
WriteLong0(val, data0 + pos0);
}
}
/** <inheritdoc /> */
public override long ReadLong()
{
int pos0 = EnsureReadCapacityAndShift(8);
fixed (byte* data0 = _data)
{
return ReadLong0(data0 + pos0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteLongArray(long[] val)
{
int cnt = val.Length << 3;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteLongArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override long[] ReadLongArray(int cnt)
{
int cnt0 = cnt << 3;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadLongArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override void WriteDoubleArray(double[] val)
{
int cnt = val.Length << 3;
int pos0 = EnsureWriteCapacityAndShift(cnt);
fixed (byte* data0 = _data)
{
WriteDoubleArray0(val, data0 + pos0, cnt);
}
}
/** <inheritdoc /> */
public override double[] ReadDoubleArray(int cnt)
{
int cnt0 = cnt << 3;
int pos0 = EnsureReadCapacityAndShift(cnt0);
fixed (byte* data0 = _data)
{
return ReadDoubleArray0(cnt, data0 + pos0, cnt0);
}
}
/** <inheritdoc /> */
public override int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding)
{
int pos0 = EnsureWriteCapacityAndShift(byteCnt);
int written;
fixed (byte* data0 = _data)
{
written = BinaryUtils.StringToUtf8Bytes(chars, charCnt, byteCnt, encoding, data0 + pos0);
}
return written;
}
/** <inheritdoc /> */
public override void Write(byte* src, int cnt)
{
EnsureWriteCapacity(Pos + cnt);
fixed (byte* data0 = _data)
{
WriteInternal(src, cnt, data0);
}
ShiftWrite(cnt);
}
/** <inheritdoc /> */
public override void Read(byte* dest, int cnt)
{
fixed (byte* data0 = _data)
{
ReadInternal(data0, dest, cnt);
}
}
/** <inheritdoc /> */
public override int Remaining
{
get { return _data.Length - Pos; }
}
/** <inheritdoc /> */
public override byte[] GetArray()
{
return _data;
}
/** <inheritdoc /> */
public override byte[] GetArrayCopy()
{
byte[] copy = new byte[Pos];
Buffer.BlockCopy(_data, 0, copy, 0, Pos);
return copy;
}
/** <inheritdoc /> */
public override bool IsSameArray(byte[] arr)
{
return _data == arr;
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public override T Apply<TArg, T>(IBinaryStreamProcessor<TArg, T> proc, TArg arg)
{
Debug.Assert(proc != null);
fixed (byte* data0 = _data)
{
return proc.Invoke(data0, arg);
}
}
/** <inheritdoc /> */
protected override void Dispose(bool disposing)
{
// No-op.
}
/// <summary>
/// Internal array.
/// </summary>
internal byte[] InternalArray
{
get { return _data; }
}
/** <inheritdoc /> */
protected override void EnsureWriteCapacity(int cnt)
{
if (cnt > _data.Length)
{
int newCap = Capacity(_data.Length, cnt);
byte[] data0 = new byte[newCap];
// Copy the whole initial array length here because it can be changed
// from Java without position adjusting.
Buffer.BlockCopy(_data, 0, data0, 0, _data.Length);
_data = data0;
}
}
/** <inheritdoc /> */
protected override void EnsureReadCapacity(int cnt)
{
if (_data.Length - Pos < cnt)
throw new EndOfStreamException("Not enough data in stream [expected=" + cnt +
", remaining=" + (_data.Length - Pos) + ']');
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RecoveryPointsOperations operations.
/// </summary>
internal partial class RecoveryPointsOperations : IServiceOperations<RecoveryServicesBackupClient>, IRecoveryPointsOperations
{
/// <summary>
/// Initializes a new instance of the RecoveryPointsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RecoveryPointsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Lists the backup copies for the backed up item.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item whose backup copies are to be fetched.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecoveryPointResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ODataQuery<BMSRPQueryObject> odataQuery = default(ODataQuery<BMSRPQueryObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RecoveryPointResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Provides the information of the backed up data identified using
/// RecoveryPointID. This is an asynchronous operation. To know the status of
/// the operation, call the GetProtectedItemOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose backup data needs to be fetched.
/// </param>
/// <param name='recoveryPointId'>
/// RecoveryPointID represents the backed up data to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RecoveryPointResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName");
}
if (recoveryPointId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "recoveryPointId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("recoveryPointId", recoveryPointId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
_url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecoveryPointResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RecoveryPointResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the backup copies for the backed up item.
/// </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="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RecoveryPointResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RecoveryPointResource>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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 System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
internal class Utils
{
// The maximum number of characters in an XML document (0 means no limit).
internal const int MaxCharactersInDocument = 0;
// The entity expansion limit. This is used to prevent entity expansion denial of service attacks.
internal const long MaxCharactersFromEntities = (long)1e7;
// The default XML Dsig recursion limit.
// This should be within limits of real world scenarios.
// Keeping this number low will preserve some stack space
internal const int XmlDsigSearchDepth = 20;
private Utils() { }
private static bool HasNamespace(XmlElement element, string prefix, string value)
{
if (IsCommittedNamespace(element, prefix, value)) return true;
if (element.Prefix == prefix && element.NamespaceURI == value) return true;
return false;
}
// A helper function that determines if a namespace node is a committed attribute
internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns");
if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true;
return false;
}
internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
XmlNode ancestorNode = ((XmlNode)element).ParentNode;
while (ancestorNode != null)
{
XmlElement ancestorElement = ancestorNode as XmlElement;
if (ancestorElement != null)
if (HasNamespace(ancestorElement, prefix, value)) return true;
ancestorNode = ancestorNode.ParentNode;
}
return false;
}
internal static string GetAttribute(XmlElement element, string localName, string namespaceURI)
{
string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null);
if (s == null && element.HasAttribute(localName, namespaceURI))
s = element.GetAttribute(localName, namespaceURI);
return s;
}
internal static bool HasAttribute(XmlElement element, string localName, string namespaceURI)
{
return element.HasAttribute(localName) || element.HasAttribute(localName, namespaceURI);
}
internal static bool IsNamespaceNode(XmlNode n)
{
return n.NodeType == XmlNodeType.Attribute && (n.Prefix.Equals("xmlns") || (n.Prefix.Length == 0 && n.LocalName.Equals("xmlns")));
}
internal static bool IsXmlNamespaceNode(XmlNode n)
{
return n.NodeType == XmlNodeType.Attribute && n.Prefix.Equals("xml");
}
// We consider xml:space style attributes as default namespace nodes since they obey the same propagation rules
internal static bool IsDefaultNamespaceNode(XmlNode n)
{
bool b1 = n.NodeType == XmlNodeType.Attribute && n.Prefix.Length == 0 && n.LocalName.Equals("xmlns");
bool b2 = IsXmlNamespaceNode(n);
return b1 || b2;
}
internal static bool IsEmptyDefaultNamespaceNode(XmlNode n)
{
return IsDefaultNamespaceNode(n) && n.Value.Length == 0;
}
internal static string GetNamespacePrefix(XmlAttribute a)
{
Debug.Assert(IsNamespaceNode(a) || IsXmlNamespaceNode(a));
return a.Prefix.Length == 0 ? string.Empty : a.LocalName;
}
internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix)
{
return GetNamespacePrefix(a).Equals(nsPrefix);
}
internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix)
{
if (nearestAncestorWithSamePrefix == null)
return !IsEmptyDefaultNamespaceNode(a);
else
return !nearestAncestorWithSamePrefix.Value.Equals(a.Value);
}
internal static bool IsXmlPrefixDefinitionNode(XmlAttribute a)
{
return false;
// return a.Prefix.Equals("xmlns") && a.LocalName.Equals("xml") && a.Value.Equals(NamespaceUrlForXmlPrefix);
}
internal static string DiscardWhiteSpaces(string inputBuffer)
{
return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length);
}
internal static string DiscardWhiteSpaces(string inputBuffer, int inputOffset, int inputCount)
{
int i, iCount = 0;
for (i = 0; i < inputCount; i++)
if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++;
char[] rgbOut = new char[inputCount - iCount];
iCount = 0;
for (i = 0; i < inputCount; i++)
if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i]))
{
rgbOut[iCount++] = inputBuffer[inputOffset + i];
}
return new string(rgbOut);
}
internal static void SBReplaceCharWithString(StringBuilder sb, char oldChar, string newString)
{
int i = 0;
int newStringLength = newString.Length;
while (i < sb.Length)
{
if (sb[i] == oldChar)
{
sb.Remove(i, 1);
sb.Insert(i, newString);
i += newStringLength;
}
else i++;
}
}
internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver xmlResolver, string baseUri)
{
XmlReaderSettings settings = GetSecureXmlReaderSettings(xmlResolver);
XmlReader reader = XmlReader.Create(inputStream, settings, baseUri);
return reader;
}
internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlResolver)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
return settings;
}
internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
MyXmlDocument doc = new MyXmlDocument();
doc.PreserveWhitespace = document.PreserveWhitespace;
// Normalize the document
using (TextReader stringReader = new StringReader(document.OuterXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
XmlReader reader = XmlReader.Create(stringReader, settings, baseUri);
doc.Load(reader);
}
return doc;
}
internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri)
{
if (elem == null)
throw new ArgumentNullException(nameof(elem));
MyXmlDocument doc = new MyXmlDocument();
doc.PreserveWhitespace = true;
// Normalize the document
using (TextReader stringReader = new StringReader(elem.OuterXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
XmlReader reader = XmlReader.Create(stringReader, settings, baseUri);
doc.Load(reader);
}
return doc;
}
internal static XmlDocument DiscardComments(XmlDocument document)
{
XmlNodeList nodeList = document.SelectNodes("//comment()");
if (nodeList != null)
{
foreach (XmlNode node1 in nodeList)
{
node1.ParentNode.RemoveChild(node1);
}
}
return document;
}
internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments)
{
CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList();
CanonicalXmlNodeList elementList = new CanonicalXmlNodeList();
CanonicalXmlNodeList attribList = new CanonicalXmlNodeList();
CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList();
int index = 0;
elementList.Add(node);
do
{
XmlNode rootNode = (XmlNode)elementList[index];
// Add the children nodes
XmlNodeList childNodes = rootNode.ChildNodes;
if (childNodes != null)
{
foreach (XmlNode node1 in childNodes)
{
if (includeComments || (!(node1 is XmlComment)))
{
elementList.Add(node1);
}
}
}
// Add the attribute nodes
XmlAttributeCollection attribNodes = rootNode.Attributes;
if (attribNodes != null)
{
foreach (XmlNode attribNode in rootNode.Attributes)
{
if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns")
namespaceList.Add(attribNode);
else
attribList.Add(attribNode);
}
}
index++;
} while (index < elementList.Count);
foreach (XmlNode elementNode in elementList)
{
nodeList.Add(elementNode);
}
foreach (XmlNode attribNode in attribList)
{
nodeList.Add(attribNode);
}
foreach (XmlNode namespaceNode in namespaceList)
{
nodeList.Add(namespaceNode);
}
return nodeList;
}
internal static bool NodeInList(XmlNode node, XmlNodeList nodeList)
{
foreach (XmlNode nodeElem in nodeList)
{
if (nodeElem == node) return true;
}
return false;
}
internal static string GetIdFromLocalUri(string uri, out bool discardComments)
{
string idref = uri.Substring(1);
// initialize the return value
discardComments = true;
// Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional
if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal))
{
int startId = idref.IndexOf("id(", StringComparison.Ordinal);
int endId = idref.IndexOf(")", StringComparison.Ordinal);
if (endId < 0 || endId < startId + 3)
throw new CryptographicException(SR.Cryptography_Xml_InvalidReference);
idref = idref.Substring(startId + 3, endId - startId - 3);
idref = idref.Replace("\'", "");
idref = idref.Replace("\"", "");
discardComments = false;
}
return idref;
}
internal static string ExtractIdFromLocalUri(string uri)
{
string idref = uri.Substring(1);
// Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional
if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal))
{
int startId = idref.IndexOf("id(", StringComparison.Ordinal);
int endId = idref.IndexOf(")", StringComparison.Ordinal);
if (endId < 0 || endId < startId + 3)
throw new CryptographicException(SR.Cryptography_Xml_InvalidReference);
idref = idref.Substring(startId + 3, endId - startId - 3);
idref = idref.Replace("\'", "");
idref = idref.Replace("\"", "");
}
return idref;
}
// This removes all children of an element.
internal static void RemoveAllChildren(XmlElement inputElement)
{
XmlNode child = inputElement.FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
inputElement.RemoveChild(child);
child = sibling;
}
}
// Writes one stream (starting from the current position) into
// an output stream, connecting them up and reading until
// hitting the end of the input stream.
// returns the number of bytes copied
internal static long Pump(Stream input, Stream output)
{
// Use MemoryStream's WriteTo(Stream) method if possible
MemoryStream inputMS = input as MemoryStream;
if (inputMS != null && inputMS.Position == 0)
{
inputMS.WriteTo(output);
return inputMS.Length;
}
const int count = 4096;
byte[] bytes = new byte[count];
int numBytes;
long totalBytes = 0;
while ((numBytes = input.Read(bytes, 0, count)) > 0)
{
output.Write(bytes, 0, numBytes);
totalBytes += numBytes;
}
return totalBytes;
}
internal static Hashtable TokenizePrefixListString(string s)
{
Hashtable set = new Hashtable();
if (s != null)
{
string[] prefixes = s.Split(null);
foreach (string prefix in prefixes)
{
if (prefix.Equals("#default"))
{
set.Add(string.Empty, true);
}
else if (prefix.Length > 0)
{
set.Add(prefix, true);
}
}
}
return set;
}
internal static string EscapeWhitespaceData(string data)
{
StringBuilder sb = new StringBuilder();
sb.Append(data);
Utils.SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString(); ;
}
internal static string EscapeTextData(string data)
{
StringBuilder sb = new StringBuilder();
sb.Append(data);
sb.Replace("&", "&");
sb.Replace("<", "<");
sb.Replace(">", ">");
SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString(); ;
}
internal static string EscapeCData(string data)
{
return EscapeTextData(data);
}
internal static string EscapeAttributeValue(string value)
{
StringBuilder sb = new StringBuilder();
sb.Append(value);
sb.Replace("&", "&");
sb.Replace("<", "<");
sb.Replace("\"", """);
SBReplaceCharWithString(sb, (char)9, "	");
SBReplaceCharWithString(sb, (char)10, "
");
SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString();
}
internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList)
{
foreach (XmlNode node in nodeList)
{
if (node.OwnerDocument != null)
return node.OwnerDocument;
}
return null;
}
internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces)
{
if (namespaces != null)
{
foreach (XmlNode attrib in namespaces)
{
string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
// Skip the attribute if one with the same qualified name already exists
if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) continue;
XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = attrib.Value;
elem.SetAttributeNode(nsattrib);
}
}
}
internal static void AddNamespaces(XmlElement elem, Hashtable namespaces)
{
if (namespaces != null)
{
foreach (string key in namespaces.Keys)
{
if (elem.HasAttribute(key)) continue;
XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(key);
nsattrib.Value = namespaces[key] as string;
elem.SetAttributeNode(nsattrib);
}
}
}
// This method gets the attributes that should be propagated
internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem)
{
if (elem == null)
return null;
CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList();
XmlNode ancestorNode = elem;
if (ancestorNode == null) return null;
bool bDefNamespaceToAdd = true;
while (ancestorNode != null)
{
XmlElement ancestorElement = ancestorNode as XmlElement;
if (ancestorElement == null)
{
ancestorNode = ancestorNode.ParentNode;
continue;
}
if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI))
{
// Add the namespace attribute to the collection if needed
if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI))
{
string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns");
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = ancestorElement.NamespaceURI;
namespaces.Add(nsattrib);
}
}
if (ancestorElement.HasAttributes)
{
XmlAttributeCollection attribs = ancestorElement.Attributes;
foreach (XmlAttribute attrib in attribs)
{
// Add a default namespace if necessary
if (bDefNamespaceToAdd && attrib.LocalName == "xmlns")
{
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns");
nsattrib.Value = attrib.Value;
namespaces.Add(nsattrib);
bDefNamespaceToAdd = false;
continue;
}
// retain the declarations of type 'xml:*' as well
if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml")
{
namespaces.Add(attrib);
continue;
}
if (attrib.NamespaceURI.Length > 0)
{
if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI))
{
// Add the namespace attribute to the collection if needed
if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI))
{
string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns");
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = attrib.NamespaceURI;
namespaces.Add(nsattrib);
}
}
}
}
}
ancestorNode = ancestorNode.ParentNode;
}
return namespaces;
}
// output of this routine is always big endian
internal static byte[] ConvertIntToByteArray(int dwInput)
{
byte[] rgbTemp = new byte[8]; // int can never be greater than Int64
int t1; // t1 is remaining value to account for
int t2; // t2 is t1 % 256
int i = 0;
if (dwInput == 0) return new byte[1];
t1 = dwInput;
while (t1 > 0)
{
t2 = t1 % 256;
rgbTemp[i] = (byte)t2;
t1 = (t1 - t2) / 256;
i++;
}
// Now, copy only the non-zero part of rgbTemp and reverse
byte[] rgbOutput = new byte[i];
// copy and reverse in one pass
for (int j = 0; j < i; j++)
{
rgbOutput[j] = rgbTemp[i - j - 1];
}
return rgbOutput;
}
internal static int ConvertByteArrayToInt(byte[] input)
{
// Input to this routine is always big endian
int dwOutput = 0;
for (int i = 0; i < input.Length; i++)
{
dwOutput *= 256;
dwOutput += input[i];
}
return (dwOutput);
}
internal static int GetHexArraySize(byte[] hex)
{
int index = hex.Length;
while (index-- > 0)
{
if (hex[index] != 0)
break;
}
return index + 1;
}
internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType)
{
X509Certificate2Collection collection = new X509Certificate2Collection();
ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null);
if (keyInfoX509Data.Certificates != null)
{
foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates)
{
switch (certUsageType)
{
case CertUsageType.Verification:
collection.Add(certificate);
break;
case CertUsageType.Decryption:
decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
break;
}
}
}
if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null &&
keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null)
return collection;
// Open LocalMachine and CurrentUser "Other People"/"My" stores.
X509Store[] stores = new X509Store[2];
string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My");
stores[0] = new X509Store(storeName, StoreLocation.CurrentUser);
stores[1] = new X509Store(storeName, StoreLocation.LocalMachine);
for (int index = 0; index < stores.Length; index++)
{
if (stores[index] != null)
{
X509Certificate2Collection filters = null;
// We don't care if we can't open the store.
try
{
stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
filters = stores[index].Certificates;
stores[index].Close();
if (keyInfoX509Data.SubjectNames != null)
{
foreach (string subjectName in keyInfoX509Data.SubjectNames)
{
filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
}
}
if (keyInfoX509Data.IssuerSerials != null)
{
foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials)
{
filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
}
}
if (keyInfoX509Data.SubjectKeyIds != null)
{
foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds)
{
string hex = EncodeHexString(ski);
filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false);
}
}
if (decryptionIssuerSerials != null)
{
foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials)
{
filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
}
}
}
catch (CryptographicException) { }
if (filters != null)
collection.AddRange(filters);
}
}
return collection;
}
private static readonly char[] s_hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
internal static string EncodeHexString(byte[] sArray)
{
return EncodeHexString(sArray, 0, (uint)sArray.Length);
}
internal static string EncodeHexString(byte[] sArray, uint start, uint end)
{
string result = null;
if (sArray != null)
{
char[] hexOrder = new char[(end - start) * 2];
uint digit;
for (uint i = start, j = 0; i < end; i++)
{
digit = (uint)((sArray[i] & 0xf0) >> 4);
hexOrder[j++] = s_hexValues[digit];
digit = (uint)(sArray[i] & 0x0f);
hexOrder[j++] = s_hexValues[digit];
}
result = new String(hexOrder);
}
return result;
}
internal static byte[] DecodeHexString(string s)
{
string hexString = Utils.DiscardWhiteSpaces(s);
uint cbHex = (uint)hexString.Length / 2;
byte[] hex = new byte[cbHex];
int i = 0;
for (int index = 0; index < cbHex; index++)
{
hex[index] = (byte)((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i + 1]));
i += 2;
}
return hex;
}
internal static byte HexToByte(char val)
{
if (val <= '9' && val >= '0')
return (byte)(val - '0');
else if (val >= 'a' && val <= 'f')
return (byte)((val - 'a') + 10);
else if (val >= 'A' && val <= 'F')
return (byte)((val - 'A') + 10);
else
return 0xFF;
}
internal static bool IsSelfSigned(X509Chain chain)
{
X509ChainElementCollection elements = chain.ChainElements;
if (elements.Count != 1)
return false;
X509Certificate2 certificate = elements[0].Certificate;
if (String.Compare(certificate.SubjectName.Name, certificate.IssuerName.Name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
return false;
}
internal static AsymmetricAlgorithm GetAnyPublicKey(X509Certificate2 certificate)
{
return (AsymmetricAlgorithm)certificate.GetRSAPublicKey();
}
}
}
| |
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Provides support for converting byte sequences to <see cref="string"/>s and back again.
/// The resulting <see cref="string"/>s preserve the original byte sequences' sort order.
/// <para/>
/// The <see cref="string"/>s are constructed using a Base 8000h encoding of the original
/// binary data - each char of an encoded <see cref="string"/> represents a 15-bit chunk
/// from the byte sequence. Base 8000h was chosen because it allows for all
/// lower 15 bits of char to be used without restriction; the surrogate range
/// [U+D8000-U+DFFF] does not represent valid chars, and would require
/// complicated handling to avoid them and allow use of char's high bit.
/// <para/>
/// Although unset bits are used as padding in the final char, the original
/// byte sequence could contain trailing bytes with no set bits (null bytes):
/// padding is indistinguishable from valid information. To overcome this
/// problem, a char is appended, indicating the number of encoded bytes in the
/// final content char.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Implement Analysis.TokenAttributes.ITermToBytesRefAttribute and store bytes directly instead. this class will be removed in Lucene 5.0")]
public sealed class IndexableBinaryStringTools
{
private static readonly CodingCase[] CODING_CASES = new CodingCase[] {
// CodingCase(int initialShift, int finalShift)
new CodingCase(7, 1),
// CodingCase(int initialShift, int middleShift, int finalShift)
new CodingCase(14, 6, 2),
new CodingCase(13, 5, 3),
new CodingCase(12, 4, 4),
new CodingCase(11, 3, 5),
new CodingCase(10, 2, 6),
new CodingCase(9, 1, 7),
new CodingCase(8, 0)
};
// Export only static methods
private IndexableBinaryStringTools()
{
}
/// <summary>
/// Returns the number of chars required to encode the given <see cref="byte"/>s.
/// </summary>
/// <param name="inputArray"> Byte sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <returns> The number of chars required to encode the number of <see cref="byte"/>s. </returns>
// LUCENENET specific overload for CLS compliance
public static int GetEncodedLength(byte[] inputArray, int inputOffset, int inputLength)
{
// Use long for intermediaries to protect against overflow
return (int)((8L * inputLength + 14L) / 15L) + 1;
}
/// <summary>
/// Returns the number of chars required to encode the given <see cref="sbyte"/>s.
/// </summary>
/// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of sbytes in <paramref name="inputArray"/> </param>
/// <returns> The number of chars required to encode the number of <see cref="sbyte"/>s. </returns>
[CLSCompliant(false)]
public static int GetEncodedLength(sbyte[] inputArray, int inputOffset, int inputLength)
{
// Use long for intermediaries to protect against overflow
return (int)((8L * inputLength + 14L) / 15L) + 1;
}
/// <summary>
/// Returns the number of <see cref="byte"/>s required to decode the given char sequence.
/// </summary>
/// <param name="encoded"> Char sequence to be decoded </param>
/// <param name="offset"> Initial offset </param>
/// <param name="length"> Number of characters </param>
/// <returns> The number of <see cref="byte"/>s required to decode the given char sequence </returns>
public static int GetDecodedLength(char[] encoded, int offset, int length)
{
int numChars = length - 1;
if (numChars <= 0)
{
return 0;
}
else
{
// Use long for intermediaries to protect against overflow
long numFullBytesInFinalChar = encoded[offset + length - 1];
long numEncodedChars = numChars - 1;
return (int)((numEncodedChars * 15L + 7L) / 8L + numFullBytesInFinalChar);
}
}
/// <summary>
/// Encodes the input <see cref="byte"/> sequence into the output char sequence. Before
/// calling this method, ensure that the output array has sufficient
/// capacity by calling <see cref="GetEncodedLength(byte[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="byte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be GetEncodedLength(inputArray, inputOffset, inputLength) </param>
// LUCENENET specific overload for CLS compliance
public static void Encode(byte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength)
{
Encode((sbyte[])(Array)inputArray, inputOffset, inputLength, outputArray, outputOffset, outputLength);
}
/// <summary>
/// Encodes the input <see cref="sbyte"/> sequence into the output char sequence. Before
/// calling this method, ensure that the output array has sufficient
/// capacity by calling <see cref="GetEncodedLength(sbyte[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be getEncodedLength </param>
[CLSCompliant(false)]
public static void Encode(sbyte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength)
{
Debug.Assert(outputLength == GetEncodedLength(inputArray, inputOffset, inputLength));
if (inputLength > 0)
{
int inputByteNum = inputOffset;
int caseNum = 0;
int outputCharNum = outputOffset;
CodingCase codingCase;
for (; inputByteNum + CODING_CASES[caseNum].numBytes <= inputLength; ++outputCharNum)
{
codingCase = CODING_CASES[caseNum];
if (2 == codingCase.numBytes)
{
outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + (((int)((uint)(inputArray[inputByteNum + 1] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF);
} // numBytes is 3
else
{
outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift) + (((int)((uint)(inputArray[inputByteNum + 2] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF);
}
inputByteNum += codingCase.advanceBytes;
if (++caseNum == CODING_CASES.Length)
{
caseNum = 0;
}
}
// Produce final char (if any) and trailing count chars.
codingCase = CODING_CASES[caseNum];
if (inputByteNum + 1 < inputLength) // codingCase.numBytes must be 3
{
outputArray[outputCharNum++] = (char)((((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)) & (short)0x7FFF);
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = (char)1;
}
else if (inputByteNum < inputLength)
{
outputArray[outputCharNum++] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) & (short)0x7FFF);
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = caseNum == 0 ? (char)1 : (char)0;
} // No left over bits - last char is completely filled.
else
{
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = (char)1;
}
}
}
/// <summary>
/// Decodes the input <see cref="char"/> sequence into the output <see cref="byte"/> sequence. Before
/// calling this method, ensure that the output array has sufficient capacity
/// by calling <see cref="GetDecodedLength(char[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be
/// GetDecodedLength(inputArray, inputOffset, inputLength) </param>
// LUCENENET specific overload for CLS compliance
public static void Decode(char[] inputArray, int inputOffset, int inputLength, byte[] outputArray, int outputOffset, int outputLength)
{
Decode(inputArray, inputOffset, inputLength, (sbyte[])(Array)outputArray, outputOffset, outputLength);
}
/// <summary>
/// Decodes the input char sequence into the output sbyte sequence. Before
/// calling this method, ensure that the output array has sufficient capacity
/// by calling <see cref="GetDecodedLength(char[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be
/// GetDecodedLength(inputArray, inputOffset, inputLength) </param>
[CLSCompliant(false)]
public static void Decode(char[] inputArray, int inputOffset, int inputLength, sbyte[] outputArray, int outputOffset, int outputLength)
{
Debug.Assert(outputLength == GetDecodedLength(inputArray, inputOffset, inputLength));
int numInputChars = inputLength - 1;
int numOutputBytes = outputLength;
if (numOutputBytes > 0)
{
int caseNum = 0;
int outputByteNum = outputOffset;
int inputCharNum = inputOffset;
short inputChar;
CodingCase codingCase;
for (; inputCharNum < numInputChars - 1; ++inputCharNum)
{
codingCase = CODING_CASES[caseNum];
inputChar = (short)inputArray[inputCharNum];
if (2 == codingCase.numBytes)
{
if (0 == caseNum)
{
outputArray[outputByteNum] = (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
}
else
{
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
}
outputArray[outputByteNum + 1] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
} // numBytes is 3
else
{
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift));
outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
}
outputByteNum += codingCase.advanceBytes;
if (++caseNum == CODING_CASES.Length)
{
caseNum = 0;
}
}
// Handle final char
inputChar = (short)inputArray[inputCharNum];
codingCase = CODING_CASES[caseNum];
if (0 == caseNum)
{
outputArray[outputByteNum] = 0;
}
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
int bytesLeft = numOutputBytes - outputByteNum;
if (bytesLeft > 1)
{
if (2 == codingCase.numBytes)
{
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.finalMask) >> codingCase.finalShift));
} // numBytes is 3
else
{
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift));
if (bytesLeft > 2)
{
outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
}
}
}
}
}
internal class CodingCase
{
internal int numBytes, initialShift, middleShift, finalShift, advanceBytes = 2;
internal short middleMask, finalMask;
internal CodingCase(int initialShift, int middleShift, int finalShift)
{
this.numBytes = 3;
this.initialShift = initialShift;
this.middleShift = middleShift;
this.finalShift = finalShift;
this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift));
this.middleMask = (short)((short)0xFF << middleShift);
}
internal CodingCase(int initialShift, int finalShift)
{
this.numBytes = 2;
this.initialShift = initialShift;
this.finalShift = finalShift;
this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift));
if (finalShift != 0)
{
advanceBytes = 1;
}
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A mosque.
/// </summary>
public class Mosque_Core : TypeCore, IPlaceOfWorship
{
public Mosque_Core()
{
this._TypeId = 153;
this._Id = "Mosque";
this._Schema_Org_Url = "http://schema.org/Mosque";
string label = "";
GetLabel(out label, "Mosque", typeof(Mosque_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62,207};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{207};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osu.Game.Configuration;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.Input.Handlers;
using osu.Game.Screens.Play;
using static osu.Game.Input.Handlers.ReplayInputHandler;
namespace osu.Game.Rulesets.UI
{
public abstract class RulesetInputManager<T> : PassThroughInputManager, ICanAttachKeyCounter, IHasReplayHandler, IHasRecordingHandler
where T : struct
{
private ReplayRecorder recorder;
public ReplayRecorder Recorder
{
set
{
if (value != null && recorder != null)
throw new InvalidOperationException("Cannot attach more than one recorder");
recorder?.Expire();
recorder = value;
if (recorder != null)
KeyBindingContainer.Add(recorder);
}
}
protected override InputState CreateInitialState() => new RulesetInputManagerInputState<T>(base.CreateInitialState());
protected readonly KeyBindingContainer<T> KeyBindingContainer;
protected override Container<Drawable> Content => content;
private readonly Container content;
protected RulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
{
InternalChild = KeyBindingContainer =
CreateKeyBindingContainer(ruleset, variant, unique)
.WithChild(content = new Container { RelativeSizeAxes = Axes.Both });
}
[BackgroundDependencyLoader(true)]
private void load(OsuConfigManager config)
{
mouseDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableButtons);
}
#region Action mapping (for replays)
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
if (inputStateChange is ReplayStateChangeEvent<T> replayStateChanged)
{
foreach (var action in replayStateChanged.ReleasedActions)
KeyBindingContainer.TriggerReleased(action);
foreach (var action in replayStateChanged.PressedActions)
KeyBindingContainer.TriggerPressed(action);
}
else
{
base.HandleInputStateChange(inputStateChange);
}
}
#endregion
#region IHasReplayHandler
private ReplayInputHandler replayInputHandler;
public ReplayInputHandler ReplayInputHandler
{
get => replayInputHandler;
set
{
if (replayInputHandler != null) RemoveHandler(replayInputHandler);
replayInputHandler = value;
UseParentInput = replayInputHandler == null;
if (replayInputHandler != null)
AddHandler(replayInputHandler);
}
}
#endregion
#region Setting application (disables etc.)
private Bindable<bool> mouseDisabled;
protected override bool Handle(UIEvent e)
{
switch (e)
{
case MouseDownEvent _:
if (mouseDisabled.Value)
return true; // importantly, block upwards propagation so global bindings also don't fire.
break;
case MouseUpEvent mouseUp:
if (!CurrentState.Mouse.IsPressed(mouseUp.Button))
return false;
break;
}
return base.Handle(e);
}
#endregion
#region Key Counter Attachment
public void Attach(KeyCounterDisplay keyCounter)
{
var receptor = new ActionReceptor(keyCounter);
KeyBindingContainer.Add(receptor);
keyCounter.SetReceptor(receptor);
keyCounter.AddRange(KeyBindingContainer.DefaultKeyBindings
.Select(b => b.GetAction<T>())
.Distinct()
.OrderBy(action => action)
.Select(action => new KeyCounterAction<T>(action)));
}
public class ActionReceptor : KeyCounterDisplay.Receptor, IKeyBindingHandler<T>
{
public ActionReceptor(KeyCounterDisplay target)
: base(target)
{
}
public bool OnPressed(KeyBindingPressEvent<T> e) => Target.Children.OfType<KeyCounterAction<T>>().Any(c => c.OnPressed(e.Action, Clock.Rate >= 0));
public void OnReleased(KeyBindingReleaseEvent<T> e)
{
foreach (var c in Target.Children.OfType<KeyCounterAction<T>>())
c.OnReleased(e.Action, Clock.Rate >= 0);
}
}
#endregion
protected virtual KeyBindingContainer<T> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new RulesetKeyBindingContainer(ruleset, variant, unique);
public class RulesetKeyBindingContainer : DatabasedKeyBindingContainer<T>
{
public RulesetKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override void ReloadMappings()
{
base.ReloadMappings();
KeyBindings = KeyBindings.Where(b => RealmKeyBindingStore.CheckValidForGameplay(b.KeyCombination)).ToList();
}
}
}
/// <summary>
/// Expose the <see cref="ReplayInputHandler"/> in a capable <see cref="InputManager"/>.
/// </summary>
public interface IHasReplayHandler
{
ReplayInputHandler ReplayInputHandler { get; set; }
}
public interface IHasRecordingHandler
{
public ReplayRecorder Recorder { set; }
}
/// <summary>
/// Supports attaching a <see cref="KeyCounterDisplay"/>.
/// Keys will be populated automatically and a receptor will be injected inside.
/// </summary>
public interface ICanAttachKeyCounter
{
void Attach(KeyCounterDisplay keyCounter);
}
public class RulesetInputManagerInputState<T> : InputState
where T : struct
{
public ReplayState<T> LastReplayState;
public RulesetInputManagerInputState(InputState state = null)
: base(state)
{
}
}
}
| |
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Text;
using System.IO;
using Cuyahoga.Core.Service;
namespace Cuyahoga.Web.UI
{
/// <summary>
/// The BasePage class is the class that webforms have to inherit to use the templates.
/// </summary>
///
public class GenericBasePage : CuyahogaPage
{
// Member variables
private string _templateFilename;
private string _title;
private string _css;
private string _templateDir;
private BasePageControl _pageControl;
#region properties
/// <summary>
/// Template property (filename of the User Control). This property can be used to change
/// page templates run-time.
/// </summary>
public string TemplateFilename
{
set { this._templateFilename = value; }
}
/// <summary>
///
/// </summary>
protected string TemplateDir
{
set { this._templateDir = value; }
}
/// <summary>
/// The page title as shown in the title bar of the browser.
/// </summary>
public string Title
{
get { return _title; }
set { _title = value; }
}
/// <summary>
/// Path to external stylesheet file, relative from the application root.
/// </summary>
public string Css
{
get { return _css; }
set { _css = value; }
}
/// <summary>
/// Property for the template control. This property can be used for finding other controls.
/// </summary>
public UserControl TemplateControl
{
get
{
if (this.Controls.Count > 0)
{
if (this.Controls[0] is UserControl)
{
return (UserControl)this.Controls[0];
}
else
{
return null;
}
}
else
{
return null;
}
}
}
/// <summary>
/// The messagebox.
/// </summary>
public HtmlGenericControl MessageBox
{
get
{
if (this.TemplateControl != null)
{
return this.TemplateControl.FindControl("MessageBox") as HtmlGenericControl;
}
else
{
return null;
}
}
}
/// <summary>
/// The core repository for persisting Cuyahoga objects.
/// </summary>
public CoreRepository CoreRepository
{
get
{
return HttpContext.Current.Items["CoreRepository"] as CoreRepository;
}
}
#endregion
/// <summary>
/// Default constructor
/// </summary>
public GenericBasePage()
{
this._templateFilename = null;
this._templateDir = null;
this._css = null;
}
/// <summary>
/// Protected constructor that accepts template parameters. Could be handled more elegantly.
/// </summary>
/// <param name="templateFileName"></param>
/// <param name="templateDir"></param>
/// <param name="css"></param>
protected GenericBasePage(string templateFileName, string templateDir, string css)
{
this._templateFilename = templateFileName;
this._templateDir = templateDir;
this._css = css;
}
/// <summary>
/// Try to find the MessageBox control, insert the errortext and set visibility to true.
/// </summary>
/// <param name="errorText"></param>
protected virtual void ShowError(string errorText)
{
if (this.MessageBox != null)
{
this.MessageBox.InnerHtml = "An error occured: " + errorText;
this.MessageBox.Attributes["class"] = "errorbox";
this.MessageBox.Visible = true;
}
else
{
// Throw an Exception and hope it will be handled by the global application exception handler.
throw new Exception(errorText);
}
}
/// <summary>
/// Try to find the MessageBox control, insert the message and set visibility to true.
/// </summary>
/// <param name="message"></param>
protected virtual void ShowMessage(string message)
{
if (this.MessageBox != null)
{
this.MessageBox.InnerHtml = message;
this.MessageBox.Attributes["class"] = "messagebox";
this.MessageBox.Visible = true;
}
// TODO: change the class attribute to make a difference with the error (nice background image?)
}
/// <summary>
/// Show the message of the exception, and the messages of the inner exceptions.
/// </summary>
/// <param name="exception"></param>
protected virtual void ShowException(Exception exception)
{
string exceptionMessage = "<p>" + exception.Message + "</p>";
Exception innerException = exception.InnerException;
while (innerException != null)
{
exceptionMessage += "<p>" + innerException.Message + "</p>";
innerException = innerException.InnerException;
}
ShowError(exceptionMessage);
}
protected override void OnInit(EventArgs e)
{
// Init
PlaceHolder plc;
ControlCollection col = this.Controls;
// Set template directory
if (this._templateDir == null && ConfigurationManager.AppSettings["TemplateDir"] != null)
{
this._templateDir = ConfigurationManager.AppSettings["TemplateDir"];
}
// Get the template control
if (this._templateFilename == null)
{
this._templateFilename = ConfigurationManager.AppSettings["DefaultTemplate"];
}
this._pageControl = (BasePageControl)this.LoadControl(this.ResolveUrl(this._templateDir + this._templateFilename));
// Add the pagecontrol on top of the control collection of the page
_pageControl.ID = "p";
col.AddAt(0, _pageControl);
// Get the Content placeholder
plc = _pageControl.Content;
if (plc != null)
{
// Iterate through the controls in the page to find the form control.
foreach (Control control in col)
{
if (control is HtmlForm)
{
// We've found the form control. Now move all child controls into the placeholder.
HtmlForm formControl = (HtmlForm)control;
while (formControl.Controls.Count > 0)
plc.Controls.Add(formControl.Controls[0]);
}
}
// throw away all controls in the page, except the page control
while (col.Count > 1)
col.Remove(col[1]);
}
base.OnInit(e);
}
#region Register Javascript and CSS
/// <summary>
/// Register module-specific stylesheets.
/// </summary>
/// <param name="key">The unique key for the stylesheet. Note that Cuyahoga already uses 'maincss' as key.</param>
/// <param name="absoluteCssPath">The path to the css file from the application root (starting with /).</param>
protected void RegisterStylesheet(string key, string absoluteCssPath)
{
//BasePageControl pageControl = (BasePageControl)this.Controls[0];
_pageControl.RegisterStylesheet(key, absoluteCssPath);
}
/// <summary>
/// Register module-specific javascripts.
/// </summary>
/// <param name="key">The unique key for the javascrip. </param>
/// <param name="absoluteJavascriptPath">The path to the css file from the application root (starting with /).</param>
protected void RegisterJavascript(string key, string absoluteJavascriptPath)
{
//BasePageControl pageControl = (BasePageControl)this.Controls[0];
_pageControl.RegisterJavascript(key, absoluteJavascriptPath);
}
#endregion Register Javascript and CSS
/// <summary>
/// Use the PreRender event to set the page title and stylesheet. These are properties of the page control
/// which is at position 0 in the controls collection.
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
{
//Removed for CSS and Javascript Registration
//BasePageControl pageControl = (BasePageControl)this.Controls[0];
// Set the stylesheet and title properties
if (this._css == null)
{
this._css = ResolveUrl(ConfigurationManager.AppSettings["DefaultCss"]);
}
if (this._title == null)
{
this._title = ConfigurationManager.AppSettings["DefaultTitle"];
}
_pageControl.Title = this._title;
_pageControl.Css = this._css;
_pageControl.InsertStylesheets();
_pageControl.InsertJavascripts();
}
}
}
| |
#if !(NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject
{
private readonly DynamicProxy<T> _proxy;
private readonly bool _dontFallbackFirst;
internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst)
: base(expression, BindingRestrictions.Empty, value)
{
_proxy = proxy;
_dontFallbackFirst = dontFallbackFirst;
}
private new T Value { get { return (T)base.Value; } }
private bool IsOverridden(string method)
{
return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast<MethodInfo>()
.Any(info =>
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != typeof(DynamicProxy<T>) &&
info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>));
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
return IsOverridden("TryGetMember")
? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e))
: base.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
return IsOverridden("TrySetMember")
? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e))
: base.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
return IsOverridden("TryDeleteMember")
? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e))
: base.BindDeleteMember(binder);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
return IsOverridden("TryConvert")
? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e))
: base.BindConvert(binder);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
if (!IsOverridden("TryInvokeMember"))
return base.BindInvokeMember(binder, args);
//
// Generate a tree like:
//
// {
// object result;
// TryInvokeMember(payload, out result)
// ? result
// : TryGetMember(payload, out result)
// ? FallbackInvoke(result)
// : fallbackResult
// }
//
// Then it calls FallbackInvokeMember with this tree as the
// "error", giving the language the option of using this
// tree or doing .NET binding.
//
Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
DynamicMetaObject call = BuildCallMethodWithResult(
"TryInvokeMember",
binder,
GetArgArray(args),
BuildCallMethodWithResult(
"TryGetMember",
new GetBinderAdapter(binder),
NoArgs,
fallback(null),
e => binder.FallbackInvoke(e, args, null)
),
null
);
return _dontFallbackFirst ? call : fallback(call);
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryCreateInstance")
? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e))
: base.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryInvoke")
? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e))
: base.BindInvoke(binder, args);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
return IsOverridden("TryBinaryOperation")
? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e))
: base.BindBinaryOperation(binder, arg);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
return IsOverridden("TryUnaryOperation")
? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e))
: base.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryGetIndex")
? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e))
: base.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
return IsOverridden("TrySetIndex")
? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e))
: base.BindSetIndex(binder, indexes, value);
}
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryDeleteIndex")
? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e))
: base.BindDeleteIndex(binder, indexes);
}
private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion);
private readonly static Expression[] NoArgs = new Expression[0];
private static Expression[] GetArgs(params DynamicMetaObject[] args)
{
return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray();
}
private static Expression[] GetArgArray(DynamicMetaObject[] args)
{
return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) };
}
private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
{
return new Expression[]
{
Expression.NewArrayInit(typeof(object), GetArgs(args)),
Expression.Convert(value.Expression, typeof(object))
};
}
private static ConstantExpression Constant(DynamicMetaObjectBinder binder)
{
Type t = binder.GetType();
while (!t.IsVisible)
t = t.BaseType;
return Expression.Constant(binder, t);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
{
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs.Add(result);
DynamicMetaObject resultMO = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof (object))
{
UnaryExpression convert = Expression.Convert(resultMO.Expression, binder.ReturnType);
// will always be a cast or unbox
resultMO = new DynamicMetaObject(convert, resultMO.Restrictions);
}
if (fallbackInvoke != null)
resultMO = fallbackInvoke(resultMO);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] {result},
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
resultMO.Expression,
fallbackResult.Expression,
binder.ReturnType
)
),
GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof (T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
result,
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
Expression.Empty(),
fallbackResult.Expression,
typeof (void)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Returns a Restrictions object which includes our current restrictions merged
/// with a restriction limiting our type
/// </summary>
private BindingRestrictions GetRestrictions()
{
return (Value == null && HasValue)
? BindingRestrictions.GetInstanceRestriction(Expression, null)
: BindingRestrictions.GetTypeRestriction(Expression, LimitType);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _proxy.GetDynamicMemberNames(Value);
}
// It is okay to throw NotSupported from this binder. This object
// is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties.
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(InvokeMemberBinder binder) :
base(binder.Name, binder.IgnoreCase)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void CompletionRoutine();
internal delegate void CompletionRoutine<TResult>(TResult result);
/// <summary>
/// Computes expansion of <see cref="DkmClrValue"/> instances.
/// </summary>
/// <remarks>
/// This class provides implementation for the default ResultProvider component.
/// </remarks>
public abstract class ResultProvider : IDkmClrResultProvider
{
internal readonly Formatter Formatter;
static ResultProvider()
{
FatalError.Handler = FailFast.OnFatalException;
}
internal ResultProvider(Formatter formatter)
{
this.Formatter = formatter;
}
void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
// TODO: Use full name
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e)));
GetRootResultAndContinue(
value,
wl,
declaredType,
declaredTypeInfo,
inspectionContext,
resultName,
result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result))));
wl.Execute();
}
DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult)
{
try
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
return null;
}
return dataItem.Value;
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine);
return;
}
var stackFrame = evaluationResult.StackFrame;
GetChildrenAndContinue(dataItem, workList, stackFrame, initialRequestSize, inspectionContext, completionRoutine);
}
void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var dataItem = enumContext.GetDataItem<EnumContextDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
enumContext.GetItems(workList, startIndex, count, completionRoutine);
return;
}
GetItemsAndContinue(dataItem.EvalResultDataItem, workList, startIndex, count, enumContext.InspectionContext, completionRoutine);
}
string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result)
{
try
{
var dataItem = result.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return result.GetUnderlyingString();
}
return dataItem.Value?.GetUnderlyingString(result.InspectionContext);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void CreateEvaluationResultAndContinue(EvalResultDataItem dataItem, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
switch (dataItem.Kind)
{
case ExpansionKind.Error:
completionRoutine(DkmFailedEvaluationResult.Create(
inspectionContext,
StackFrame: stackFrame,
Name: dataItem.Name,
FullName: dataItem.FullName,
ErrorMessage: dataItem.DisplayValue,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null));
break;
case ExpansionKind.NativeView:
{
var value = dataItem.Value;
var name = Resources.NativeView;
var fullName = dataItem.FullName;
var display = dataItem.Name;
DkmEvaluationResult evalResult;
if (value.IsError())
{
evalResult = DkmFailedEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
ErrorMessage: display,
Flags: dataItem.Flags,
Type: null,
DataItem: dataItem);
}
else
{
// For Native View, create a DkmIntermediateEvaluationResult.
// This will allow the C++ EE to take over expansion.
var process = inspectionContext.RuntimeInstance.Process;
var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp));
evalResult = DkmIntermediateEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
Expression: display,
IntermediateLanguage: cpp,
TargetRuntime: process.GetNativeRuntimeInstance(),
DataItem: dataItem);
}
completionRoutine(evalResult);
}
break;
case ExpansionKind.NonPublicMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.NonPublicMembers,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.StaticMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Formatter.StaticMembersString,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Class,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.RawView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.RawView,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: dataItem.EditableValue,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.DynamicView:
case ExpansionKind.ResultsView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
dataItem.Name,
dataItem.FullName,
dataItem.Flags,
dataItem.DisplayValue,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Method,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.TypeVariable:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
dataItem.Name,
dataItem.FullName,
dataItem.Flags,
dataItem.DisplayValue,
EditableValue: null,
Type: dataItem.DisplayValue,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.PointerDereference:
case ExpansionKind.Default:
// This call will evaluate DebuggerDisplayAttributes.
GetResultAndContinue(
dataItem,
workList,
declaredType: DkmClrType.Create(dataItem.Value.Type.AppDomain, dataItem.DeclaredTypeAndInfo.Type),
declaredTypeInfo: dataItem.DeclaredTypeAndInfo.Info,
inspectionContext: inspectionContext,
parent: dataItem.Parent,
completionRoutine: completionRoutine);
break;
default:
throw ExceptionUtilities.UnexpectedValue(dataItem.Kind);
}
}
private static DkmEvaluationResult CreateEvaluationResult(
DkmInspectionContext inspectionContext,
DkmClrValue value,
string name,
string typeName,
string display,
EvalResultDataItem dataItem)
{
if (value.IsError())
{
// Evaluation failed
return DkmFailedEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: dataItem.FullName,
ErrorMessage: display,
Flags: dataItem.Flags,
Type: typeName,
DataItem: dataItem);
}
else
{
ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null;
if (!value.IsNull)
{
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo();
if (customUIVisualizerInfo != null)
{
customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo);
}
}
// If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category,
// which typically appears to be set to the default value ("Other").
var category = (dataItem.Category != DkmEvaluationResultCategory.Other) ? dataItem.Category : value.Category;
// Valid value
return DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: display,
EditableValue: dataItem.EditableValue,
Type: typeName,
Category: category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: customUIVisualizers,
ExternalModules: null,
DataItem: dataItem);
}
}
/// <returns>
/// The qualified name (i.e. including containing types and namespaces) of a named, pointer,
/// or array type followed by the qualified name of the actual runtime type, if provided.
/// </returns>
private static string GetTypeName(DkmInspectionContext inspectionContext, DkmClrValue value, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, ExpansionKind kind)
{
var declaredLmrType = declaredType.GetLmrType();
var runtimeType = value.Type;
var runtimeLmrType = runtimeType.GetLmrType();
var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers);
var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, CustomTypeInfo: null, FormatSpecifiers: Formatter.NoFormatSpecifiers);
var includeRuntimeTypeName =
!string.Equals(declaredTypeName, runtimeTypeName, StringComparison.OrdinalIgnoreCase) && // Names will reflect "dynamic", types will not.
!declaredLmrType.IsPointer &&
(kind != ExpansionKind.PointerDereference) &&
(!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown));
return includeRuntimeTypeName ?
string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName) :
declaredTypeName;
}
internal EvalResultDataItem CreateDataItem(
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfo,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
EvalResultDataItem parent,
ExpansionFlags expansionFlags,
bool childShouldParenthesize,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultCategory category,
DkmEvaluationResultFlags flags,
DkmEvaluationFlags evalFlags)
{
if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw");
}
Expansion expansion;
// If the declared type is Nullable<T>, the value should
// have no expansion if null, or be expanded as a T.
var declaredType = declaredTypeAndInfo.Type;
var lmrNullableTypeArg = declaredType.GetNullableTypeArgument();
if (lmrNullableTypeArg != null && !value.HasExceptionThrown())
{
Debug.Assert(value.Type.GetProxyType() == null);
DkmClrValue nullableValue;
if (value.IsError())
{
expansion = null;
}
else if ((nullableValue = value.GetNullableValue(inspectionContext)) == null)
{
Debug.Assert(declaredType.Equals(value.Type.GetLmrType()));
// No expansion of "null".
expansion = null;
}
else
{
value = nullableValue;
Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary.
// CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array.
expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(lmrNullableTypeArg), value, ExpansionFlags.IncludeResultsView);
}
}
else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
expansion = null;
}
else
{
expansion = DebuggerTypeProxyExpansion.CreateExpansion(
this,
inspectionContext,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers,
flags,
this.Formatter.GetEditableValue(value, inspectionContext));
if (expansion == null)
{
expansion = value.HasExceptionThrown()
? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags)
: this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags);
}
}
return new EvalResultDataItem(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
parent: parent,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: childShouldParenthesize,
fullName: fullName,
childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers: formatSpecifiers,
category: category,
flags: flags,
editableValue: this.Formatter.GetEditableValue(value, inspectionContext),
inspectionContext: inspectionContext);
}
private void GetRootResultAndContinue(
DkmClrValue value,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
string name,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var type = value.Type.GetLmrType();
if (type.IsTypeVariables())
{
Debug.Assert(type.Equals(declaredType.GetLmrType()));
var declaredTypeAndInfo = new TypeAndCustomInfo(type, declaredTypeInfo);
var expansion = new TypeVariablesExpansion(declaredTypeAndInfo);
var dataItem = new EvalResultDataItem(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: declaredTypeAndInfo,
parent: null,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable));
// Note: We're not including value.EvalFlags in Flags parameter
// below (there shouldn't be a reason to do so).
completionRoutine(DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: Resources.TypeVariablesName,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: "",
EditableValue: null,
Type: "",
Category: dataItem.Category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0)
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRow(
inspectionContext,
name,
declaredType,
declaredTypeInfo,
value,
this.Formatter);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0)
{
var dataItem = DynamicViewExpansion.CreateMembersOnlyRow(
inspectionContext,
name,
value,
this.Formatter);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable(
inspectionContext,
name,
declaredType,
declaredTypeInfo,
value,
this.Formatter);
if (dataItem != null)
{
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
ReadOnlyCollection<string> formatSpecifiers;
var fullName = this.Formatter.TrimAndGetFormatSpecifiers(name, out formatSpecifiers);
dataItem = CreateDataItem(
inspectionContext,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(declaredType.GetLmrType(), declaredTypeInfo),
value: value,
parent: null,
expansionFlags: ExpansionFlags.All,
childShouldParenthesize: this.Formatter.NeedsParentheses(fullName),
fullName: fullName,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Other,
flags: value.EvalFlags,
evalFlags: inspectionContext.EvaluationFlags);
GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, parent: null, completionRoutine: completionRoutine);
}
}
}
private void GetResultAndContinue(
EvalResultDataItem dataItem,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var value = dataItem.Value; // Value may have been replaced (specifically, for Nullable<T>).
DebuggerDisplayInfo displayInfo;
if (value.TryGetDebuggerDisplayInfo(out displayInfo))
{
var targetType = displayInfo.TargetType;
var attribute = displayInfo.Attribute;
CompletionRoutine<Exception> onException =
e => completionRoutine(CreateEvaluationResultFromException(e, dataItem, inspectionContext));
EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.Name,
displayName => EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.Value,
displayValue => EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.TypeName,
displayType =>
{
completionRoutine(GetResult(inspectionContext, dataItem, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, parent));
workList.Execute();
},
onException),
onException),
onException);
}
else
{
completionRoutine(GetResult(inspectionContext, dataItem, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, parent: parent));
}
}
private static void EvaluateDebuggerDisplayStringAndContinue(
DkmClrValue value,
WorkList workList,
DkmInspectionContext inspectionContext,
DkmClrType targetType,
string str,
CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted,
CompletionRoutine<Exception> onException)
{
DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine =
result =>
{
try
{
onCompleted(result);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.ReportNonFatalException(e, DkmComponentManager.ReportCurrentNonFatalException))
{
onException(e);
}
};
if (str == null)
{
completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult));
}
else
{
value.EvaluateDebuggerDisplayString(workList.InnerWorkList, inspectionContext, targetType, str, completionRoutine);
}
}
private DkmEvaluationResult GetResult(
DkmInspectionContext inspectionContext,
EvalResultDataItem dataItem,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
string displayName,
string displayValue,
string displayType,
EvalResultDataItem parent)
{
var name = dataItem.Name;
Debug.Assert(name != null);
var typeDeclaringMemberAndInfo = dataItem.TypeDeclaringMemberAndInfo;
// Note: Don't respect the debugger display name on the root element:
// 1) In the Watch window, that's where the user's text goes.
// 2) In the Locals window, that's where the local name goes.
// Note: Dev12 respects the debugger display name in the Locals window,
// but not in the Watch window, but we can't distinguish and this
// behavior seems reasonable.
if (displayName != null && parent != null)
{
name = displayName;
}
else if (typeDeclaringMemberAndInfo.Type != null)
{
bool unused;
if (typeDeclaringMemberAndInfo.Type.IsInterface)
{
var interfaceTypeName = this.Formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out unused);
name = string.Format("{0}.{1}", interfaceTypeName, name);
}
else
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
builder.Append(" (");
builder.Append(this.Formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused));
builder.Append(')');
name = pooled.ToStringAndFree();
}
}
var value = dataItem.Value;
string display;
if (value.HasExceptionThrown())
{
display = dataItem.DisplayValue ?? value.GetExceptionMessage(dataItem.FullNameWithoutFormatSpecifiers ?? dataItem.Name, this.Formatter);
}
else if (displayValue != null)
{
display = value.IncludeObjectId(displayValue);
}
else
{
display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
}
var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, dataItem.Kind);
return CreateEvaluationResult(inspectionContext, value, name, typeName, display, dataItem);
}
private void GetChildrenAndContinue(EvalResultDataItem dataItem, DkmWorkList workList, DkmStackWalkFrame stackFrame, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var expansion = dataItem.Expansion;
var rows = ArrayBuilder<EvalResultDataItem>.GetInstance();
int index = 0;
if (expansion != null)
{
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index);
}
var numRows = rows.Count;
Debug.Assert(index >= numRows);
Debug.Assert(initialRequestSize >= numRows);
var initialChildren = new DkmEvaluationResult[numRows];
var wl = new WorkList(workList, e => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e)));
GetEvaluationResultsAndContinue(rows, initialChildren, 0, numRows, wl, inspectionContext, stackFrame,
() => wl.ContinueWith(
() =>
{
var enumContext = DkmEvaluationResultEnumContext.Create(index, stackFrame, inspectionContext, new EnumContextDataItem(dataItem));
completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext));
rows.Free();
}));
wl.Execute();
}
private void GetItemsAndContinue(EvalResultDataItem dataItem, DkmWorkList workList, int startIndex, int count, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var expansion = dataItem.Expansion;
var value = dataItem.Value;
var rows = ArrayBuilder<EvalResultDataItem>.GetInstance();
if (expansion != null)
{
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, value, startIndex, count, visitAll: false, index: ref index);
}
var numRows = rows.Count;
Debug.Assert(count >= numRows);
var results = new DkmEvaluationResult[numRows];
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e)));
GetEvaluationResultsAndContinue(rows, results, 0, numRows, wl, inspectionContext, value.StackFrame,
() => wl.ContinueWith(
() =>
{
completionRoutine(new DkmEvaluationEnumAsyncResult(results));
rows.Free();
}));
wl.Execute();
}
private void GetEvaluationResultsAndContinue(ArrayBuilder<EvalResultDataItem> rows, DkmEvaluationResult[] results, int index, int numRows, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine completionRoutine)
{
if (index < numRows)
{
CreateEvaluationResultAndContinue(rows[index], workList, inspectionContext, stackFrame,
result => workList.ContinueWith(
() =>
{
results[index] = result;
GetEvaluationResultsAndContinue(rows, results, index + 1, numRows, workList, inspectionContext, stackFrame, completionRoutine);
}));
}
else
{
completionRoutine();
}
}
internal Expansion GetTypeExpansion(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
ExpansionFlags flags)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(!declaredType.IsTypeVariables());
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
return null;
}
var runtimeType = value.Type.GetLmrType();
// If the value is an array, expand the array elements.
if (runtimeType.IsArray)
{
var sizes = value.ArrayDimensions;
if (sizes == null)
{
// Null array. No expansion.
return null;
}
var lowerBounds = value.ArrayLowerBounds;
Type elementType;
DkmClrCustomTypeInfo elementTypeInfo;
if (declaredType.IsArray)
{
elementType = declaredType.GetElementType();
elementTypeInfo = DynamicFlagsCustomTypeInfo.Create(declaredTypeAndInfo.Info).SkipOne().GetCustomTypeInfo();
}
else
{
elementType = runtimeType.GetElementType();
elementTypeInfo = null;
}
return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(elementType, elementTypeInfo), sizes, lowerBounds);
}
if (this.Formatter.IsPredefinedType(runtimeType))
{
return null;
}
if (declaredType.IsPointer)
{
// If this ever happens, the element type info is just .SkipOne().
Debug.Assert(!DynamicFlagsCustomTypeInfo.Create(declaredTypeAndInfo.Info).Any());
var elementType = declaredType.GetElementType();
return value.IsNull || elementType.IsVoid()
? null
: new PointerDereferenceExpansion(new TypeAndCustomInfo(elementType));
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) &&
runtimeType.IsEmptyResultsViewException())
{
// The value is an exception thrown expanding an empty
// IEnumerable. Use the runtime type of the exception and
// skip base types. (This matches the native EE behavior
// to expose a single property from the exception.)
flags &= ~ExpansionFlags.IncludeBaseMembers;
}
return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this.Formatter);
}
private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResultDataItem dataItem, DkmInspectionContext inspectionContext)
{
return DkmFailedEvaluationResult.Create(
inspectionContext,
dataItem.Value.StackFrame,
Name: dataItem.Name,
FullName: null,
ErrorMessage: e.Message,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null);
}
private sealed class WorkList
{
internal readonly DkmWorkList InnerWorkList;
private readonly CompletionRoutine<Exception> _onException;
private CompletionRoutine _completionRoutine;
internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException)
{
InnerWorkList = workList;
_onException = onException;
}
internal void ContinueWith(CompletionRoutine completionRoutine)
{
Debug.Assert(_completionRoutine == null);
_completionRoutine = completionRoutine;
}
internal void Execute()
{
while (_completionRoutine != null)
{
var completionRoutine = _completionRoutine;
_completionRoutine = null;
try
{
completionRoutine();
}
catch (Exception e) when (ExpressionEvaluatorFatalError.ReportNonFatalException(e, DkmComponentManager.ReportCurrentNonFatalException))
{
_onException(e);
}
}
}
}
}
}
| |
// 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.
using System;
namespace IronPythonTest {
public class IntegerTest {
public static Int32 Int32Int32MaxValue = (Int32)Int32.MaxValue;
public static Int32 Int32Int32MinValue = (Int32)Int32.MinValue;
public static Int32 Int32UInt32MinValue = (Int32)UInt32.MinValue;
public static Int32 Int32Int16MaxValue = (Int32)Int16.MaxValue;
public static Int32 Int32Int16MinValue = (Int32)Int16.MinValue;
public static Int32 Int32UInt16MaxValue = (Int32)UInt16.MaxValue;
public static Int32 Int32UInt16MinValue = (Int32)UInt16.MinValue;
public static Int32 Int32UInt64MinValue = (Int32)UInt64.MinValue;
public static Int32 Int32ByteMaxValue = (Int32)Byte.MaxValue;
public static Int32 Int32ByteMinValue = (Int32)Byte.MinValue;
public static Int32 Int32SByteMaxValue = (Int32)SByte.MaxValue;
public static Int32 Int32SByteMinValue = (Int32)SByte.MinValue;
public static Int32 Int32CharMaxValue = (Int32)Char.MaxValue;
public static Int32 Int32CharMinValue = (Int32)Char.MinValue;
public static Int32 Int32Val0 = (Int32)('a');
public static Int32 Int32Val1 = (Int32)(10);
public static Int32 Int32Val2 = (Int32)(42);
public static Int32 Int32Val3 = (Int32)(-24);
public static Int32 Int32Val6 = (Int32)(0);
public static Int32 Int32Val7 = (Int32)(1);
public static Int32 Int32Val8 = (Int32)(-1);
public static UInt32 UInt32Int32MaxValue = (UInt32)Int32.MaxValue;
public static UInt32 UInt32UInt32MaxValue = (UInt32)UInt32.MaxValue;
public static UInt32 UInt32UInt32MinValue = (UInt32)UInt32.MinValue;
public static UInt32 UInt32Int16MaxValue = (UInt32)Int16.MaxValue;
public static UInt32 UInt32UInt16MaxValue = (UInt32)UInt16.MaxValue;
public static UInt32 UInt32UInt16MinValue = (UInt32)UInt16.MinValue;
public static UInt32 UInt32UInt64MinValue = (UInt32)UInt64.MinValue;
public static UInt32 UInt32ByteMaxValue = (UInt32)Byte.MaxValue;
public static UInt32 UInt32ByteMinValue = (UInt32)Byte.MinValue;
public static UInt32 UInt32SByteMaxValue = (UInt32)SByte.MaxValue;
public static UInt32 UInt32CharMaxValue = (UInt32)Char.MaxValue;
public static UInt32 UInt32CharMinValue = (UInt32)Char.MinValue;
public static UInt32 UInt32Val0 = (UInt32)('a');
public static UInt32 UInt32Val1 = (UInt32)(10);
public static UInt32 UInt32Val2 = (UInt32)(42);
public static UInt32 UInt32Val6 = (UInt32)(0);
public static UInt32 UInt32Val7 = (UInt32)(1);
public static Int16 Int16UInt32MinValue = (Int16)UInt32.MinValue;
public static Int16 Int16Int16MaxValue = (Int16)Int16.MaxValue;
public static Int16 Int16Int16MinValue = (Int16)Int16.MinValue;
public static Int16 Int16UInt16MinValue = (Int16)UInt16.MinValue;
public static Int16 Int16UInt64MinValue = (Int16)UInt64.MinValue;
public static Int16 Int16ByteMaxValue = (Int16)Byte.MaxValue;
public static Int16 Int16ByteMinValue = (Int16)Byte.MinValue;
public static Int16 Int16SByteMaxValue = (Int16)SByte.MaxValue;
public static Int16 Int16SByteMinValue = (Int16)SByte.MinValue;
public static Int16 Int16CharMinValue = (Int16)Char.MinValue;
public static Int16 Int16Val0 = (Int16)('a');
public static Int16 Int16Val1 = (Int16)(10);
public static Int16 Int16Val2 = (Int16)(42);
public static Int16 Int16Val3 = (Int16)(-24);
public static Int16 Int16Val6 = (Int16)(0);
public static Int16 Int16Val7 = (Int16)(1);
public static Int16 Int16Val8 = (Int16)(-1);
public static UInt16 UInt16UInt32MinValue = (UInt16)UInt32.MinValue;
public static UInt16 UInt16Int16MaxValue = (UInt16)Int16.MaxValue;
public static UInt16 UInt16UInt16MaxValue = (UInt16)UInt16.MaxValue;
public static UInt16 UInt16UInt16MinValue = (UInt16)UInt16.MinValue;
public static UInt16 UInt16UInt64MinValue = (UInt16)UInt64.MinValue;
public static UInt16 UInt16ByteMaxValue = (UInt16)Byte.MaxValue;
public static UInt16 UInt16ByteMinValue = (UInt16)Byte.MinValue;
public static UInt16 UInt16SByteMaxValue = (UInt16)SByte.MaxValue;
public static UInt16 UInt16CharMaxValue = (UInt16)Char.MaxValue;
public static UInt16 UInt16CharMinValue = (UInt16)Char.MinValue;
public static UInt16 UInt16Val0 = (UInt16)('a');
public static UInt16 UInt16Val1 = (UInt16)(10);
public static UInt16 UInt16Val2 = (UInt16)(42);
public static UInt16 UInt16Val6 = (UInt16)(0);
public static UInt16 UInt16Val7 = (UInt16)(1);
public static Int64 Int64Int32MaxValue = (Int64)Int32.MaxValue;
public static Int64 Int64Int32MinValue = (Int64)Int32.MinValue;
public static Int64 Int64UInt32MaxValue = (Int64)UInt32.MaxValue;
public static Int64 Int64UInt32MinValue = (Int64)UInt32.MinValue;
public static Int64 Int64Int16MaxValue = (Int64)Int16.MaxValue;
public static Int64 Int64Int16MinValue = (Int64)Int16.MinValue;
public static Int64 Int64UInt16MaxValue = (Int64)UInt16.MaxValue;
public static Int64 Int64UInt16MinValue = (Int64)UInt16.MinValue;
public static Int64 Int64Int64MaxValue = (Int64)Int64.MaxValue;
public static Int64 Int64Int64MinValue = (Int64)Int64.MinValue;
public static Int64 Int64UInt64MinValue = (Int64)UInt64.MinValue;
public static Int64 Int64ByteMaxValue = (Int64)Byte.MaxValue;
public static Int64 Int64ByteMinValue = (Int64)Byte.MinValue;
public static Int64 Int64SByteMaxValue = (Int64)SByte.MaxValue;
public static Int64 Int64SByteMinValue = (Int64)SByte.MinValue;
public static Int64 Int64CharMaxValue = (Int64)Char.MaxValue;
public static Int64 Int64CharMinValue = (Int64)Char.MinValue;
public static Int64 Int64Val0 = (Int64)('a');
public static Int64 Int64Val1 = (Int64)(10);
public static Int64 Int64Val2 = (Int64)(42);
public static Int64 Int64Val3 = (Int64)(-24);
public static Int64 Int64Val6 = (Int64)(0);
public static Int64 Int64Val7 = (Int64)(1);
public static Int64 Int64Val8 = (Int64)(-1);
public static UInt64 UInt64Int32MaxValue = (UInt64)Int32.MaxValue;
public static UInt64 UInt64UInt32MaxValue = (UInt64)UInt32.MaxValue;
public static UInt64 UInt64UInt32MinValue = (UInt64)UInt32.MinValue;
public static UInt64 UInt64Int16MaxValue = (UInt64)Int16.MaxValue;
public static UInt64 UInt64UInt16MaxValue = (UInt64)UInt16.MaxValue;
public static UInt64 UInt64UInt16MinValue = (UInt64)UInt16.MinValue;
public static UInt64 UInt64Int64MaxValue = (UInt64)Int64.MaxValue;
public static UInt64 UInt64UInt64MaxValue = (UInt64)UInt64.MaxValue;
public static UInt64 UInt64UInt64MinValue = (UInt64)UInt64.MinValue;
public static UInt64 UInt64ByteMaxValue = (UInt64)Byte.MaxValue;
public static UInt64 UInt64ByteMinValue = (UInt64)Byte.MinValue;
public static UInt64 UInt64SByteMaxValue = (UInt64)SByte.MaxValue;
public static UInt64 UInt64CharMaxValue = (UInt64)Char.MaxValue;
public static UInt64 UInt64CharMinValue = (UInt64)Char.MinValue;
public static UInt64 UInt64Val0 = (UInt64)('a');
public static UInt64 UInt64Val1 = (UInt64)(10);
public static UInt64 UInt64Val2 = (UInt64)(42);
public static UInt64 UInt64Val6 = (UInt64)(0);
public static UInt64 UInt64Val7 = (UInt64)(1);
public static Byte ByteUInt32MinValue = (Byte)UInt32.MinValue;
public static Byte ByteUInt16MinValue = (Byte)UInt16.MinValue;
public static Byte ByteUInt64MinValue = (Byte)UInt64.MinValue;
public static Byte ByteByteMaxValue = (Byte)Byte.MaxValue;
public static Byte ByteByteMinValue = (Byte)Byte.MinValue;
public static Byte ByteSByteMaxValue = (Byte)SByte.MaxValue;
public static Byte ByteCharMinValue = (Byte)Char.MinValue;
public static Byte ByteVal0 = (Byte)('a');
public static Byte ByteVal1 = (Byte)(10);
public static Byte ByteVal2 = (Byte)(42);
public static Byte ByteVal6 = (Byte)(0);
public static Byte ByteVal7 = (Byte)(1);
public static SByte SByteUInt32MinValue = (SByte)UInt32.MinValue;
public static SByte SByteUInt16MinValue = (SByte)UInt16.MinValue;
public static SByte SByteUInt64MinValue = (SByte)UInt64.MinValue;
public static SByte SByteByteMinValue = (SByte)Byte.MinValue;
public static SByte SByteSByteMaxValue = (SByte)SByte.MaxValue;
public static SByte SByteSByteMinValue = (SByte)SByte.MinValue;
public static SByte SByteCharMinValue = (SByte)Char.MinValue;
public static SByte SByteVal0 = (SByte)('a');
public static SByte SByteVal1 = (SByte)(10);
public static SByte SByteVal2 = (SByte)(42);
public static SByte SByteVal3 = (SByte)(-24);
public static SByte SByteVal6 = (SByte)(0);
public static SByte SByteVal7 = (SByte)(1);
public static SByte SByteVal8 = (SByte)(-1);
public static Char CharUInt32MinValue = (Char)UInt32.MinValue;
public static Char CharInt16MaxValue = (Char)Int16.MaxValue;
public static Char CharUInt16MaxValue = (Char)UInt16.MaxValue;
public static Char CharUInt16MinValue = (Char)UInt16.MinValue;
public static Char CharUInt64MinValue = (Char)UInt64.MinValue;
public static Char CharByteMaxValue = (Char)Byte.MaxValue;
public static Char CharByteMinValue = (Char)Byte.MinValue;
public static Char CharSByteMaxValue = (Char)SByte.MaxValue;
public static Char CharCharMaxValue = (Char)Char.MaxValue;
public static Char CharCharMinValue = (Char)Char.MinValue;
public static Char CharVal0 = (Char)('a');
public static Char CharVal1 = (Char)(10);
public static Char CharVal2 = (Char)(42);
public static Char CharVal6 = (Char)(0);
public static Char CharVal7 = (Char)(1);
public static Boolean BooleanInt32MaxValue = (Boolean)true;
public static Boolean BooleanInt32MinValue = (Boolean)true;
public static Boolean BooleanUInt32MaxValue = (Boolean)true;
public static Boolean BooleanUInt32MinValue = (Boolean)false;
public static Boolean BooleanInt16MaxValue = (Boolean)true;
public static Boolean BooleanInt16MinValue = (Boolean)true;
public static Boolean BooleanUInt16MaxValue = (Boolean)true;
public static Boolean BooleanUInt16MinValue = (Boolean)false;
public static Boolean BooleanInt64MaxValue = (Boolean)true;
public static Boolean BooleanInt64MinValue = (Boolean)true;
public static Boolean BooleanUInt64MaxValue = (Boolean)true;
public static Boolean BooleanUInt64MinValue = (Boolean)false;
public static Boolean BooleanByteMaxValue = (Boolean)true;
public static Boolean BooleanByteMinValue = (Boolean)false;
public static Boolean BooleanSByteMaxValue = (Boolean)true;
public static Boolean BooleanSByteMinValue = (Boolean)true;
public static Boolean BooleanVal1 = (Boolean)(true);
public static Boolean BooleanVal2 = (Boolean)(true);
public static Boolean BooleanVal3 = (Boolean)(true);
public static Boolean BooleanVal4 = (Boolean)(true);
public static Boolean BooleanVal5 = (Boolean)(false);
public static Boolean BooleanVal6 = (Boolean)(false);
public static Boolean BooleanVal7 = (Boolean)(true);
public static Boolean BooleanVal8 = (Boolean)(true);
public static uint uintT(uint val) {
return val;
}
public static ushort ushortT(ushort val) {
return val;
}
public static ulong ulongT(ulong val) {
return val;
}
public static int intT(int val) {
return val;
}
public static short shortT(short val) {
return val;
}
public static long longT(long val) {
return val;
}
public static byte byteT(byte val) {
return val;
}
public static sbyte sbyteT(sbyte val) {
return val;
}
public static char charT(char val) {
return val;
}
public static bool boolT(bool val) {
return val;
}
public static bool AreEqual(object x, object y) {
if (x == y) return true;
if (x == null || y == null) return false;
return x.ToString() == y.ToString();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.