context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
using System.IO;
#if !SILVERLIGHT
using log4net;
#endif
using FluorineFx.Util;
using FluorineFx.IO;
namespace FluorineFx.IO.FLV
{
/// <summary>
/// A Reader is used to read the contents of a FLV file.
/// </summary>
class FlvReader : ITagReader, IKeyFrameDataAnalyzer
{
#if !SILVERLIGHT
private static readonly ILog log = LogManager.GetLogger(typeof(FlvReader));
#endif
object _syncLock = new object();
private FileInfo _file;
private AMFReader _reader;
/// <summary>
/// Set to true to generate metadata automatically before the first tag.
/// </summary>
private bool _generateMetadata;
/// <summary>
/// Keyframe metadata.
/// </summary>
private KeyFrameMeta _keyframeMeta;
/// <summary>
/// Position of first video tag.
/// </summary>
private long _firstVideoTag = -1;
/// <summary>
/// Position of first audio tag.
/// </summary>
private long _firstAudioTag = -1;
/// <summary>
/// Current tag.
/// </summary>
private int _tagPosition;
/// <summary>
/// Duration in milliseconds.
/// </summary>
private long _duration;
/// <summary>
/// Mapping between file position and timestamp in ms.
/// (Long, Long)
/// </summary>
private Dictionary<long, long> _posTimeMap;
/// <summary>
/// Mapping between file position and tag number.
/// (Long, Integer)
/// </summary>
private Dictionary<long, int> _posTagMap;
/// <summary>
/// The header of this FLV file.
/// </summary>
private FlvHeader _header;
public FlvReader()
{
}
public FlvReader(FileInfo file)
: this(file, false)
{
}
public FlvReader(FileInfo file, bool generateMetadata)
{
_file = file;
FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
//_reader = new AMFReader(file.Open(FileMode.Open));
_reader = new AMFReader(fs);
_generateMetadata = generateMetadata;
if (GetRemainingBytes() >= 9)
DecodeHeader();
_keyframeMeta = AnalyzeKeyFrames();
}
/// <summary>
/// Gets an object that can be used to synchronize access.
/// </summary>
public object SyncRoot { get { return _syncLock; } }
/// <summary>
/// Get the remaining bytes that could be read from a file or ByteBuffer.
/// </summary>
/// <returns></returns>
private long GetRemainingBytes()
{
return _reader.BaseStream.Length - _reader.BaseStream.Position;
}
/// <summary>
/// Get the total readable bytes in a file or ByteBuffer.
/// </summary>
/// <returns></returns>
private long GetTotalBytes()
{
return _file.Length;
}
/// <summary>
/// Get the current position in a file or ByteBuffer.
/// </summary>
/// <returns></returns>
private long GetCurrentPosition()
{
return _reader.BaseStream.Position;
}
/// <summary>
/// Modifies current position.
/// </summary>
/// <param name="pos"></param>
private void SetCurrentPosition(long pos)
{
if (pos == long.MaxValue)
{
pos = _file.Length;
}
_reader.BaseStream.Position = pos;
}
#region ITagReader Members
public IStreamableFile File
{
get { return null; }
}
public int Offset
{
get { return 0; }
}
public long BytesRead
{
get { return GetCurrentPosition(); }
}
public long Duration
{
get { return _duration; }
}
public void DecodeHeader()
{
// SIGNATURE, lets just skip
_header = new FlvHeader();
byte[] signature = _reader.ReadBytes(3);//FLV
_header.Version = _reader.ReadByte();
_header.SetTypeFlags(_reader.ReadByte());
_header.DataOffset = _reader.ReadInt32();
#if !SILVERLIGHT
if (log.IsDebugEnabled)
{
log.Debug("Flv header: " + _header.ToString());
}
#endif
}
/// <summary>
/// Gets or sets the current position.
/// The caller must ensure the pos is a valid one
/// </summary>
public long Position
{
get
{
return GetCurrentPosition();
}
set
{
SetCurrentPosition(value);
if (value == long.MaxValue)
{
_tagPosition = _posTagMap.Count + 1;
return;
}
// Make sure we have informations about the keyframes.
AnalyzeKeyFrames();
// Update the current tag number
if (_posTagMap.ContainsKey(value))
{
_tagPosition = (int)_posTagMap[value];
}
}
}
public bool HasMoreTags()
{
return GetRemainingBytes() > 4;
}
public ITag ReadTag()
{
lock (this.SyncRoot)
{
long oldPos = GetCurrentPosition();
ITag tag = ReadTagHeader();
if (_tagPosition == 0 && tag.DataType != IOConstants.TYPE_METADATA && _generateMetadata)
{
// Generate initial metadata automatically
SetCurrentPosition(oldPos);
KeyFrameMeta meta = AnalyzeKeyFrames();
_tagPosition++;
if (meta != null)
{
return CreateFileMeta();
}
}
// This assists in 'properly' handling damaged FLV files
long newPosition = GetCurrentPosition() + tag.BodySize;
if (newPosition <= GetTotalBytes())
{
byte[] buffer = _reader.ReadBytes(tag.BodySize);
tag.Body = buffer;
_tagPosition++;
}
return tag;
}
}
public void Close()
{
_reader.Close();
}
public bool HasVideo()
{
KeyFrameMeta meta = AnalyzeKeyFrames();
if (meta == null)
return false;
return (!meta.AudioOnly && meta.Positions.Length > 0);
}
#endregion
#region IKeyFrameDataAnalyzer Members
/// <summary>
/// Key frames analysis may be used as a utility method so synchronize it.
/// </summary>
/// <returns></returns>
public KeyFrameMeta AnalyzeKeyFrames()
{
lock (this.SyncRoot)
{
if (_keyframeMeta != null)
return _keyframeMeta;
// Lists of video positions and timestamps
List<long> positionList = new List<long>();
List<int> timestampList = new List<int>();
// Lists of audio positions and timestamps
List<long> audioPositionList = new List<long>();
List<int> audioTimestampList = new List<int>();
long origPos = GetCurrentPosition();
// point to the first tag
SetCurrentPosition(9);
// Maps positions to tags
_posTagMap = new Dictionary<long,int>();
int idx = 0;
bool audioOnly = true;
while (this.HasMoreTags())
{
long pos = GetCurrentPosition();
_posTagMap.Add(pos, idx++);
// Read tag header and duration
ITag tmpTag = this.ReadTagHeader();
_duration = tmpTag.Timestamp;
if (tmpTag.DataType == IOConstants.TYPE_VIDEO)
{
if (audioOnly)
{
audioOnly = false;
audioPositionList.Clear();
audioTimestampList.Clear();
}
if (_firstVideoTag == -1)
{
_firstVideoTag = pos;
}
// Grab Frame type
byte frametype = _reader.ReadByte();
if (((frametype & IOConstants.MASK_VIDEO_FRAMETYPE) >> 4) == IOConstants.FLAG_FRAMETYPE_KEYFRAME)
{
positionList.Add(pos);
timestampList.Add(tmpTag.Timestamp);
}
}
else if (tmpTag.DataType == IOConstants.TYPE_AUDIO)
{
if (_firstAudioTag == -1)
{
_firstAudioTag = pos;
}
if (audioOnly)
{
audioPositionList.Add(pos);
audioTimestampList.Add(tmpTag.Timestamp);
}
}
// This properly handles damaged FLV files - as far as duration/size is concerned
long newPosition = pos + tmpTag.BodySize + 15;
if (newPosition >= GetTotalBytes())
{
#if !SILVERLIGHT
log.Info("New position exceeds limit");
if (log.IsDebugEnabled)
{
log.Debug("Keyframe analysis");
log.Debug(" data type=" + tmpTag.DataType + " bodysize=" + tmpTag.BodySize);
log.Debug(" remaining=" + GetRemainingBytes() + " limit=" + GetTotalBytes() + " new pos=" + newPosition + " pos=" + pos);
}
#endif
break;
}
else
{
SetCurrentPosition(newPosition);
}
}
// restore the pos
SetCurrentPosition(origPos);
_keyframeMeta = new KeyFrameMeta();
_keyframeMeta.Duration = _duration;
_posTimeMap = new Dictionary<long,long>();
if (audioOnly)
{
// The flv only contains audio tags, use their lists to support pause and seeking
positionList = audioPositionList;
timestampList = audioTimestampList;
}
_keyframeMeta.AudioOnly = audioOnly;
_keyframeMeta.Positions = new long[positionList.Count];
_keyframeMeta.Timestamps = new int[timestampList.Count];
for (int i = 0; i < _keyframeMeta.Positions.Length; i++)
{
_keyframeMeta.Positions[i] = (long)positionList[i];
_keyframeMeta.Timestamps[i] = (int)timestampList[i];
_posTimeMap.Add((long)positionList[i], (long)((int)timestampList[i]));
}
return _keyframeMeta;
}
}
#endregion
public int VideoCodecId
{
get
{
KeyFrameMeta meta = AnalyzeKeyFrames();
if (meta == null)
return -1;
long old = GetCurrentPosition();
SetCurrentPosition( _firstVideoTag );
ReadTagHeader();
byte frametype = _reader.ReadByte();
SetCurrentPosition(old);
return frametype & IOConstants.MASK_VIDEO_CODEC;
}
}
public int AudioCodecId
{
get
{
KeyFrameMeta meta = AnalyzeKeyFrames();
if (meta == null)
return -1;
long old = GetCurrentPosition();
SetCurrentPosition(_firstAudioTag);
ReadTagHeader();
byte frametype = _reader.ReadByte();
SetCurrentPosition(old);
return frametype & IOConstants.MASK_SOUND_FORMAT;
}
}
/// <summary>
/// Create tag for metadata event.
/// </summary>
/// <returns></returns>
private ITag CreateFileMeta()
{
// Create tag for onMetaData event
ByteBuffer buf = ByteBuffer.Allocate(1024);
buf.AutoExpand = true;
AMFWriter output = new AMFWriter(buf);
// Duration property
output.WriteString("onMetaData");
Dictionary<string, object> props = new Dictionary<string,object>();
props.Add("duration", _duration / 1000.0);
if (_firstVideoTag != -1)
{
long old = GetCurrentPosition();
SetCurrentPosition(_firstVideoTag);
ReadTagHeader();
byte frametype = _reader.ReadByte();
// Video codec id
props.Add("videocodecid", frametype & IOConstants.MASK_VIDEO_CODEC);
SetCurrentPosition(old);
}
if (_firstAudioTag != -1)
{
long old = GetCurrentPosition();
SetCurrentPosition(_firstAudioTag);
ReadTagHeader();
byte frametype = _reader.ReadByte();
// Audio codec id
props.Add("audiocodecid", (frametype & IOConstants.MASK_SOUND_FORMAT) >> 4);
SetCurrentPosition(old);
}
props.Add("canSeekToEnd", true);
output.WriteAssociativeArray(ObjectEncoding.AMF0, props);
buf.Flip();
ITag result = new Tag(IOConstants.TYPE_METADATA, 0, buf.Limit, buf.ToArray(), 0);
return result;
}
public ByteBuffer GetFileData()
{
// TODO as of now, return null will disable cache
// we need to redesign the cache architecture so that
// the cache is layed underneath FLVReader not above it,
// thus both tag cache and file cache are feasible.
return null;
}
/// <summary>
/// Read only header part of a tag.
/// </summary>
/// <returns></returns>
private ITag ReadTagHeader()
{
// PREVIOUS TAG SIZE
int previousTagSize = _reader.ReadInt32();
// START OF FLV TAG
byte dataType = _reader.ReadByte();
int bodySize = _reader.ReadUInt24();
int timestamp = _reader.ReadUInt24();
timestamp |= _reader.ReadByte() << 24;
int streamId = _reader.ReadUInt24();
return new Tag(dataType, timestamp, bodySize, null, previousTagSize);
}
}
}
| |
using Icu.Collation;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Analysis
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// base test class for testing Unicode collation.
/// </summary>
public abstract class CollationTestBase : LuceneTestCase
{
protected internal string FirstRangeBeginningOriginal = "\u062F";
protected internal string FirstRangeEndOriginal = "\u0698";
protected internal string SecondRangeBeginningOriginal = "\u0633";
protected internal string SecondRangeEndOriginal = "\u0638";
// LUCENENET: The all locales may are not available for collation.
protected readonly string[] availableCollationLocales = RuleBasedCollator.GetAvailableCollationLocales().ToArray();
/// <summary>
/// Convenience method to perform the same function as CollationKeyFilter.
/// </summary>
/// <param name="keyBits"> the result from
/// collator.getCollationKey(original).toByteArray() </param>
/// <returns> The encoded collation key for the original String </returns>
/// @deprecated only for testing deprecated filters
[Obsolete("only for testing deprecated filters")]
protected internal virtual string EncodeCollationKey(byte[] keyBits)
{
// Ensure that the backing char[] array is large enough to hold the encoded
// Binary String
int encodedLength = IndexableBinaryStringTools.GetEncodedLength(keyBits, 0, keyBits.Length);
char[] encodedBegArray = new char[encodedLength];
IndexableBinaryStringTools.Encode(keyBits, 0, keyBits.Length, encodedBegArray, 0, encodedLength);
return new string(encodedBegArray);
}
public virtual void TestFarsiRangeFilterCollating(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
doc.Add(new StringField("body", "body", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
Search.Query query = new TermQuery(new Term("body", "body"));
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeFilter with a Farsi
// Collator (or an Arabic one for the case when Farsi searcher not
// supported).
ScoreDoc[] result = searcher.Search(query, new TermRangeFilter("content", firstBeg, firstEnd, true, true), 1).ScoreDocs;
Assert.AreEqual(0, result.Length, "The index Term should not be included.");
result = searcher.Search(query, new TermRangeFilter("content", secondBeg, secondEnd, true, true), 1).ScoreDocs;
Assert.AreEqual(1, result.Length, "The index Term should be included.");
reader.Dispose();
dir.Dispose();
}
public virtual void TestFarsiRangeQueryCollating(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeQuery with a Farsi
// Collator (or an Arabic one for the case when Farsi is not supported).
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
Search.Query query = new TermRangeQuery("content", firstBeg, firstEnd, true, true);
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
AreEqual(0, hits.Length, "The index Term should not be included.");
query = new TermRangeQuery("content", secondBeg, secondEnd, true, true);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "The index Term should be included.");
reader.Dispose();
dir.Dispose();
}
public virtual void TestFarsiTermRangeQuery(Analyzer analyzer, BytesRef firstBeg, BytesRef firstEnd, BytesRef secondBeg, BytesRef secondEnd)
{
Directory farsiIndex = NewDirectory();
IndexWriter writer = new IndexWriter(farsiIndex, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, analyzer));
Document doc = new Document();
doc.Add(new TextField("content", "\u0633\u0627\u0628", Field.Store.YES));
doc.Add(new StringField("body", "body", Field.Store.YES));
writer.AddDocument(doc);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(farsiIndex);
IndexSearcher search = this.NewSearcher(reader);
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the single
// index Term below should NOT be returned by a TermRangeQuery
// with a Farsi Collator (or an Arabic one for the case when Farsi is
// not supported).
Search.Query csrq = new TermRangeQuery("content", firstBeg, firstEnd, true, true);
ScoreDoc[] result = search.Search(csrq, null, 1000).ScoreDocs;
Assert.AreEqual(0, result.Length, "The index Term should not be included.");
csrq = new TermRangeQuery("content", secondBeg, secondEnd, true, true);
result = search.Search(csrq, null, 1000).ScoreDocs;
Assert.AreEqual(1, result.Length, "The index Term should be included.");
reader.Dispose();
farsiIndex.Dispose();
}
// Test using various international locales with accented characters (which
// sort differently depending on locale)
//
// Copied (and slightly modified) from
// Lucene.Net.Search.TestSort.testInternationalSort()
//
// TODO: this test is really fragile. there are already 3 different cases,
// depending upon unicode version.
public virtual void TestCollationKeySort(Analyzer usAnalyzer, Analyzer franceAnalyzer, Analyzer swedenAnalyzer, Analyzer denmarkAnalyzer, string usResult, string frResult, string svResult, string dkResult)
{
Directory indexStore = NewDirectory();
IndexWriter writer = new IndexWriter(indexStore, new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false)));
// document data:
// the tracer field is used to determine which document was hit
string[][] sortData = new string[][] { new string[] { "A", "x", "p\u00EAche", "p\u00EAche", "p\u00EAche", "p\u00EAche" }, new string[] { "B", "y", "HAT", "HAT", "HAT", "HAT" }, new string[] { "C", "x", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9", "p\u00E9ch\u00E9" }, new string[] { "D", "y", "HUT", "HUT", "HUT", "HUT" }, new string[] { "E", "x", "peach", "peach", "peach", "peach" }, new string[] { "F", "y", "H\u00C5T", "H\u00C5T", "H\u00C5T", "H\u00C5T" }, new string[] { "G", "x", "sin", "sin", "sin", "sin" }, new string[] { "H", "y", "H\u00D8T", "H\u00D8T", "H\u00D8T", "H\u00D8T" }, new string[] { "I", "x", "s\u00EDn", "s\u00EDn", "s\u00EDn", "s\u00EDn" }, new string[] { "J", "y", "HOT", "HOT", "HOT", "HOT" } };
FieldType customType = new FieldType();
customType.IsStored = true;
for (int i = 0; i < sortData.Length; ++i)
{
Document doc = new Document();
doc.Add(new Field("tracer", sortData[i][0], customType));
doc.Add(new TextField("contents", sortData[i][1], Field.Store.NO));
if (sortData[i][2] != null)
{
doc.Add(new TextField("US", usAnalyzer.GetTokenStream("US", new StringReader(sortData[i][2]))));
}
if (sortData[i][3] != null)
{
doc.Add(new TextField("France", franceAnalyzer.GetTokenStream("France", new StringReader(sortData[i][3]))));
}
if (sortData[i][4] != null)
{
doc.Add(new TextField("Sweden", swedenAnalyzer.GetTokenStream("Sweden", new StringReader(sortData[i][4]))));
}
if (sortData[i][5] != null)
{
doc.Add(new TextField("Denmark", denmarkAnalyzer.GetTokenStream("Denmark", new StringReader(sortData[i][5]))));
}
writer.AddDocument(doc);
}
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(indexStore);
IndexSearcher searcher = new IndexSearcher(reader);
Sort sort = new Sort();
Search.Query queryX = new TermQuery(new Term("contents", "x"));
Search.Query queryY = new TermQuery(new Term("contents", "y"));
sort.SetSort(new SortField("US", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, usResult);
sort.SetSort(new SortField("France", SortFieldType.STRING));
this.AssertMatches(searcher, queryX, sort, frResult);
sort.SetSort(new SortField("Sweden", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, svResult);
sort.SetSort(new SortField("Denmark", SortFieldType.STRING));
this.AssertMatches(searcher, queryY, sort, dkResult);
reader.Dispose();
indexStore.Dispose();
}
// Make sure the documents returned by the search match the expected list
// Copied from TestSort.java
private void AssertMatches(IndexSearcher searcher, Search.Query query, Sort sort, string expectedResult)
{
ScoreDoc[] result = searcher.Search(query, null, 1000, sort).ScoreDocs;
StringBuilder buff = new StringBuilder(10);
int n = result.Length;
for (int i = 0; i < n; ++i)
{
Document doc = searcher.Doc(result[i].Doc);
IIndexableField[] v = doc.GetFields("tracer");
for (var j = 0; j < v.Length; ++j)
{
buff.Append(v[j].GetStringValue());
}
}
Assert.AreEqual(expectedResult, buff.ToString());
}
public virtual void AssertThreadSafe(Analyzer analyzer)
{
int numTestPoints = 100;
int numThreads = TestUtil.NextInt(Random(), 3, 5);
Dictionary<string, BytesRef> map = new Dictionary<string, BytesRef>();
// create a map<String,SortKey> up front.
// then with multiple threads, generate sort keys for all the keys in the map
// and ensure they are the same as the ones we produced in serial fashion.
for (int i = 0; i < numTestPoints; i++)
{
string term = TestUtil.RandomSimpleString(Random());
IOException priorException = null;
TokenStream ts = analyzer.GetTokenStream("fake", new StringReader(term));
try
{
ITermToBytesRefAttribute termAtt = ts.AddAttribute<ITermToBytesRefAttribute>();
BytesRef bytes = termAtt.BytesRef;
ts.Reset();
Assert.IsTrue(ts.IncrementToken());
termAtt.FillBytesRef();
// ensure we make a copy of the actual bytes too
map[term] = BytesRef.DeepCopyOf(bytes);
Assert.IsFalse(ts.IncrementToken());
ts.End();
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
ThreadClass[] threads = new ThreadClass[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper(this, analyzer, map);
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Start();
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly CollationTestBase OuterInstance;
private Analyzer Analyzer;
private Dictionary<string, BytesRef> Map;
public ThreadAnonymousInnerClassHelper(CollationTestBase outerInstance, Analyzer analyzer, Dictionary<string, BytesRef> map)
{
this.OuterInstance = outerInstance;
this.Analyzer = analyzer;
this.Map = map;
}
public override void Run()
{
try
{
foreach (var mapping in this.Map)
{
string term = mapping.Key;
BytesRef expected = mapping.Value;
IOException priorException = null;
TokenStream ts = this.Analyzer.GetTokenStream("fake", new StringReader(term));
try
{
ITermToBytesRefAttribute termAtt = ts.AddAttribute<ITermToBytesRefAttribute>();
BytesRef bytes = termAtt.BytesRef;
ts.Reset();
IsTrue(ts.IncrementToken());
termAtt.FillBytesRef();
AreEqual(expected, bytes);
IsFalse(ts.IncrementToken());
ts.End();
}
catch (IOException e)
{
priorException = e;
}
finally
{
IOUtils.DisposeWhileHandlingException(priorException, ts);
}
}
}
catch (IOException e)
{
throw (Exception)e;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
** Class: SortedList
**
** Purpose: Represents a collection of key/value pairs
** that are sorted by the keys and are accessible
** by key and by index.
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections
{
// The SortedList class implements a sorted list of keys and values. Entries in
// a sorted list are sorted by their keys and are accessible both by key and by
// index. The keys of a sorted list can be ordered either according to a
// specific IComparer implementation given when the sorted list is
// instantiated, or according to the IComparable implementation provided
// by the keys themselves. In either case, a sorted list does not allow entries
// with duplicate keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimToSize or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]
[DebuggerDisplay("Count = {Count}")]
#if FEATURE_CORECLR
[Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
#endif
public class SortedList : IDictionary
{
private Object[] _keys;
private Object[] _values;
private int _size;
private int _version;
private IComparer _comparer;
private KeyList _keyList;
private ValueList _valueList;
private Object _syncRoot;
private const int _defaultCapacity = 16;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
Init();
}
private void Init()
{
_keys = Array.Empty<Object>();
_values = Array.Empty<Object>();
_size = 0;
_comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException("initialCapacity", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
_keys = new Object[initialCapacity];
_values = new Object[initialCapacity];
_comparer = new Comparer(CultureInfo.CurrentCulture);
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer comparer)
: this()
{
if (comparer != null) _comparer = comparer;
}
// Constructs a new sorted list with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(IComparer comparer, int capacity)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d)
: this(d, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary d, IComparer comparer)
: this(comparer, (d != null ? d.Count : 0))
{
if (d == null)
throw new ArgumentNullException("d", SR.ArgumentNull_Dictionary);
Contract.EndContractBlock();
d.Keys.CopyTo(_keys, 0);
d.Values.CopyTo(_values, 0);
// Array.Sort(Array keys, Array values, IComparer comparer) does not exist in System.Runtime contract v4.0.10.0.
// This works around that by sorting only on the keys and then assigning values accordingly.
Array.Sort(_keys, comparer);
for (int i = 0; i < _keys.Length; i++)
{
_values[i] = d[_keys[i]];
}
_size = d.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public virtual void Add(Object key, Object value)
{
if (key == null) throw new ArgumentNullException("key", SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_keys, 0, _size, key, _comparer);
if (i >= 0)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, GetKey(i), key));
Insert(~i, key, value);
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public virtual int Capacity
{
get
{
return _keys.Length;
}
set
{
if (value < Count)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _keys.Length)
{
if (value > 0)
{
Object[] newKeys = new Object[value];
Object[] newValues = new Object[value];
if (_size > 0)
{
Array.Copy(_keys, 0, newKeys, 0, _size);
Array.Copy(_values, 0, newValues, 0, _size);
}
_keys = newKeys;
_values = newValues;
}
else
{
// size can only be zero here.
Debug.Assert(_size == 0, "Size is not zero");
_keys = Array.Empty<Object>();
_values = Array.Empty<Object>();
}
}
}
}
// Returns the number of entries in this sorted list.
//
public virtual int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Keys
{
get
{
return GetKeyList();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Values
{
get
{
return GetValueList();
}
}
// Is this SortedList read-only?
public virtual bool IsReadOnly
{
get { return false; }
}
public virtual bool IsFixedSize
{
get { return false; }
}
// Is this SortedList synchronized (thread-safe)?
public virtual bool IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all entries from this sorted list.
public virtual void Clear()
{
// clear does not change the capacity
_version++;
Array.Clear(_keys, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
Array.Clear(_values, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
// Makes a virtually identical copy of this SortedList. This is a shallow
// copy. IE, the Objects in the SortedList are not cloned - we copy the
// references to those objects.
public virtual Object Clone()
{
SortedList sl = new SortedList(_size);
Array.Copy(_keys, 0, sl._keys, 0, _size);
Array.Copy(_values, 0, sl._values, 0, _size);
sl._size = _size;
sl._version = _version;
sl._comparer = _comparer;
// Don't copy keyList nor valueList.
return sl;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool Contains(Object key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool ContainsKey(Object key)
{
// Yes, this is a SPEC'ed duplicate of Contains().
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
public virtual bool ContainsValue(Object value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array", SR.ArgumentNull_Array);
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
for (int i = 0; i < Count; i++)
{
DictionaryEntry entry = new DictionaryEntry(_keys[i], _values[i]);
array.SetValue(entry, i + arrayIndex);
}
}
// Copies the values in this SortedList to an KeyValuePairs array.
// KeyValuePairs is different from Dictionary Entry in that it has special
// debugger attributes on its fields.
internal virtual KeyValuePairs[] ToKeyValuePairsArray()
{
KeyValuePairs[] array = new KeyValuePairs[Count];
for (int i = 0; i < Count; i++)
{
array[i] = new KeyValuePairs(_keys[i], _values[i]);
}
return array;
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the current capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = _keys.Length == 0 ? 16 : _keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > ArrayList.MaxArrayLength) newCapacity = ArrayList.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
public virtual Object GetByIndex(int index)
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return _values[index];
}
// Returns an IEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns an IDictionaryEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
public virtual IDictionaryEnumerator GetEnumerator()
{
return new SortedListEnumerator(this, 0, _size, SortedListEnumerator.DictEntry);
}
// Returns the key of the entry at the given index.
//
public virtual Object GetKey(int index)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return _keys[index];
}
// Returns an IList representing the keys of this sorted list. The
// returned list is an alias for the keys of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding, inserting, or modifying elements
// (the Add, AddRange, Insert, InsertRange,
// Reverse, Set, SetRange, and Sort methods
// throw exceptions), but it does allow removal of elements (through the
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
public virtual IList GetKeyList()
{
if (_keyList == null) _keyList = new KeyList(this);
return _keyList;
}
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding or inserting elements (the
// Add, AddRange, Insert and InsertRange
// methods throw exceptions), but it does allow modification and removal of
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
public virtual IList GetValueList()
{
if (_valueList == null) _valueList = new ValueList(this);
return _valueList;
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
public virtual Object this[Object key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0) return _values[i];
return null;
}
set
{
if (key == null) throw new ArgumentNullException("key", SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_keys, 0, _size, key, _comparer);
if (i >= 0)
{
_values[i] = value;
_version++;
return;
}
Insert(~i, key, value);
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
public virtual int IndexOfKey(Object key)
{
if (key == null)
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
Contract.EndContractBlock();
int ret = Array.BinarySearch(_keys, 0, _size, key, _comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
public virtual int IndexOfValue(Object value)
{
return Array.IndexOf(_values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, Object key, Object value)
{
if (_size == _keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_keys, index, _keys, index + 1, _size - index);
Array.Copy(_values, index, _values, index + 1, _size - index);
}
_keys[index] = key;
_values[index] = value;
_size++;
_version++;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
public virtual void RemoveAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_keys, index + 1, _keys, index, _size - index);
Array.Copy(_values, index + 1, _values, index, _size - index);
}
_keys[_size] = null;
_values[_size] = null;
_version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
public virtual void Remove(Object key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
}
// Sets the value at an index to a given value. The previous value of
// the given entry is overwritten.
//
public virtual void SetByIndex(int index, Object value)
{
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
_values[index] = value;
_version++;
}
// Returns a thread-safe SortedList.
//
public static SortedList Synchronized(SortedList list)
{
if (list == null)
throw new ArgumentNullException("list");
Contract.EndContractBlock();
return new SyncSortedList(list);
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// sortedList.Clear();
// sortedList.TrimToSize();
//
public virtual void TrimToSize()
{
Capacity = _size;
}
private class SyncSortedList : SortedList
{
private SortedList _list;
private Object _root;
internal SyncSortedList(SortedList list)
{
_list = list;
_root = list.SyncRoot;
}
public override int Count
{
get { lock (_root) { return _list.Count; } }
}
public override Object SyncRoot
{
get { return _root; }
}
public override bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public override bool IsFixedSize
{
get { return _list.IsFixedSize; }
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object this[Object key]
{
get
{
lock (_root)
{
return _list[key];
}
}
set
{
lock (_root)
{
_list[key] = value;
}
}
}
public override void Add(Object key, Object value)
{
lock (_root)
{
_list.Add(key, value);
}
}
public override int Capacity
{
get { lock (_root) { return _list.Capacity; } }
}
public override void Clear()
{
lock (_root)
{
_list.Clear();
}
}
public override Object Clone()
{
lock (_root)
{
return _list.Clone();
}
}
public override bool Contains(Object key)
{
lock (_root)
{
return _list.Contains(key);
}
}
public override bool ContainsKey(Object key)
{
lock (_root)
{
return _list.ContainsKey(key);
}
}
public override bool ContainsValue(Object key)
{
lock (_root)
{
return _list.ContainsValue(key);
}
}
public override void CopyTo(Array array, int index)
{
lock (_root)
{
_list.CopyTo(array, index);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetByIndex(int index)
{
lock (_root)
{
return _list.GetByIndex(index);
}
}
public override IDictionaryEnumerator GetEnumerator()
{
lock (_root)
{
return _list.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override Object GetKey(int index)
{
lock (_root)
{
return _list.GetKey(index);
}
}
public override IList GetKeyList()
{
lock (_root)
{
return _list.GetKeyList();
}
}
public override IList GetValueList()
{
lock (_root)
{
return _list.GetValueList();
}
}
public override int IndexOfKey(Object key)
{
if (key == null)
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
Contract.EndContractBlock();
lock (_root)
{
return _list.IndexOfKey(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int IndexOfValue(Object value)
{
lock (_root)
{
return _list.IndexOfValue(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void RemoveAt(int index)
{
lock (_root)
{
_list.RemoveAt(index);
}
}
public override void Remove(Object key)
{
lock (_root)
{
_list.Remove(key);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void SetByIndex(int index, Object value)
{
lock (_root)
{
_list.SetByIndex(index, value);
}
}
internal override KeyValuePairs[] ToKeyValuePairsArray()
{
return _list.ToKeyValuePairsArray();
}
public override void TrimToSize()
{
lock (_root)
{
_list.TrimToSize();
}
}
}
private class SortedListEnumerator : IDictionaryEnumerator
{
private SortedList _sortedList;
private Object _key;
private Object _value;
private int _index;
private int _startIndex; // Store for Reset.
private int _endIndex;
private int _version;
private bool _current; // Is the current element valid?
private int _getObjectRetType; // What should GetObject return?
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
internal SortedListEnumerator(SortedList sortedList, int index, int count,
int getObjRetType)
{
_sortedList = sortedList;
_index = index;
_startIndex = index;
_endIndex = index + count;
_version = sortedList._version;
_getObjectRetType = getObjRetType;
_current = false;
}
public virtual Object Key
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return _key;
}
}
public virtual bool MoveNext()
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < _endIndex)
{
_key = _sortedList._keys[_index];
_value = _sortedList._values[_index];
_index++;
_current = true;
return true;
}
_key = null;
_value = null;
_current = false;
return false;
}
public virtual DictionaryEntry Entry
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return new DictionaryEntry(_key, _value);
}
}
public virtual Object Current
{
get
{
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
if (_getObjectRetType == Keys)
return _key;
else if (_getObjectRetType == Values)
return _value;
else
return new DictionaryEntry(_key, _value);
}
}
public virtual Object Value
{
get
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
return _value;
}
}
public virtual void Reset()
{
if (_version != _sortedList._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = _startIndex;
_current = false;
_key = null;
_value = null;
}
}
private class KeyList : IList
{
private SortedList _sortedList;
internal KeyList(SortedList sortedList)
{
_sortedList = sortedList;
}
public virtual int Count
{
get { return _sortedList._size; }
}
public virtual bool IsReadOnly
{
get { return true; }
}
public virtual bool IsFixedSize
{
get { return true; }
}
public virtual bool IsSynchronized
{
get { return _sortedList.IsSynchronized; }
}
public virtual Object SyncRoot
{
get { return _sortedList.SyncRoot; }
}
public virtual int Add(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return 0; // suppress compiler warning
}
public virtual void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual bool Contains(Object key)
{
return _sortedList.Contains(key);
}
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(_sortedList._keys, 0, array, arrayIndex, _sortedList.Count);
}
public virtual void Insert(int index, Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual Object this[int index]
{
get
{
return _sortedList.GetKey(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator(_sortedList, 0, _sortedList.Count, SortedListEnumerator.Keys);
}
public virtual int IndexOf(Object key)
{
if (key == null)
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
Contract.EndContractBlock();
int i = Array.BinarySearch(_sortedList._keys, 0,
_sortedList.Count, key, _sortedList._comparer);
if (i >= 0) return i;
return -1;
}
public virtual void Remove(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
private class ValueList : IList
{
private SortedList _sortedList;
internal ValueList(SortedList sortedList)
{
_sortedList = sortedList;
}
public virtual int Count
{
get { return _sortedList._size; }
}
public virtual bool IsReadOnly
{
get { return true; }
}
public virtual bool IsFixedSize
{
get { return true; }
}
public virtual bool IsSynchronized
{
get { return _sortedList.IsSynchronized; }
}
public virtual Object SyncRoot
{
get { return _sortedList.SyncRoot; }
}
public virtual int Add(Object key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual bool Contains(Object value)
{
return _sortedList.ContainsValue(value);
}
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
Contract.EndContractBlock();
// defer error checking to Array.Copy
Array.Copy(_sortedList._values, 0, array, arrayIndex, _sortedList.Count);
}
public virtual void Insert(int index, Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual Object this[int index]
{
get
{
return _sortedList.GetByIndex(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator(_sortedList, 0, _sortedList.Count, SortedListEnumerator.Values);
}
public virtual int IndexOf(Object value)
{
return Array.IndexOf(_sortedList._values, value, 0, _sortedList.Count);
}
public virtual void Remove(Object value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public virtual void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
// internal debug view class for sorted list
internal class SortedListDebugView
{
private SortedList _sortedList;
public SortedListDebugView(SortedList sortedList)
{
if (sortedList == null)
{
throw new ArgumentNullException("sortedList");
}
Contract.EndContractBlock();
_sortedList = sortedList;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePairs[] Items
{
get
{
return _sortedList.ToKeyValuePairsArray();
}
}
}
}
}
| |
/*
Copyright (c) 2006 Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.CodeDom;
namespace PHP.Core.CodeDom
{
/// <summary>
/// Abstract base for <see cref="PhpMemberAttributeConverter"/> and <see cref="PhpTypeAttributeConverter"/>.
/// </summary>
/// <remarks>This is almost identical to what C# and VB uses, i.e. conversion between string and an
/// arbitrary type based on arrays that hold corresponding name-value pairs at the same indices.</remarks>
internal abstract class PhpModifierAttributeConverter : TypeConverter
{
protected abstract object DefaultValue { get; }
protected abstract string[] Names { get; }
protected abstract object[] Values { get; }
protected PhpModifierAttributeConverter()
{ }
#region TypeConverter Overrides
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter.
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Converts the given value to the type of this converter.
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string str_value = value as string;
if (str_value != null)
{
string[] names = Names;
for (int i = 0; i < names.Length; i++)
{
if (names[i].EqualsOrdinalIgnoreCase(str_value))
{
return Values[i];
}
}
}
return this.DefaultValue;
}
/// <summary>
/// Converts the given value object to the specified type, using the arguments.
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
{
if (destinationType == null) throw new ArgumentNullException("destinationType");
if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);
object[] values = this.Values;
for (int i = 0; i < values.Length; i++)
{
if (values[i].Equals(value))
{
return Names[i];
}
}
return "(unknown)";
}
/// <summary>
/// Returns a collection of standard values for the data type this type converter is designed for.
/// </summary>
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new TypeConverter.StandardValuesCollection(Values);
}
/// <summary>
/// Returns whether the collection of standard values returned from GetStandardValues is an exclusive list.
/// </summary>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
/// <summary>
/// Returns whether this object supports a standard set of values that can be picked from a list.
/// </summary>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
#endregion
}
/// <summary>
/// Provides conversion between strings and <see cref="MemberAttributes"/>.
/// </summary>
internal class PhpMemberAttributeConverter : PhpModifierAttributeConverter
{
#region Fields and Properties
private static PhpMemberAttributeConverter defaultConverter;
public static PhpMemberAttributeConverter Default
{
get
{ return defaultConverter; }
}
private static string[] names;
protected override string[] Names
{
get
{ return names; }
}
private static object[] values;
protected override object[] Values
{
get
{ return values; }
}
protected override object DefaultValue
{
get
{ return MemberAttributes.Public; }
}
#endregion
private PhpMemberAttributeConverter()
{ }
static PhpMemberAttributeConverter()
{
defaultConverter = new PhpMemberAttributeConverter();
names = new string[] { Keywords.Public, Keywords.Protected, Keywords.Private };
values = new object[] { MemberAttributes.Public, MemberAttributes.Family, MemberAttributes.Private };
}
}
/// <summary>
/// Provides conversion between strings and <see cref="System.Reflection.TypeAttributes"/>.
/// </summary>
internal class PhpTypeAttributeConverter : PhpModifierAttributeConverter
{
#region Fields and Properties
private static PhpTypeAttributeConverter defaultConverter;
public static PhpTypeAttributeConverter Default
{
get
{ return defaultConverter; }
}
private static string[] names;
protected override string[] Names
{
get
{ return names; }
}
private static object[] values;
protected override object[] Values
{
get
{ return values; }
}
protected override object DefaultValue
{
get
{ return System.Reflection.TypeAttributes.Public; }
}
#endregion
private PhpTypeAttributeConverter()
{ }
static PhpTypeAttributeConverter()
{
defaultConverter = new PhpTypeAttributeConverter();
names = ArrayUtils.EmptyStrings;
values = ArrayUtils.EmptyObjects;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Globalization {
using System.Text;
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
internal static class TimeSpanFormat {
[System.Security.SecuritySafeCritical] // auto-generated
private static String IntToString(int n, int digits) {
return ParseNumbers.IntToString(n, 10, digits, '0', 0);
}
internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(false /*isNegative*/);
internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/);
internal enum Pattern {
None = 0,
Minimum = 1,
Full = 2,
}
//
// Format
//
// Actions: Main method called from TimeSpan.ToString
//
internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider) {
if (format == null || format.Length == 0)
format = "c";
// standard formats
if (format.Length == 1) {
char f = format[0];
if (f == 'c' || f == 't' || f == 'T')
return FormatStandard(value, true, format, Pattern.Minimum);
if (f == 'g' || f == 'G') {
Pattern pattern;
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
if (value._ticks < 0)
format = dtfi.FullTimeSpanNegativePattern;
else
format = dtfi.FullTimeSpanPositivePattern;
if (f == 'g')
pattern = Pattern.Minimum;
else
pattern = Pattern.Full;
return FormatStandard(value, false, format, pattern);
}
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
}
//
// FormatStandard
//
// Actions: Format the TimeSpan instance using the specified format.
//
private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern) {
StringBuilder sb = StringBuilderCache.Acquire();
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
if (value._ticks < 0) {
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
FormatLiterals literal;
if (isInvariant) {
if (value._ticks < 0)
literal = NegativeInvariantFormatLiterals;
else
literal = PositiveInvariantFormatLiterals;
}
else {
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
if (fraction != 0) { // truncate the partial second to the specified length
fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
// Pattern.Full: [-]dd.hh:mm:ss.fffffff
// Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]
sb.Append(literal.Start); // [-]
if (pattern == Pattern.Full || day != 0) { //
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
sb.Append(IntToString(hours, literal.hh)); // hh
sb.Append(literal.HourMinuteSep); // :
sb.Append(IntToString(minutes, literal.mm)); // mm
sb.Append(literal.MinuteSecondSep); // :
sb.Append(IntToString(seconds, literal.ss)); // ss
if (!isInvariant && pattern == Pattern.Minimum) {
int effectiveDigits = literal.ff;
while (effectiveDigits > 0) {
if (fraction % 10 == 0) {
fraction = fraction / 10;
effectiveDigits--;
}
else {
break;
}
}
if (effectiveDigits > 0) {
sb.Append(literal.SecondFractionSep); // [.FFFFFFF]
sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
}
else if (pattern == Pattern.Full || fraction != 0) {
sb.Append(literal.SecondFractionSep); // [.]
sb.Append(IntToString(fraction, literal.ff)); // [fffffff]
} //
sb.Append(literal.End); //
return StringBuilderCache.GetStringAndRelease(sb);
}
//
// FormatCustomized
//
// Actions: Format the TimeSpan instance using the specified format.
//
internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {
Contract.Assert(dtfi != null, "dtfi == null");
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
if (value._ticks < 0) {
day = -day;
time = -time;
}
int hours = (int)(time / TimeSpan.TicksPerHour % 24);
int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
StringBuilder result = StringBuilderCache.Acquire();
while (i < format.Length) {
char ch = format[i];
int nextChar;
switch (ch) {
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
//
// The fraction of a second in single-digit precision. The remaining digits are truncated.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
//
// Displays the most significant digit of the seconds fraction. Nothing is displayed if the digit is zero.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0) {
if (tmp % 10 == 0) {
tmp = tmp / 10;
effectiveDigits--;
}
else {
break;
}
}
if (effectiveDigits > 0) {
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
case 'd':
//
// tokenLen == 1 : Day as digits with no leading zero.
// tokenLen == 2+: Day as digits with leading zero for single-digit days.
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
StringBuilder enquotedString = new StringBuilder();
tokenLen = DateTimeFormat.ParseQuoteString(format, i, enquotedString);
result.Append(enquotedString);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day
// Most of the cases, "%" can be ignored.
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%') {
result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For example, "\d" will insert the character 'd' into the string.
//
nextChar = DateTimeFormat.ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
default:
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
}
internal struct FormatLiterals {
internal String Start {
get {
return literals[0];
}
}
internal String DayHourSep {
get {
return literals[1];
}
}
internal String HourMinuteSep {
get {
return literals[2];
}
}
internal String MinuteSecondSep {
get {
return literals[3];
}
}
internal String SecondFractionSep {
get {
return literals[4];
}
}
internal String End {
get {
return literals[5];
}
}
internal String AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
private String[] literals;
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative) {
FormatLiterals x = new FormatLiterals();
x.literals = new String[6];
x.literals[0] = isNegative ? "-" : String.Empty;
x.literals[1] = ".";
x.literals[2] = ":";
x.literals[3] = ":";
x.literals[4] = ".";
x.literals[5] = String.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
x.mm = 2;
x.ss = 2;
x.ff = DateTimeFormat.MaxSecondsFractionDigits;
return x;
}
// For the "v1" TimeSpan localized patterns, the data is simply literal field separators with
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
internal void Init(String format, bool useInvariantFieldLengths) {
literals = new String[6];
for (int i = 0; i < literals.Length; i++)
literals[i] = String.Empty;
dd = 0;
hh = 0;
mm = 0;
ss = 0;
ff = 0;
StringBuilder sb = StringBuilderCache.Acquire();
bool inQuote = false;
char quote = '\'';
int field = 0;
for (int i = 0; i < format.Length; i++) {
switch (format[i]) {
case '\'':
case '\"':
if (inQuote && (quote == format[i])) {
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
if (field >= 0 && field <= 5) {
literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else {
return; // how did we get here?
}
}
else if (!inQuote) {
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
else {
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
case '%':
Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote) {
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
if (!inQuote) {
Contract.Assert((field == 0 && sb.Length == 0) || field == 1,
"field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
break;
case 'h':
if (!inQuote) {
Contract.Assert((field == 1 && sb.Length == 0) || field == 2,
"field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
break;
case 'm':
if (!inQuote) {
Contract.Assert((field == 2 && sb.Length == 0) || field == 3,
"field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
break;
case 's':
if (!inQuote) {
Contract.Assert((field == 3 && sb.Length == 0) || field == 4,
"field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
break;
case 'f':
case 'F':
if (!inQuote) {
Contract.Assert((field == 4 && sb.Length == 0) || field == 5,
"field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
break;
default:
sb.Append(format[i]);
break;
}
}
Contract.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths) {
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
else {
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
if (ss < 1 || ss > 2) ss = 2;
if (ff < 1 || ff > 7) ff = 7;
}
StringBuilderCache.Release(sb);
}
} //end of struct FormatLiterals
}
}
| |
using IKVM.Attributes;
using ikvm.@internal;
using java.lang;
using java.util;
using System;
using System.Runtime.CompilerServices;
namespace lanterna.input
{
//[Implements(new string[]
{
"lanterna.input.CharacterPattern"
})]
public class EscapeSequenceCharacterPattern : java.lang.Object, CharacterPattern
{
//[InnerClass, Modifiers, Signature("Ljava/lang/Enum<Lcom/googlecode/lanterna/input/EscapeSequenceCharacterPattern_State;>;"), SourceFile("EscapeSequenceCharacterPattern.java")]
[Serializable]
internal class State : Enum
{
//[Modifiers]
public static EscapeSequenceCharacterPattern.State START;
//[Modifiers]
public static EscapeSequenceCharacterPattern.State INTRO;
//[Modifiers]
public static EscapeSequenceCharacterPattern.State NUM1;
//[Modifiers]
public static EscapeSequenceCharacterPattern.State NUM2;
//[Modifiers]
public static EscapeSequenceCharacterPattern.State DONE;
//[Modifiers]
private static EscapeSequenceCharacterPattern.State[] _VALUES;
//[MethodImpl(MethodImplOptions.NoInlining)]
public static void __<clinit>()
{
}
//[LineNumberTable(41), Signature("()V")]
//[MethodImpl(MethodImplOptions.NoInlining)]
private State(string str, int i) : base(str, i)
{
GC.KeepAlive(this);
}
//[LineNumberTable(41)]
//[MethodImpl(MethodImplOptions.NoInlining)]
public static EscapeSequenceCharacterPattern.State[] values()
{
return (EscapeSequenceCharacterPattern.State[])EscapeSequenceCharacterPattern.State._VALUES.Clone();
}
//[LineNumberTable(41)]
//[MethodImpl(MethodImplOptions.NoInlining)]
public static EscapeSequenceCharacterPattern.State valueOf(string name)
{
return (EscapeSequenceCharacterPattern.State)Enum.valueOf(ClassLiteral<EscapeSequenceCharacterPattern.State>.Value, name);
}
//[LineNumberTable(new byte[]
{
159,
132,
130,
63,
50
})]
static State()
{
EscapeSequenceCharacterPattern.State.START = new EscapeSequenceCharacterPattern.State("START", 0);
EscapeSequenceCharacterPattern.State.INTRO = new EscapeSequenceCharacterPattern.State("INTRO", 1);
EscapeSequenceCharacterPattern.State.NUM1 = new EscapeSequenceCharacterPattern.State("NUM1", 2);
EscapeSequenceCharacterPattern.State.NUM2 = new EscapeSequenceCharacterPattern.State("NUM2", 3);
EscapeSequenceCharacterPattern.State.DONE = new EscapeSequenceCharacterPattern.State("DONE", 4);
EscapeSequenceCharacterPattern.State._VALUES = new EscapeSequenceCharacterPattern.State[]
{
EscapeSequenceCharacterPattern.State.START,
EscapeSequenceCharacterPattern.State.INTRO,
EscapeSequenceCharacterPattern.State.NUM1,
EscapeSequenceCharacterPattern.State.NUM2,
EscapeSequenceCharacterPattern.State.DONE
};
}
}
public const int SHIFT = 1;
public const int ALT = 2;
public const int CTRL = 4;
//[Signature("Ljava/util/Map<Ljava/lang/Integer;Lcom/googlecode/lanterna/input/KeyType;>;")]
internal Map _stdMap;
//[Signature("Ljava/util/Map<Ljava/lang/Character;Lcom/googlecode/lanterna/input/KeyType;>;")]
internal Map _finMap;
protected internal bool useEscEsc;
//[Modifiers]
protected internal Map stdMap
{
//[HideFromJava]
get
{
return this._stdMap;
}
//[HideFromJava]
private set
{
this._stdMap = value;
}
}
//[Modifiers]
protected internal Map finMap
{
//[HideFromJava]
get
{
return this._finMap;
}
//[HideFromJava]
private set
{
this._finMap = value;
}
}
//[LineNumberTable(new byte[]
{
159,
125,
98,
233,
46,
236,
69,
236,
72,
232,
70,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
153,
120,
120,
120,
120,
120,
120,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121,
121
})]
//[MethodImpl(MethodImplOptions.NoInlining)]
public EscapeSequenceCharacterPattern()
{
this._stdMap = new HashMap();
this._finMap = new HashMap();
this.useEscEsc = true;
this._finMap.put(Character.valueOf('A'), KeyType._ArrowUp);
this._finMap.put(Character.valueOf('B'), KeyType._ArrowDown);
this._finMap.put(Character.valueOf('C'), KeyType._ArrowRight);
this._finMap.put(Character.valueOf('D'), KeyType._ArrowLeft);
this._finMap.put(Character.valueOf('E'), KeyType._Unknown);
this._finMap.put(Character.valueOf('G'), KeyType._Unknown);
this._finMap.put(Character.valueOf('H'), KeyType._Home);
this._finMap.put(Character.valueOf('F'), KeyType._End);
this._finMap.put(Character.valueOf('P'), KeyType._F1);
this._finMap.put(Character.valueOf('Q'), KeyType._F2);
this._finMap.put(Character.valueOf('R'), KeyType._F3);
this._finMap.put(Character.valueOf('S'), KeyType._F4);
this._finMap.put(Character.valueOf('Z'), KeyType._ReverseTab);
this._stdMap.put(Integer.valueOf(1), KeyType._Home);
this._stdMap.put(Integer.valueOf(2), KeyType._Insert);
this._stdMap.put(Integer.valueOf(3), KeyType._Delete);
this._stdMap.put(Integer.valueOf(4), KeyType._End);
this._stdMap.put(Integer.valueOf(5), KeyType._PageUp);
this._stdMap.put(Integer.valueOf(6), KeyType._PageDown);
this._stdMap.put(Integer.valueOf(11), KeyType._F1);
this._stdMap.put(Integer.valueOf(12), KeyType._F2);
this._stdMap.put(Integer.valueOf(13), KeyType._F3);
this._stdMap.put(Integer.valueOf(14), KeyType._F4);
this._stdMap.put(Integer.valueOf(15), KeyType._F5);
this._stdMap.put(Integer.valueOf(16), KeyType._F5);
this._stdMap.put(Integer.valueOf(17), KeyType._F6);
this._stdMap.put(Integer.valueOf(18), KeyType._F7);
this._stdMap.put(Integer.valueOf(19), KeyType._F8);
this._stdMap.put(Integer.valueOf(20), KeyType._F9);
this._stdMap.put(Integer.valueOf(21), KeyType._F10);
this._stdMap.put(Integer.valueOf(23), KeyType._F11);
this._stdMap.put(Integer.valueOf(24), KeyType._F12);
this._stdMap.put(Integer.valueOf(25), KeyType._F13);
this._stdMap.put(Integer.valueOf(26), KeyType._F14);
this._stdMap.put(Integer.valueOf(28), KeyType._F15);
this._stdMap.put(Integer.valueOf(29), KeyType._F16);
this._stdMap.put(Integer.valueOf(31), KeyType._F17);
this._stdMap.put(Integer.valueOf(32), KeyType._F18);
this._stdMap.put(Integer.valueOf(33), KeyType._F19);
}
//[LineNumberTable(new byte[]
{
159,
112,
162,
103,
102,
101,
107,
107,
139
})]
//[MethodImpl(MethodImplOptions.NoInlining)]
protected internal virtual KeyStroke getKeyStroke(KeyType key, int mods)
{
int bShift = 0;
int bCtrl = 0;
int bAlt = 0;
if (key == null)
{
return null;
}
if (mods >= 0)
{
bShift = (((mods & 1) == 0) ? 0 : 1);
bAlt = (((mods & 2) == 0) ? 0 : 1);
bCtrl = (((mods & 4) == 0) ? 0 : 1);
}
return new KeyStroke(key, bCtrl != 0, bAlt != 0, bShift != 0);
}
//[LineNumberTable(new byte[]
{
159,
106,
97,
73,
102,
121,
122,
116,
184,
181,
131,
102,
100,
110,
132,
101,
110,
132
})]
//[MethodImpl(MethodImplOptions.NoInlining)]
protected internal virtual KeyStroke getKeyStrokeRaw(char first, int num1, int num2, char last, bool bEsc)
{
int bPuttyCtrl = 0;
KeyType kt;
if (last == '~' && this._stdMap.containsKey(Integer.valueOf(num1)))
{
kt = (KeyType)this._stdMap.get(Integer.valueOf(num1));
}
else if (this._finMap.containsKey(Character.valueOf(last)))
{
kt = (KeyType)this._finMap.get(Character.valueOf(last));
if (first == 'O' && last >= 'A' && last <= 'D')
{
bPuttyCtrl = 1;
}
}
else
{
kt = null;
}
int mods = num2 - 1;
if (bEsc)
{
if (mods >= 0)
{
mods |= 2;
}
else
{
mods = 2;
}
}
if (bPuttyCtrl != 0)
{
if (mods >= 0)
{
mods |= 4;
}
else
{
mods = 4;
}
}
return this.getKeyStroke(kt, mods);
}
//[LineNumberTable(new byte[]
{
159,
100,
162,
103,
101,
102,
132,
127,
9,
159,
14,
103,
131,
103,
195,
115,
233,
69,
109,
131,
106,
134,
103,
108,
106,
149,
139,
134,
106,
149,
139,
134,
131,
102,
105,
112,
144
}), Signature("(Ljava/util/List<Ljava/lang/Character;>;)Lcom/googlecode/lanterna/input/CharacterPattern_Matching;")]
//[MethodImpl(MethodImplOptions.NoInlining)]
public virtual CharacterPattern.Matching match(List cur)
{
EscapeSequenceCharacterPattern.State state = EscapeSequenceCharacterPattern.State.START;
int num = 0;
int num2 = 0;
int first = 0;
int last = 0;
int bEsc = 0;
Iterator iterator = cur.iterator();
while (iterator.hasNext())
{
int ch = (int)((Character)iterator.next()).charValue();
switch (EscapeSequenceCharacterPattern_1._SwitchMap_com_googlecode_lanterna_input_EscapeSequenceCharacterPattern_State[state.ordinal()])
{
case 1:
if (ch != 27)
{
return null;
}
state = EscapeSequenceCharacterPattern.State.INTRO;
break;
case 2:
if (this.useEscEsc && ch == 27 && bEsc == 0)
{
bEsc = 1;
}
else
{
if (ch != 91 && ch != 79)
{
return null;
}
first = ch;
state = EscapeSequenceCharacterPattern.State.NUM1;
}
break;
case 3:
if (ch == 59)
{
state = EscapeSequenceCharacterPattern.State.NUM2;
}
else if (Character.isDigit((char)ch))
{
num = num * 10 + Character.digit((char)ch, 10);
}
else
{
last = ch;
state = EscapeSequenceCharacterPattern.State.DONE;
}
break;
case 4:
if (Character.isDigit((char)ch))
{
num2 = num2 * 10 + Character.digit((char)ch, 10);
}
else
{
last = ch;
state = EscapeSequenceCharacterPattern.State.DONE;
}
break;
case 5:
return null;
}
}
if (state == EscapeSequenceCharacterPattern.State.DONE)
{
KeyStroke ks = this.getKeyStrokeRaw((char)first, num, num2, (char)last, bEsc != 0);
return (ks == null) ? null : new CharacterPattern.Matching(ks);
}
return CharacterPattern.Matching._NOT_YET;
}
}
}
| |
using System.Collections.Generic;
namespace Masb.Languages.Experimentals.PolyMethodic
{
public static class Parser
{
public static FileNode Parse(Token[] tokens)
{
var pos = 0;
// skipping a single start-file token
if (tokens[pos++].Type != TokenType.StartFile)
return null;
SkipSpaces(tokens, ref pos);
// reading file members
IMemberNode member;
var members = new List<IMemberNode>();
while ((member = ReadMember(tokens, ref pos)) != null)
members.Add(member);
return new FileNode(members);
}
private static ClassNode ReadClassNode(Token[] tokens, ref int pos)
{
int newPos = pos;
MethodFlags flags = 0;
// method visibility
switch (tokens[newPos].Subtype)
{
case TokenSubtype.PublicKeyword:
flags |= MethodFlags.IsPublic;
newPos++;
break;
case TokenSubtype.PrivateKeyword:
flags |= MethodFlags.IsPrivate;
newPos++;
break;
default:
if (tokens[newPos].Subtype == TokenSubtype.ProtectedKeyword)
{
flags |= MethodFlags.IsProtected;
newPos++;
}
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.InternalKeyword)
{
flags |= MethodFlags.IsInternal;
newPos++;
}
break;
}
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.ClassKeyword)
{
newPos++;
if (tokens[newPos].Type == TokenType.Space)
{
newPos++;
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.IdentifierOrContextualKeyword)
{
var className = tokens[newPos++];
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.OpenBracesSymbol)
{
newPos++;
IMemberNode member;
var members = new List<IMemberNode>();
while ((member = ReadMember(tokens, ref newPos)) != null)
members.Add(member);
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.CloseBracesSymbol)
{
newPos++;
pos = newPos;
return new ClassNode(className, members, flags);
}
}
else
{
// error branch
return null;
}
}
}
}
return null;
}
private static IMemberNode ReadMember(Token[] tokens, ref int pos)
{
SkipSpaces(tokens, ref pos);
return ReadClassNode(tokens, ref pos)
?? ReadMethodNode(tokens, ref pos) as IMemberNode;
}
private static MethodNode ReadMethodNode(Token[] tokens, ref int pos)
{
var newPos = pos;
MethodFlags flags = 0;
// method visibility
switch (tokens[newPos].Subtype)
{
case TokenSubtype.PublicKeyword:
flags |= MethodFlags.IsPublic;
newPos++;
break;
case TokenSubtype.PrivateKeyword:
flags |= MethodFlags.IsPrivate;
newPos++;
break;
default:
if (tokens[newPos].Subtype == TokenSubtype.ProtectedKeyword)
{
flags |= MethodFlags.IsProtected;
newPos++;
}
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.InternalKeyword)
{
flags |= MethodFlags.IsInternal;
newPos++;
}
break;
}
// method instance/static
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.StaticKeyword)
{
flags |= MethodFlags.IsStatic;
newPos++;
}
IdentifierOrKeywordToken type;
{
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.PolyKeyword)
{
flags |= MethodFlags.IsPolyMethod;
newPos++;
}
SkipSpaces(tokens, ref newPos);
// reading type (an identifier or keyword)
if (tokens[newPos].Type == TokenType.IdentifierOrKeyword)
type = (IdentifierOrKeywordToken)tokens[newPos++];
else
return null;
}
SkipSpaces(tokens, ref newPos);
// reading name (an identifier or keyword)
IdentifierOrKeywordToken name;
if (tokens[newPos].Type == TokenType.IdentifierOrKeyword)
name = (IdentifierOrKeywordToken)tokens[newPos++];
else
return null;
SkipSpaces(tokens, ref newPos);
// reading args list
if (tokens[newPos].Subtype == TokenSubtype.OpenParenthesysSymbol)
{
newPos++;
if (tokens[newPos].Subtype == TokenSubtype.CloseParenthesysSymbol)
{
newPos++;
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.OpenBracesSymbol)
{
newPos++;
// reading statements in the method body
IStatementNode statement;
var statements = new List<IStatementNode>();
while ((statement = ReadStatement(tokens, ref newPos)) != null)
statements.Add(statement);
SkipSpaces(tokens, ref newPos);
if (tokens[newPos].Subtype == TokenSubtype.CloseBracesSymbol)
{
newPos++;
pos = newPos;
return new MethodNode(name, type, statements, flags);
}
}
else
{
// error branch: missing braces
}
}
}
else
{
// error branch: missing parenthesys
}
return null;
}
private static void SkipSpaces(Token[] tokens, ref int pos)
{
// skipping spaces
while (tokens[pos].Type == TokenType.Space)
pos++;
}
private static IStatementNode ReadStatement(Token[] tokens, ref int pos)
{
SkipSpaces(tokens, ref pos);
return ReadReturn(tokens, ref pos)
?? ReadSplit(tokens, ref pos)
?? ReadBlock(tokens, ref pos) as IStatementNode;
}
private static SplitStatementNode ReadSplit(Token[] tokens, ref int pos)
{
if (tokens[pos].Subtype == TokenSubtype.SplitKeyword)
{
pos++;
var alternatives = new List<IStatementNode>();
while (true)
{
SkipSpaces(tokens, ref pos);
if (tokens[pos].Subtype == TokenSubtype.BranchKeyword)
pos++;
else
break;
var statement = ReadStatement(tokens, ref pos);
if (statement == null)
{
// error
return null;
}
alternatives.Add(statement);
}
if (alternatives.Count == 0)
{
// error
return null;
}
return new SplitStatementNode(alternatives);
}
return null;
}
private static ReturnStatementNode ReadReturn(Token[] tokens, ref int pos)
{
if (tokens[pos].Subtype == TokenSubtype.ReturnKeyword)
{
pos++;
SkipSpaces(tokens, ref pos);
var expression = ReadExpression(tokens, ref pos);
if (expression == null)
{
// error
return null;
}
if (tokens[pos].Subtype == TokenSubtype.StatementSeparatorSymbol)
pos++;
else
{
// error
return null;
}
return new ReturnStatementNode(expression);
}
return null;
}
private static BlockStatementNode ReadBlock(Token[] tokens, ref int pos)
{
if (tokens[pos].Subtype == TokenSubtype.OpenBracesSymbol)
{
pos++;
// reading statements in the method body
IStatementNode statement;
var statements = new List<IStatementNode>();
while ((statement = ReadStatement(tokens, ref pos)) != null)
statements.Add(statement);
if (tokens[pos++].Subtype == TokenSubtype.CloseBracesSymbol)
return new BlockStatementNode(statements);
}
else
{
// error branch: missing braces
}
return null;
}
private static IExpressionNode ReadExpression(Token[] tokens, ref int pos)
{
SkipSpaces(tokens, ref pos);
return ReadLiteral(tokens, ref pos) as IExpressionNode;
}
private static LiteralExpressionNode ReadLiteral(Token[] tokens, ref int pos)
{
if (tokens[pos].Type == TokenType.String || tokens[pos].Type == TokenType.Number)
return new LiteralExpressionNode(tokens[pos++]);
return null;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G02_Continent (editable root object).<br/>
/// This is a generated base class of <see cref="G02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="G03_SubContinentObjects"/> of type <see cref="G03_SubContinentColl"/> (1:M relation to <see cref="G04_SubContinent"/>)
/// </remarks>
[Serializable]
public partial class G02_Continent : BusinessBase<G02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G03_Continent_Child> G03_Continent_SingleObjectProperty = RegisterProperty<G03_Continent_Child>(p => p.G03_Continent_SingleObject, "G03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The G03 Continent Single Object.</value>
public G03_Continent_Child G03_Continent_SingleObject
{
get { return GetProperty(G03_Continent_SingleObjectProperty); }
private set { LoadProperty(G03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<G03_Continent_ReChild> G03_Continent_ASingleObjectProperty = RegisterProperty<G03_Continent_ReChild>(p => p.G03_Continent_ASingleObject, "G03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The G03 Continent ASingle Object.</value>
public G03_Continent_ReChild G03_Continent_ASingleObject
{
get { return GetProperty(G03_Continent_ASingleObjectProperty); }
private set { LoadProperty(G03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="G03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<G03_SubContinentColl> G03_SubContinentObjectsProperty = RegisterProperty<G03_SubContinentColl>(p => p.G03_SubContinentObjects, "G03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the G03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The G03 Sub Continent Objects.</value>
public G03_SubContinentColl G03_SubContinentObjects
{
get { return GetProperty(G03_SubContinentObjectsProperty); }
private set { LoadProperty(G03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G02_Continent"/> object.</returns>
public static G02_Continent NewG02_Continent()
{
return DataPortal.Create<G02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="G02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID parameter of the G02_Continent to fetch.</param>
/// <returns>A reference to the fetched <see cref="G02_Continent"/> object.</returns>
public static G02_Continent GetG02_Continent(int continent_ID)
{
return DataPortal.Fetch<G02_Continent>(continent_ID);
}
/// <summary>
/// Factory method. Deletes a <see cref="G02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the G02_Continent to delete.</param>
public static void DeleteG02_Continent(int continent_ID)
{
DataPortal.Delete<G02_Continent>(continent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G02_Continent()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(G03_Continent_SingleObjectProperty, DataPortal.CreateChild<G03_Continent_Child>());
LoadProperty(G03_Continent_ASingleObjectProperty, DataPortal.CreateChild<G03_Continent_ReChild>());
LoadProperty(G03_SubContinentObjectsProperty, DataPortal.CreateChild<G03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="G02_Continent"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID">The Continent ID.</param>
protected void DataPortal_Fetch(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, continent_ID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
FetchChildren();
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID"));
LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
private void FetchChildren()
{
LoadProperty(G03_Continent_SingleObjectProperty, G03_Continent_Child.GetG03_Continent_Child(Continent_ID));
LoadProperty(G03_Continent_ASingleObjectProperty, G03_Continent_ReChild.GetG03_Continent_ReChild(Continent_ID));
LoadProperty(G03_SubContinentObjectsProperty, G03_SubContinentColl.GetG03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="G02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="G02_Continent"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(Continent_ID);
}
/// <summary>
/// Deletes the <see cref="G02_Continent"/> object from database.
/// </summary>
/// <param name="continent_ID">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
protected void DataPortal_Delete(int continent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteG02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, continent_ID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(G03_Continent_SingleObjectProperty, DataPortal.CreateChild<G03_Continent_Child>());
LoadProperty(G03_Continent_ASingleObjectProperty, DataPortal.CreateChild<G03_Continent_ReChild>());
LoadProperty(G03_SubContinentObjectsProperty, DataPortal.CreateChild<G03_SubContinentColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Text;
using log4net.spi;
using log4net.helpers;
namespace log4net.Layout
{
/// <summary>
/// A flexible layout configurable with pattern string.
/// </summary>
/// <remarks>
/// <para>
/// The goal of this class is to <see cref="PatternLayout.Format"/> a
/// <see cref="LoggingEvent"/> and return the results as a string. The results
/// depend on the <i>conversion pattern</i>.
/// </para>
/// <para>
/// The conversion pattern is closely related to the conversion
/// pattern of the printf function in C. A conversion pattern is
/// composed of literal text and format control expressions called
/// <i>conversion specifiers</i>.
/// </para>
/// <para>
/// <i>You are free to insert any literal text within the conversion
/// pattern.</i>
/// </para>
/// <para>
/// Each conversion specifier starts with a percent sign (%) and is
/// followed by optional <i>format modifiers</i> and a <i>conversion
/// character</i>. The conversion character specifies the type of
/// data, e.g. logger, level, date, thread name. The format
/// modifiers control such things as field width, padding, left and
/// right justification. The following is a simple example.
/// </para>
/// <para>
/// Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume
/// that the log4net environment was set to use a PatternLayout. Then the
/// statements
/// </para>
/// <code>
/// ILog log = LogManager.GetLogger(typeof(TestApp));
/// log.Debug("Message 1");
/// log.Warn("Message 2");
/// </code>
/// <para>would yield the output</para>
/// <code>
/// DEBUG [main]: Message 1
/// WARN [main]: Message 2
/// </code>
/// <para>
/// Note that there is no explicit separator between text and
/// conversion specifiers. The pattern parser knows when it has reached
/// the end of a conversion specifier when it reads a conversion
/// character. In the example above the conversion specifier
/// <b>%-5p</b> means the level of the logging event should be left
/// justified to a width of five characters.
/// </para>
/// <para>
/// The recognized conversion characters are :
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Conversion Character</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term>a</term>
/// <description>
/// Used to output the frienly name of the AppDomain where the
/// logging event was generated.
/// </description>
/// </item>
/// <item>
/// <term>c</term>
/// <description>
/// <para>
/// Used to output the logger of the logging event. The
/// logger conversion specifier can be optionally followed by
/// <i>precision specifier</i>, that is a decimal constant in
/// brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the logger name will be
/// printed. By default the logger name is printed in full.
/// </para>
/// <para>
/// For example, for the logger name "a.b.c" the pattern
/// <b>%c{2}</b> will output "b.c".
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>C</term>
/// <description>
/// <para>
/// Used to output the fully qualified class name of the caller
/// issuing the logging request. This conversion specifier
/// can be optionally followed by <i>precision specifier</i>, that
/// is a decimal constant in brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the class name will be
/// printed. By default the class name is output in fully qualified form.
/// </para>
/// <para>
/// For example, for the class name "log4net.Layout.PatternLayout", the
/// pattern <b>%C{1}</b> will output "PatternLayout".
/// </para>
/// <para>
/// <b>WARNING</b> Generating the caller class information is
/// slow. Thus, it's use should be avoided unless execution speed is
/// not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>d</term>
/// <description>
/// <para>
/// Used to output the date of the logging event. The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%d{HH:mm:ss,fff}</b> or
/// <b>%d{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.ISO8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="DateTime.ToString"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.ISO8601DateFormatter"/>. For example,
/// <b>%d{ISO8601}</b> or <b>%d{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>F</term>
/// <description>
/// <para>
/// Used to output the file name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. It's use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>l</term>
/// <description>
/// <para>
/// Used to output location information of the caller which generated
/// the logging event.
/// </para>
/// <para>
/// The location information depends on the CLI implementation but
/// usually consists of the fully qualified name of the calling
/// method followed by the callers source the file name and line
/// number between parentheses.
/// </para>
/// <para>
/// The location information can be very useful. However, it's
/// generation is <b>extremely</b> slow. It's use should be avoided
/// unless execution speed is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>L</term>
/// <description>
/// <para>
/// Used to output the line number from where the logging request
/// was issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. It's use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>m</term>
/// <description>
/// <para>
/// Used to output the application supplied message associated with
/// the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>M</term>
/// <description>
/// <para>
/// Used to output the method name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. It's use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>n</term>
/// <description>
/// <para>
/// Outputs the platform dependent line separator character or
/// characters.
/// </para>
/// <para>
/// This conversion character offers practically the same
/// performance as using non-portable line separator strings such as
/// "\n", or "\r\n". Thus, it is the preferred way of specifying a
/// line separator.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>p</term>
/// <description>
/// <para>
/// Used to output the level of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>P</term>
/// <description>
/// <para>
/// Used to output the an event specific property. The key to
/// lookup must be specified within braces and directly following the
/// pattern specifier, e.g. <c>%X{user}</c> would include the value
/// from the property that is keyed by the string 'user'. Each property value
/// that is to be included in the log must be specified separately.
/// Properties are added to events by loggers or appenders. By default
/// no properties are defined.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>r</term>
/// <description>
/// <para>
/// Used to output the number of milliseconds elapsed since the start
/// of the application until the creation of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>t</term>
/// <description>
/// <para>
/// Used to output the name of the thread that generated the
/// logging event. Uses the thread number if no name is available.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>u</term>
/// <description>
/// <para>
/// Used to output the user name for the currently active user
/// (Principal.Identity.Name).
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller information is
/// extremely slow. It's use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>W</term>
/// <description>
/// <para>
/// Used to output the WindowsIdentity for the currently
/// active user.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller WindowsIdentity information is
/// extremely slow. It's use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>x</term>
/// <description>
/// <para>
/// Used to output the NDC (nested diagnostic context) associated
/// with the thread that generated the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>X</term>
/// <description>
/// <para>
/// Used to output the MDC (mapped diagnostic context) associated
/// with the thread that generated the logging event. The key to lookup
/// must be specified within braces and directly following the
/// pattern specifier, e.g. <c>%X{user}</c> would include the value
/// from the MDC that is keyed by the string 'user'. Each MDC value
/// that is to be included in the log must be specified separately.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>%</term>
/// <description>
/// <para>
/// The sequence %% outputs a single percent sign.
/// </para>
/// </description>
/// </item>
/// </list>
/// <para>
/// By default the relevant information is output as is. However,
/// with the aid of format modifiers it is possible to change the
/// minimum field width, the maximum field width and justification.
/// </para>
/// <para>
/// The optional format modifier is placed between the percent sign
/// and the conversion character.
/// </para>
/// <para>
/// The first optional format modifier is the <i>left justification
/// flag</i> which is just the minus (-) character. Then comes the
/// optional <i>minimum field width</i> modifier. This is a decimal
/// constant that represents the minimum number of characters to
/// output. If the data item requires fewer characters, it is padded on
/// either the left or the right until the minimum width is
/// reached. The default is to pad on the left (right justify) but you
/// can specify right padding with the left justification flag. The
/// padding character is space. If the data item is larger than the
/// minimum field width, the field is expanded to accommodate the
/// data. The value is never truncated.
/// </para>
/// <para>
/// This behaviour can be changed using the <i>maximum field
/// width</i> modifier which is designated by a period followed by a
/// decimal constant. If the data item is longer than the maximum
/// field, then the extra characters are removed from the
/// <i>beginning</i> of the data item and not from the end. For
/// example, it the maximum field width is eight and the data item is
/// ten characters long, then the first two characters of the data item
/// are dropped. This behaviour deviates from the printf function in C
/// where truncation is done from the end.
/// </para>
/// <para>
/// Below are various format modifier examples for the logger
/// conversion specifier.
/// </para>
/// <div class="tablediv">
/// <table class="dtTABLE" cellspacing="0">
/// <tr>
/// <th>Format modifier</th>
/// <th>left justify</th>
/// <th>minimum width</th>
/// <th>maximum width</th>
/// <th>comment</th>
/// </tr>
/// <tr>
/// <td align="center">%20c</td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is less than 20
/// characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20c</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger
/// name is less than 20 characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%.30c</td>
/// <td align="center">NA</td>
/// <td align="center">none</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Truncate from the beginning if the logger
/// name is longer than 30 characters.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%20.30c</td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20.30c</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// </table>
/// </div>
/// </remarks>
/// <example>
/// This is essentially the TTCC layout
/// <code><b>%r [%t] %-5p %c %x - %m\n</b></code>
/// </example>
/// <example>
/// Similar to the TTCC layout except that the relative time is
/// right padded if less than 6 digits, thread name is right padded if
/// less than 15 characters and truncated if longer and the logger
/// name is left padded if shorter than 30 characters and truncated if
/// longer.
/// <code><b>%-6r [%15.15t] %-5p %30.30c %x - %m\n</b></code>
/// </example>
public class PatternLayout : LayoutSkeleton
{
#region Constants
/// <summary>
/// Default pattern string for log output.
/// Currently set to the string <b>"%m%n"</b>
/// which just prints the application supplied message.
/// </summary>
public const string DEFAULT_CONVERSION_PATTERN ="%m%n";
/// <summary>
/// A conversion pattern equivalent to the TTCCLayout. Current value is <b>%r [%t] %p %c %x - %m%n</b>.
/// </summary>
public const string TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n";
/// <summary>
/// Initial buffer size
/// </summary>
protected const int BUF_SIZE = 256;
/// <summary>
/// Maximum buffer size before it is recycled
/// </summary>
protected const int MAX_CAPACITY = 1024;
#endregion
#region Member Variables
/// <summary>
/// output buffer appended to when Format() is invoked
/// </summary>
private StringBuilder m_sbuf = new StringBuilder(BUF_SIZE);
/// <summary>
/// the pattern
/// </summary>
private string m_pattern;
/// <summary>
/// the head of the pattern converter chain
/// </summary>
private PatternConverter m_head;
#endregion
#region Constructors
/// <summary>
/// Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN
/// </summary>
/// <remarks>
/// The default pattern just produces the application supplied message.
/// </remarks>
public PatternLayout() : this(DEFAULT_CONVERSION_PATTERN)
{
}
/// <summary>
/// Constructs a PatternLayout using the supplied conversion pattern
/// </summary>
/// <param name="pattern">the pattern to use</param>
public PatternLayout(string pattern)
{
m_pattern = pattern;
m_head = CreatePatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).Parse();
}
#endregion
/// <summary>
/// The <b>ConversionPattern</b> option. This is the string which
/// controls formatting and consists of a mix of literal content and
/// conversion specifiers.
/// </summary>
public string ConversionPattern
{
get { return m_pattern; }
set
{
m_pattern = value;
m_head = CreatePatternParser(m_pattern).Parse();
}
}
/// <summary>
/// Returns PatternParser used to parse the conversion string. Subclasses
/// may override this to return a subclass of PatternParser which recognize
/// custom conversion characters.
/// </summary>
/// <param name="pattern">the pattern to parse</param>
/// <returns></returns>
virtual protected PatternParser CreatePatternParser(string pattern)
{
return new PatternParser(pattern);
}
#region Implementation of IOptionHandler
/// <summary>
/// Does not do anything as options become effective immediately.
/// </summary>
override public void ActivateOptions()
{
// nothing to do.
}
#endregion
#region Override implementation of LayoutSkeleton
/// <summary>
/// The PatternLayout does not handle the exception contained within
/// LoggingEvents. Thus, it returns <c>true</c>.
/// </summary>
override public bool IgnoresException
{
get { return true; }
}
/// <summary>
/// Produces a formatted string as specified by the conversion pattern.
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the formatted string</returns>
override public string Format(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
// Reset working string buffer
if (m_sbuf.Capacity > MAX_CAPACITY)
{
m_sbuf = new StringBuilder(BUF_SIZE);
}
else
{
m_sbuf.Length = 0;
}
PatternConverter c = m_head;
// loop through the chain of pattern converters
while(c != null)
{
c.Format(m_sbuf, loggingEvent);
c = c.Next;
}
return m_sbuf.ToString();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Implements operations of invoke-cimmethod cmdlet.
/// </para>
/// </summary>
internal sealed class CimInvokeCimMethod : CimAsyncOperation
{
/// <summary>
/// Containing all necessary information originated from
/// the parameters of <see cref="InvokeCimMethodCommand"/>
/// </summary>
internal class CimInvokeCimMethodContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="theNamespace"></param>
/// <param name="theCollection"></param>
/// <param name="theProxy"></param>
internal CimInvokeCimMethodContext(string theNamespace,
string theMethodName,
CimMethodParametersCollection theCollection,
CimSessionProxy theProxy)
{
this.proxy = theProxy;
this.methodName = theMethodName;
this.collection = theCollection;
this.nameSpace = theNamespace;
}
/// <summary>
/// <para>namespace</para>
/// </summary>
internal string MethodName
{
get
{
return this.methodName;
}
}
private string methodName;
/// <summary>
/// <para>parameters collection</para>
/// </summary>
internal CimMethodParametersCollection ParametersCollection
{
get
{
return this.collection;
}
}
private CimMethodParametersCollection collection;
}
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimInvokeCimMethod()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to retrieve ciminstances
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object.</param>
public void InvokeCimMethod(InvokeCimMethodCommand cmdlet)
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName);
string nameSpace;
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cmdlet.MethodName);
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.CimInstanceComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet));
}
break;
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
case CimBaseCommand.QueryComputerSet:
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet));
}
break;
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.CimClassSessionSet:
case CimBaseCommand.QuerySessionSet:
case CimBaseCommand.CimInstanceSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in cmdlet.CimSession)
{
CimSessionProxy proxy = CreateSessionProxy(session, cmdlet);
proxys.Add(proxy);
}
break;
default:
break;
}
CimMethodParametersCollection paramsCollection =
CreateParametersCollection(cmdlet.Arguments, cmdlet.CimClass, cmdlet.CimInstance, cmdlet.MethodName);
// Invoke methods
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
{
string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.ClassName);
if(cmdlet.ResourceUri != null )
{
nameSpace = cmdlet.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
}
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.ClassName,
cmdlet.MethodName,
paramsCollection);
}
}
break;
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.CimClassSessionSet:
{
string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.CimClass.CimSystemProperties.ClassName);
nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.CimClass.CimSystemProperties.ClassName,
cmdlet.MethodName,
paramsCollection);
}
}
break;
case CimBaseCommand.QueryComputerSet:
case CimBaseCommand.QuerySessionSet:
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
foreach (CimSessionProxy proxy in proxys)
{
// create context object
CimInvokeCimMethodContext context = new CimInvokeCimMethodContext(
nameSpace,
cmdlet.MethodName,
paramsCollection,
proxy);
proxy.ContextObject = context;
// firstly query instance and then invoke method upon returned instances
proxy.QueryInstancesAsync(nameSpace, ConstValue.GetQueryDialectWithDefault(cmdlet.QueryDialect), cmdlet.Query);
}
break;
case CimBaseCommand.CimInstanceComputerSet:
case CimBaseCommand.CimInstanceSessionSet:
{
string target = cmdlet.CimInstance.ToString();
if(cmdlet.ResourceUri != null )
{
nameSpace = cmdlet.Namespace;
}
else
{
nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace);
}
foreach (CimSessionProxy proxy in proxys)
{
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
proxy.InvokeMethodAsync(
nameSpace,
cmdlet.CimInstance,
cmdlet.MethodName,
paramsCollection);
}
}
break;
default:
break;
}
}
/// <summary>
/// <para>
/// Invoke cimmethod on given <see cref="CimInstance"/>
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
public void InvokeCimMethodOnCimInstance(CimInstance cimInstance, XOperationContextBase context, CmdletOperationBase operation)
{
DebugHelper.WriteLogEx();
CimInvokeCimMethodContext cimInvokeCimMethodContext = context as CimInvokeCimMethodContext;
Debug.Assert(cimInvokeCimMethodContext != null, "CimInvokeCimMethod::InvokeCimMethodOnCimInstance should has CimInvokeCimMethodContext != NULL.");
string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cimInvokeCimMethodContext.MethodName);
if (!operation.ShouldProcess(cimInstance.ToString(), action))
{
return;
}
CimSessionProxy proxy = CreateCimSessionProxy(cimInvokeCimMethodContext.Proxy);
proxy.InvokeMethodAsync(
cimInvokeCimMethodContext.Namespace,
cimInstance,
cimInvokeCimMethodContext.MethodName,
cimInvokeCimMethodContext.ParametersCollection);
}
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
InvokeCimMethodCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
if(cmdlet.ResourceUri != null )
{
proxy.ResourceUri = cmdlet.ResourceUri;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
CimInstance cimInstance,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(computerName, cimInstance);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
InvokeCimMethodCommand cmdlet)
{
CimSessionProxy proxy = CreateCimSessionProxy(session);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimMethodParametersCollection"/> with given key properties.
/// And/or <see cref="CimClass"/> object.
/// </para>
/// </summary>
/// <param name="parameters"></param>
/// <param name="cimClass"></param>
/// <param name="cimInstance"></param>
/// <param name="methodName"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create.</exception>
/// <exception cref="ArgumentException">CimProperty.Create.</exception>
private CimMethodParametersCollection CreateParametersCollection(
IDictionary parameters,
CimClass cimClass,
CimInstance cimInstance,
string methodName)
{
DebugHelper.WriteLogEx();
CimMethodParametersCollection collection = null;
if (parameters == null)
{
return collection;
}
else if (parameters.Count == 0)
{
return collection;
}
collection = new CimMethodParametersCollection();
IDictionaryEnumerator enumerator = parameters.GetEnumerator();
while (enumerator.MoveNext())
{
string parameterName = enumerator.Key.ToString();
CimFlags parameterFlags = CimFlags.In;
object parameterValue = GetBaseObject(enumerator.Value);
DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4,
parameterName,
parameterValue,
parameterFlags);
CimMethodParameter parameter = null;
CimMethodDeclaration declaration = null;
string className = null;
if (cimClass != null)
{
className = cimClass.CimSystemProperties.ClassName;
declaration = cimClass.CimClassMethods[methodName];
if (declaration == null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentUICulture, Strings.InvalidMethod, methodName, className));
}
}
else if (cimInstance != null)
{
className = cimInstance.CimClass.CimSystemProperties.ClassName;
declaration = cimInstance.CimClass.CimClassMethods[methodName];
}
if (declaration != null)
{
CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName];
if (paramDeclaration == null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, parameterName, methodName, className));
}
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
paramDeclaration.CimType,
parameterFlags);
// FIXME: check in/out qualifier
// parameterFlags = paramDeclaration.Qualifiers;
}
else
{
if (parameterValue == null)
{
// try the best to get the type while value is null
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
CimType.String,
parameterFlags);
}
else
{
CimType referenceType = CimType.Unknown;
object referenceObject = GetReferenceOrReferenceArrayObject(parameterValue, ref referenceType);
if (referenceObject != null)
{
parameter = CimMethodParameter.Create(
parameterName,
referenceObject,
referenceType,
parameterFlags);
}
else
{
parameter = CimMethodParameter.Create(
parameterName,
parameterValue,
parameterFlags);
}
}
}
if (parameter != null)
collection.Add(parameter);
}
return collection;
}
#endregion
#region const strings
/// <summary>
/// Operation target.
/// </summary>
private const string targetClass = @"{0}";
/// <summary>
/// Action.
/// </summary>
private const string actionTemplate = @"Invoke-CimMethod: {0}";
#endregion
}
}
| |
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace PokeD.CPGL.Components.Input
{
public class GamePadListenerComponent : InputListenerComponent
{
public bool CheckControllerConnections { get; set; }
/// <summary>
/// The index of the controller.
/// </summary>
public PlayerIndex PlayerIndex { get; }
/// <summary>
/// When a button is held down, the interval in which
/// ButtonRepeated fires. Value in milliseconds.
/// </summary>
public int RepeatDelay { get; }
/// <summary>
/// The amount of time a button has to be held down
/// in order to fire ButtonRepeated the first time.
/// Value in milliseconds.
/// </summary>
public int RepeatInitialDelay { get; }
/// <summary>
/// Whether vibration is enabled for this controller.
/// </summary>
public bool VibrationEnabled { get; set; }
/// <summary>
/// General setting for the strength of the left motor.
/// This motor has a slow, deep, powerful rumble.
/// <para>
/// This setting will modify all future vibrations
/// through this listener.
/// </para>
/// </summary>
public float VibrationStrengthLeft
{
get { return _vibrationStrengthLeft; }
// Clamp the value, just to be sure.
set { _vibrationStrengthLeft = MathHelper.Clamp(value, 0, 1); }
}
/// <summary>
/// General setting for the strength of the right motor.
/// This motor has a snappy, quick, high-pitched rumble.
/// <para>
/// This setting will modify all future vibrations
/// through this listener.
/// </para>
/// </summary>
public float VibrationStrengthRight
{
get { return _vibrationStrengthRight; }
// Clamp the value, just to be sure.
set { _vibrationStrengthRight = MathHelper.Clamp(value, 0, 1); }
}
/// <summary>
/// The treshold of movement that has to be met in order
/// for the listener to fire an event with the trigger's
/// updated position.
/// <para>
/// In essence this defines the event's
/// resolution.
/// </para>
/// At a value of 0 this will fire every time
/// the trigger's position is not 0f.
/// </summary>
public float TriggerDeltaTreshold { get; }
/// <summary>
/// The treshold of movement that has to be met in order
/// for the listener to fire an event with the thumbstick's
/// updated position.
/// <para>
/// In essence this defines the event's
/// resolution.
/// </para>
/// At a value of 0 this will fire every time
/// the thumbstick's position is not {x:0, y:0}.
/// </summary>
public float ThumbStickDeltaTreshold { get; }
/// <summary>
/// How deep the triggers have to be depressed in order to
/// register as a ButtonDown event.
/// </summary>
public float TriggerDownTreshold { get; }
/// <summary>
/// How deep the triggers have to be depressed in order to
/// register as a ButtonDown event.
/// </summary>
public float ThumbstickDownTreshold { get; }
public BaseEventHandler<GamePadEventArgs> ControllerConnectionChanged = new CustomEventHandler<GamePadEventArgs>();
public BaseEventHandler<GamePadEventArgs> ButtonDown = new CustomEventHandler<GamePadEventArgs>();
public BaseEventHandler<GamePadEventArgs> ButtonUp = new CustomEventHandler<GamePadEventArgs>();
public BaseEventHandler<GamePadEventArgs> ButtonRepeated = new CustomEventHandler<GamePadEventArgs>();
public BaseEventHandler<GamePadEventArgs> ThumbStickMoved = new CustomEventHandler<GamePadEventArgs>();
public BaseEventHandler<GamePadEventArgs> TriggerMoved = new CustomEventHandler<GamePadEventArgs>();
private static readonly bool[] _gamePadConnections = new bool[4];
// These buttons are not to be evaluated normally, but with the debounce filter
// in their respective methods.
private readonly Buttons[] _excludedButtons =
{
Buttons.LeftTrigger, Buttons.RightTrigger,
Buttons.LeftThumbstickDown, Buttons.LeftThumbstickUp, Buttons.LeftThumbstickRight,
Buttons.LeftThumbstickLeft,
Buttons.RightThumbstickLeft, Buttons.RightThumbstickRight, Buttons.RightThumbstickUp,
Buttons.RightThumbstickDown
};
private GamePadState _currentState;
//private int _lastPacketNumber;
// Implementation doesn't work, see explanation in CheckAllButtons().
private GameTime _gameTime;
private Buttons _lastButton;
private Buttons _lastLeftStickDirection;
private Buttons _lastRightStickDirection;
private GamePadState _lastThumbStickState;
private GamePadState _lastTriggerState;
private float _leftCurVibrationStrength;
private bool _leftStickDown;
private bool _leftTriggerDown;
private bool _leftVibrating;
private GameTime _previousGameTime;
private GamePadState _previousState;
private int _repeatedButtonTimer;
private float _rightCurVibrationStrength;
private bool _rightStickDown;
private bool _rightTriggerDown;
private bool _rightVibrating;
private TimeSpan _vibrationDurationLeft;
private TimeSpan _vibrationDurationRight;
private TimeSpan _vibrationStart;
private float _vibrationStrengthLeft;
private float _vibrationStrengthRight;
public GamePadListenerComponent(PortableGame game) : this(game, new GamePadListenerSettings()) { }
public GamePadListenerComponent(PortableGame game, GamePadListenerSettings settings) : base(game)
{
PlayerIndex = settings.PlayerIndex;
VibrationEnabled = settings.VibrationEnabled;
VibrationStrengthLeft = settings.VibrationStrengthLeft;
VibrationStrengthRight = settings.VibrationStrengthRight;
ThumbStickDeltaTreshold = settings.ThumbStickDeltaTreshold;
ThumbstickDownTreshold = settings.ThumbstickDownTreshold;
TriggerDeltaTreshold = settings.TriggerDeltaTreshold;
TriggerDownTreshold = settings.TriggerDownTreshold;
RepeatInitialDelay = settings.RepeatInitialDelay;
RepeatDelay = settings.RepeatDelay;
_previousGameTime = new GameTime();
_previousState = GamePadState.Default;
}
/// <summary>
/// Send a vibration command to the controller.
/// Returns true if the operation succeeded.
/// <para>
/// Motor values that are unset preserve
/// their current vibration strength and duration.
/// </para>
/// Note: Vibration currently only works on select platforms,
/// like Monogame.Windows.
/// </summary>
/// <param name="durationMs">Duration of the vibration in milliseconds.</param>
/// <param name="leftStrength">
/// The strength of the left motor.
/// This motor has a slow, deep, powerful rumble.
/// </param>
/// <param name="rightStrength">
/// The strength of the right motor.
/// This motor has a snappy, quick, high-pitched rumble.
/// </param>
/// <returns>Returns true if the operation succeeded.</returns>
public bool Vibrate(int durationMs, float leftStrength = float.NegativeInfinity, float rightStrength = float.NegativeInfinity)
{
if (!VibrationEnabled)
return false;
var lstrength = MathHelper.Clamp(leftStrength, 0, 1);
var rstrength = MathHelper.Clamp(rightStrength, 0, 1);
if (float.IsNegativeInfinity(leftStrength))
lstrength = _leftCurVibrationStrength;
if (float.IsNegativeInfinity(rightStrength))
rstrength = _rightCurVibrationStrength;
var success = GamePad.SetVibration(PlayerIndex, lstrength * VibrationStrengthLeft,
rstrength * VibrationStrengthRight);
if (success)
{
_leftVibrating = true;
_rightVibrating = true;
if (leftStrength > 0)
_vibrationDurationLeft = new TimeSpan(0, 0, 0, 0, durationMs);
else
{
if (lstrength > 0)
_vibrationDurationLeft -= _gameTime.TotalGameTime - _vibrationStart;
else
_leftVibrating = false;
}
if (rightStrength > 0)
_vibrationDurationRight = new TimeSpan(0, 0, 0, 0, durationMs);
else
{
if (rstrength > 0)
_vibrationDurationRight -= _gameTime.TotalGameTime - _vibrationStart;
else
_rightVibrating = false;
}
_vibrationStart = _gameTime.TotalGameTime;
_leftCurVibrationStrength = lstrength;
_rightCurVibrationStrength = rstrength;
}
return success;
}
private void CheckAllButtons()
{
// PacketNumber only and always changes if there is a difference between GamePadStates.
// ...At least, that's the theory. It doesn't seem to be implemented. Disabled for now.
//if (_lastPacketNumber == _currentState.PacketNumber)
// return;
foreach (Buttons button in Enum.GetValues(typeof(Buttons)))
{
if (_excludedButtons.Contains(button))
break;
if (_currentState.IsButtonDown(button) && _previousState.IsButtonUp(button))
RaiseButtonDown(button);
if (_currentState.IsButtonUp(button) && _previousState.IsButtonDown(button))
RaiseButtonUp(button);
}
// Checks triggers as buttons and floats
CheckTriggers(s => s.Triggers.Left, Buttons.LeftTrigger);
CheckTriggers(s => s.Triggers.Right, Buttons.RightTrigger);
// Checks thumbsticks as vector2s
CheckThumbSticks(s => s.ThumbSticks.Right, Buttons.RightStick);
CheckThumbSticks(s => s.ThumbSticks.Left, Buttons.LeftStick);
}
private void CheckTriggers(Func<GamePadState, float> getButtonState, Buttons button)
{
var debounce = 0.05f; // Value used to qualify a trigger as coming Up from a Down state
var curstate = getButtonState(_currentState);
var curdown = curstate > TriggerDownTreshold;
var prevdown = button == Buttons.RightTrigger ? _rightTriggerDown : _leftTriggerDown;
if (!prevdown && curdown)
{
RaiseButtonDown(button);
if (button == Buttons.RightTrigger)
_rightTriggerDown = true;
else
_leftTriggerDown = true;
}
else
{
if (prevdown && (curstate < debounce))
{
RaiseButtonUp(button);
if (button == Buttons.RightTrigger)
_rightTriggerDown = false;
else
_leftTriggerDown = false;
}
}
var prevstate = getButtonState(_lastTriggerState);
if (curstate > TriggerDeltaTreshold)
{
if (Math.Abs(prevstate - curstate) >= TriggerDeltaTreshold)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) TriggerMoved)?.Invoke(this, MakeArgs(button, curstate));
_lastTriggerState = _currentState;
}
}
else
{
if (prevstate > TriggerDeltaTreshold)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) TriggerMoved)?.Invoke(this, MakeArgs(button, curstate));
_lastTriggerState = _currentState;
}
}
}
private void CheckThumbSticks(Func<GamePadState, Vector2> getButtonState, Buttons button)
{
const float debounce = 0.15f;
var curVector = getButtonState(_currentState);
var curdown = curVector.Length() > ThumbstickDownTreshold;
var right = button == Buttons.RightStick;
var prevdown = right ? _rightStickDown : _leftStickDown;
var prevdir = button == Buttons.RightStick ? _lastRightStickDirection : _lastLeftStickDirection;
Buttons curdir;
if (curVector.Y > curVector.X)
{
if (curVector.Y > -curVector.X)
curdir = right ? Buttons.RightThumbstickUp : Buttons.LeftThumbstickUp;
else
curdir = right ? Buttons.RightThumbstickLeft : Buttons.LeftThumbstickLeft;
}
else
{
if (curVector.Y < -curVector.X)
curdir = right ? Buttons.RightThumbstickDown : Buttons.LeftThumbstickDown;
else
curdir = right ? Buttons.RightThumbstickRight : Buttons.LeftThumbstickRight;
}
if (!prevdown && curdown)
{
if (right)
_lastRightStickDirection = curdir;
else
_lastLeftStickDirection = curdir;
RaiseButtonDown(curdir);
if (button == Buttons.RightStick)
_rightStickDown = true;
else
_leftStickDown = true;
}
else
{
if (prevdown && (curVector.Length() < debounce))
{
RaiseButtonUp(prevdir);
if (button == Buttons.RightStick)
_rightStickDown = false;
else
_leftStickDown = false;
}
else
{
if (prevdown && curdown && (curdir != prevdir))
{
RaiseButtonUp(prevdir);
if (right)
_lastRightStickDirection = curdir;
else
_lastLeftStickDirection = curdir;
RaiseButtonDown(curdir);
}
}
}
var prevVector = getButtonState(_lastThumbStickState);
if (curVector.Length() > ThumbStickDeltaTreshold)
{
if (Vector2.Distance(curVector, prevVector) >= ThumbStickDeltaTreshold)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ThumbStickMoved)?.Invoke(this, MakeArgs(button, thumbStickState: curVector));
_lastThumbStickState = _currentState;
}
}
else
{
if (prevVector.Length() > ThumbStickDeltaTreshold)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ThumbStickMoved)?.Invoke(this, MakeArgs(button, thumbStickState: curVector));
_lastThumbStickState = _currentState;
}
}
}
private void CheckConnections()
{
if (!CheckControllerConnections)
return;
foreach (PlayerIndex index in Enum.GetValues(typeof(PlayerIndex)))
{
if (GamePad.GetState(index).IsConnected ^ _gamePadConnections[(int) index]) // We need more XORs in this world
{
_gamePadConnections[(int) index] = !_gamePadConnections[(int) index];
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ControllerConnectionChanged)?.Invoke(null, new GamePadEventArgs(GamePadState.Default, GamePad.GetState(index), TimeSpan.Zero, index));
}
}
}
private void CheckVibrate()
{
if (_leftVibrating && (_vibrationStart + _vibrationDurationLeft < _gameTime.TotalGameTime))
Vibrate(0, 0);
if (_rightVibrating && (_vibrationStart + _vibrationDurationRight < _gameTime.TotalGameTime))
Vibrate(0, rightStrength: 0);
}
public override void Update(GameTime gameTime)
{
CheckConnections();
_gameTime = gameTime;
_currentState = GamePad.GetState(PlayerIndex);
CheckVibrate();
if (!_currentState.IsConnected)
return;
CheckAllButtons();
CheckRepeatButton();
//_lastPacketNumber = _currentState.PacketNumber;
_previousGameTime = gameTime;
_previousState = _currentState;
}
private GamePadEventArgs MakeArgs(Buttons? button, float triggerstate = 0, Vector2? thumbStickState = null)
{
var elapsedTime = _gameTime.TotalGameTime - _previousGameTime.TotalGameTime;
return new GamePadEventArgs(_previousState, _currentState, elapsedTime, PlayerIndex, button, triggerstate, thumbStickState);
}
private void RaiseButtonDown(Buttons button)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ButtonDown)?.Invoke(this, MakeArgs(button));
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ButtonRepeated)?.Invoke(this, MakeArgs(button));
_lastButton = button;
_repeatedButtonTimer = 0;
}
private void RaiseButtonUp(Buttons button)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ButtonUp)?.Invoke(this, MakeArgs(button));
_lastButton = 0;
}
private void CheckRepeatButton()
{
_repeatedButtonTimer += _gameTime.ElapsedGameTime.Milliseconds;
if ((_repeatedButtonTimer < RepeatInitialDelay) || (_lastButton == 0))
return;
if (_repeatedButtonTimer < RepeatInitialDelay + RepeatDelay)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ButtonRepeated)?.Invoke(this, MakeArgs(_lastButton));
_repeatedButtonTimer = RepeatDelay + RepeatInitialDelay;
}
else
{
if (_repeatedButtonTimer > RepeatInitialDelay + RepeatDelay * 2)
{
((BaseEventHandlerWithInvoke<GamePadEventArgs>) ButtonRepeated)?.Invoke(this, MakeArgs(_lastButton));
_repeatedButtonTimer = RepeatDelay + RepeatInitialDelay;
}
}
}
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
// See the GNU Lesser General Public License for more details.
// -----
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace fxpa
{
public abstract class DynamicCustomObject : CustomObject, IPropertyContainer
{
protected static readonly Font DefaultDynamicObjectFont = new Font("Tahoma", 10);
public bool Enabled
{
get
{
return this.Visible;
}
set
{
this.Visible = value;
}
}
Pen _defaultControlPointPen = Pens.LightGray;
public Pen DefaultControlPointPen
{
get { return _defaultControlPointPen; }
set { _defaultControlPointPen = value; }
}
Pen _defaultSelectedControlPointPen = Pens.Red;
public Pen DefaultSelectedControlPointPen
{
get { return _defaultSelectedControlPointPen; }
set { _defaultSelectedControlPointPen = value; }
}
int _defaultAbsoluteControlPointSelectionRectanglesSize = 5;
public int DefaultAbsoluteControlPointSelectionRectanglesSize
{
get { return _defaultAbsoluteControlPointSelectionRectanglesSize; }
set { _defaultAbsoluteControlPointSelectionRectanglesSize = value; }
}
protected List<int> _selectedControlPoints = new List<int>();
public ICollection<int> SelectedControlPoints
{
get { return _selectedControlPoints; }
}
protected List<PointF> _controlPoints = new List<PointF>();
public ICollection<PointF> ControlPoints
{
get { return _controlPoints; }
}
public abstract bool IsBuilding
{
get;
}
bool _selected = false;
public bool Selected
{
get { return _selected; }
set { _selected = value; }
}
/// <summary>
///
/// </summary>
public DynamicCustomObject(string name)
{
base.Name = name;
}
void RaiseUpdatedEvent()
{
Manager.HandleDynamicObjectUpdated(this);
}
/// <summary>
///
/// </summary>
/// <param name="transformationMatrix"></param>
/// <param name="point"></param>
/// <param name="absoluteSelectionMargin"></param>
/// <param name="canLoseSelection">If the control is selected and current point unselects it, can it set state to unselected.</param>
/// <returns>Return true to mark - selected.</returns>
public virtual bool TrySelect(Matrix transformationMatrix, PointF drawingSpaceSelectionPoint, float absoluteSelectionMargin, bool canLoseSelection)
{
if (IsBuilding)
{
return false;
}
if (TrySelectControlPoints(transformationMatrix, drawingSpaceSelectionPoint, absoluteSelectionMargin) > 0)
{
Selected = true;
return true;
}
if (canLoseSelection)
{
Selected = false;
}
return false;
}
/// <summary>
/// Return true, when building is done.
/// </summary>
/// <param name="point"></param>
public abstract bool AddBuildingPoint(PointF point);
/// <summary>
/// Return true, when building is done.
/// Used by those objects that need key input.
/// </summary>
/// <param name="point"></param>
public virtual bool AddBuildingKey(KeyPressEventArgs key)
{
return false;
}
/// <summary>
/// Return true, when building is done.
/// Used by those objects that need key input.
/// </summary>
public virtual bool AddBuildingKey(KeyEventArgs key)
{
return false;
}
/// <summary>
/// Return false to specify the entire object need to be removed, true - the point was deleted.
/// </summary>
public virtual bool DeleteControlPoint(int pointIndex)
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="mouseLocation"></param>
/// <returns>Returns true to indicate hover is active and a redraw is needed.</returns>
public virtual bool SetMouseHover(PointF mouseLocation)
{
return false;
}
/// <summary>
/// Helper - extends the given line segment to the ends of the drawing space.
/// </summary>
protected void StretchSegmentToDrawingSpace(ref PointF point1, ref PointF point2, RectangleF drawingSpace)
{
//if (_controlPoints.Count < 2)
//{
// return;
//}
SimpleLine thisLine = new SimpleLine(point1, point2);
PointF?[] intersectionPoints = new PointF?[4];
// The order is important, so preserve it.
intersectionPoints[0] = thisLine.Intersection(new SimpleLine(new PointF(drawingSpace.X, drawingSpace.Y), new PointF(drawingSpace.X, drawingSpace.Y + drawingSpace.Width)));
intersectionPoints[1] = thisLine.Intersection(new SimpleLine(new PointF(drawingSpace.X + drawingSpace.Width, drawingSpace.Y), new PointF(drawingSpace.X + drawingSpace.Width, drawingSpace.Y + drawingSpace.Width)));
intersectionPoints[2] = thisLine.Intersection(new SimpleLine(new PointF(drawingSpace.X, drawingSpace.Y), new PointF(drawingSpace.X + drawingSpace.Height, drawingSpace.Y)));
intersectionPoints[3] = thisLine.Intersection(new SimpleLine(new PointF(drawingSpace.X, drawingSpace.Y + drawingSpace.Height), new PointF(drawingSpace.X + drawingSpace.Height, drawingSpace.Y + drawingSpace.Height)));
if (intersectionPoints[0].HasValue == false)
{// Parallel to the 0,0 / 0, 10 line.
point1 = new PointF(point1.X, drawingSpace.Y);
point2 = new PointF(point1.X, drawingSpace.Y + drawingSpace.Height);
return;
}
else if (intersectionPoints[1].HasValue == false)
{// Parallel to the 0,0 / 10, 0 line.
point1 = new PointF(drawingSpace.X, point1.Y);
point2 = new PointF(drawingSpace.X + drawingSpace.Width, point1.Y);
return;
}
// Establish the best 2 points (shortest line = best performance).
int pointIndex1 = -1, pointIndex2 = -1;
for (int i = 0; i < intersectionPoints.Length; i++)
{
if (intersectionPoints[i].HasValue == false)
{
continue;
}
// Is the point within drawing space (Contains method does not deliver needed results).
float xCalculationErrorMargin = (drawingSpace.X + drawingSpace.Width) / 100;
float yCalculationErrorMargin = (drawingSpace.Y + drawingSpace.Height) / 100;
if (intersectionPoints[i].Value.X < drawingSpace.X - xCalculationErrorMargin
|| intersectionPoints[i].Value.X > drawingSpace.X + drawingSpace.Width + xCalculationErrorMargin
|| intersectionPoints[i].Value.Y < drawingSpace.Y - yCalculationErrorMargin
|| intersectionPoints[i].Value.Y > drawingSpace.Y + drawingSpace.Height + yCalculationErrorMargin)
{// Point outside.
continue;
}
// Point approved.
if (pointIndex1 < 0)
{
pointIndex1 = i;
}
else
{
pointIndex2 = i;
break;
}
}
if (pointIndex1 < 0 || pointIndex2 < 0)
{
// SystemMonitor.Error("This scenario should not happen.");
pointIndex1 = 0;
pointIndex2 = 1;
}
point1 = intersectionPoints[pointIndex1].Value;
point2 = intersectionPoints[pointIndex2].Value;
}
/// <summary>
///
/// </summary>
public virtual void Drag(PointF drawingSpaceMoveVector)
{
if (IsBuilding)
{
return;
}
if (_selectedControlPoints.Count > 0)
{// Drag selected point only.
foreach (int pointIndex in _selectedControlPoints)
{
_controlPoints[pointIndex] = new PointF(_controlPoints[pointIndex].X + drawingSpaceMoveVector.X, _controlPoints[pointIndex].Y + drawingSpaceMoveVector.Y);
}
}
else
{// Drag entire object.
for (int i = 0; i < _controlPoints.Count; i++)
{
_controlPoints[i] = new PointF(_controlPoints[i].X + drawingSpaceMoveVector.X, _controlPoints[i].Y + drawingSpaceMoveVector.Y);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="drawingSpace">This parameter is used in "total space" objects like an endless line.</param>
/// <returns></returns>
public virtual RectangleF GetContainingRectangle(RectangleF drawingSpace)
{
if (ControlPoints.Count == 0)
{
return new RectangleF();
}
float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue;
foreach (PointF point in ControlPoints)
{
minX = Math.Min(minX, point.X);
maxX = Math.Max(maxX, point.X);
minY = Math.Min(minY, point.Y);
maxY = Math.Max(maxY, point.Y);
}
return new RectangleF(minX, minY, maxX - minX, maxY - minY);
}
/// <summary>
/// Helper.
/// </summary>
protected int TrySelectControlPoints(Matrix transformationMatrix, PointF point, float absoluteSelectionMargin)
{
_selectedControlPoints.Clear();
for (int i = 0; i < _controlPoints.Count; i++)
{
if (MathHelper.GetAbsoluteDistance(transformationMatrix, _controlPoints[i], point) <= absoluteSelectionMargin)
{
_selectedControlPoints.Add(i);
}
}
return _selectedControlPoints.Count;
}
/// <summary>
/// Helper.
/// </summary>
protected bool TrySelectLine(Matrix transformationMatrix, bool allowLineSegmentOnly, PointF linePoint1, PointF linePoint2, PointF location, float absoluteSelectionMargin)
{
float lineSegmentLocation;
PointF intersectionPoint;
SimpleLine line = new SimpleLine(linePoint1, linePoint2);
float? distance = line.DistanceToPoint(location, out lineSegmentLocation, out intersectionPoint);
if (MathHelper.GetAbsoluteDistance(transformationMatrix, location, intersectionPoint) <= absoluteSelectionMargin)
{// Selection.
return allowLineSegmentOnly == false || (lineSegmentLocation >=0 && lineSegmentLocation <= 1);
}
return false;
}
/// <summary>
/// Control points selection rectangle is rendered in absolute size, ignoring scaling.
/// </summary>
/// <param name="g"></param>
/// <param name="pen">Pass null to use default control point pen.</param>
protected void DrawControlPoints(GraphicsWrapper g)
{
float xMargin = 0.5f * Math.Abs(_defaultAbsoluteControlPointSelectionRectanglesSize / g.DrawingSpaceTransform.Elements[0]);
float yMargin = 0.5f * Math.Abs(_defaultAbsoluteControlPointSelectionRectanglesSize / g.DrawingSpaceTransform.Elements[3]);
for (int i = 0; i < _controlPoints.Count; i++)
{
PointF point = _controlPoints[i];
if (_selectedControlPoints.Contains(i))
{
g.DrawRectangle(_defaultSelectedControlPointPen, point.X - xMargin, point.Y - yMargin, xMargin * 2, yMargin * 2);
}
else
{
g.DrawRectangle(_defaultControlPointPen, point.X - xMargin, point.Y - yMargin, xMargin * 2, yMargin * 2);
}
}
}
public string[] GetPropertiesNames()
{
return new string[] { };
}
public object GetPropertyValue(string name)
{
return null;
}
public Type GetPropertyType(string name)
{
return null;
}
public bool SetPropertyValue(string name, object value)
{
return false;
}
public void PropertyChanged()
{
RaiseUpdatedEvent();
}
}
}
| |
//-------------------------------------------------------------------------------------------------
// <copyright company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
// </copyright>
//
// <summary>
//
//
//
// </summary>
//-------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace ReverseProxy
{
public class AzureStorageProxyBase : ProxyBase
{
protected string resourcePresented;
protected string prefix;
protected string PresentedAccount;
protected string PresentedKey;
protected string ManagedAccount;
protected string ManagedKey;
protected AzureStorageProxyBase(string resourcePresented, string prefix)
{
this.resourcePresented = resourcePresented;
this.prefix = prefix;
}
public AzureStorageProxyBase(string resourcePresented, string prefix, string presentedAccount, string presentedKey, string managedAccount, string managedKey)
{
this.resourcePresented = resourcePresented;
this.prefix = prefix;
this.PresentedAccount = presentedAccount;
this.PresentedKey = presentedKey;
this.ManagedAccount = managedAccount;
this.ManagedKey = managedKey;
}
protected override bool ShouldRewrite(string contentType)
{
return
contentType.StartsWith("application/xml", StringComparison.OrdinalIgnoreCase) ||
contentType.StartsWith("application/atom+xml", StringComparison.OrdinalIgnoreCase) ||
contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
}
protected override string RewriteResponse(string responseContent, string path)
{
var p = path.Split('/');
var service = p[0].ToLower();
var host = String.Format("{0}.{1}.core.windows.net", ManagedAccount, service);
return responseContent.Replace(host, resourcePresented + "/" + prefix + "/" + service);
}
protected override Uri BuildUri(SerialilzableWebRequest request)
{
var p = request.Path.Split('/');
var service = p.Length > 0 ? p[0].ToLower() : "";
var host = String.Format("{0}.{1}.core.windows.net", ManagedAccount, service);
var path = String.Join("/", p.Skip(1));
var ub = new UriBuilder() { Host = host, Path = path, Query = request.Query };
return ub.Uri;
}
protected override void AugmentHeaders(SerialilzableWebRequest request, HttpWebRequest remoteRequest)
{
var p = request.Path.Split('/');
var service = p.Length > 0 ? p[0].ToLower() : "";
var copyHeader = request.Headers.Get("x-ms-copy-source");
if (copyHeader != null)
{
var copyPath = copyHeader.Split('/');
if (copyPath.Length > 4 && copyPath[3] == copyPath[5])
{
copyPath = copyPath.Skip(5).ToArray();
copyPath[0] = "";
}
copyPath[1] = ManagedAccount;
remoteRequest.Headers.Set("x-ms-copy-source", String.Join("/", copyPath));
}
var authHeader = request.Headers.Get("Authorization");
// Only sign a request that contains a verified signature.
if (authHeader != null)
{
remoteRequest.Headers.Set("Authorization", SharedKeyAuthorizationHeader(authHeader.StartsWith("SharedKeyLite"), ManagedAccount, ManagedKey, remoteRequest.Method, remoteRequest.Headers, remoteRequest.RequestUri, remoteRequest.ContentLength, service == "table"));
}
}
protected override string ExtractPath(string path)
{
var p = path.Split('/');
// this works around features of AzureStorageClient with custom endpoints
if (p.Length >= 6 && p[2].ToLower() == p[4].ToLower() && p[1].ToLower() == p[3].ToLower())
{
return String.Join("/", p.Skip(p.Length == 9 ? 6 : 4));
}
else
{
return String.Join("/", p.Skip(2));
}
}
protected override bool _authenticate(HttpContext context)
{
var request = context.Request;
var p = request.Url.AbsolutePath.Split('/');
var service = p[2].ToLower();
var authHeader = request.Headers.Get("Authorization");
// If there is no authentication header, it may be a public blob so let a GET go through,
// but be sure not to sign somethign that didn't already have a verified signature.
if (authHeader == null)
{
if (request.HttpMethod.Equals("get", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else
{
return false;
}
}
var computedSignature = SharedKeyAuthorizationHeader(authHeader.StartsWith("SharedKeyLite"), PresentedAccount, PresentedKey, request.HttpMethod, request.Headers, request.Url, request.ContentLength, service == "table");
if (authHeader != computedSignature)
{
var encodedUri = (new UriBuilder(request.Url) { Path = request.Url.AbsolutePath.Replace(":", "%3A").Replace("@", "%40") }).Uri;
var computedSignature2 = SharedKeyAuthorizationHeader(authHeader.StartsWith("SharedKeyLite"), PresentedAccount, PresentedKey, request.HttpMethod, request.Headers, encodedUri, request.ContentLength, service == "table");
if (authHeader == computedSignature2)
{
return true;
}
{
return false;
}
}
return true;
}
public static string SharedKeyAuthorizationHeader(bool lite, string StorageAccount, string StorageKey, string method, NameValueCollection Headers, Uri uri, long contentLength, bool IsTableStorage = false, string contentType = "")
{
string MessageSignature;
string algorithm = lite ? "SharedKeyLite " : "SharedKey ";
var ifMatch = Headers.Get("If-Match") ?? "";
var md5 = Headers.Get("Content-MD5") ?? "";
if (IsTableStorage)
{
// One of the following is required
string now;
if (Headers.AllKeys.Contains("Date"))
{
now = Headers["Date"];
}
else
{
now = Headers["x-ms-date"];
}
if (lite)
{
MessageSignature = String.Format("{0}\n{1}",
now,
GetCanonicalizedResource(uri, StorageAccount, IsTableStorage)
);
}
else
{
MessageSignature = String.Format("{0}\n\n{1}\n{2}\n{3}",
method,
"application/atom+xml",
now,
GetCanonicalizedResource(uri, StorageAccount, IsTableStorage)
);
}
}
else
{
if (lite)
{
MessageSignature = String.Format("{0}\n{1}\n{2}\n{3}\n{4}{5}",
method,
md5,
contentType,
"", // Is now used
GetCanonicalizedHeaders(Headers),
GetCanonicalizedResource(uri, StorageAccount, IsTableStorage)
);
}
else
{
MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
method,
(method == "GET" ||
method == "HEAD" ||
method == "DELETE" && (Headers["User-Agent"] ?? String.Empty).StartsWith("WA-Storage", StringComparison.OrdinalIgnoreCase))
? String.Empty : contentLength.ToString(),
ifMatch,
GetCanonicalizedHeaders(Headers),
GetCanonicalizedResource(uri, StorageAccount, IsTableStorage),
md5
);
}
}
byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);
System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(StorageKey));
String AuthorizationHeader = algorithm + StorageAccount + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
return AuthorizationHeader;
}
public static string GetCanonicalizedHeaders(NameValueCollection headers)
{
ArrayList headerNameList = new ArrayList();
StringBuilder sb = new StringBuilder();
foreach (string headerName in headers.Keys)
{
if (headerName.ToLowerInvariant().StartsWith("x-ms-", StringComparison.Ordinal))
{
headerNameList.Add(headerName.ToLowerInvariant());
}
}
headerNameList.Sort();
foreach (string headerName in headerNameList)
{
StringBuilder builder = new StringBuilder(headerName);
string separator = ":";
foreach (string headerValue in GetHeaderValues(headers, headerName))
{
string trimmedValue = headerValue.Replace("\r\n", String.Empty);
builder.Append(separator);
builder.Append(trimmedValue);
separator = ",";
}
sb.Append(builder.ToString());
sb.Append("\n");
}
return sb.ToString();
}
// Get header values.
public static ArrayList GetHeaderValues(NameValueCollection headers, string headerName)
{
ArrayList list = new ArrayList();
string[] values = headers.GetValues(headerName);
if (values != null)
{
foreach (string str in values)
{
list.Add(str.TrimStart(null));
}
}
return list;
}
// Get canonicalized resourcePresented.
public static string GetCanonicalizedResource(Uri address, string accountName, bool IsTableStorage)
{
StringBuilder str = new StringBuilder();
StringBuilder builder = new StringBuilder("/");
builder.Append(accountName);
builder.Append(address.AbsolutePath);
str.Append(builder.ToString());
NameValueCollection values2 = new NameValueCollection();
if (!IsTableStorage)
{
NameValueCollection values = HttpUtility.ParseQueryString(address.Query);
foreach (string str2 in values.Keys)
{
ArrayList list = new ArrayList(values.GetValues(str2));
list.Sort();
StringBuilder builder2 = new StringBuilder();
foreach (object obj2 in list)
{
if (builder2.Length > 0)
{
builder2.Append(",");
}
builder2.Append(obj2.ToString());
}
values2.Add((str2 == null) ? str2 : str2.ToLowerInvariant(), builder2.ToString());
}
}
ArrayList list2 = new ArrayList(values2.AllKeys);
list2.Sort();
foreach (string str3 in list2)
{
StringBuilder builder3 = new StringBuilder(string.Empty);
builder3.Append(str3);
builder3.Append(":");
builder3.Append(values2[str3]);
str.Append("\n");
str.Append(builder3.ToString());
}
return str.ToString();
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Text;
namespace Cassandra
{
internal class TokenMap
{
internal readonly TokenFactory Factory;
private readonly List<IToken> _ring;
private readonly Dictionary<string, Dictionary<IToken, ISet<Host>>> _tokenToHostsByKeyspace;
private readonly Dictionary<IToken, Host> _primaryReplicas;
private static readonly Logger Logger = new Logger(typeof(ControlConnection));
internal TokenMap(TokenFactory factory, Dictionary<string, Dictionary<IToken, ISet<Host>>> tokenToHostsByKeyspace, List<IToken> ring, Dictionary<IToken, Host> primaryReplicas)
{
Factory = factory;
_tokenToHostsByKeyspace = tokenToHostsByKeyspace;
_ring = ring;
_primaryReplicas = primaryReplicas;
}
internal IDictionary<IToken, ISet<Host>> GetByKeyspace(string keyspaceName)
{
return _tokenToHostsByKeyspace[keyspaceName];
}
public static TokenMap Build(string partitioner, ICollection<Host> hosts, ICollection<KeyspaceMetadata> keyspaces)
{
var factory = TokenFactory.GetFactory(partitioner);
if (factory == null)
{
return null;
}
var primaryReplicas = new Dictionary<IToken, Host>();
var allSorted = new SortedSet<IToken>();
var datacenters = new Dictionary<string, DatacenterInfo>();
foreach (var host in hosts)
{
if (host.Datacenter != null)
{
DatacenterInfo dc;
if (!datacenters.TryGetValue(host.Datacenter, out dc))
{
datacenters[host.Datacenter] = dc = new DatacenterInfo();
}
dc.HostLength++;
dc.AddRack(host.Rack);
}
foreach (var tokenStr in host.Tokens)
{
try
{
var token = factory.Parse(tokenStr);
allSorted.Add(token);
primaryReplicas[token] = host;
}
catch
{
Logger.Error(string.Format("Token {0} could not be parsed using {1} partitioner implementation", tokenStr, partitioner));
}
}
}
var ring = new List<IToken>(allSorted);
var tokenToHosts = new Dictionary<string, Dictionary<IToken, ISet<Host>>>(keyspaces.Count);
var ksTokensCache = new Dictionary<string, Dictionary<IToken, ISet<Host>>>();
//Only consider nodes that have tokens
var hostCount = hosts.Count(h => h.Tokens.Any());
foreach (var ks in keyspaces)
{
Dictionary<IToken, ISet<Host>> replicas;
if (ks.StrategyClass == ReplicationStrategies.SimpleStrategy)
{
replicas = ComputeTokenToReplicaSimple(ks.Replication["replication_factor"], hostCount, ring, primaryReplicas);
}
else if (ks.StrategyClass == ReplicationStrategies.NetworkTopologyStrategy)
{
var key = GetReplicationKey(ks.Replication);
if (!ksTokensCache.TryGetValue(key, out replicas))
{
replicas = ComputeTokenToReplicaNetwork(ks.Replication, ring, primaryReplicas, datacenters);
ksTokensCache.Add(key, replicas);
}
}
else
{
//No replication information, use primary replicas
replicas = primaryReplicas.ToDictionary(kv => kv.Key, kv => (ISet<Host>)new HashSet<Host>(new [] { kv.Value }));
}
tokenToHosts[ks.Name] = replicas;
}
return new TokenMap(factory, tokenToHosts, ring, primaryReplicas);
}
private static string GetReplicationKey(IDictionary<string, int> replication)
{
var key = new StringBuilder();
foreach (var kv in replication)
{
key.Append(kv.Key);
key.Append(":");
key.Append(kv.Value);
key.Append(",");
}
return key.ToString();
}
private static Dictionary<IToken, ISet<Host>> ComputeTokenToReplicaNetwork(IDictionary<string, int> replicationFactors,
IList<IToken> ring,
IDictionary<IToken, Host> primaryReplicas,
IDictionary<string, DatacenterInfo> datacenters)
{
var replicas = new Dictionary<IToken, ISet<Host>>();
for (var i = 0; i < ring.Count; i++)
{
var token = ring[i];
var replicasByDc = new Dictionary<string, int>();
var tokenReplicas = new OrderedHashSet<Host>();
var racksPlaced = new Dictionary<string, HashSet<string>>();
var skippedHosts = new List<Host>();
for (var j = 0; j < ring.Count; j++)
{
var replicaIndex = i + j;
if (replicaIndex >= ring.Count)
{
//circle back
replicaIndex = replicaIndex % ring.Count;
}
var h = primaryReplicas[ring[replicaIndex]];
var dc = h.Datacenter;
int dcRf;
if (!replicationFactors.TryGetValue(dc, out dcRf))
{
continue;
}
dcRf = Math.Min(dcRf, datacenters[dc].HostLength);
int dcReplicas;
replicasByDc.TryGetValue(dc, out dcReplicas);
//Amount of replicas per dc is equals to the rf or the amount of host in the datacenter
if (dcReplicas >= dcRf)
{
continue;
}
HashSet<string> racksPlacedInDc;
if (!racksPlaced.TryGetValue(dc, out racksPlacedInDc))
{
racksPlaced[dc] = racksPlacedInDc = new HashSet<string>();
}
if (h.Rack != null && racksPlacedInDc.Contains(h.Rack) && racksPlacedInDc.Count < datacenters[dc].Racks.Count)
{
// We already selected a replica for this rack
// Skip until replicas in other racks are added
if (skippedHosts.Count < dcRf - dcReplicas)
{
skippedHosts.Add(h);
}
continue;
}
dcReplicas += tokenReplicas.Add(h) ? 1 : 0;
replicasByDc[dc] = dcReplicas;
if (h.Rack != null && racksPlacedInDc.Add(h.Rack) && racksPlacedInDc.Count == datacenters[dc].Racks.Count)
{
// We finished placing all replicas for all racks in this dc
// Add the skipped hosts
replicasByDc[dc] += AddSkippedHosts(dc, dcRf, dcReplicas, tokenReplicas, skippedHosts);
}
if (IsDoneForToken(replicationFactors, replicasByDc, datacenters))
{
break;
}
}
replicas[token] = tokenReplicas;
}
return replicas;
}
internal static int AddSkippedHosts(string dc, int dcRf, int dcReplicas, ISet<Host> tokenReplicas, IList<Host> skippedHosts)
{
var counter = 0;
var length = dcRf - dcReplicas;
foreach (var h in skippedHosts.Where(h => h.Datacenter == dc))
{
tokenReplicas.Add(h);
if (++counter == length)
{
break;
}
}
return counter;
}
internal static bool IsDoneForToken(IDictionary<string, int> replicationFactors,
IDictionary<string, int> replicasByDc,
IDictionary<string, DatacenterInfo> datacenters)
{
foreach (var dcName in replicationFactors.Keys)
{
DatacenterInfo dc;
if (!datacenters.TryGetValue(dcName, out dc))
{
// A DC is included in the RF but the DC does not exist in the topology
continue;
}
var rf = Math.Min(replicationFactors[dcName], dc.HostLength);
if (rf > 0 && (!replicasByDc.ContainsKey(dcName) || replicasByDc[dcName] < rf))
{
return false;
}
}
return true;
}
/// <summary>
/// Converts token-primary to token-replicas
/// </summary>
private static Dictionary<IToken, ISet<Host>> ComputeTokenToReplicaSimple(int replicationFactor, int hostCount, List<IToken> ring, Dictionary<IToken, Host> primaryReplicas)
{
var rf = Math.Min(replicationFactor, hostCount);
var tokenToReplicas = new Dictionary<IToken, ISet<Host>>(ring.Count);
for (var i = 0; i < ring.Count; i++)
{
var token = ring[i];
var replicas = new HashSet<Host>();
replicas.Add(primaryReplicas[token]);
var j = 1;
while (replicas.Count < rf)
{
var nextReplicaIndex = i + j;
if (nextReplicaIndex >= ring.Count)
{
//circle back
nextReplicaIndex = nextReplicaIndex % ring.Count;
}
var nextReplica = primaryReplicas[ring[nextReplicaIndex]];
replicas.Add(nextReplica);
j++;
}
tokenToReplicas.Add(token, replicas);
}
return tokenToReplicas;
}
public ICollection<Host> GetReplicas(string keyspaceName, IToken token)
{
// Find the primary replica
var i = _ring.BinarySearch(token);
if (i < 0)
{
//no exact match, use closest index
i = ~i;
if (i >= _ring.Count)
{
i = 0;
}
}
var closestToken = _ring[i];
if (keyspaceName != null && _tokenToHostsByKeyspace.ContainsKey(keyspaceName))
{
return _tokenToHostsByKeyspace[keyspaceName][closestToken];
}
return new Host[] { _primaryReplicas[closestToken] };
}
internal class DatacenterInfo
{
private readonly HashSet<string> _racks;
public DatacenterInfo()
{
_racks = new HashSet<string>();
}
public int HostLength { get; set; }
public ISet<string> Racks { get { return _racks; } }
public void AddRack(string name)
{
if (name == null)
{
return;
}
_racks.Add(name);
}
}
private class OrderedHashSet<T> : ISet<T>
{
private readonly HashSet<T> _set;
private readonly LinkedList<T> _list;
public int Count { get { return _set.Count; } }
public bool IsReadOnly { get { return false; } }
public OrderedHashSet()
{
_set = new HashSet<T>();
_list = new LinkedList<T>();
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void ICollection<T>.Add(T item)
{
Add(item);
}
public void UnionWith(IEnumerable<T> other)
{
_set.UnionWith(other);
}
public void IntersectWith(IEnumerable<T> other)
{
_set.IntersectWith(other);
}
public void ExceptWith(IEnumerable<T> other)
{
_set.ExceptWith(other);
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
_set.SymmetricExceptWith(other);
}
public bool IsSubsetOf(IEnumerable<T> other)
{
return _set.IsSubsetOf(other);
}
public bool IsSupersetOf(IEnumerable<T> other)
{
return _set.IsSupersetOf(other);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return _set.IsProperSupersetOf(other);
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return _set.IsProperSubsetOf(other);
}
public bool Overlaps(IEnumerable<T> other)
{
return _set.Overlaps(other);
}
public bool SetEquals(IEnumerable<T> other)
{
return _set.SetEquals(other);
}
public bool Add(T item)
{
var added = _set.Add(item);
if (added)
{
_list.AddLast(item);
}
return added;
}
public void Clear()
{
_set.Clear();
_list.Clear();
}
public bool Contains(T item)
{
return _set.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_set.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
var removed = _set.Remove(item);
if (removed)
{
_list.Remove(item);
}
return removed;
}
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using MoonSharp.Interpreter;
using MoonSharp.VsCodeDebugger;
namespace Fungus
{
/// <summary>
/// Wrapper for a MoonSharp Lua Script instance.
/// A debug server is started automatically when running in the Unity Editor. Use VS Code to debug Lua scripts.
/// </summary>
public class LuaEnvironment : MonoBehaviour
{
[Tooltip("Start a Lua debug server on scene start.")]
[SerializeField] protected bool startDebugServer = true;
[Tooltip("Port to use for the Lua debug server.")]
[SerializeField] protected int debugServerPort = 41912;
/// <summary>
/// The MoonSharp interpreter instance.
/// </summary>
protected Script interpreter;
/// <summary>
/// Flag used to avoid startup dependency issues.
/// </summary>
protected bool initialised = false;
protected virtual void Start()
{
InitEnvironment();
}
/// <summary>
/// Detach the MoonSharp script from the debugger.
/// </summary>
protected virtual void OnDestroy()
{
if (DebugServer != null)
{
DebugServer.Detach(interpreter);
}
}
/// <summary>
/// Register all Lua files in the project so they can be accessed at runtime.
/// </summary>
protected virtual void InitLuaScriptFiles()
{
object[] result = Resources.LoadAll("Lua", typeof(TextAsset));
interpreter.Options.ScriptLoader = new LuaScriptLoader(result.OfType<TextAsset>());
}
/// <summary>
/// A Unity coroutine method which updates a Lua coroutine each frame.
/// <param name="closure">A MoonSharp closure object representing a function.</param>
/// <param name="onComplete">A delegate method that is called when the coroutine completes. Includes return parameter.</param>
/// </summary>
protected virtual IEnumerator RunLuaCoroutine(Closure closure, Action<DynValue> onComplete = null)
{
DynValue co = interpreter.CreateCoroutine(closure);
DynValue returnValue = null;
while (co.Coroutine.State != CoroutineState.Dead)
{
try
{
returnValue = co.Coroutine.Resume();
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, GetSourceCode());
}
yield return null;
}
if (onComplete != null)
{
onComplete(returnValue);
}
}
protected virtual string GetSourceCode()
{
// Get most recently executed source code
string sourceCode = "";
if (interpreter.SourceCodeCount > 0)
{
MoonSharp.Interpreter.Debugging.SourceCode sc = interpreter.GetSourceCode(interpreter.SourceCodeCount - 1);
if (sc != null)
{
sourceCode = sc.Code;
}
}
return sourceCode;
}
/// <summary>
/// Starts a standard Unity coroutine.
/// The coroutine is managed by the LuaEnvironment monobehavior, so you can call StopAllCoroutines to
/// stop all active coroutines later.
/// </summary>
protected virtual IEnumerator RunUnityCoroutineImpl(IEnumerator coroutine)
{
if (coroutine == null)
{
UnityEngine.Debug.LogWarning("Coroutine must not be null");
yield break;
}
yield return StartCoroutine(coroutine);
}
/// <summary>
/// Writes a MoonSharp exception to the debug log in a helpful format.
/// </summary>
/// <param name="decoratedMessage">Decorated message from a MoonSharp exception</param>
/// <param name="debugInfo">Debug info, usually the Lua script that was running.</param>
protected static void LogException(string decoratedMessage, string debugInfo)
{
string output = decoratedMessage + "\n";
char[] separators = { '\r', '\n' };
string[] lines = debugInfo.Split(separators, StringSplitOptions.None);
// Show line numbers for script listing
int count = 1;
foreach (string line in lines)
{
output += count.ToString() + ": " + line + "\n";
count++;
}
UnityEngine.Debug.LogError(output);
}
#region Public members
/// <summary>
/// Instance of VS Code debug server when debugging option is enabled.
/// </summary>
public static MoonSharpVsCodeDebugServer DebugServer { get; private set; }
/// <summary>
/// Returns the first Lua Environment found in the scene, or creates one if none exists.
/// This is a slow operation, call it once at startup and cache the returned value.
/// </summary>
public static LuaEnvironment GetLua()
{
var luaEnv = GameObject.FindObjectOfType<LuaEnvironment>();
if (luaEnv == null)
{
GameObject prefab = Resources.Load<GameObject>("Prefabs/LuaEnvironment");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.name = "LuaEnvironment";
luaEnv = go.GetComponent<LuaEnvironment>();
}
}
return luaEnv;
}
/// <summary>
/// Register a type given it's assembly qualified name.
/// </summary>
public static void RegisterType(string typeName, bool extensionType = false)
{
System.Type t = null;
try
{
t = System.Type.GetType(typeName);
}
catch
{}
if (t == null)
{
UnityEngine.Debug.LogWarning("Type not found: " + typeName);
return;
}
// Registering System.Object breaks MoonSharp's automated conversion of Lists and Dictionaries to Lua tables.
if (t == typeof(System.Object))
{
return;
}
if (!UserData.IsTypeRegistered(t))
{
try
{
if (extensionType)
{
UserData.RegisterExtensionType(t);
}
else
{
UserData.RegisterType(t);
}
}
catch (ArgumentException ex)
{
UnityEngine.Debug.LogWarning(ex.Message);
}
}
}
/// <summary>
/// Start a Unity coroutine from a Lua call.
/// </summary>
public virtual Task RunUnityCoroutine(IEnumerator coroutine)
{
if (coroutine == null)
{
return null;
}
// We use the Task class so we can poll the coroutine to check if it has finished.
// Standard Unity coroutines don't support this check.
return new Task(RunUnityCoroutineImpl(coroutine));
}
/// <summary>
/// Initialise the Lua interpreter so we can start running Lua code.
/// </summary>
public virtual void InitEnvironment()
{
if (initialised)
{
return;
}
Script.DefaultOptions.DebugPrint = (s) => { UnityEngine.Debug.Log(s); };
// In some use cases (e.g. downloadable Lua files) some Lua modules can pose a potential security risk.
// You can restrict which core lua modules are available here if needed. See the MoonSharp documentation for details.
interpreter = new Script(CoreModules.Preset_Complete);
// Load all Lua scripts in the project
InitLuaScriptFiles();
// Initialize any attached initializer components (e.g. LuaUtils)
LuaEnvironmentInitializer[] initializers = GetComponents<LuaEnvironmentInitializer>();
foreach (LuaEnvironmentInitializer initializer in initializers)
{
initializer.Initialize();
}
//
// Change this to #if UNITY_STANDALONE if you want to debug a standalone build.
//
#if UNITY_EDITOR
if (startDebugServer &&
DebugServer == null)
{
// Create the debugger server
DebugServer = new MoonSharpVsCodeDebugServer(debugServerPort);
// Start the debugger server
DebugServer.Start();
// Attach the MoonSharp script to the debugger
DebugServer.AttachToScript(interpreter, gameObject.name);
}
#endif
initialised = true;
}
/// <summary>
/// The MoonSharp interpreter instance used to run Lua code.
/// </summary>
public virtual Script Interpreter { get { return interpreter; } }
/// <summary>
/// Loads and compiles a string containing Lua script, returning a closure (Lua function) which can be executed later.
/// <param name="luaString">The Lua code to be run.</param>
/// <param name="friendlyName">A descriptive name to be used in error reports.</param>
/// </summary>
public virtual Closure LoadLuaFunction(string luaString, string friendlyName)
{
InitEnvironment();
string processedString;
var initializer = GetComponent<LuaEnvironmentInitializer>();
if (initializer != null)
{
processedString = initializer.PreprocessScript(luaString);
}
else
{
processedString = luaString;
}
// Load the Lua script
DynValue res = null;
try
{
res = interpreter.LoadString(processedString, null, friendlyName);
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, luaString);
}
if (res == null ||
res.Type != DataType.Function)
{
UnityEngine.Debug.LogError("Failed to create Lua function from Lua string");
return null;
}
return res.Function;
}
/// <summary>
/// Load and run a previously compiled Lua script. May be run as a coroutine.
/// <param name="fn">A previously compiled Lua function.</param>
/// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param>
/// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param>
/// </summary>
public virtual void RunLuaFunction(Closure fn, bool runAsCoroutine, Action<DynValue> onComplete = null)
{
if (fn == null)
{
if (onComplete != null)
{
onComplete(null);
}
return;
}
// Execute the Lua script
if (runAsCoroutine)
{
StartCoroutine(RunLuaCoroutine(fn, onComplete));
}
else
{
DynValue returnValue = null;
try
{
returnValue = fn.Call();
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, GetSourceCode());
}
if (onComplete != null)
{
onComplete(returnValue);
}
}
}
/// <summary>
/// Load and run a string containing Lua script. May be run as a coroutine.
/// <param name="luaString">The Lua code to be run.</param>
/// <param name="friendlyName">A descriptive name to be used in error reports.</param>
/// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param>
/// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param>
/// </summary>
public virtual void DoLuaString(string luaString, string friendlyName, bool runAsCoroutine, Action<DynValue> onComplete = null)
{
Closure fn = LoadLuaFunction(luaString, friendlyName);
RunLuaFunction(fn, runAsCoroutine, onComplete);
}
#endregion
}
}
| |
using System;
using BTCPayServer.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BTCPayServer.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200625064111_refundnotificationpullpayments")]
public partial class refundnotificationpullpayments : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
int? maxLength = this.IsMySql(migrationBuilder.ActiveProvider) ? (int?)255 : null;
migrationBuilder.DropTable(
name: "RefundAddresses");
migrationBuilder.AddColumn<string>(
name: "CurrentRefundId",
table: "Invoices",
nullable: true,
maxLength: maxLength);
migrationBuilder.CreateTable(
name: "Notifications",
columns: table => new
{
Id = table.Column<string>(maxLength: 36, nullable: false),
Created = table.Column<DateTimeOffset>(nullable: false),
ApplicationUserId = table.Column<string>(maxLength: 50, nullable: false),
NotificationType = table.Column<string>(maxLength: 100, nullable: false),
Seen = table.Column<bool>(nullable: false),
Blob = table.Column<byte[]>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Notifications", x => x.Id);
table.ForeignKey(
name: "FK_Notifications_AspNetUsers_ApplicationUserId",
column: x => x.ApplicationUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "PullPayments",
columns: table => new
{
Id = table.Column<string>(maxLength: 30, nullable: false),
StoreId = table.Column<string>(maxLength: 50, nullable: true),
Period = table.Column<long>(nullable: true),
StartDate = table.Column<DateTimeOffset>(nullable: false),
EndDate = table.Column<DateTimeOffset>(nullable: true),
Archived = table.Column<bool>(nullable: false),
Blob = table.Column<byte[]>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PullPayments", x => x.Id);
table.ForeignKey(
name: "FK_PullPayments_Stores_StoreId",
column: x => x.StoreId,
principalTable: "Stores",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Payouts",
columns: table => new
{
Id = table.Column<string>(maxLength: 30, nullable: false),
Date = table.Column<DateTimeOffset>(nullable: false),
PullPaymentDataId = table.Column<string>(maxLength: 30, nullable: true),
State = table.Column<string>(maxLength: 20, nullable: false),
PaymentMethodId = table.Column<string>(maxLength: 20, nullable: false),
Destination = table.Column<string>(maxLength: maxLength, nullable: true),
Blob = table.Column<byte[]>(nullable: true),
Proof = table.Column<byte[]>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Payouts", x => x.Id);
table.ForeignKey(
name: "FK_Payouts_PullPayments_PullPaymentDataId",
column: x => x.PullPaymentDataId,
principalTable: "PullPayments",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Refunds",
columns: table => new
{
InvoiceDataId = table.Column<string>(maxLength: maxLength, nullable: false),
PullPaymentDataId = table.Column<string>(maxLength: maxLength, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Refunds", x => new { x.InvoiceDataId, x.PullPaymentDataId });
table.ForeignKey(
name: "FK_Refunds_Invoices_InvoiceDataId",
column: x => x.InvoiceDataId,
principalTable: "Invoices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Refunds_PullPayments_PullPaymentDataId",
column: x => x.PullPaymentDataId,
principalTable: "PullPayments",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Invoices_Id_CurrentRefundId",
table: "Invoices",
columns: new[] { "Id", "CurrentRefundId" });
migrationBuilder.CreateIndex(
name: "IX_Notifications_ApplicationUserId",
table: "Notifications",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_Payouts_Destination",
table: "Payouts",
column: "Destination",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Payouts_PullPaymentDataId",
table: "Payouts",
column: "PullPaymentDataId");
migrationBuilder.CreateIndex(
name: "IX_Payouts_State",
table: "Payouts",
column: "State");
migrationBuilder.CreateIndex(
name: "IX_PullPayments_StoreId",
table: "PullPayments",
column: "StoreId");
migrationBuilder.CreateIndex(
name: "IX_Refunds_PullPaymentDataId",
table: "Refunds",
column: "PullPaymentDataId");
if (this.SupportAddForeignKey(this.ActiveProvider))
migrationBuilder.AddForeignKey(
name: "FK_Invoices_Refunds_Id_CurrentRefundId",
table: "Invoices",
columns: new[] { "Id", "CurrentRefundId" },
principalTable: "Refunds",
principalColumns: new[] { "InvoiceDataId", "PullPaymentDataId" },
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Invoices_Refunds_Id_CurrentRefundId",
table: "Invoices");
migrationBuilder.DropTable(
name: "Notifications");
migrationBuilder.DropTable(
name: "Payouts");
migrationBuilder.DropTable(
name: "Refunds");
migrationBuilder.DropTable(
name: "PullPayments");
migrationBuilder.DropIndex(
name: "IX_Invoices_Id_CurrentRefundId",
table: "Invoices");
migrationBuilder.DropColumn(
name: "CurrentRefundId",
table: "Invoices");
migrationBuilder.CreateTable(
name: "RefundAddresses",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
Blob = table.Column<byte[]>(type: "BLOB", nullable: true),
InvoiceDataId = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RefundAddresses", x => x.Id);
table.ForeignKey(
name: "FK_RefundAddresses_Invoices_InvoiceDataId",
column: x => x.InvoiceDataId,
principalTable: "Invoices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_RefundAddresses_InvoiceDataId",
table: "RefundAddresses",
column: "InvoiceDataId");
}
}
}
| |
// 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.Composition.Convention;
using System.Composition.Debugging;
using System.Composition.Hosting.Core;
using System.Composition.TypedParts;
using System.Composition.TypedParts.Util;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace System.Composition.Hosting
{
/// <summary>
/// Configures and constructs a lightweight container.
/// </summary>
[DebuggerTypeProxy(typeof(ContainerConfigurationDebuggerProxy))]
public class ContainerConfiguration
{
private AttributedModelProvider _defaultAttributeContext;
private readonly IList<ExportDescriptorProvider> _addedSources = new List<ExportDescriptorProvider>();
private readonly IList<Tuple<IEnumerable<Type>, AttributedModelProvider>> _types = new List<Tuple<IEnumerable<Type>, AttributedModelProvider>>();
/// <summary>
/// Create the container. The value returned from this method provides
/// the exports in the container, as well as a means to dispose the container.
/// </summary>
/// <returns>The container.</returns>
public CompositionHost CreateContainer()
{
var providers = _addedSources.ToList();
foreach (var typeSet in _types)
{
var ac = typeSet.Item2 ?? _defaultAttributeContext ?? new DirectAttributeContext();
providers.Add(new TypedPartExportDescriptorProvider(typeSet.Item1, ac));
}
return CompositionHost.CreateCompositionHost(providers.ToArray());
}
/// <summary>
/// Add an export descriptor provider to the container.
/// </summary>
/// <param name="exportDescriptorProvider">An export descriptor provider.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider)
{
if (exportDescriptorProvider == null) throw new ArgumentNullException(nameof(exportDescriptorProvider));
_addedSources.Add(exportDescriptorProvider);
return this;
}
/// <summary>
/// Add conventions defined using a <see cref="AttributedModelProvider"/> to the container.
/// These will be used as the default conventions; types and assemblies added with a
/// specific convention will use their own.
/// </summary>
/// <param name="conventions"></param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions)
{
if (conventions == null) throw new ArgumentNullException(nameof(conventions));
if (_defaultAttributeContext != null)
throw new InvalidOperationException(System.Composition.Properties.Resources.ContainerConfiguration_DefaultConventionSet);
_defaultAttributeContext = conventions;
return this;
}
/// <summary>
/// Add a part type to the container. If the part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="partType">The part type.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithPart(Type partType)
{
return WithPart(partType, null);
}
/// <summary>
/// Add a part type to the container. If the part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="partType">The part type.</param>
/// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithPart(Type partType, AttributedModelProvider conventions)
{
if (partType == null) throw new ArgumentNullException(nameof(partType));
return WithParts(new[] { partType }, conventions);
}
/// <summary>
/// Add a part type to the container. If the part type does not have any exports it
/// will be ignored.
/// </summary>
/// <typeparam name="TPart">The part type.</typeparam>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithPart<TPart>()
{
return WithPart<TPart>(null);
}
/// <summary>
/// Add a part type to the container. If the part type does not have any exports it
/// will be ignored.
/// </summary>
/// <typeparam name="TPart">The part type.</typeparam>
/// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithPart<TPart>(AttributedModelProvider conventions)
{
return WithPart(typeof(TPart), conventions);
}
/// <summary>
/// Add part types to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="partTypes">The part types.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithParts(params Type[] partTypes)
{
return WithParts((IEnumerable<Type>)partTypes);
}
/// <summary>
/// Add part types to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="partTypes">The part types.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithParts(IEnumerable<Type> partTypes)
{
return WithParts(partTypes, null);
}
/// <summary>
/// Add part types to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="partTypes">The part types.</param>
/// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithParts(IEnumerable<Type> partTypes, AttributedModelProvider conventions)
{
if (partTypes == null) throw new ArgumentNullException(nameof(partTypes));
_types.Add(Tuple.Create(partTypes, conventions));
return this;
}
/// <summary>
/// Add part types from an assembly to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="assembly">The assembly from which to add part types.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithAssembly(Assembly assembly)
{
return WithAssembly(assembly, null);
}
/// <summary>
/// Add part types from an assembly to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="assembly">The assembly from which to add part types.</param>
/// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithAssembly(Assembly assembly, AttributedModelProvider conventions)
{
return WithAssemblies(new[] { assembly }, conventions);
}
/// <summary>
/// Add part types from a list of assemblies to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="assemblies">Assemblies containing part types.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies)
{
return WithAssemblies(assemblies, null);
}
/// <summary>
/// Add part types from a list of assemblies to the container. If a part type does not have any exports it
/// will be ignored.
/// </summary>
/// <param name="assemblies">Assemblies containing part types.</param>
/// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param>
/// <returns>A configuration object allowing configuration to continue.</returns>
public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies, AttributedModelProvider conventions)
{
if (assemblies == null) throw new ArgumentNullException(nameof(assemblies));
return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions);
}
internal ExportDescriptorProvider[] DebugGetAddedExportDescriptorProviders()
{
return _addedSources.ToArray();
}
internal Tuple<IEnumerable<Type>, AttributedModelProvider>[] DebugGetRegisteredTypes()
{
return _types.ToArray();
}
internal AttributedModelProvider DebugGetDefaultAttributeContext()
{
return _defaultAttributeContext;
}
}
}
| |
#pragma warning disable 1634, 1691
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#pragma warning disable 1634, 1691
#pragma warning disable 56506
using System;
using System.Management.Automation;
using Dbg = System.Management.Automation;
using System.Management.Automation.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Globalization;
using System.ComponentModel;
#if CORECLR
// Use stub for SystemException
using Microsoft.PowerShell.CoreClr.Stubs;
using System.Reflection;
#endif
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class from which all Security Descriptor commands
/// are derived.
/// </summary>
public abstract class SecurityDescriptorCommandsBase : PSCmdlet
{
/// <summary>
/// Gets or sets the filter property. The filter
/// property allows for provider-specific filtering of results.
/// </summary>
[Parameter]
public string Filter
{
get
{
return _filter;
}
set
{
_filter = value;
}
}
/// <summary>
/// Gets or sets the include property. The include property
/// specifies the items on which the command will act.
/// </summary>
[Parameter]
public string[] Include
{
get
{
return _include;
}
set
{
_include = value;
}
}
/// <summary>
/// Gets or sets the exclude property. The exclude property
/// specifies the items on which the command will not act.
/// </summary>
[Parameter]
public string[] Exclude
{
get
{
return _exclude;
}
set
{
_exclude = value;
}
}
/// <summary>
/// The context for the command that is passed to the core command providers.
/// </summary>
internal CmdletProviderContext CmdletProviderContext
{
get
{
CmdletProviderContext coreCommandContext =
new CmdletProviderContext(this);
Collection<string> includeFilter =
SessionStateUtilities.ConvertArrayToCollection<string>(Include);
Collection<string> excludeFilter =
SessionStateUtilities.ConvertArrayToCollection<string>(Exclude);
coreCommandContext.SetFilters(includeFilter,
excludeFilter,
Filter);
return coreCommandContext;
}
} // CmdletProviderContext
#region brokered properties
/// <summary>
/// Add brokered properties for easy access to important properties
/// of security descriptor
/// </summary>
static internal void AddBrokeredProperties(
Collection<PSObject> results,
bool audit,
bool allCentralAccessPolicies)
{
foreach (PSObject result in results)
{
if (audit)
{
//Audit
result.Properties.Add
(
new PSCodeProperty
(
"Audit",
typeof(SecurityDescriptorCommandsBase).GetMethod("GetAudit")
)
);
}
//CentralAccessPolicyId retrieval does not require elevation, so we always add this property.
result.Properties.Add
(
new PSCodeProperty
(
"CentralAccessPolicyId",
typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyId")
)
);
#if !CORECLR //GetAllCentralAccessPolicies and GetCentralAccessPolicyName are not supported in OneCore powershell
//because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
if (allCentralAccessPolicies)
{
//AllCentralAccessPolicies
result.Properties.Add
(
new PSCodeProperty
(
"AllCentralAccessPolicies",
typeof(SecurityDescriptorCommandsBase).GetMethod("GetAllCentralAccessPolicies")
)
);
}
//CentralAccessPolicyName retrieval does not require elevation, so we always add this property.
result.Properties.Add
(
new PSCodeProperty
(
"CentralAccessPolicyName",
typeof(SecurityDescriptorCommandsBase).GetMethod("GetCentralAccessPolicyName")
)
);
#endif
}
}
/// <summary>
/// Gets the Path of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the path.
/// </param>
/// <returns>
/// The path of the provided PSObject.
/// </returns>
public static string GetPath(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
else
{
// These are guaranteed to not be null, but even checking
// them for null causes a presharp warning
#pragma warning disable 56506
//Get path
return instance.Properties["PSPath"].Value.ToString();
#pragma warning enable 56506
}
}
/// <summary>
/// Gets the Owner of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the Owner.
/// </param>
/// <returns>
/// The Owner of the provided PSObject.
/// </returns>
public static string GetOwner(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
if (sd == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
//Get owner
try
{
IdentityReference ir = sd.GetOwner(typeof(NTAccount));
return ir.ToString();
}
catch (IdentityNotMappedException)
{
// All Acl cmdlets returning SIDs will return a string
// representation of the SID in all cases where the SID
// cannot be mapped to a proper user or group name.
}
// We are here since we cannot get IdentityReference from sd..
// So return sddl..
return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Owner);
}
/// <summary>
/// Gets the Group of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the Group.
/// </param>
/// <returns>
/// The Group of the provided PSObject.
/// </returns>
public static string GetGroup(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
if (sd == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
//Get Group
try
{
IdentityReference ir = sd.GetGroup(typeof(NTAccount));
return ir.ToString();
}
catch (IdentityNotMappedException)
{
// All Acl cmdlets returning SIDs will return a string
// representation of the SID in all cases where the SID
// cannot be mapped to a proper user or group name.
}
// We are here since we cannot get IdentityReference from sd..
// So return sddl..
return sd.GetSecurityDescriptorSddlForm(AccessControlSections.Group);
}
/// <summary>
/// Gets the access rules of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the access rules.
/// </param>
/// <returns>
/// The access rules of the provided PSObject.
/// </returns>
public static AuthorizationRuleCollection GetAccess(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
if (sd == null)
{
PSTraceSource.NewArgumentException("instance");
}
//Get DACL
AuthorizationRuleCollection dacl;
CommonObjectSecurity cos = sd as CommonObjectSecurity;
if (cos != null)
{
dacl = cos.GetAccessRules(true, true, typeof(NTAccount));
}
else
{
DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity;
Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity");
dacl = dos.GetAccessRules(true, true, typeof(NTAccount));
}
return dacl;
}
/// <summary>
/// Gets the audit rules of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the audit rules.
/// </param>
/// <returns>
/// The audit rules of the provided PSObject.
/// </returns>
public static AuthorizationRuleCollection GetAudit(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
if (sd == null)
{
PSTraceSource.NewArgumentException("instance");
}
AuthorizationRuleCollection sacl;
CommonObjectSecurity cos = sd as CommonObjectSecurity;
if (cos != null)
{
sacl = cos.GetAuditRules(true, true, typeof(NTAccount));
}
else
{
DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity;
Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity");
sacl = dos.GetAuditRules(true, true, typeof(NTAccount));
}
return sacl;
}
/// <summary>
/// Gets the central access policy ID of the provided PSObject.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the central access policy ID.
/// </param>
/// <returns>
/// The central access policy ID of the provided PSObject.
/// </returns>
public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance)
{
SessionState sessionState = new SessionState();
string path = sessionState.Path.GetUnresolvedProviderPathFromPSPath(
GetPath(instance));
IntPtr pOwner = IntPtr.Zero, pGroup = IntPtr.Zero;
IntPtr pDacl = IntPtr.Zero, pSacl = IntPtr.Zero, pSd = IntPtr.Zero;
try
{
// Get the file's SACL containing the CAPID ACE.
uint rs = NativeMethods.GetNamedSecurityInfo(
path,
NativeMethods.SeObjectType.SE_FILE_OBJECT,
NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION,
out pOwner,
out pGroup,
out pDacl,
out pSacl,
out pSd);
if (rs != NativeMethods.ERROR_SUCCESS)
{
throw new Win32Exception((int)rs);
}
if (pSacl == IntPtr.Zero)
{
return null;
}
NativeMethods.ACL sacl = new NativeMethods.ACL();
sacl = ClrFacade.PtrToStructure<NativeMethods.ACL>(pSacl);
if (sacl.AceCount == 0)
{
return null;
}
// Extract the first CAPID from the SACL that does not have INHERIT_ONLY_ACE flag set.
IntPtr pAce = pSacl + Marshal.SizeOf(new NativeMethods.ACL());
for (uint aceIdx = 0; aceIdx < sacl.AceCount; aceIdx++)
{
NativeMethods.ACE_HEADER ace = new NativeMethods.ACE_HEADER();
ace = ClrFacade.PtrToStructure<NativeMethods.ACE_HEADER>(pAce);
Dbg.Diagnostics.Assert(ace.AceType ==
NativeMethods.SYSTEM_SCOPED_POLICY_ID_ACE_TYPE,
"Unexpected ACE type: " + ace.AceType.ToString(CultureInfo.CurrentCulture));
if ((ace.AceFlags & NativeMethods.INHERIT_ONLY_ACE) == 0)
{
break;
}
pAce += ace.AceSize;
}
IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) -
Marshal.SizeOf(new uint());
bool ret = NativeMethods.IsValidSid(pSid);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return new SecurityIdentifier(pSid);
}
finally
{
NativeMethods.LocalFree(pSd);
}
}
#if !CORECLR
/// <summary>
/// Gets the central access policy name of the provided PSObject.
/// </summary>
/// <remarks>
/// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
/// </remarks>
/// <param name="instance">
/// The PSObject for which to obtain the central access policy name.
/// </param>
/// <returns>
/// The central access policy name of the provided PSObject.
/// </returns>
public static string GetCentralAccessPolicyName(PSObject instance)
{
SecurityIdentifier capId = GetCentralAccessPolicyId(instance);
if (capId == null)
{
return null; // file does not have the scope ace
}
int capIdSize = capId.BinaryLength;
byte[] capIdArray = new byte[capIdSize];
capId.GetBinaryForm(capIdArray, 0);
IntPtr caps = IntPtr.Zero;
IntPtr pCapId = Marshal.AllocHGlobal(capIdSize);
try
{
// Retrieve the CAP by CAPID.
Marshal.Copy(capIdArray, 0, pCapId, capIdSize);
IntPtr[] ppCapId = new IntPtr[1];
ppCapId[0] = pCapId;
uint capCount = 0;
uint rs = NativeMethods.LsaQueryCAPs(
ppCapId,
1,
out caps,
out capCount);
if (rs != NativeMethods.STATUS_SUCCESS)
{
throw new Win32Exception((int)rs);
}
if (capCount == 0 || caps == IntPtr.Zero)
{
return null;
}
// Get the CAP name.
NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY();
cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(caps);
// LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes.
return Marshal.PtrToStringUni(cap.Name.Buffer, cap.Name.Length / 2);
}
finally
{
Marshal.FreeHGlobal(pCapId);
uint rs = NativeMethods.LsaFreeMemory(caps);
Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS,
"LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture));
}
}
/// <summary>
/// Gets the names and IDs of all central access policies available on the machine.
/// </summary>
/// <remarks>
/// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
/// </remarks>
/// <param name="instance">
/// The PSObject argument is ignored.
/// </param>
/// <returns>
/// The names and IDs of all central access policies available on the machine.
/// </returns>
public static string[] GetAllCentralAccessPolicies(PSObject instance)
{
IntPtr caps = IntPtr.Zero;
try
{
// Retrieve all CAPs.
uint capCount = 0;
uint rs = NativeMethods.LsaQueryCAPs(
null,
0,
out caps,
out capCount);
if (rs != NativeMethods.STATUS_SUCCESS)
{
throw new Win32Exception((int)rs);
}
Dbg.Diagnostics.Assert(capCount < 0xFFFF,
"Too many central access policies");
if (capCount == 0 || caps == IntPtr.Zero)
{
return null;
}
// Add CAP names and IDs to a string array.
string[] policies = new string[capCount];
NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY();
IntPtr capPtr = caps;
for (uint capIdx = 0; capIdx < capCount; capIdx++)
{
// Retrieve CAP name.
Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero,
"Invalid central access policies array");
cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(capPtr);
// LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes.
policies[capIdx] = "\"" + Marshal.PtrToStringUni(
cap.Name.Buffer,
cap.Name.Length / 2) + "\"";
// Retrieve CAPID.
IntPtr pCapId = cap.CAPID;
Dbg.Diagnostics.Assert(pCapId != IntPtr.Zero,
"Invalid central access policies array");
bool ret = NativeMethods.IsValidSid(pCapId);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
SecurityIdentifier sid = new SecurityIdentifier(pCapId);
policies[capIdx] += " (" + sid.ToString() + ")";
capPtr += Marshal.SizeOf(cap);
}
return policies;
}
finally
{
uint rs = NativeMethods.LsaFreeMemory(caps);
Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS,
"LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture));
}
}
#endif
/// <summary>
/// Gets the security descriptor (in SDDL form) of the
/// provided PSObject. SDDL form is the Security Descriptor
/// Definition Language.
/// </summary>
/// <param name="instance">
/// The PSObject for which to obtain the security descriptor.
/// </param>
/// <returns>
/// The security descriptor of the provided PSObject, in SDDL form.
/// </returns>
public static string GetSddl(PSObject instance)
{
if (instance == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
if (sd == null)
{
throw PSTraceSource.NewArgumentNullException("instance");
}
string sddl = sd.GetSecurityDescriptorSddlForm(AccessControlSections.All);
return sddl;
}
#endregion brokered properties
/// <summary>
/// The filter to be used to when globbing to get the item.
/// </summary>
private string _filter;
/// <summary>
/// The glob string used to determine which items are included.
/// </summary>
private string[] _include = new string[0];
/// <summary>
/// The glob string used to determine which items are excluded.
/// </summary>
private string[] _exclude = new string[0];
}
/// <summary>
/// Defines the implementation of the 'get-acl' cmdlet.
/// This cmdlet gets the security descriptor of an item at the specified path.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Acl", SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113305")]
public sealed class GetAclCommand : SecurityDescriptorCommandsBase
{
/// <summary>
/// Initialzes a new instance of the GetAclCommand
/// class. Sets the default path to the current location.
/// </summary>
public GetAclCommand()
{
//Default for path is the current location
_path = new string[] { "." };
}
#region parameters
private string[] _path;
/// <summary>
/// Gets or sets the path of the item for which to obtain the
/// security descriptor. Default is the current location.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
[ValidateNotNullOrEmpty()]
public string[] Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
private PSObject _inputObject = null;
/// <summary>
/// InputObject Parameter
/// Gets or sets the inputObject for which to obtain the security descriptor
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "ByInputObject")]
public PSObject InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = value;
}
}
/// <summary>
/// Gets or sets the literal path of the item for which to obtain the
/// security descriptor. Default is the current location.
/// </summary>
[Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
[ValidateNotNullOrEmpty()]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Gets or sets the audit flag of the command. This flag
/// determines if audit rules should also be retrieved.
/// </summary>
[Parameter()]
public SwitchParameter Audit
{
get
{
return _audit;
}
set
{
_audit = value;
}
}
private SwitchParameter _audit;
#if CORECLR
/// <summary>
/// Parameter '-AllCentralAccessPolicies' is not supported in OneCore powershell,
/// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
/// </summary>
private SwitchParameter AllCentralAccessPolicies
{
get; set;
}
#else
/// <summary>
/// Gets or sets the AllCentralAccessPolicies flag of the command. This flag
/// determines whether the information about all central access policies
/// available on the machine should be displayed.
/// </summary>
[Parameter()]
public SwitchParameter AllCentralAccessPolicies
{
get
{
return allCentralAccessPolicies;
}
set
{
allCentralAccessPolicies = value;
}
}
private SwitchParameter allCentralAccessPolicies;
#endif
#endregion
/// <summary>
/// Processes records from the input pipeline.
/// For each input file, the command retrieves its
/// corresponding security descriptor.
/// </summary>
protected override void ProcessRecord()
{
Collection<PSObject> sd = null;
AccessControlSections sections =
AccessControlSections.Owner |
AccessControlSections.Group |
AccessControlSections.Access;
if (_audit)
{
sections |= AccessControlSections.Audit;
}
if (_inputObject != null)
{
PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"];
if (methodInfo != null)
{
object customDescriptor = null;
try
{
customDescriptor = PSObject.Base(methodInfo.Invoke());
if (!(customDescriptor is FileSystemSecurity))
{
customDescriptor = new CommonSecurityDescriptor(false, false, customDescriptor.ToString());
}
}
catch (Exception e)
{
// Calling user code, Catch-all OK
CommandProcessorBase.CheckForSevereException(e);
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.MethodInvokeFail,
"GetAcl_OperationNotSupported"
);
WriteError(er);
return;
}
WriteObject(customDescriptor, true);
}
else
{
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.GetMethodNotFound,
"GetAcl_OperationNotSupported"
);
WriteError(er);
}
}
else
{
foreach (string p in Path)
{
List<string> pathsToProcess = new List<string>();
string currentPath = null;
try
{
if (_isLiteralPath)
{
pathsToProcess.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
}
else
{
Collection<PathInfo> resolvedPaths =
SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext);
foreach (PathInfo pi in resolvedPaths)
{
pathsToProcess.Add(pi.Path);
}
}
foreach (string rp in pathsToProcess)
{
currentPath = rp;
CmdletProviderContext context = new CmdletProviderContext(this.Context);
context.SuppressWildcardExpansion = true;
if (!InvokeProvider.Item.Exists(rp, false, _isLiteralPath))
{
ErrorRecord er =
SecurityUtils.CreatePathNotFoundErrorRecord(
rp,
"GetAcl_PathNotFound"
);
WriteError(er);
continue;
}
InvokeProvider.SecurityDescriptor.Get(rp, sections, context);
sd = context.GetAccumulatedObjects();
if (sd != null)
{
AddBrokeredProperties(
sd,
_audit,
AllCentralAccessPolicies);
WriteObject(sd, true);
}
}
}
catch (NotSupportedException)
{
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.OperationNotSupportedOnPath,
"GetAcl_OperationNotSupported",
currentPath
);
WriteError(er);
}
catch (ItemNotFoundException)
{
ErrorRecord er =
SecurityUtils.CreatePathNotFoundErrorRecord(
p,
"GetAcl_PathNotFound_Exception"
);
WriteError(er);
continue;
}
}
}
}
} // class GetAclCommand : PSCmdlet
/// <summary>
/// Defines the implementation of the 'set-acl' cmdlet.
/// This cmdlet sets the security descriptor of an item at the specified path.
/// </summary>
[Cmdlet(VerbsCommon.Set, "Acl", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath",
HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113389")]
public sealed class SetAclCommand : SecurityDescriptorCommandsBase
{
private string[] _path;
/// <summary>
/// Gets or sets the path of the item for which to set the
/// security descriptor.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
public string[] Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
private PSObject _inputObject = null;
/// <summary>
/// InputObject Parameter
/// Gets or sets the inputObject for which to set the security descriptor
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByInputObject")]
public PSObject InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = value;
}
}
/// <summary>
/// Gets or sets the literal path of the item for which to set the
/// security descriptor.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
private object _securityDescriptor;
/// <summary>
/// Gets or sets the security descriptor object to be
/// set on the target item(s).
/// </summary>
[Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByPath")]
[Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByLiteralPath")]
[Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByInputObject")]
public object AclObject
{
get
{
return _securityDescriptor;
}
set
{
_securityDescriptor = PSObject.Base(value);
}
}
#if CORECLR
/// <summary>
/// Parameter '-CentralAccessPolicy' is not supported in OneCore powershell,
/// because function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
/// </summary>
private string CentralAccessPolicy
{
get; set;
}
#else
private string centralAccessPolicy;
/// <summary>
/// Gets or sets the central access policy to be
/// set on the target item(s).
/// </summary>
[Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
[Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
public string CentralAccessPolicy
{
get
{
return centralAccessPolicy;
}
set
{
centralAccessPolicy = value;
}
}
#endif
private SwitchParameter _clearCentralAccessPolicy;
/// <summary>
/// Clears the central access policy applied on the target item(s).
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = "ByPath")]
[Parameter(Mandatory = false, ParameterSetName = "ByLiteralPath")]
public SwitchParameter ClearCentralAccessPolicy
{
get
{
return _clearCentralAccessPolicy;
}
set
{
_clearCentralAccessPolicy = value;
}
}
private SwitchParameter _passthru;
/// <summary>
/// Gets or sets the Passthru flag for the operation.
/// If true, the security descriptor is also passed
/// down the output pipeline.
/// </summary>
[Parameter()]
public SwitchParameter Passthru
{
get
{
return _passthru;
}
set
{
_passthru = value;
}
}
/// <summary>
/// Returns a newly allocated SACL with no ACEs in it.
/// Free the returned SACL by calling Marshal.FreeHGlobal.
/// </summary>
private IntPtr GetEmptySacl()
{
IntPtr pSacl = IntPtr.Zero;
bool ret = true;
try
{
// Calculate the size of the empty SACL, align to DWORD.
uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) +
Marshal.SizeOf(new uint()) - 1) & 0xFFFFFFFC;
Dbg.Diagnostics.Assert(saclSize < 0xFFFF,
"Acl size must be less than max SD size of 0xFFFF");
// Allocate and initialize the SACL.
pSacl = Marshal.AllocHGlobal((int)saclSize);
ret = NativeMethods.InitializeAcl(
pSacl,
saclSize,
NativeMethods.ACL_REVISION);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (!ret)
{
Marshal.FreeHGlobal(pSacl);
pSacl = IntPtr.Zero;
}
}
return pSacl;
}
/// <summary>
/// Returns a newly allocated SACL with the supplied CAPID in it.
/// Free the returned SACL by calling Marshal.FreeHGlobal.
/// </summary>
/// <remarks>
/// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer.
/// So the parameter "-CentralAccessPolicy" is not supported on OneCore powershell,
/// and thus this method won't be hit in OneCore powershell.
/// </remarks>
private IntPtr GetSaclWithCapId(string capStr)
{
IntPtr pCapId = IntPtr.Zero, pSacl = IntPtr.Zero;
IntPtr caps = IntPtr.Zero;
bool ret = true, freeCapId = true;
uint rs = NativeMethods.STATUS_SUCCESS;
try
{
// Convert the supplied SID from string to binary form.
ret = NativeMethods.ConvertStringSidToSid(capStr, out pCapId);
if (!ret)
{
// We may have got a CAP friendly name instead of CAPID.
// Enumerate all CAPs on the system and try to find one with
// a matching friendly name.
// If we retrieve the CAPID from the LSA, the CAPID need not
// be deallocated separately (but with the entire buffer
// returned by LsaQueryCAPs).
freeCapId = false;
uint capCount = 0;
rs = NativeMethods.LsaQueryCAPs(
null,
0,
out caps,
out capCount);
if (rs != NativeMethods.STATUS_SUCCESS)
{
throw new Win32Exception((int)rs);
}
Dbg.Diagnostics.Assert(capCount < 0xFFFF,
"Too many central access policies");
if (capCount == 0 || caps == IntPtr.Zero)
{
return IntPtr.Zero;
}
// Find the supplied string among available CAP names, use the corresponding CAPID.
NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY();
IntPtr capPtr = caps;
for (uint capIdx = 0; capIdx < capCount; capIdx++)
{
Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero,
"Invalid central access policies array");
cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(capPtr);
// LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes.
string capName = Marshal.PtrToStringUni(
cap.Name.Buffer,
cap.Name.Length / 2);
if (capName.Equals(capStr, StringComparison.OrdinalIgnoreCase))
{
pCapId = cap.CAPID;
break;
}
capPtr += Marshal.SizeOf(cap);
}
}
if (pCapId == IntPtr.Zero)
{
Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier);
WriteError(new ErrorRecord(
e,
"SetAcl_CentralAccessPolicy",
ErrorCategory.InvalidArgument,
AclObject));
return IntPtr.Zero;
}
ret = NativeMethods.IsValidSid(pCapId);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
uint sidSize = NativeMethods.GetLengthSid(pCapId);
// Calculate the size of the SACL with one CAPID ACE, align to DWORD.
uint saclSize = (uint)(Marshal.SizeOf(new NativeMethods.ACL()) +
Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) +
sidSize - 1) & 0xFFFFFFFC;
Dbg.Diagnostics.Assert(saclSize < 0xFFFF,
"Acl size must be less than max SD size of 0xFFFF");
// Allocate and initialize the SACL.
pSacl = Marshal.AllocHGlobal((int)saclSize);
ret = NativeMethods.InitializeAcl(
pSacl,
saclSize,
NativeMethods.ACL_REVISION);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
// Add CAPID to the SACL.
rs = NativeMethods.RtlAddScopedPolicyIDAce(
pSacl,
NativeMethods.ACL_REVISION,
NativeMethods.SUB_CONTAINERS_AND_OBJECTS_INHERIT,
0,
pCapId);
if (rs != NativeMethods.STATUS_SUCCESS)
{
if (rs == NativeMethods.STATUS_INVALID_PARAMETER)
{
throw new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyIdentifier);
}
else
{
throw new Win32Exception((int)rs);
}
}
}
finally
{
if (!ret || rs != NativeMethods.STATUS_SUCCESS)
{
Marshal.FreeHGlobal(pSacl);
pSacl = IntPtr.Zero;
}
rs = NativeMethods.LsaFreeMemory(caps);
Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS,
"LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture));
if (freeCapId)
{
NativeMethods.LocalFree(pCapId);
}
}
return pSacl;
}
/// <summary>
/// Returns the current thread or process token with the specified privilege enabled
/// and the previous state of this privilege. Free the returned token
/// by calling NativeMethods.CloseHandle.
/// </summary>
private IntPtr GetTokenWithEnabledPrivilege(
string privilege,
NativeMethods.TOKEN_PRIVILEGE previousState)
{
IntPtr pToken = IntPtr.Zero;
bool ret = true;
try
{
// First try to open the thread token for privilege adjustment.
ret = NativeMethods.OpenThreadToken(
NativeMethods.GetCurrentThread(),
NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES,
true,
out pToken);
if (!ret)
{
if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NO_TOKEN)
{
// Client is not impersonating. Open the process token.
ret = NativeMethods.OpenProcessToken(
NativeMethods.GetCurrentProcess(),
NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_ADJUST_PRIVILEGES,
out pToken);
}
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
// Get the LUID of the specified privilege.
NativeMethods.LUID luid = new NativeMethods.LUID();
ret = NativeMethods.LookupPrivilegeValue(
null,
privilege,
ref luid);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
// Enable the privilege.
NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE();
newState.PrivilegeCount = 1;
newState.Privilege.Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
newState.Privilege.Luid = luid;
uint previousSize = 0;
ret = NativeMethods.AdjustTokenPrivileges(
pToken,
false,
ref newState,
(uint)Marshal.SizeOf(previousState),
ref previousState,
ref previousSize);
if (!ret)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (!ret)
{
NativeMethods.CloseHandle(pToken);
pToken = IntPtr.Zero;
}
}
return pToken;
}
/// Processes records from the input pipeline.
/// For each input file, the command sets its
/// security descriptor to the specified
/// Access Control List (ACL).
protected override void ProcessRecord()
{
ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity;
if (_inputObject != null)
{
PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"];
if (methodInfo != null)
{
CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor;
string sddl;
if (aclObjectSecurity != null)
{
sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
}
else if (aclCommonSD != null)
{
sddl = aclCommonSD.GetSddlForm(AccessControlSections.All);
}
else
{
Exception e = new ArgumentException("AclObject");
WriteError(new ErrorRecord(
e,
"SetAcl_AclObject",
ErrorCategory.InvalidArgument,
AclObject));
return;
}
try
{
methodInfo.Invoke(sddl);
}
catch (Exception e)
{
// Calling user code, Catch-all OK
CommandProcessorBase.CheckForSevereException(e);
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.MethodInvokeFail,
"SetAcl_OperationNotSupported"
);
WriteError(er);
return;
}
}
else
{
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.SetMethodNotFound,
"SetAcl_OperationNotSupported"
);
WriteError(er);
}
}
else
{
if (Path == null)
{
Exception e = new ArgumentException("Path");
WriteError(new ErrorRecord(
e,
"SetAcl_Path",
ErrorCategory.InvalidArgument,
AclObject));
return;
}
if (aclObjectSecurity == null)
{
Exception e = new ArgumentException("AclObject");
WriteError(new ErrorRecord(
e,
"SetAcl_AclObject",
ErrorCategory.InvalidArgument,
AclObject));
return;
}
if (CentralAccessPolicy != null || ClearCentralAccessPolicy)
{
if (!DownLevelHelper.IsWin8AndAbove())
{
Exception e = new ParameterBindingException();
WriteError(new ErrorRecord(
e,
"SetAcl_OperationNotSupported",
ErrorCategory.InvalidArgument,
null));
return;
}
}
if (CentralAccessPolicy != null && ClearCentralAccessPolicy)
{
Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters);
ErrorRecord er =
SecurityUtils.CreateInvalidArgumentErrorRecord(
e,
"SetAcl_OperationNotSupported"
);
WriteError(er);
return;
}
IntPtr pSacl = IntPtr.Zero;
NativeMethods.TOKEN_PRIVILEGE previousState = new NativeMethods.TOKEN_PRIVILEGE();
try
{
if (CentralAccessPolicy != null)
{
pSacl = GetSaclWithCapId(CentralAccessPolicy);
if (pSacl == IntPtr.Zero)
{
SystemException e = new SystemException(
UtilsStrings.GetSaclWithCapIdFail);
WriteError(new ErrorRecord(e,
"SetAcl_CentralAccessPolicy",
ErrorCategory.InvalidResult,
null));
return;
}
}
else if (ClearCentralAccessPolicy)
{
pSacl = GetEmptySacl();
if (pSacl == IntPtr.Zero)
{
SystemException e = new SystemException(
UtilsStrings.GetEmptySaclFail);
WriteError(new ErrorRecord(e,
"SetAcl_ClearCentralAccessPolicy",
ErrorCategory.InvalidResult,
null));
return;
}
}
foreach (string p in Path)
{
Collection<PathInfo> pathsToProcess = new Collection<PathInfo>();
CmdletProviderContext context = this.CmdletProviderContext;
context.PassThru = Passthru;
if (_isLiteralPath)
{
ProviderInfo Provider = null;
PSDriveInfo Drive = null;
string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive);
pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState));
context.SuppressWildcardExpansion = true;
}
else
{
pathsToProcess = SessionState.Path.GetResolvedPSPathFromPSPath(p, CmdletProviderContext);
}
foreach (PathInfo pathInfo in pathsToProcess)
{
if (ShouldProcess(pathInfo.Path))
{
try
{
InvokeProvider.SecurityDescriptor.Set(pathInfo.Path,
aclObjectSecurity,
context);
if (CentralAccessPolicy != null || ClearCentralAccessPolicy)
{
if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem))
{
Exception e = new ArgumentException("Path");
WriteError(new ErrorRecord(
e,
"SetAcl_Path",
ErrorCategory.InvalidArgument,
AclObject));
continue;
}
// Enable the security privilege required to set SCOPE_SECURITY_INFORMATION.
IntPtr pToken = GetTokenWithEnabledPrivilege("SeSecurityPrivilege", previousState);
if (pToken == IntPtr.Zero)
{
SystemException e = new SystemException(
UtilsStrings.GetTokenWithEnabledPrivilegeFail);
WriteError(new ErrorRecord(e,
"SetAcl_AdjustTokenPrivileges",
ErrorCategory.InvalidResult,
null));
return;
}
// Set the file's CAPID.
uint rs = NativeMethods.SetNamedSecurityInfo(
pathInfo.ProviderPath,
NativeMethods.SeObjectType.SE_FILE_OBJECT,
NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
pSacl);
// Restore privileges to the previous state.
if (pToken != IntPtr.Zero)
{
NativeMethods.TOKEN_PRIVILEGE newState = new NativeMethods.TOKEN_PRIVILEGE();
uint newSize = 0;
NativeMethods.AdjustTokenPrivileges(
pToken,
false,
ref previousState,
(uint)Marshal.SizeOf(newState),
ref newState,
ref newSize);
NativeMethods.CloseHandle(pToken);
pToken = IntPtr.Zero;
}
if (rs != NativeMethods.ERROR_SUCCESS)
{
Exception e = new Win32Exception(
(int)rs,
UtilsStrings.SetCentralAccessPolicyFail);
WriteError(new ErrorRecord(e,
"SetAcl_SetNamedSecurityInfo",
ErrorCategory.InvalidResult,
null));
}
}
}
catch (NotSupportedException)
{
ErrorRecord er =
SecurityUtils.CreateNotSupportedErrorRecord(
UtilsStrings.OperationNotSupportedOnPath,
"SetAcl_OperationNotSupported",
pathInfo.Path
);
WriteError(er);
}
}
}
}
}
finally
{
Marshal.FreeHGlobal(pSacl);
}
}
}
} // class SetAclCommand
}// namespace Microsoft.PowerShell.Commands
#pragma warning restore 56506
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Responses/PlayerUpdateResponse.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Responses {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/PlayerUpdateResponse.proto</summary>
public static partial class PlayerUpdateResponseReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Responses/PlayerUpdateResponse.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PlayerUpdateResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjpQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL1BsYXllclVwZGF0",
"ZVJlc3BvbnNlLnByb3RvEh9QT0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVzcG9u",
"c2VzGiJQT0dPUHJvdG9zL01hcC9Gb3J0L0ZvcnREYXRhLnByb3RvGihQT0dP",
"UHJvdG9zL01hcC9Qb2tlbW9uL1dpbGRQb2tlbW9uLnByb3RvIpYBChRQbGF5",
"ZXJVcGRhdGVSZXNwb25zZRI6Cg13aWxkX3Bva2Vtb25zGAEgAygLMiMuUE9H",
"T1Byb3Rvcy5NYXAuUG9rZW1vbi5XaWxkUG9rZW1vbhIsCgVmb3J0cxgCIAMo",
"CzIdLlBPR09Qcm90b3MuTWFwLkZvcnQuRm9ydERhdGESFAoMZm9ydHNfbmVh",
"cmJ5GAMgASgFYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Map.Fort.FortDataReflection.Descriptor, global::POGOProtos.Map.Pokemon.WildPokemonReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.PlayerUpdateResponse), global::POGOProtos.Networking.Responses.PlayerUpdateResponse.Parser, new[]{ "WildPokemons", "Forts", "FortsNearby" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PlayerUpdateResponse : pb::IMessage<PlayerUpdateResponse> {
private static readonly pb::MessageParser<PlayerUpdateResponse> _parser = new pb::MessageParser<PlayerUpdateResponse>(() => new PlayerUpdateResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PlayerUpdateResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Responses.PlayerUpdateResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerUpdateResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerUpdateResponse(PlayerUpdateResponse other) : this() {
wildPokemons_ = other.wildPokemons_.Clone();
forts_ = other.forts_.Clone();
fortsNearby_ = other.fortsNearby_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerUpdateResponse Clone() {
return new PlayerUpdateResponse(this);
}
/// <summary>Field number for the "wild_pokemons" field.</summary>
public const int WildPokemonsFieldNumber = 1;
private static readonly pb::FieldCodec<global::POGOProtos.Map.Pokemon.WildPokemon> _repeated_wildPokemons_codec
= pb::FieldCodec.ForMessage(10, global::POGOProtos.Map.Pokemon.WildPokemon.Parser);
private readonly pbc::RepeatedField<global::POGOProtos.Map.Pokemon.WildPokemon> wildPokemons_ = new pbc::RepeatedField<global::POGOProtos.Map.Pokemon.WildPokemon>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Map.Pokemon.WildPokemon> WildPokemons {
get { return wildPokemons_; }
}
/// <summary>Field number for the "forts" field.</summary>
public const int FortsFieldNumber = 2;
private static readonly pb::FieldCodec<global::POGOProtos.Map.Fort.FortData> _repeated_forts_codec
= pb::FieldCodec.ForMessage(18, global::POGOProtos.Map.Fort.FortData.Parser);
private readonly pbc::RepeatedField<global::POGOProtos.Map.Fort.FortData> forts_ = new pbc::RepeatedField<global::POGOProtos.Map.Fort.FortData>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Map.Fort.FortData> Forts {
get { return forts_; }
}
/// <summary>Field number for the "forts_nearby" field.</summary>
public const int FortsNearbyFieldNumber = 3;
private int fortsNearby_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int FortsNearby {
get { return fortsNearby_; }
set {
fortsNearby_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PlayerUpdateResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PlayerUpdateResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!wildPokemons_.Equals(other.wildPokemons_)) return false;
if(!forts_.Equals(other.forts_)) return false;
if (FortsNearby != other.FortsNearby) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= wildPokemons_.GetHashCode();
hash ^= forts_.GetHashCode();
if (FortsNearby != 0) hash ^= FortsNearby.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
wildPokemons_.WriteTo(output, _repeated_wildPokemons_codec);
forts_.WriteTo(output, _repeated_forts_codec);
if (FortsNearby != 0) {
output.WriteRawTag(24);
output.WriteInt32(FortsNearby);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += wildPokemons_.CalculateSize(_repeated_wildPokemons_codec);
size += forts_.CalculateSize(_repeated_forts_codec);
if (FortsNearby != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(FortsNearby);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PlayerUpdateResponse other) {
if (other == null) {
return;
}
wildPokemons_.Add(other.wildPokemons_);
forts_.Add(other.forts_);
if (other.FortsNearby != 0) {
FortsNearby = other.FortsNearby;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
wildPokemons_.AddEntriesFrom(input, _repeated_wildPokemons_codec);
break;
}
case 18: {
forts_.AddEntriesFrom(input, _repeated_forts_codec);
break;
}
case 24: {
FortsNearby = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/test.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Grpc.Testing {
public static class TestService
{
static readonly string __ServiceName = "grpc.testing.TestService";
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallRequest> __Marshaller_StreamingOutputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingOutputCallResponse> __Marshaller_StreamingOutputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingOutputCallResponse.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingInputCallRequest> __Marshaller_StreamingInputCallRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallRequest.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.StreamingInputCallResponse> __Marshaller_StreamingInputCallResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.StreamingInputCallResponse.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_EmptyCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"EmptyCall",
__Marshaller_Empty,
__Marshaller_Empty);
static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_StreamingOutputCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.ServerStreaming,
__ServiceName,
"StreamingOutputCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> __Method_StreamingInputCall = new Method<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse>(
MethodType.ClientStreaming,
__ServiceName,
"StreamingInputCall",
__Marshaller_StreamingInputCallRequest,
__Marshaller_StreamingInputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_FullDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"FullDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
static readonly Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> __Method_HalfDuplexCall = new Method<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"HalfDuplexCall",
__Marshaller_StreamingOutputCallRequest,
__Marshaller_StreamingOutputCallResponse);
// service descriptor
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[0]; }
}
// client interface
[System.Obsolete("Client side interfaced will be removed in the next release. Use client class directly.")]
public interface ITestServiceClient
{
global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options);
AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options);
global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options);
AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options);
AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options);
AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options);
AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options);
AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options);
}
// server-side interface
[System.Obsolete("Service implementations should inherit from the generated abstract base class instead.")]
public interface ITestService
{
Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, ServerCallContext context);
Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context);
Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, ServerCallContext context);
Task FullDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
Task HalfDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context);
}
// server-side abstract class
public abstract class TestServiceBase
{
public virtual Task<global::Grpc.Testing.Empty> EmptyCall(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task<global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<global::Grpc.Testing.StreamingInputCallRequest> requestStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task FullDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task HalfDuplexCall(IAsyncStreamReader<global::Grpc.Testing.StreamingOutputCallRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.StreamingOutputCallResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
// client stub
public class TestServiceClient : ClientBase<TestServiceClient>, ITestServiceClient
{
public TestServiceClient(Channel channel) : base(channel)
{
}
public TestServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected TestServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected TestServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCall(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.Empty EmptyCall(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_EmptyCall, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return EmptyCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> EmptyCallAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_EmptyCall, null, options, request);
}
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCall(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request);
}
public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingOutputCall(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncServerStreamingCall<global::Grpc.Testing.StreamingOutputCallResponse> StreamingOutputCall(global::Grpc.Testing.StreamingOutputCallRequest request, CallOptions options)
{
return CallInvoker.AsyncServerStreamingCall(__Method_StreamingOutputCall, null, options, request);
}
public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingInputCall(new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncClientStreamingCall<global::Grpc.Testing.StreamingInputCallRequest, global::Grpc.Testing.StreamingInputCallResponse> StreamingInputCall(CallOptions options)
{
return CallInvoker.AsyncClientStreamingCall(__Method_StreamingInputCall, null, options);
}
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return FullDuplexCall(new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> FullDuplexCall(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_FullDuplexCall, null, options);
}
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return HalfDuplexCall(new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncDuplexStreamingCall<global::Grpc.Testing.StreamingOutputCallRequest, global::Grpc.Testing.StreamingOutputCallResponse> HalfDuplexCall(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_HalfDuplexCall, null, options);
}
protected override TestServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new TestServiceClient(configuration);
}
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(ITestService serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall)
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall)
.AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall)
.AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall)
.AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall).Build();
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(TestServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_EmptyCall, serviceImpl.EmptyCall)
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_StreamingOutputCall, serviceImpl.StreamingOutputCall)
.AddMethod(__Method_StreamingInputCall, serviceImpl.StreamingInputCall)
.AddMethod(__Method_FullDuplexCall, serviceImpl.FullDuplexCall)
.AddMethod(__Method_HalfDuplexCall, serviceImpl.HalfDuplexCall).Build();
}
// creates a new client
public static TestServiceClient NewClient(Channel channel)
{
return new TestServiceClient(channel);
}
}
public static class UnimplementedService
{
static readonly string __ServiceName = "grpc.testing.UnimplementedService";
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_UnimplementedCall = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"UnimplementedCall",
__Marshaller_Empty,
__Marshaller_Empty);
// service descriptor
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[1]; }
}
// client interface
[System.Obsolete("Client side interfaced will be removed in the next release. Use client class directly.")]
public interface IUnimplementedServiceClient
{
global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, CallOptions options);
AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, CallOptions options);
}
// server-side interface
[System.Obsolete("Service implementations should inherit from the generated abstract base class instead.")]
public interface IUnimplementedService
{
Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, ServerCallContext context);
}
// server-side abstract class
public abstract class UnimplementedServiceBase
{
public virtual Task<global::Grpc.Testing.Empty> UnimplementedCall(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
// client stub
public class UnimplementedServiceClient : ClientBase<UnimplementedServiceClient>, IUnimplementedServiceClient
{
public UnimplementedServiceClient(Channel channel) : base(channel)
{
}
public UnimplementedServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UnimplementedServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected UnimplementedServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCall(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.Empty UnimplementedCall(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnimplementedCall, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnimplementedCallAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> UnimplementedCallAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnimplementedCall, null, options, request);
}
protected override UnimplementedServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new UnimplementedServiceClient(configuration);
}
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(IUnimplementedService serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build();
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(UnimplementedServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_UnimplementedCall, serviceImpl.UnimplementedCall).Build();
}
// creates a new client
public static UnimplementedServiceClient NewClient(Channel channel)
{
return new UnimplementedServiceClient(channel);
}
}
public static class ReconnectService
{
static readonly string __ServiceName = "grpc.testing.ReconnectService";
static readonly Marshaller<global::Grpc.Testing.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Grpc.Testing.ReconnectInfo> __Marshaller_ReconnectInfo = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ReconnectInfo.Parser.ParseFrom);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty> __Method_Start = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.Empty>(
MethodType.Unary,
__ServiceName,
"Start",
__Marshaller_Empty,
__Marshaller_Empty);
static readonly Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo> __Method_Stop = new Method<global::Grpc.Testing.Empty, global::Grpc.Testing.ReconnectInfo>(
MethodType.Unary,
__ServiceName,
"Stop",
__Marshaller_Empty,
__Marshaller_ReconnectInfo);
// service descriptor
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.TestReflection.Descriptor.Services[2]; }
}
// client interface
[System.Obsolete("Client side interfaced will be removed in the next release. Use client class directly.")]
public interface IReconnectServiceClient
{
global::Grpc.Testing.Empty Start(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::Grpc.Testing.Empty Start(global::Grpc.Testing.Empty request, CallOptions options);
AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.Empty request, CallOptions options);
global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, CallOptions options);
AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, CallOptions options);
}
// server-side interface
[System.Obsolete("Service implementations should inherit from the generated abstract base class instead.")]
public interface IReconnectService
{
Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.Empty request, ServerCallContext context);
Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, ServerCallContext context);
}
// server-side abstract class
public abstract class ReconnectServiceBase
{
public virtual Task<global::Grpc.Testing.Empty> Start(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
public virtual Task<global::Grpc.Testing.ReconnectInfo> Stop(global::Grpc.Testing.Empty request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
// client stub
public class ReconnectServiceClient : ClientBase<ReconnectServiceClient>, IReconnectServiceClient
{
public ReconnectServiceClient(Channel channel) : base(channel)
{
}
public ReconnectServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
///<summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ReconnectServiceClient() : base()
{
}
///<summary>Protected constructor to allow creation of configured clients.</summary>
protected ReconnectServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Start(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.Empty Start(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Start, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StartAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.Empty> StartAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Start, null, options, request);
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Stop(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Grpc.Testing.ReconnectInfo Stop(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Stop, null, options, request);
}
public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StopAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncUnaryCall<global::Grpc.Testing.ReconnectInfo> StopAsync(global::Grpc.Testing.Empty request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Stop, null, options, request);
}
protected override ReconnectServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ReconnectServiceClient(configuration);
}
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(IReconnectService serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_Start, serviceImpl.Start)
.AddMethod(__Method_Stop, serviceImpl.Stop).Build();
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(ReconnectServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_Start, serviceImpl.Start)
.AddMethod(__Method_Stop, serviceImpl.Stop).Build();
}
// creates a new client
public static ReconnectServiceClient NewClient(Channel channel)
{
return new ReconnectServiceClient(channel);
}
}
}
#endregion
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using Microsoft.Win32;
namespace NUnit.Core
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft .NET Compact Framework</summary>
NetCF,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version();
private static RuntimeFramework currentFramework;
private static RuntimeFramework[] availableFrameworks;
private RuntimeType runtime;
private Version frameworkVersion;
private Version clrVersion;
private string displayName;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
this.runtime = runtime;
this.frameworkVersion = version;
this.clrVersion = version;
if (frameworkVersion.Major == 3)
this.clrVersion = new Version(2, 0);
else if (runtime == RuntimeType.Mono && version.Major == 1)
this.clrVersion = new Version(1, 1);
this.displayName = GetDefaultDisplayName(runtime, version);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMono ? RuntimeType.Mono : RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono && major == 1)
minor = 0;
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.clrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.displayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
}
return currentFramework;
}
}
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
FrameworkCollection frameworks = new FrameworkCollection();
AppendDotNetFrameworks(frameworks);
AppendDefaultMonoFramework(frameworks);
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (this.Matches(framework))
return true;
return false;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime
{
get { return runtime; }
}
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion
{
get { return frameworkVersion; }
}
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion
{
get { return clrVersion; }
}
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.clrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName
{
get { return displayName; }
}
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphentated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Matches(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return runtime.ToString().ToLower();
}
else
{
string vstring = frameworkVersion.ToString();
if (runtime == RuntimeType.Any)
return "v" + vstring;
else
return runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if this framework "matches" the one supplied
/// as an argument. Two frameworks match if their runtime types
/// are the same or either one is RuntimeType.Any and all specified
/// components of the CLR version are equal. Negative (i.e. unspecified)
/// version components are ignored.
/// </summary>
/// <param name="other">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Matches(RuntimeFramework other)
{
if (this.Runtime != RuntimeType.Any
&& other.Runtime != RuntimeType.Any
&& this.Runtime != other.Runtime)
return false;
if (this.AllowAnyVersion || other.AllowAnyVersion)
return true;
return this.ClrVersion.Major == other.ClrVersion.Major
&& this.ClrVersion.Minor == other.ClrVersion.Minor
&& ( this.ClrVersion.Build < 0
|| other.ClrVersion.Build < 0
|| this.ClrVersion.Build == other.ClrVersion.Build )
&& ( this.ClrVersion.Revision < 0
|| other.ClrVersion.Revision < 0
|| this.ClrVersion.Revision == other.ClrVersion.Revision );
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
foreach (string item in Enum.GetNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version.ToString();
else
return runtime.ToString() + " " + version.ToString();
}
private static void AppendMonoFrameworks(FrameworkCollection frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(FrameworkCollection frameworks)
{
// TODO: Find multiple installed Mono versions under Linux
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Use registry to find alternate versions
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key == null) return;
foreach (string version in key.GetSubKeyNames())
{
RegistryKey subKey = key.OpenSubKey(version);
string monoPrefix = subKey.GetValue("SdkInstallRoot") as string;
AppendMonoFramework(frameworks, monoPrefix, version);
}
}
else
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(FrameworkCollection frameworks)
{
string monoPrefix = null;
string version = null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key != null)
{
version = key.GetValue("DefaultCLR") as string;
if (version != null && version != "")
{
key = key.OpenSubKey(version);
if (key != null)
monoPrefix = key.GetValue("SdkInstallRoot") as string;
}
}
}
else // Assuming we're currently running Mono - change if more runtimes are added
{
string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
}
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(FrameworkCollection frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.displayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.displayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.displayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
}
}
private static void AppendDotNetFrameworks(FrameworkCollection frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy");
if (key != null)
{
foreach (string name in key.GetSubKeyNames())
{
if (name.StartsWith("v"))
{
RegistryKey key2 = key.OpenSubKey(name);
foreach (string build in key2.GetValueNames())
frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version(name.Substring(1) + "." + build)));
}
}
}
}
}
#if NET_2_0
private class FrameworkCollection : System.Collections.Generic.List<RuntimeFramework> { }
#else
private class FrameworkCollection : ArrayList
{
public new RuntimeFramework[] ToArray()
{
return (RuntimeFramework[])ToArray(typeof(RuntimeFramework));
}
}
#endif
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.SignalR.Client
{
public partial class HubConnection
{
private static class Log
{
private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true };
private static readonly Action<ILogger, string, int, Exception?> _preparingNonBlockingInvocation =
LoggerMessage.Define<string, int>(LogLevel.Trace, new EventId(1, "PreparingNonBlockingInvocation"), "Preparing non-blocking invocation of '{Target}', with {ArgumentCount} argument(s).");
private static readonly Action<ILogger, string, string, string, int, Exception?> _preparingBlockingInvocation =
LoggerMessage.Define<string, string, string, int>(LogLevel.Trace, new EventId(2, "PreparingBlockingInvocation"), "Preparing blocking invocation '{InvocationId}' of '{Target}', with return type '{ReturnType}' and {ArgumentCount} argument(s).");
private static readonly Action<ILogger, string, Exception?> _registeringInvocation =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(3, "RegisteringInvocation"), "Registering Invocation ID '{InvocationId}' for tracking.");
private static readonly Action<ILogger, string, string, string, string, Exception?> _issuingInvocation =
LoggerMessage.Define<string, string, string, string>(LogLevel.Trace, new EventId(4, "IssuingInvocation"), "Issuing Invocation '{InvocationId}': {ReturnType} {MethodName}({Args}).", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, string, string?, Exception?> _sendingMessage =
LoggerMessage.Define<string, string?>(LogLevel.Debug, new EventId(5, "SendingMessage"), "Sending {MessageType} message '{InvocationId}'.", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, string, string?, Exception?> _messageSent =
LoggerMessage.Define<string, string?>(LogLevel.Debug, new EventId(6, "MessageSent"), "Sending {MessageType} message '{InvocationId}' completed.", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, string, Exception> _failedToSendInvocation =
LoggerMessage.Define<string>(LogLevel.Error, new EventId(7, "FailedToSendInvocation"), "Sending Invocation '{InvocationId}' failed.");
private static readonly Action<ILogger, string?, string, string, Exception?> _receivedInvocation =
LoggerMessage.Define<string?, string, string>(LogLevel.Trace, new EventId(8, "ReceivedInvocation"), "Received Invocation '{InvocationId}': {MethodName}({Args}).", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, string, Exception?> _droppedCompletionMessage =
LoggerMessage.Define<string>(LogLevel.Warning, new EventId(9, "DroppedCompletionMessage"), "Dropped unsolicited Completion message for invocation '{InvocationId}'.");
private static readonly Action<ILogger, string, Exception?> _droppedStreamMessage =
LoggerMessage.Define<string>(LogLevel.Warning, new EventId(10, "DroppedStreamMessage"), "Dropped unsolicited StreamItem message for invocation '{InvocationId}'.");
private static readonly Action<ILogger, Exception?> _shutdownConnection =
LoggerMessage.Define(LogLevel.Trace, new EventId(11, "ShutdownConnection"), "Shutting down connection.");
private static readonly Action<ILogger, Exception> _shutdownWithError =
LoggerMessage.Define(LogLevel.Error, new EventId(12, "ShutdownWithError"), "Connection is shutting down due to an error.");
private static readonly Action<ILogger, string, Exception?> _removingInvocation =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(13, "RemovingInvocation"), "Removing pending invocation {InvocationId}.");
private static readonly Action<ILogger, string, Exception?> _missingHandler =
LoggerMessage.Define<string>(LogLevel.Warning, new EventId(14, "MissingHandler"), "Failed to find handler for '{Target}' method.");
private static readonly Action<ILogger, string, Exception?> _receivedStreamItem =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(15, "ReceivedStreamItem"), "Received StreamItem for Invocation {InvocationId}.");
private static readonly Action<ILogger, string, Exception?> _cancelingStreamItem =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(16, "CancelingStreamItem"), "Canceling dispatch of StreamItem message for Invocation {InvocationId}. The invocation was canceled.");
private static readonly Action<ILogger, string, Exception?> _receivedStreamItemAfterClose =
LoggerMessage.Define<string>(LogLevel.Warning, new EventId(17, "ReceivedStreamItemAfterClose"), "Invocation {InvocationId} received stream item after channel was closed.");
private static readonly Action<ILogger, string, Exception?> _receivedInvocationCompletion =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(18, "ReceivedInvocationCompletion"), "Received Completion for Invocation {InvocationId}.");
private static readonly Action<ILogger, string, Exception?> _cancelingInvocationCompletion =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(19, "CancelingInvocationCompletion"), "Canceling dispatch of Completion message for Invocation {InvocationId}. The invocation was canceled.");
private static readonly Action<ILogger, string?, string?, int, Exception?> _releasingConnectionLock =
LoggerMessage.Define<string?, string?, int>(LogLevel.Trace, new EventId(20, "ReleasingConnectionLock"), "Releasing Connection Lock in {MethodName} ({FilePath}:{LineNumber}).");
private static readonly Action<ILogger, Exception?> _stopped =
LoggerMessage.Define(LogLevel.Debug, new EventId(21, "Stopped"), "HubConnection stopped.");
private static readonly Action<ILogger, string, Exception?> _invocationAlreadyInUse =
LoggerMessage.Define<string>(LogLevel.Critical, new EventId(22, "InvocationAlreadyInUse"), "Invocation ID '{InvocationId}' is already in use.");
private static readonly Action<ILogger, string, Exception?> _receivedUnexpectedResponse =
LoggerMessage.Define<string>(LogLevel.Error, new EventId(23, "ReceivedUnexpectedResponse"), "Unsolicited response received for invocation '{InvocationId}'.");
private static readonly Action<ILogger, string, int, Exception?> _hubProtocol =
LoggerMessage.Define<string, int>(LogLevel.Information, new EventId(24, "HubProtocol"), "Using HubProtocol '{Protocol} v{Version}'.");
private static readonly Action<ILogger, string, string, string, int, Exception?> _preparingStreamingInvocation =
LoggerMessage.Define<string, string, string, int>(LogLevel.Trace, new EventId(25, "PreparingStreamingInvocation"), "Preparing streaming invocation '{InvocationId}' of '{Target}', with return type '{ReturnType}' and {ArgumentCount} argument(s).");
private static readonly Action<ILogger, Exception?> _resettingKeepAliveTimer =
LoggerMessage.Define(LogLevel.Trace, new EventId(26, "ResettingKeepAliveTimer"), "Resetting keep-alive timer, received a message from the server.");
private static readonly Action<ILogger, Exception> _errorDuringClosedEvent =
LoggerMessage.Define(LogLevel.Error, new EventId(27, "ErrorDuringClosedEvent"), "An exception was thrown in the handler for the Closed event.");
private static readonly Action<ILogger, Exception?> _sendingHubHandshake =
LoggerMessage.Define(LogLevel.Debug, new EventId(28, "SendingHubHandshake"), "Sending Hub Handshake.");
private static readonly Action<ILogger, Exception?> _receivedPing =
LoggerMessage.Define(LogLevel.Trace, new EventId(31, "ReceivedPing"), "Received a ping message.");
private static readonly Action<ILogger, string, Exception> _errorInvokingClientSideMethod =
LoggerMessage.Define<string>(LogLevel.Error, new EventId(34, "ErrorInvokingClientSideMethod"), "Invoking client side method '{MethodName}' failed.");
private static readonly Action<ILogger, Exception> _errorProcessingHandshakeResponse =
LoggerMessage.Define(LogLevel.Error, new EventId(35, "ErrorReceivingHandshakeResponse"), "The underlying connection closed while processing the handshake response. See exception for details.");
private static readonly Action<ILogger, string, Exception?> _handshakeServerError =
LoggerMessage.Define<string>(LogLevel.Error, new EventId(36, "HandshakeServerError"), "Server returned handshake error: {Error}");
private static readonly Action<ILogger, Exception?> _receivedClose =
LoggerMessage.Define(LogLevel.Debug, new EventId(37, "ReceivedClose"), "Received close message.");
private static readonly Action<ILogger, string, Exception?> _receivedCloseWithError =
LoggerMessage.Define<string>(LogLevel.Error, new EventId(38, "ReceivedCloseWithError"), "Received close message with an error: {Error}");
private static readonly Action<ILogger, Exception?> _handshakeComplete =
LoggerMessage.Define(LogLevel.Debug, new EventId(39, "HandshakeComplete"), "Handshake with server complete.");
private static readonly Action<ILogger, string, Exception?> _registeringHandler =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(40, "RegisteringHandler"), "Registering handler for client method '{MethodName}'.");
private static readonly Action<ILogger, Exception?> _starting =
LoggerMessage.Define(LogLevel.Debug, new EventId(41, "Starting"), "Starting HubConnection.");
private static readonly Action<ILogger, string?, string?, int, Exception?> _waitingOnConnectionLock =
LoggerMessage.Define<string?, string?, int>(LogLevel.Trace, new EventId(42, "WaitingOnConnectionLock"), "Waiting on Connection Lock in {MethodName} ({FilePath}:{LineNumber}).");
private static readonly Action<ILogger, Exception> _errorStartingConnection =
LoggerMessage.Define(LogLevel.Error, new EventId(43, "ErrorStartingConnection"), "Error starting connection.");
private static readonly Action<ILogger, Exception?> _started =
LoggerMessage.Define(LogLevel.Information, new EventId(44, "Started"), "HubConnection started.");
private static readonly Action<ILogger, string, Exception?> _sendingCancellation =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(45, "SendingCancellation"), "Sending Cancellation for Invocation '{InvocationId}'.");
private static readonly Action<ILogger, Exception?> _cancelingOutstandingInvocations =
LoggerMessage.Define(LogLevel.Debug, new EventId(46, "CancelingOutstandingInvocations"), "Canceling all outstanding invocations.");
private static readonly Action<ILogger, Exception?> _receiveLoopStarting =
LoggerMessage.Define(LogLevel.Debug, new EventId(47, "ReceiveLoopStarting"), "Receive loop starting.");
private static readonly Action<ILogger, double, Exception?> _startingServerTimeoutTimer =
LoggerMessage.Define<double>(LogLevel.Debug, new EventId(48, "StartingServerTimeoutTimer"), "Starting server timeout timer. Duration: {ServerTimeout:0.00}ms", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, Exception?> _notUsingServerTimeout =
LoggerMessage.Define(LogLevel.Debug, new EventId(49, "NotUsingServerTimeout"), "Not using server timeout because the transport inherently tracks server availability.");
private static readonly Action<ILogger, Exception> _serverDisconnectedWithError =
LoggerMessage.Define(LogLevel.Error, new EventId(50, "ServerDisconnectedWithError"), "The server connection was terminated with an error.");
private static readonly Action<ILogger, Exception?> _invokingClosedEventHandler =
LoggerMessage.Define(LogLevel.Debug, new EventId(51, "InvokingClosedEventHandler"), "Invoking the Closed event handler.");
private static readonly Action<ILogger, Exception?> _stopping =
LoggerMessage.Define(LogLevel.Debug, new EventId(52, "Stopping"), "Stopping HubConnection.");
private static readonly Action<ILogger, Exception?> _terminatingReceiveLoop =
LoggerMessage.Define(LogLevel.Debug, new EventId(53, "TerminatingReceiveLoop"), "Terminating receive loop.");
private static readonly Action<ILogger, Exception?> _waitingForReceiveLoopToTerminate =
LoggerMessage.Define(LogLevel.Debug, new EventId(54, "WaitingForReceiveLoopToTerminate"), "Waiting for the receive loop to terminate.");
private static readonly Action<ILogger, string, Exception?> _unableToSendCancellation =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(55, "UnableToSendCancellation"), "Unable to send cancellation for invocation '{InvocationId}'. The connection is inactive.");
private static readonly Action<ILogger, long, Exception?> _processingMessage =
LoggerMessage.Define<long>(LogLevel.Debug, new EventId(56, "ProcessingMessage"), "Processing {MessageLength} byte message from server.");
private static readonly Action<ILogger, string?, string, Exception> _argumentBindingFailure =
LoggerMessage.Define<string?, string>(LogLevel.Error, new EventId(57, "ArgumentBindingFailure"), "Failed to bind arguments received in invocation '{InvocationId}' of '{MethodName}'.");
private static readonly Action<ILogger, string, Exception?> _removingHandlers =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(58, "RemovingHandlers"), "Removing handlers for client method '{MethodName}'.");
private static readonly Action<ILogger, string, Exception?> _sendingMessageGeneric =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(59, "SendingMessageGeneric"), "Sending {MessageType} message.", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, string, Exception?> _messageSentGeneric =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(60, "MessageSentGeneric"), "Sending {MessageType} message completed.", SkipEnabledCheckLogOptions);
private static readonly Action<ILogger, Exception?> _acquiredConnectionLockForPing =
LoggerMessage.Define(LogLevel.Trace, new EventId(61, "AcquiredConnectionLockForPing"), "Acquired the Connection Lock in order to ping the server.");
private static readonly Action<ILogger, Exception?> _unableToAcquireConnectionLockForPing =
LoggerMessage.Define(LogLevel.Trace, new EventId(62, "UnableToAcquireConnectionLockForPing"), "Skipping ping because a send is already in progress.");
private static readonly Action<ILogger, string, Exception?> _startingStream =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(63, "StartingStream"), "Initiating stream '{StreamId}'.");
private static readonly Action<ILogger, string, Exception?> _sendingStreamItem =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(64, "StreamItemSent"), "Sending item for stream '{StreamId}'.");
private static readonly Action<ILogger, string, Exception?> _cancelingStream =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(65, "CancelingStream"), "Stream '{StreamId}' has been canceled by client.");
private static readonly Action<ILogger, string, Exception?> _completingStream =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(66, "CompletingStream"), "Sending completion message for stream '{StreamId}'.");
private static readonly Action<ILogger, HubConnectionState, HubConnectionState, HubConnectionState, Exception?> _stateTransitionFailed =
LoggerMessage.Define<HubConnectionState, HubConnectionState, HubConnectionState>(LogLevel.Error, new EventId(67, "StateTransitionFailed"), "The HubConnection failed to transition from the {ExpectedState} state to the {NewState} state because it was actually in the {ActualState} state.");
private static readonly Action<ILogger, Exception?> _reconnecting =
LoggerMessage.Define(LogLevel.Information, new EventId(68, "Reconnecting"), "HubConnection reconnecting.");
private static readonly Action<ILogger, Exception> _reconnectingWithError =
LoggerMessage.Define(LogLevel.Error, new EventId(69, "ReconnectingWithError"), "HubConnection reconnecting due to an error.");
private static readonly Action<ILogger, long, TimeSpan, Exception?> _reconnected =
LoggerMessage.Define<long, TimeSpan>(LogLevel.Information, new EventId(70, "Reconnected"), "HubConnection reconnected successfully after {ReconnectAttempts} attempts and {ElapsedTime} elapsed.");
private static readonly Action<ILogger, long, TimeSpan, Exception?> _reconnectAttemptsExhausted =
LoggerMessage.Define<long, TimeSpan>(LogLevel.Information, new EventId(71, "ReconnectAttemptsExhausted"), "Reconnect retries have been exhausted after {ReconnectAttempts} failed attempts and {ElapsedTime} elapsed. Disconnecting.");
private static readonly Action<ILogger, long, TimeSpan, Exception?> _awaitingReconnectRetryDelay =
LoggerMessage.Define<long, TimeSpan>(LogLevel.Trace, new EventId(72, "AwaitingReconnectRetryDelay"), "Reconnect attempt number {ReconnectAttempts} will start in {RetryDelay}.");
private static readonly Action<ILogger, Exception> _reconnectAttemptFailed =
LoggerMessage.Define(LogLevel.Trace, new EventId(73, "ReconnectAttemptFailed"), "Reconnect attempt failed.");
private static readonly Action<ILogger, Exception> _errorDuringReconnectingEvent =
LoggerMessage.Define(LogLevel.Error, new EventId(74, "ErrorDuringReconnectingEvent"), "An exception was thrown in the handler for the Reconnecting event.");
private static readonly Action<ILogger, Exception> _errorDuringReconnectedEvent =
LoggerMessage.Define(LogLevel.Error, new EventId(75, "ErrorDuringReconnectedEvent"), "An exception was thrown in the handler for the Reconnected event.");
private static readonly Action<ILogger, Exception> _errorDuringNextRetryDelay =
LoggerMessage.Define(LogLevel.Error, new EventId(76, "ErrorDuringNextRetryDelay"), $"An exception was thrown from {nameof(IRetryPolicy)}.{nameof(IRetryPolicy.NextRetryDelay)}().");
private static readonly Action<ILogger, Exception?> _firstReconnectRetryDelayNull =
LoggerMessage.Define(LogLevel.Warning, new EventId(77, "FirstReconnectRetryDelayNull"), "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
private static readonly Action<ILogger, Exception?> _reconnectingStoppedDuringRetryDelay =
LoggerMessage.Define(LogLevel.Trace, new EventId(78, "ReconnectingStoppedDueToStateChangeDuringRetryDelay"), "Connection stopped during reconnect delay. Done reconnecting.");
private static readonly Action<ILogger, Exception?> _reconnectingStoppedDuringReconnectAttempt =
LoggerMessage.Define(LogLevel.Trace, new EventId(79, "ReconnectingStoppedDueToStateChangeDuringReconnectAttempt"), "Connection stopped during reconnect attempt. Done reconnecting.");
private static readonly Action<ILogger, HubConnectionState, HubConnectionState, Exception?> _attemptingStateTransition =
LoggerMessage.Define<HubConnectionState, HubConnectionState>(LogLevel.Trace, new EventId(80, "AttemptingStateTransition"), "The HubConnection is attempting to transition from the {ExpectedState} state to the {NewState} state.");
private static readonly Action<ILogger, Exception> _errorInvalidHandshakeResponse =
LoggerMessage.Define(LogLevel.Error, new EventId(81, "ErrorInvalidHandshakeResponse"), "Received an invalid handshake response.");
private static readonly Action<ILogger, double, Exception> _errorHandshakeTimedOut =
LoggerMessage.Define<double>(LogLevel.Error, new EventId(82, "ErrorHandshakeTimedOut"), "The handshake timed out after {HandshakeTimeoutSeconds} seconds.");
private static readonly Action<ILogger, Exception> _errorHandshakeCanceled =
LoggerMessage.Define(LogLevel.Error, new EventId(83, "ErrorHandshakeCanceled"), "The handshake was canceled by the client.");
private static readonly Action<ILogger, string, Exception?> _erroredStream =
LoggerMessage.Define<string>(LogLevel.Trace, new EventId(84, "ErroredStream"), "Client threw an error for stream '{StreamId}'.");
public static void PreparingNonBlockingInvocation(ILogger logger, string target, int count)
{
_preparingNonBlockingInvocation(logger, target, count, null);
}
public static void PreparingBlockingInvocation(ILogger logger, string invocationId, string target, string returnType, int count)
{
_preparingBlockingInvocation(logger, invocationId, target, returnType, count, null);
}
public static void PreparingStreamingInvocation(ILogger logger, string invocationId, string target, string returnType, int count)
{
_preparingStreamingInvocation(logger, invocationId, target, returnType, count, null);
}
public static void RegisteringInvocation(ILogger logger, string invocationId)
{
_registeringInvocation(logger, invocationId, null);
}
public static void IssuingInvocation(ILogger logger, string invocationId, string returnType, string methodName, object?[] args)
{
if (logger.IsEnabled(LogLevel.Trace))
{
var argsList = args == null ? string.Empty : string.Join(", ", args.Select(a => a?.GetType().FullName ?? "(null)"));
_issuingInvocation(logger, invocationId, returnType, methodName, argsList, null);
}
}
public static void SendingMessage(ILogger logger, HubMessage message)
{
if (logger.IsEnabled(LogLevel.Debug))
{
if (message is HubInvocationMessage invocationMessage)
{
_sendingMessage(logger, message.GetType().Name, invocationMessage.InvocationId, null);
}
else
{
_sendingMessageGeneric(logger, message.GetType().Name, null);
}
}
}
public static void MessageSent(ILogger logger, HubMessage message)
{
if (logger.IsEnabled(LogLevel.Debug))
{
if (message is HubInvocationMessage invocationMessage)
{
_messageSent(logger, message.GetType().Name, invocationMessage.InvocationId, null);
}
else
{
_messageSentGeneric(logger, message.GetType().Name, null);
}
}
}
public static void FailedToSendInvocation(ILogger logger, string invocationId, Exception exception)
{
_failedToSendInvocation(logger, invocationId, exception);
}
public static void ReceivedInvocation(ILogger logger, string? invocationId, string methodName, object?[] args)
{
if (logger.IsEnabled(LogLevel.Trace))
{
var argsList = args == null ? string.Empty : string.Join(", ", args.Select(a => a?.GetType().FullName ?? "(null)"));
_receivedInvocation(logger, invocationId, methodName, argsList, null);
}
}
public static void DroppedCompletionMessage(ILogger logger, string invocationId)
{
_droppedCompletionMessage(logger, invocationId, null);
}
public static void DroppedStreamMessage(ILogger logger, string invocationId)
{
_droppedStreamMessage(logger, invocationId, null);
}
public static void ShutdownConnection(ILogger logger)
{
_shutdownConnection(logger, null);
}
public static void ShutdownWithError(ILogger logger, Exception exception)
{
_shutdownWithError(logger, exception);
}
public static void RemovingInvocation(ILogger logger, string invocationId)
{
_removingInvocation(logger, invocationId, null);
}
public static void MissingHandler(ILogger logger, string target)
{
_missingHandler(logger, target, null);
}
public static void ReceivedStreamItem(ILogger logger, string invocationId)
{
_receivedStreamItem(logger, invocationId, null);
}
public static void CancelingStreamItem(ILogger logger, string invocationId)
{
_cancelingStreamItem(logger, invocationId, null);
}
public static void ReceivedStreamItemAfterClose(ILogger logger, string invocationId)
{
_receivedStreamItemAfterClose(logger, invocationId, null);
}
public static void ReceivedInvocationCompletion(ILogger logger, string invocationId)
{
_receivedInvocationCompletion(logger, invocationId, null);
}
public static void CancelingInvocationCompletion(ILogger logger, string invocationId)
{
_cancelingInvocationCompletion(logger, invocationId, null);
}
public static void Stopped(ILogger logger)
{
_stopped(logger, null);
}
public static void InvocationAlreadyInUse(ILogger logger, string invocationId)
{
_invocationAlreadyInUse(logger, invocationId, null);
}
public static void ReceivedUnexpectedResponse(ILogger logger, string invocationId)
{
_receivedUnexpectedResponse(logger, invocationId, null);
}
public static void HubProtocol(ILogger logger, string hubProtocol, int version)
{
_hubProtocol(logger, hubProtocol, version, null);
}
public static void ResettingKeepAliveTimer(ILogger logger)
{
_resettingKeepAliveTimer(logger, null);
}
public static void ErrorDuringClosedEvent(ILogger logger, Exception exception)
{
_errorDuringClosedEvent(logger, exception);
}
public static void SendingHubHandshake(ILogger logger)
{
_sendingHubHandshake(logger, null);
}
public static void ReceivedPing(ILogger logger)
{
_receivedPing(logger, null);
}
public static void ErrorInvokingClientSideMethod(ILogger logger, string methodName, Exception exception)
{
_errorInvokingClientSideMethod(logger, methodName, exception);
}
public static void ErrorReceivingHandshakeResponse(ILogger logger, Exception exception)
{
_errorProcessingHandshakeResponse(logger, exception);
}
public static void HandshakeServerError(ILogger logger, string error)
{
_handshakeServerError(logger, error, null);
}
public static void ReceivedClose(ILogger logger)
{
_receivedClose(logger, null);
}
public static void ReceivedCloseWithError(ILogger logger, string error)
{
_receivedCloseWithError(logger, error, null);
}
public static void HandshakeComplete(ILogger logger)
{
_handshakeComplete(logger, null);
}
public static void RegisteringHandler(ILogger logger, string methodName)
{
_registeringHandler(logger, methodName, null);
}
public static void RemovingHandlers(ILogger logger, string methodName)
{
_removingHandlers(logger, methodName, null);
}
public static void Starting(ILogger logger)
{
_starting(logger, null);
}
public static void ErrorStartingConnection(ILogger logger, Exception ex)
{
_errorStartingConnection(logger, ex);
}
public static void Started(ILogger logger)
{
_started(logger, null);
}
public static void SendingCancellation(ILogger logger, string invocationId)
{
_sendingCancellation(logger, invocationId, null);
}
public static void CancelingOutstandingInvocations(ILogger logger)
{
_cancelingOutstandingInvocations(logger, null);
}
public static void ReceiveLoopStarting(ILogger logger)
{
_receiveLoopStarting(logger, null);
}
public static void StartingServerTimeoutTimer(ILogger logger, TimeSpan serverTimeout)
{
if (logger.IsEnabled(LogLevel.Debug))
{
_startingServerTimeoutTimer(logger, serverTimeout.TotalMilliseconds, null);
}
}
public static void NotUsingServerTimeout(ILogger logger)
{
_notUsingServerTimeout(logger, null);
}
public static void ServerDisconnectedWithError(ILogger logger, Exception ex)
{
_serverDisconnectedWithError(logger, ex);
}
public static void InvokingClosedEventHandler(ILogger logger)
{
_invokingClosedEventHandler(logger, null);
}
public static void Stopping(ILogger logger)
{
_stopping(logger, null);
}
public static void TerminatingReceiveLoop(ILogger logger)
{
_terminatingReceiveLoop(logger, null);
}
public static void WaitingForReceiveLoopToTerminate(ILogger logger)
{
_waitingForReceiveLoopToTerminate(logger, null);
}
public static void ProcessingMessage(ILogger logger, long length)
{
_processingMessage(logger, length, null);
}
public static void WaitingOnConnectionLock(ILogger logger, string? memberName, string? filePath, int lineNumber)
{
_waitingOnConnectionLock(logger, memberName, filePath, lineNumber, null);
}
public static void ReleasingConnectionLock(ILogger logger, string? memberName, string? filePath, int lineNumber)
{
_releasingConnectionLock(logger, memberName, filePath, lineNumber, null);
}
public static void UnableToSendCancellation(ILogger logger, string invocationId)
{
_unableToSendCancellation(logger, invocationId, null);
}
public static void ArgumentBindingFailure(ILogger logger, string? invocationId, string target, Exception exception)
{
_argumentBindingFailure(logger, invocationId, target, exception);
}
public static void AcquiredConnectionLockForPing(ILogger logger)
{
_acquiredConnectionLockForPing(logger, null);
}
public static void UnableToAcquireConnectionLockForPing(ILogger logger)
{
_unableToAcquireConnectionLockForPing(logger, null);
}
public static void StartingStream(ILogger logger, string streamId)
{
_startingStream(logger, streamId, null);
}
public static void SendingStreamItem(ILogger logger, string streamId)
{
_sendingStreamItem(logger, streamId, null);
}
public static void CancelingStream(ILogger logger, string streamId)
{
_cancelingStream(logger, streamId, null);
}
public static void CompletingStream(ILogger logger, string streamId)
{
_completingStream(logger, streamId, null);
}
public static void StateTransitionFailed(ILogger logger, HubConnectionState expectedState, HubConnectionState newState, HubConnectionState actualState)
{
_stateTransitionFailed(logger, expectedState, newState, actualState, null);
}
public static void Reconnecting(ILogger logger)
{
_reconnecting(logger, null);
}
public static void ReconnectingWithError(ILogger logger, Exception exception)
{
_reconnectingWithError(logger, exception);
}
public static void Reconnected(ILogger logger, long reconnectAttempts, TimeSpan elapsedTime)
{
_reconnected(logger, reconnectAttempts, elapsedTime, null);
}
public static void ReconnectAttemptsExhausted(ILogger logger, long reconnectAttempts, TimeSpan elapsedTime)
{
_reconnectAttemptsExhausted(logger, reconnectAttempts, elapsedTime, null);
}
public static void AwaitingReconnectRetryDelay(ILogger logger, long reconnectAttempts, TimeSpan retryDelay)
{
_awaitingReconnectRetryDelay(logger, reconnectAttempts, retryDelay, null);
}
public static void ReconnectAttemptFailed(ILogger logger, Exception exception)
{
_reconnectAttemptFailed(logger, exception);
}
public static void ErrorDuringReconnectingEvent(ILogger logger, Exception exception)
{
_errorDuringReconnectingEvent(logger, exception);
}
public static void ErrorDuringReconnectedEvent(ILogger logger, Exception exception)
{
_errorDuringReconnectedEvent(logger, exception);
}
public static void ErrorDuringNextRetryDelay(ILogger logger, Exception exception)
{
_errorDuringNextRetryDelay(logger, exception);
}
public static void FirstReconnectRetryDelayNull(ILogger logger)
{
_firstReconnectRetryDelayNull(logger, null);
}
public static void ReconnectingStoppedDuringRetryDelay(ILogger logger)
{
_reconnectingStoppedDuringRetryDelay(logger, null);
}
public static void ReconnectingStoppedDuringReconnectAttempt(ILogger logger)
{
_reconnectingStoppedDuringReconnectAttempt(logger, null);
}
public static void AttemptingStateTransition(ILogger logger, HubConnectionState expectedState, HubConnectionState newState)
{
_attemptingStateTransition(logger, expectedState, newState, null);
}
public static void ErrorInvalidHandshakeResponse(ILogger logger, Exception exception)
{
_errorInvalidHandshakeResponse(logger, exception);
}
public static void ErrorHandshakeTimedOut(ILogger logger, TimeSpan handshakeTimeout, Exception exception)
{
_errorHandshakeTimedOut(logger, handshakeTimeout.TotalSeconds, exception);
}
public static void ErrorHandshakeCanceled(ILogger logger, Exception exception)
{
_errorHandshakeCanceled(logger, exception);
}
public static void ErroredStream(ILogger logger, string streamId, Exception exception)
{
_erroredStream(logger, streamId, exception);
}
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using log4net;
using MindTouch.Collections;
using MindTouch.Dream.Services;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Dream.AmazonS3 {
/// <summary>
/// Amazon S3 Client abstraction for use by <see cref="S3StorageService"/>
/// </summary>
/// <remarks>This class is deprecated and has been replaced with MindTouch.Aws.AwsS3Client. It will be removed in a future version.</remarks>
[Obsolete("This class has been replaced with MindTouch.Aws.AwsS3Client and will be removed in a future version")]
public class AmazonS3Client : IAmazonS3Client {
//--- Constants ---
private const string EXPIRE = "X-Amz-Meta-Expire";
private const string TTL = "X-Amz-Meta-TTL";
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly AmazonS3ClientConfig _config;
private readonly Plug _bucketPlug;
private readonly Plug _rootPlug;
private readonly ExpiringHashSet<string> _expirationEntries;
private readonly string[] _keyRootParts;
//--- Constructors ---
/// <summary>
/// Create new client instance
/// </summary>
/// <param name="config">Client configuration.</param>
/// <param name="timerFactory">Timer factory.</param>
public AmazonS3Client(AmazonS3ClientConfig config, TaskTimerFactory timerFactory) {
_config = config;
_bucketPlug = Plug.New(_config.S3BaseUri)
.WithS3Authentication(_config.PrivateKey, _config.PublicKey)
.WithTimeout(_config.Timeout)
.At(_config.Bucket);
_rootPlug = _bucketPlug;
if(!string.IsNullOrEmpty(_config.RootPath)) {
_keyRootParts = _config.RootPath.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
if(_keyRootParts != null && _keyRootParts.Any()) {
_rootPlug = _rootPlug.At(_keyRootParts);
}
}
_expirationEntries = new ExpiringHashSet<string>(timerFactory);
_expirationEntries.EntryExpired += OnDelete;
}
//--- Methods ---
/// <summary>
/// Retrieve file or directory information at given path.
/// </summary>
/// <param name="path">Path to retrieve.</param>
/// <param name="head">Perform a HEAD request only.</param>
/// <returns></returns>
public AmazonS3DataInfo GetDataInfo(string path, bool head) {
return IsDirectoryPath(path)
? GetDirectory(path, head)
: GetFile(path, head);
}
/// <summary>
/// Store a file at a path.
/// </summary>
/// <param name="path">Storage path.</param>
/// <param name="fileHandle">File to store.</param>
public void PutFile(string path, AmazonS3FileHandle fileHandle) {
if(IsDirectoryPath(path)) {
throw new InvalidOperationException(string.Format("cannot put a file at a path with a trailing {0}", _config.Delimiter));
}
var p = _rootPlug.AtPath(path);
if(fileHandle.TimeToLive.HasValue) {
var expiration = fileHandle.Expiration ?? DateTime.UtcNow.Add(fileHandle.TimeToLive.Value);
p = p.WithHeader(EXPIRE, expiration.ToEpoch().ToInvariantString())
.WithHeader(TTL, fileHandle.TimeToLive.Value.TotalSeconds.ToInvariantString());
_expirationEntries.SetOrUpdate(path, expiration, fileHandle.TimeToLive.Value);
}
var request = DreamMessage.Ok(fileHandle.MimeType, fileHandle.Size, fileHandle.Stream);
var response = p.Put(request, new Result<DreamMessage>()).Wait();
if(response.IsSuccessful) {
return;
}
throw new DreamResponseException(response);
}
/// <summary>
/// Delete a file or directory.
/// </summary>
/// <param name="path">Path to delete.</param>
public void Delete(string path) {
if(IsDirectoryPath(path)) {
DeleteDirectory(path);
} else {
DeleteFile(path);
}
}
/// <summary>
/// See <see cref="IDisposable.Dispose"/>.
/// </summary>
public void Dispose() {
_expirationEntries.EntryExpired -= OnDelete;
_expirationEntries.Dispose();
}
private AmazonS3DataInfo GetFile(string path, bool head) {
var response = _rootPlug.AtPath(path).InvokeEx(head ? "HEAD" : "GET", DreamMessage.Ok(), new Result<DreamMessage>()).Wait();
if(response.Status == DreamStatus.NotFound) {
response.Close();
return null;
}
if(!response.IsSuccessful) {
response.Memorize(new Result()).Wait();
throw new DreamResponseException(response);
}
// got a file
var expireEpoch = response.Headers[EXPIRE];
var expiration = string.IsNullOrEmpty(expireEpoch) ? (DateTime?)null : DateTimeUtil.FromEpoch(SysUtil.ChangeType<uint>(expireEpoch));
var ttlString = response.Headers[TTL];
var ttl = string.IsNullOrEmpty(ttlString) ? (TimeSpan?)null : TimeSpan.FromSeconds(SysUtil.ChangeType<double>(ttlString));
if(expiration.HasValue && ttl.HasValue) {
if(DateTime.UtcNow > expiration) {
// lazy expiration
_log.DebugFormat("lazy expiration of {0}", path);
_expirationEntries.Delete(path);
response.Close();
return null;
}
_expirationEntries.SetOrUpdate(path, expiration.Value, ttl.Value);
}
var filehandle = new AmazonS3FileHandle {
Expiration = expiration,
TimeToLive = ttl,
Size = response.ContentLength,
MimeType = response.ContentType,
Modified = response.Headers.LastModified ?? DateTime.UtcNow,
Stream = head ? null : response.ToStream(),
};
if(head) {
response.Close();
}
return new AmazonS3DataInfo(filehandle);
}
private AmazonS3DataInfo GetDirectory(string path, bool head) {
string marker = null;
var hasItems = false;
var doc = new XDoc("files");
while(true) {
var p = _bucketPlug.With("delimiter", _config.Delimiter).With("prefix", GetRootedPath(path));
if(!string.IsNullOrEmpty(marker)) {
p = p.With("marker", marker);
}
var dirResponse = p.Get(new Result<DreamMessage>()).Wait();
var dirDoc = dirResponse.ToDocument().UsePrefix("aws", "http://s3.amazonaws.com/doc/2006-03-01/");
if(!dirResponse.IsSuccessful) {
throw new Exception(string.Format("{0}: {1}", dirDoc["Code"].AsText, dirDoc["Message"].AsText));
}
// list directories
foreach(var dir in dirDoc["aws:CommonPrefixes/aws:Prefix"]) {
string last = GetName(dir.AsText);
if(string.IsNullOrEmpty(last)) {
continue;
}
doc.Start("folder")
.Elem("name", last)
.End();
hasItems = true;
}
// list files
foreach(var file in dirDoc["aws:Contents"]) {
var filename = GetName(file["aws:Key"].AsText);
var size = file["aws:Size"].AsText;
var modified = file["aws:LastModified"].AsDate ?? DateTime.MaxValue;
// Note (arnec): The S3 version of the Storage Service does not track creation time and never reports on expirations
// in listings
doc.Start("file")
.Elem("name", filename)
.Elem("size", size)
.Elem("date.created", modified)
.Elem("date.modified", modified)
.End();
hasItems = true;
}
marker = dirDoc["aws:NextMarker"].AsText;
if(!string.IsNullOrEmpty(marker) && !head) {
// there are more items in this directory
continue;
}
if(!hasItems) {
// no items, i.e. no file or directory at path
return null;
}
return new AmazonS3DataInfo(head ? new XDoc("files") : doc);
}
}
private void OnDelete(object sender, ExpirationEventArgs<string> e) {
var filepathEntry = e.Entry;
if(filepathEntry.When > DateTime.UtcNow) {
_log.DebugFormat("Ignoring premature expiration event for '{0}' scheduled for '{1}'", filepathEntry.Value, filepathEntry.When);
return;
}
DeleteFile(filepathEntry.Value);
}
private void DeleteFile(string path) {
var response = _rootPlug.AtPath(path).Delete(new Result<DreamMessage>()).Wait();
if(response.Status != DreamStatus.NoContent) {
// request failed, bail
throw new DreamResponseException(response);
}
_expirationEntries.Delete(path);
}
private void DeleteDirectory(string path) {
string marker = null;
while(true) {
var p = _bucketPlug.With("prefix", GetRootedPath(path));
if(!string.IsNullOrEmpty(marker)) {
p = p.With("marker", marker);
}
var response = p.Get(new Result<DreamMessage>()).Wait();
var dirDoc = response.ToDocument().UsePrefix("aws", "http://s3.amazonaws.com/doc/2006-03-01/");
if(!response.IsSuccessful) {
throw new Exception(string.Format("{0}: {1}", dirDoc["Code"].AsText, dirDoc["Message"].AsText));
}
foreach(var keyDoc in dirDoc["aws:Contents/aws:Key"]) {
var key = keyDoc.AsText;
response = _bucketPlug.AtPath(key).Delete(new Result<DreamMessage>()).Wait();
if(!response.IsSuccessful && response.Status != DreamStatus.NoContent) {
throw new DreamResponseException(response);
}
_expirationEntries.Delete(key);
}
marker = dirDoc["aws:NextMarker"].AsText;
if(string.IsNullOrEmpty(marker)) {
// there are no more items
return;
}
}
}
private string GetName(string path) {
return path.Split(new[] { _config.Delimiter }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
}
private string GetRootedPath(string path) {
if(_keyRootParts == null || !_keyRootParts.Any()) {
return path;
}
return string.Join(_config.Delimiter, ArrayUtil.Concat(_keyRootParts, new[] { path }));
}
private bool IsDirectoryPath(string path) {
return path.EndsWith(_config.Delimiter);
}
}
}
| |
// 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.Runtime.CompilerServices;
using Internal.NativeFormat;
namespace Internal.TypeSystem
{
[Flags]
public enum MethodSignatureFlags
{
None = 0x0000,
// TODO: Generic, etc.
UnmanagedCallingConventionMask = 0x000F,
UnmanagedCallingConventionCdecl = 0x0001,
UnmanagedCallingConventionStdCall = 0x0002,
UnmanagedCallingConventionThisCall = 0x0003,
Static = 0x0010,
}
/// <summary>
/// Represents the parameter types, the return type, and flags of a method.
/// </summary>
public sealed class MethodSignature
{
internal MethodSignatureFlags _flags;
internal int _genericParameterCount;
internal TypeDesc _returnType;
internal TypeDesc[] _parameters;
public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters)
{
_flags = flags;
_genericParameterCount = genericParameterCount;
_returnType = returnType;
_parameters = parameters;
Debug.Assert(parameters != null, "Parameters must not be null");
}
public MethodSignatureFlags Flags
{
get
{
return _flags;
}
}
public bool IsStatic
{
get
{
return (_flags & MethodSignatureFlags.Static) != 0;
}
}
public int GenericParameterCount
{
get
{
return _genericParameterCount;
}
}
public TypeDesc ReturnType
{
get
{
return _returnType;
}
}
/// <summary>
/// Gets the parameter type at the specified index.
/// </summary>
[IndexerName("Parameter")]
public TypeDesc this[int index]
{
get
{
return _parameters[index];
}
}
/// <summary>
/// Gets the number of parameters of this method signature.
/// </summary>
public int Length
{
get
{
return _parameters.Length;
}
}
public bool Equals(MethodSignature otherSignature)
{
// TODO: Generics, etc.
if (this._flags != otherSignature._flags)
return false;
if (this._genericParameterCount != otherSignature._genericParameterCount)
return false;
if (this._returnType != otherSignature._returnType)
return false;
if (this._parameters.Length != otherSignature._parameters.Length)
return false;
for (int i = 0; i < this._parameters.Length; i++)
{
if (this._parameters[i] != otherSignature._parameters[i])
return false;
}
return true;
}
public override bool Equals(object obj)
{
return obj is MethodSignature && Equals((MethodSignature)obj);
}
public override int GetHashCode()
{
return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters);
}
}
/// <summary>
/// Helper structure for building method signatures by cloning an existing method signature.
/// </summary>
/// <remarks>
/// This can potentially avoid array allocation costs for allocating the parameter type list.
/// </remarks>
public struct MethodSignatureBuilder
{
private MethodSignature _template;
private MethodSignatureFlags _flags;
private int _genericParameterCount;
private TypeDesc _returnType;
private TypeDesc[] _parameters;
public MethodSignatureBuilder(MethodSignature template)
{
_template = template;
_flags = template._flags;
_genericParameterCount = template._genericParameterCount;
_returnType = template._returnType;
_parameters = template._parameters;
}
public MethodSignatureFlags Flags
{
set
{
_flags = value;
}
}
public TypeDesc ReturnType
{
set
{
_returnType = value;
}
}
[System.Runtime.CompilerServices.IndexerName("Parameter")]
public TypeDesc this[int index]
{
set
{
if (_parameters[index] == value)
return;
if (_template != null && _parameters == _template._parameters)
{
TypeDesc[] parameters = new TypeDesc[_parameters.Length];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = _parameters[i];
_parameters = parameters;
}
_parameters[index] = value;
}
}
public int Length
{
set
{
_parameters = new TypeDesc[value];
_template = null;
}
}
public MethodSignature ToSignature()
{
if (_template == null ||
_flags != _template._flags ||
_genericParameterCount != _template._genericParameterCount ||
_returnType != _template._returnType ||
_parameters != _template._parameters)
{
_template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters);
}
return _template;
}
}
/// <summary>
/// Represents the fundamental base type for all methods within the type system.
/// </summary>
public abstract partial class MethodDesc : TypeSystemEntity
{
public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0];
private int _hashcode;
/// <summary>
/// Allows a performance optimization that skips the potentially expensive
/// construction of a hash code if a hash code has already been computed elsewhere.
/// Use to allow objects to have their hashcode computed
/// independently of the allocation of a MethodDesc object
/// For instance, compute the hashcode when looking up the object,
/// then when creating the object, pass in the hashcode directly.
/// The hashcode specified MUST exactly match the algorithm implemented
/// on this type normally.
/// </summary>
protected void SetHashCode(int hashcode)
{
_hashcode = hashcode;
Debug.Assert(hashcode == ComputeHashCode());
}
public sealed override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return AcquireHashCode();
}
private int AcquireHashCode()
{
_hashcode = ComputeHashCode();
return _hashcode;
}
/// <summary>
/// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method.
/// </summary>
protected virtual int ComputeHashCode()
{
return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
public override bool Equals(Object o)
{
// Its only valid to compare two MethodDescs in the same context
Debug.Assert(Object.ReferenceEquals(o, null) || !(o is MethodDesc) || Object.ReferenceEquals(((MethodDesc)o).Context, this.Context));
return Object.ReferenceEquals(this, o);
}
/// <summary>
/// Gets the type that owns this method. This will be a <see cref="DefType"/> or
/// an <see cref="ArrayType"/>.
/// </summary>
public abstract TypeDesc OwningType
{
get;
}
/// <summary>
/// Gets the signature of the method.
/// </summary>
public abstract MethodSignature Signature
{
get;
}
/// <summary>
/// Gets the generic instantiation information of this method.
/// For generic definitions, retrieves the generic parameters of the method.
/// For generic instantiation, retrieves the generic arguments of the method.
/// </summary>
public virtual Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
/// <summary>
/// Gets a value indicating whether this method has a generic instantiation.
/// This will be true for generic method instantiations and generic definitions.
/// </summary>
public bool HasInstantiation
{
get
{
return this.Instantiation.Length != 0;
}
}
/// <summary>
/// Gets a value indicating whether the method's <see cref="Instantiation"/>
/// contains any generic variables.
/// </summary>
public bool ContainsGenericVariables
{
get
{
// TODO: Cache?
Instantiation instantiation = this.Instantiation;
for (int i = 0; i < instantiation.Length; i++)
{
if (instantiation[i].ContainsGenericVariables)
return true;
}
return false;
}
}
/// <summary>
/// Gets a value indicating whether this method is an instance constructor.
/// </summary>
public bool IsConstructor
{
get
{
// TODO: Precise check
// TODO: Cache?
return this.Name == ".ctor";
}
}
/// <summary>
/// Gets a value indicating whether this is a public parameterless instance constructor
/// on a non-abstract type.
/// </summary>
public virtual bool IsDefaultConstructor
{
get
{
return OwningType.GetDefaultConstructor() == this;
}
}
/// <summary>
/// Gets a value indicating whether this method is a static constructor.
/// </summary>
public bool IsStaticConstructor
{
get
{
return this == this.OwningType.GetStaticConstructor();
}
}
/// <summary>
/// Gets the name of the method as specified in the metadata.
/// </summary>
public virtual string Name
{
get
{
return null;
}
}
/// <summary>
/// Gets a value indicating whether the method is virtual.
/// </summary>
public virtual bool IsVirtual
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method should not override any
/// virtual methods defined in any of the base classes.
/// </summary>
public virtual bool IsNewSlot
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method needs to be overriden
/// by all non-abstract classes deriving from the method's owning type.
/// </summary>
public virtual bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating that this method cannot be overriden.
/// </summary>
public virtual bool IsFinal
{
get
{
return false;
}
}
public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName);
/// <summary>
/// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>.
/// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'.
/// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a method definition. This property
/// is true for non-generic methods and for uninstantiated generic methods.
/// </summary>
public bool IsMethodDefinition
{
get
{
return GetMethodDefinition() == this;
}
}
/// <summary>
/// Retrieves the generic definition of the method on the generic definition of the owning type.
/// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetTypicalMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a typical definition. This property is true
/// if neither the owning type, nor the method are instantiated.
/// </summary>
public bool IsTypicalMethodDefinition
{
get
{
return GetTypicalMethodDefinition() == this;
}
}
public bool IsFinalizer
{
get
{
return OwningType.GetFinalizer() == this || OwningType.IsObject && Name == "Finalize";
}
}
public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Instantiation instantiation = Instantiation;
TypeDesc[] clone = null;
for (int i = 0; i < instantiation.Length; i++)
{
TypeDesc uninst = instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = instantiation[j];
}
}
clone[i] = inst;
}
}
MethodDesc method = this;
TypeDesc owningType = method.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
{
method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType);
if (clone == null && instantiation.Length != 0)
return Context.GetInstantiatedMethod(method, instantiation);
}
return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone));
}
}
}
| |
using System;
using System.Globalization;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.TestingHost.Utils;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.General
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class Identifiertests
{
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture environment;
private static readonly Random random = new Random();
class A { }
class B : A { }
public Identifiertests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.environment = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ID_IsSystem()
{
GrainId testGrain = Constants.DirectoryServiceId;
output.WriteLine("Testing GrainID " + testGrain);
Assert.True(testGrain.IsSystemTarget); // System grain ID is not flagged as a system ID
GrainId sGrain = (GrainId)SerializationManager.DeepCopy(testGrain);
output.WriteLine("Testing GrainID " + sGrain);
Assert.True(sGrain.IsSystemTarget); // String round-trip grain ID is not flagged as a system ID
Assert.Equal(testGrain, sGrain); // Should be equivalent GrainId object
Assert.Same(testGrain, sGrain); // Should be same / intern'ed GrainId object
ActivationId testActivation = ActivationId.GetSystemActivation(testGrain, SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2456), 0));
output.WriteLine("Testing ActivationID " + testActivation);
Assert.True(testActivation.IsSystem); // System activation ID is not flagged as a system ID
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsNullKeyExtension()
{
Assert.Throws<ArgumentNullException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: null));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsEmptyKeyExtension()
{
Assert.Throws<ArgumentException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: ""));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeyKeyExtGrainCategoryDisallowsWhiteSpaceKeyExtension()
{
Assert.Throws<ArgumentException>(() =>
UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: " \t\n\r"));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeySerializationShouldReproduceAnIdenticalObject()
{
{
var expected = UniqueKey.NewKey(Guid.NewGuid());
BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
writer.Write(expected);
BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
var actual = reader.ReadUniqueKey();
Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #1).
}
{
var kx = random.Next().ToString(CultureInfo.InvariantCulture);
var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
writer.Write(expected);
BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
var actual = reader.ReadUniqueKey();
Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #2).
}
{
var kx = random.Next().ToString(CultureInfo.InvariantCulture) + new String('*', 400);
var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
writer.Write(expected);
BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
var actual = reader.ReadUniqueKey();
Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #3).
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ParsingUniqueKeyStringificationShouldReproduceAnIdenticalObject()
{
UniqueKey expected1 = UniqueKey.NewKey(Guid.NewGuid());
string str1 = expected1.ToHexString();
UniqueKey actual1 = UniqueKey.Parse(str1);
Assert.Equal(expected1, actual1); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 1).
string kx3 = "case 3";
UniqueKey expected3 = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx3);
string str3 = expected3.ToHexString();
UniqueKey actual3 = UniqueKey.Parse(str3);
Assert.Equal(expected3, actual3); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 3).
long pk = random.Next();
UniqueKey expected4 = UniqueKey.NewKey(pk);
string str4 = expected4.ToHexString();
UniqueKey actual4 = UniqueKey.Parse(str4);
Assert.Equal(expected4, actual4); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 4).
pk = random.Next();
string kx5 = "case 5";
UniqueKey expected5 = UniqueKey.NewKey(pk, category: UniqueKey.Category.KeyExtGrain, keyExt: kx5);
string str5 = expected5.ToHexString();
UniqueKey actual5 = UniqueKey.Parse(str5);
Assert.Equal(expected5, actual5); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 5).
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void GrainIdShouldEncodeAndDecodePrimaryKeyGuidCorrectly()
{
const int repeat = 100;
for (int i = 0; i < repeat; ++i)
{
Guid expected = Guid.NewGuid();
GrainId grainId = GrainId.GetGrainIdForTesting(expected);
Guid actual = grainId.Key.PrimaryKeyToGuid();
Assert.Equal(expected, actual); // Failed to encode and decode grain id
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void GrainId_ToFromPrintableString()
{
Guid guid = Guid.NewGuid();
GrainId grainId = GrainId.GetGrainIdForTesting(guid);
GrainId roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key
string extKey = "Guid-ExtKey-1";
guid = Guid.NewGuid();
grainId = GrainId.GetGrainId(0, guid, extKey);
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + Extended Key
grainId = GrainId.GetGrainId(0, guid, null);
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + null Extended Key
long key = random.Next();
guid = UniqueKey.NewKey(key).PrimaryKeyToGuid();
grainId = GrainId.GetGrainIdForTesting(guid);
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key
extKey = "Long-ExtKey-2";
key = random.Next();
guid = UniqueKey.NewKey(key).PrimaryKeyToGuid();
grainId = GrainId.GetGrainId(0, guid, extKey);
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + Extended Key
guid = UniqueKey.NewKey(key).PrimaryKeyToGuid();
grainId = GrainId.GetGrainId(0, guid, null);
roundTripped = RoundTripGrainIdToParsable(grainId);
Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + null Extended Key
}
private GrainId RoundTripGrainIdToParsable(GrainId input)
{
string str = input.ToParsableString();
GrainId output = GrainId.FromParsableString(str);
return output;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueTypeCodeDataShouldStore32BitsOfInformation()
{
const int expected = unchecked((int)0xfabccbaf);
var uk = UniqueKey.NewKey(0, UniqueKey.Category.None, expected);
var actual = uk.BaseTypeCode;
Assert.Equal(expected, actual);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsGuid()
{
const int all32Bits = unchecked((int)0xffffffff);
var expectedKey1 = Guid.NewGuid();
const string expectedKeyExt1 = "1";
var uk1 = UniqueKey.NewKey(expectedKey1, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt1);
string actualKeyExt1;
var actualKey1 = uk1.PrimaryKeyToGuid(out actualKeyExt1);
Assert.Equal(expectedKey1, actualKey1); //"UniqueKey objects should preserve the value of their primary key (Guid case #1).");
Assert.Equal(expectedKeyExt1, actualKeyExt1); //"UniqueKey objects should preserve the value of their key extension (Guid case #1).");
var expectedKey2 = Guid.NewGuid();
const string expectedKeyExt2 = "2";
var uk2 = UniqueKey.NewKey(expectedKey2, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt2);
string actualKeyExt2;
var actualKey2 = uk2.PrimaryKeyToGuid(out actualKeyExt2);
Assert.Equal(expectedKey2, actualKey2); // "UniqueKey objects should preserve the value of their primary key (Guid case #2).");
Assert.Equal(expectedKeyExt2, actualKeyExt2); // "UniqueKey objects should preserve the value of their key extension (Guid case #2).");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsLong()
{
const int all32Bits = unchecked((int)0xffffffff);
var n1 = random.Next();
var n2 = random.Next();
const string expectedKeyExt = "1";
var expectedKey = unchecked((long)((((ulong)((uint)n1)) << 32) | ((uint)n2)));
var uk = UniqueKey.NewKey(expectedKey, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt);
string actualKeyExt;
var actualKey = uk.PrimaryKeyToLong(out actualKeyExt);
Assert.Equal(expectedKey, actualKey); // "UniqueKey objects should preserve the value of their primary key (long case).");
Assert.Equal(expectedKeyExt, actualKeyExt); // "UniqueKey objects should preserve the value of their key extension (long case).");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ID_HashCorrectness()
{
// This tests that our optimized Jenkins hash computes the same value as the reference implementation
int testCount = 1000;
for (int i = 0; i < testCount; i++)
{
byte[] byteData = new byte[24];
random.NextBytes(byteData);
ulong u1 = BitConverter.ToUInt64(byteData, 0);
ulong u2 = BitConverter.ToUInt64(byteData, 8);
ulong u3 = BitConverter.ToUInt64(byteData, 16);
var referenceHash = JenkinsHash.ComputeHash(byteData);
var optimizedHash = JenkinsHash.ComputeHash(u1, u2, u3);
Assert.Equal(referenceHash, optimizedHash); // "Optimized hash value doesn't match the reference value for inputs {0}, {1}, {2}", u1, u2, u3
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ID_Interning_GrainID()
{
Guid guid = new Guid();
GrainId gid1 = GrainId.FromParsableString(guid.ToString("B"));
GrainId gid2 = GrainId.FromParsableString(guid.ToString("N"));
Assert.Equal(gid1, gid2); // Should be equal GrainId's
Assert.Same(gid1, gid2); // Should be same / intern'ed GrainId object
// Round-trip through Serializer
GrainId gid3 = (GrainId)SerializationManager.RoundTripSerializationForTesting(gid1);
Assert.Equal(gid1, gid3); // Should be equal GrainId's
Assert.Equal(gid2, gid3); // Should be equal GrainId's
Assert.Same(gid1, gid3); // Should be same / intern'ed GrainId object
Assert.Same(gid2, gid3); // Should be same / intern'ed GrainId object
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ID_Interning_string_equals()
{
Interner<string, string> interner = new Interner<string, string>();
const string str = "1";
string r1 = interner.FindOrCreate("1", _ => str);
string r2 = interner.FindOrCreate("1", _ => null); // Should always be found
Assert.Equal(r1, r2); // 1: Objects should be equal
Assert.Same(r1, r2); // 2: Objects should be same / intern'ed
// Round-trip through Serializer
string r3 = (string)SerializationManager.RoundTripSerializationForTesting(r1);
Assert.Equal(r1, r3); // 3: Should be equal
Assert.Equal(r2, r3); // 4: Should be equal
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void ID_Intern_FindOrCreate_derived_class()
{
Interner<int, A> interner = new Interner<int, A>();
var obj1 = new A();
var obj2 = new B();
var obj3 = new B();
var r1 = interner.FindOrCreate(1, _ => obj1);
Assert.Equal(obj1, r1); // Objects should be equal
Assert.Same(obj1, r1); // Objects should be same / intern'ed
var r2 = interner.FindOrCreate(2, _ => obj2);
Assert.Equal(obj2, r2); // Objects should be equal
Assert.Same(obj2, r2); // Objects should be same / intern'ed
// FindOrCreate should not replace instances of same class
var r3 = interner.FindOrCreate(2, _ => obj3);
Assert.Same(obj2, r3); // FindOrCreate should return previous object
Assert.NotSame(obj3, r3); // FindOrCreate should not replace previous object of same class
// FindOrCreate should not replace cached instances with instances of most derived class
var r4 = interner.FindOrCreate(1, _ => obj2);
Assert.Same(obj1, r4); // FindOrCreate return previously cached object
Assert.NotSame(obj2, r4); // FindOrCreate should not replace previously cached object
// FindOrCreate should not replace cached instances with instances of less derived class
var r5 = interner.FindOrCreate(2, _ => obj1);
Assert.NotSame(obj1, r5); // FindOrCreate should not replace previously cached object
Assert.Same(obj2, r5); // FindOrCreate return previously cached object
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void Interning_SiloAddress()
{
//string addrStr1 = "1.2.3.4@11111@1";
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
Assert.Equal(a1, a2); // Should be equal SiloAddress's
Assert.Same(a1, a2); // Should be same / intern'ed SiloAddress object
// Round-trip through Serializer
SiloAddress a3 = (SiloAddress)SerializationManager.RoundTripSerializationForTesting(a1);
Assert.Equal(a1, a3); // Should be equal SiloAddress's
Assert.Equal(a2, a3); // Should be equal SiloAddress's
Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object
Assert.Same(a2, a3); // Should be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void Interning_SiloAddress2()
{
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2222), 12345);
Assert.NotEqual(a1, a2); // Should not be equal SiloAddress's
Assert.NotSame(a1, a2); // Should not be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void Interning_SiloAddress_Serialization()
{
SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345);
// Round-trip through Serializer
SiloAddress a3 = (SiloAddress)SerializationManager.RoundTripSerializationForTesting(a1);
Assert.Equal(a1, a3); // Should be equal SiloAddress's
Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void GrainID_AsGuid()
{
string guidString = "0699605f-884d-4343-9977-f40a39ab7b2b";
Guid grainIdGuid = Guid.Parse(guidString);
GrainId grainId = GrainId.GetGrainIdForTesting(grainIdGuid);
//string grainIdToKeyString = grainId.ToKeyString();
string grainIdToFullString = grainId.ToFullString();
string grainIdToGuidString = GrainIdToGuidString(grainId);
string grainIdKeyString = grainId.Key.ToString();
output.WriteLine("Guid={0}", grainIdGuid);
output.WriteLine("GrainId={0}", grainId);
//output.WriteLine("GrainId.ToKeyString={0}", grainIdToKeyString);
output.WriteLine("GrainId.Key.ToString={0}", grainIdKeyString);
output.WriteLine("GrainIdToGuidString={0}", grainIdToGuidString);
output.WriteLine("GrainId.ToFullString={0}", grainIdToFullString);
// Equal: Public APIs
//Assert.Equal(guidString, grainIdToKeyString); // GrainId.ToKeyString
Assert.Equal(guidString, grainIdToGuidString); // GrainIdToGuidString
// Equal: Internal APIs
Assert.Equal(grainIdGuid, grainId.GetPrimaryKey()); // GetPrimaryKey Guid
// NOT-Equal: Internal APIs
Assert.NotEqual(guidString, grainIdKeyString); // GrainId.Key.ToString
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")]
public void SiloAddress_ToFrom_ParsableString()
{
SiloAddress address1 = SiloAddress.NewLocalAddress(12345);
string addressStr1 = address1.ToParsableString();
SiloAddress addressObj1 = SiloAddress.FromParsableString(addressStr1);
output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}",
address1, addressStr1, addressObj1);
Assert.Equal(address1, addressObj1); // SiloAddress equal after To-From-ParsableString
//const string addressStr2 = "127.0.0.1-11111-144611139";
const string addressStr2 = "127.0.0.1:11111@144611139";
SiloAddress addressObj2 = SiloAddress.FromParsableString(addressStr2);
string addressStr2Out = addressObj2.ToParsableString();
output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}",
addressStr2, addressStr2Out, addressObj2);
Assert.Equal(addressStr2, addressStr2Out); // SiloAddress equal after From-To-ParsableString
}
internal string GrainIdToGuidString(GrainId grainId)
{
const string pkIdentifierStr = "PrimaryKey:";
string grainIdFullString = grainId.ToFullString();
int pkStartIdx = grainIdFullString.IndexOf(pkIdentifierStr, StringComparison.Ordinal) + pkIdentifierStr.Length + 1;
string pkGuidString = grainIdFullString.Substring(pkStartIdx, Guid.Empty.ToString().Length);
return pkGuidString;
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers"), TestCategory("GrainReference")]
public void GrainReference_Test1()
{
Guid guid = Guid.NewGuid();
GrainId regularGrainId = GrainId.GetGrainIdForTesting(guid);
GrainReference grainRef = GrainReference.FromGrainId(regularGrainId);
TestGrainReference(grainRef);
grainRef = GrainReference.FromGrainId(regularGrainId, "generic");
TestGrainReference(grainRef);
GrainId systemTragetGrainId = GrainId.NewSystemTargetGrainIdByTypeCode(2);
grainRef = GrainReference.FromGrainId(systemTragetGrainId, null, SiloAddress.NewLocalAddress(1));
TestGrainReference(grainRef);
GrainId observerGrainId = GrainId.NewClientId();
grainRef = GrainReference.NewObserverGrainReference(observerGrainId, GuidId.GetNewGuidId());
TestGrainReference(grainRef);
GrainId geoObserverGrainId = GrainId.NewClientId("clusterid");
grainRef = GrainReference.NewObserverGrainReference(geoObserverGrainId, GuidId.GetNewGuidId());
TestGrainReference(grainRef);
}
private void TestGrainReference(GrainReference grainRef)
{
GrainReference roundTripped = RoundTripGrainReferenceToKey(grainRef);
Assert.Equal(grainRef, roundTripped); // GrainReference.ToKeyString
roundTripped = SerializationManager.RoundTripSerializationForTesting(grainRef);
Assert.Equal(grainRef, roundTripped); // GrainReference.OrleansSerializer
roundTripped = TestingUtils.RoundTripDotNetSerializer(grainRef);
Assert.Equal(grainRef, roundTripped); // GrainReference.DotNetSerializer
}
private GrainReference RoundTripGrainReferenceToKey(GrainReference input)
{
string str = input.ToKeyString();
GrainReference output = this.environment.Services.GetRequiredService<IGrainReferenceConverter>().GetGrainFromKeyString(str);
return output;
}
}
}
| |
// Copyright 2018 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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Google.Cloud.Diagnostics.AspNetCore.Analyzers
{
// TODO: Support for VB as well?
// TODO: Add a code fix provider?
/// <summary>
/// Analyzer which checks to make sure the earliest usage of the UseGoogleTrace extension method on
/// an IApplicationBuilder symbol happens before the earliest usage any UseMvc... extension method
/// on the same symbol. Chains of method calls all on an IApplicationBuilder are assumed to all be
/// called on the same instance.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class GoogleTraceBeforeMvcAnalyzer : DiagnosticAnalyzer
{
public const string RuleId = "GCP0005";
private const string IApplicationBuilderFullName = "Microsoft.AspNetCore.Builder.IApplicationBuilder";
private const string UseGoogleTrace = "UseGoogleTrace";
private const string UseMvc = "UseMvc";
private static readonly LocalizableString Title =
"Add Google Trace before MVC";
private static readonly LocalizableString MessageFormat =
$"{UseGoogleTrace} should be used before {{0}} so requests can be traced";
private static readonly LocalizableString Description =
"Google Trace middleware should be added before MVC to the request pipeline.";
private static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(
RuleId,
Title,
MessageFormat,
category: "Usage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: Description,
helpLinkUri: "http://googlecloudplatform.github.io/google-cloud-dotnet/docs/Google.Cloud.Diagnostics.AspNetCore/#initializing-tracing");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(
GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterSyntaxNodeAction(AnalyzeSyntaxNode, SyntaxKind.InvocationExpression);
}
// Visible for testing
internal static readonly ConditionalWeakTable<ISymbol, ApplicationBuilderSymbolInfo> _applicationBuilderSymbolInfos =
new ConditionalWeakTable<ISymbol, ApplicationBuilderSymbolInfo>();
private static void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context)
{
// Skip invocations that aren't made on member access expressions.
// We want something like app.Xyz()
var invocationNode = (InvocationExpressionSyntax)context.Node;
if (!(invocationNode.Expression is MemberAccessExpressionSyntax memberAccess))
{
return;
}
var name = memberAccess.Name.ToString();
GetAccessInfoDelegate getAccessInfo =
name == UseGoogleTrace ? scopeInfo => ref scopeInfo.UseGoogleTraceAccessInfo :
name.StartsWith(UseMvc) ? scopeInfo => ref scopeInfo.UseMvcAccessInfo :
default(GetAccessInfoDelegate);
if (getAccessInfo == null)
{
return;
}
// Walk up a chain of method calls on IApplicationBuilder (if there is one), and see if
// there is a local/parameter/field/property symbol at the end of the chain. If so, record
// the name access for that symbol.
var nameAccessNode = memberAccess.Name;
var semanticModel = context.SemanticModel;
do
{
var symbol = semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol;
// TODO: Do we want to support things that are reference convertible to IApplicationBuilder as well?
// All receivers of the method invocations must be of type IApplicationBuilder.
if (symbol?.Type()?.ToDisplayString() != IApplicationBuilderFullName)
{
break;
}
switch (symbol.Kind)
{
case SymbolKind.Local:
case SymbolKind.Field:
case SymbolKind.Parameter:
case SymbolKind.Property:
UpdateInvocationLocation(context, symbol, nameAccessNode, getAccessInfo);
return;
case SymbolKind.Method:
// Walk up the chain...
memberAccess =
(memberAccess.Expression as InvocationExpressionSyntax)?.Expression as MemberAccessExpressionSyntax;
break;
}
}
while (memberAccess != null);
}
private static void UpdateInvocationLocation(
SyntaxNodeAnalysisContext context,
ISymbol symbol,
SimpleNameSyntax currentAccessNode,
GetAccessInfoDelegate getAccessInfo)
{
var symbolInfo = _applicationBuilderSymbolInfos.GetOrCreateValue(symbol);
var scopeEnclosingNode =
currentAccessNode.FirstAncestorOrSelf<CSharpSyntaxNode>(IsScopeEnclosingNode);
lock (symbolInfo)
{
if (!symbolInfo.Scopes.TryGetValue(scopeEnclosingNode, out var scopeInfo))
{
symbolInfo.Scopes[scopeEnclosingNode] = scopeInfo = new ScopeInfo();
}
if (scopeInfo.DiagnosticReported)
{
return;
}
ref var existingAccessInfo = ref getAccessInfo(scopeInfo);
if (existingAccessInfo.location == null ||
currentAccessNode.GetLocation().SourceSpan.Start < existingAccessInfo.location.SourceSpan.Start)
{
existingAccessInfo = (currentAccessNode.GetLocation(), currentAccessNode.ToString());
VerifyInvocationOrder(context, scopeInfo);
}
}
}
private static void VerifyInvocationOrder(
SyntaxNodeAnalysisContext context, ScopeInfo scopeInfo)
{
if (scopeInfo.UseMvcAccessInfo.location == null ||
scopeInfo.UseGoogleTraceAccessInfo.location == null)
{
return;
}
if (scopeInfo.UseMvcAccessInfo.location.SourceTree !=
scopeInfo.UseGoogleTraceAccessInfo.location.SourceTree)
{
throw new InvalidOperationException("Unexpected: the same scope spanned two different files");
}
if (scopeInfo.UseMvcAccessInfo.location.SourceSpan.Start <
scopeInfo.UseGoogleTraceAccessInfo.location.SourceSpan.Start)
{
context.ReportDiagnostic(
Diagnostic.Create(
Rule,
scopeInfo.UseGoogleTraceAccessInfo.location,
scopeInfo.UseMvcAccessInfo.name));
scopeInfo.DiagnosticReported = true;
}
}
private static bool IsScopeEnclosingNode(CSharpSyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.StructDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.LocalFunctionStatement:
return true;
}
return false;
}
/// <summary>
/// Information regarding a single IApplicationBuilder symbol's accesses across various scopes.
/// </summary>
public class ApplicationBuilderSymbolInfo
{
// TODO: Assignments to a symbol should split a scope area into two, but I don't
// know if that will be possible given how the analyzer is invoked.
// A collection of scopes keyed by the immediate enclosing node of that scope.
public readonly Dictionary<CSharpSyntaxNode, ScopeInfo> Scopes =
new Dictionary<CSharpSyntaxNode, ScopeInfo>();
}
/// <summary>
/// Information about a single IApplicationBuilder symbol's accesses within in single scope.
/// </summary>
public class ScopeInfo
{
public bool DiagnosticReported;
public (Location location, string name) UseGoogleTraceAccessInfo;
public (Location location, string name) UseMvcAccessInfo;
}
/// <summary>
/// Delegate to gets a reference to the information for a single access of either UseMvc... or UseGoogleTrace.
/// </summary>
private delegate ref (Location location, string name) GetAccessInfoDelegate(ScopeInfo scopeInfo);
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// 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 !NET_1_0 && !NET_1_1
#define ASYNC_ADONET
#endif
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using IDictionary = System.Collections.IDictionary;
using IList = System.Collections.IList;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses Microsoft SQL
/// Server 2000 as its backing store.
/// </summary>
public class SqlErrorLog : ErrorLog
{
private readonly string _connectionString;
private const int _maxAppNameLength = 60;
#if ASYNC_ADONET
private delegate RV Function<RV, A>(A a);
#endif
/// <summary>
/// Initializes a new instance of the <see cref="SqlErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public SqlErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the SQL error log.");
_connectionString = connectionString;
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
string appName = Mask.NullString((string) config["applicationName"]);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public SqlErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Microsoft SQL Server Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
Guid id = Guid.NewGuid();
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
using (SqlCommand command = Commands.LogError(
id, this.ApplicationName,
error.HostName, error.Type, error.Source, error.Message, error.User,
error.StatusCode, error.Time.ToUniversalTime(), errorXml))
{
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
return id.ToString();
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
using (SqlCommand command = Commands.GetErrorsXml(this.ApplicationName, pageIndex, pageSize))
{
command.Connection = connection;
connection.Open();
#if !NET_1_0 && !NET_1_1
string xml = ReadSingleXmlStringResult(command.ExecuteReader());
ErrorsXmlToList(xml, errorEntryList);
#else
XmlReader reader = command.ExecuteXmlReader();
try
{
ErrorsXmlToList(reader, errorEntryList);
}
finally
{
reader.Close();
}
#endif
int total;
Commands.GetErrorsXmlOutputs(command, out total);
return total;
}
}
private static string ReadSingleXmlStringResult(SqlDataReader reader)
{
using (reader)
{
if (!reader.Read())
return null;
//
// See following MS KB article why the XML string is read
// and reconstructed in chunks:
//
// The XML data row is truncated at 2,033 characters when you use the SqlDataReader object
// http://support.microsoft.com/kb/310378
//
// When you read XML data from Microsoft SQL Server by using
// the SqlDataReader object, the XML in the first column of
// the first row is truncated at 2,033 characters. You
// expect all of the contents of the XML data to be
// contained in a single row and column. This behavior
// occurs because, for XML results greater than 2,033
// characters in length, SQL Server returns the XML in
// multiple rows of 2,033 characters each.
//
// See also comment 18 in issue 129:
// http://code.google.com/p/elmah/issues/detail?id=129#c18
//
StringBuilder sb = new StringBuilder(/* capacity */ 2033);
do { sb.Append(reader.GetString(0)); } while (reader.Read());
return sb.ToString();
}
}
#if ASYNC_ADONET
/// <summary>
/// Begins an asynchronous version of <see cref="GetErrors"/>.
/// </summary>
public override IAsyncResult BeginGetErrors(int pageIndex, int pageSize, IList errorEntryList,
AsyncCallback asyncCallback, object asyncState)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
//
// Modify the connection string on the fly to support async
// processing otherwise the asynchronous methods on the
// SqlCommand will throw an exception. This ensures the
// right behavior regardless of whether configured
// connection string sets the Async option to true or not.
//
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(this.ConnectionString);
csb.AsynchronousProcessing = true;
SqlConnection connection = new SqlConnection(csb.ConnectionString);
//
// Create the command object with input parameters initialized
// and setup to call the stored procedure.
//
SqlCommand command = Commands.GetErrorsXml(this.ApplicationName, pageIndex, pageSize);
command.Connection = connection;
//
// Create a closure to handle the ending of the async operation
// and retrieve results.
//
AsyncResultWrapper asyncResult = null;
Function<int, IAsyncResult> endHandler = delegate
{
Debug.Assert(asyncResult != null);
using (connection)
using (command)
{
string xml = ReadSingleXmlStringResult(command.EndExecuteReader(asyncResult.InnerResult));
ErrorsXmlToList(xml, errorEntryList);
int total;
Commands.GetErrorsXmlOutputs(command, out total);
return total;
}
};
//
// Open the connenction and execute the command asynchronously,
// returning an IAsyncResult that wrap the downstream one. This
// is needed to be able to send our own AsyncState object to
// the downstream IAsyncResult object. In order to preserve the
// one sent by caller, we need to maintain and return it from
// our wrapper.
//
try
{
connection.Open();
asyncResult = new AsyncResultWrapper(
command.BeginExecuteReader(
asyncCallback != null ? /* thunk */ delegate { asyncCallback(asyncResult); } : (AsyncCallback) null,
endHandler), asyncState);
return asyncResult;
}
catch (Exception)
{
connection.Dispose();
throw;
}
}
private void ErrorsXmlToList(string xml, IList errorEntryList)
{
if (xml == null || xml.Length == 0)
return;
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
ErrorsXmlToList(reader, errorEntryList);
}
/// <summary>
/// Ends an asynchronous version of <see cref="ErrorLog.GetErrors"/>.
/// </summary>
public override int EndGetErrors(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
AsyncResultWrapper wrapper = asyncResult as AsyncResultWrapper;
if (wrapper == null)
throw new ArgumentException("Unexepcted IAsyncResult type.", "asyncResult");
Function<int, IAsyncResult> endHandler = (Function<int, IAsyncResult>) wrapper.InnerResult.AsyncState;
return endHandler(wrapper.InnerResult);
}
#endif
private void ErrorsXmlToList(XmlReader reader, IList errorEntryList)
{
Debug.Assert(reader != null);
if (errorEntryList != null)
{
while (reader.IsStartElement("error"))
{
string id = reader.GetAttribute("errorId");
Error error = ErrorXml.Decode(reader);
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml;
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
using (SqlCommand command = Commands.GetErrorXml(this.ApplicationName, errorGuid))
{
command.Connection = connection;
connection.Open();
errorXml = (string) command.ExecuteScalar();
}
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
private sealed class Commands
{
private Commands() {}
public static SqlCommand LogError(
Guid id,
string appName,
string hostName,
string typeName,
string source,
string message,
string user,
int statusCode,
DateTime time,
string xml)
{
SqlCommand command = new SqlCommand("ELMAH_LogError");
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameters = command.Parameters;
parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id;
parameters.Add("@Application", SqlDbType.NVarChar, _maxAppNameLength).Value = appName;
parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = hostName;
parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = typeName;
parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = source;
parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = message;
parameters.Add("@User", SqlDbType.NVarChar, 50).Value = user;
parameters.Add("@AllXml", SqlDbType.NText).Value = xml;
parameters.Add("@StatusCode", SqlDbType.Int).Value = statusCode;
parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = time;
return command;
}
public static SqlCommand GetErrorXml(string appName, Guid id)
{
SqlCommand command = new SqlCommand("ELMAH_GetErrorXml");
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameters = command.Parameters;
parameters.Add("@Application", SqlDbType.NVarChar, _maxAppNameLength).Value = appName;
parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id;
return command;
}
public static SqlCommand GetErrorsXml(string appName, int pageIndex, int pageSize)
{
SqlCommand command = new SqlCommand("ELMAH_GetErrorsXml");
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameters = command.Parameters;
parameters.Add("@Application", SqlDbType.NVarChar, _maxAppNameLength).Value = appName;
parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
parameters.Add("@TotalCount", SqlDbType.Int).Direction = ParameterDirection.Output;
return command;
}
public static void GetErrorsXmlOutputs(SqlCommand command, out int totalCount)
{
Debug.Assert(command != null);
totalCount = (int) command.Parameters["@TotalCount"].Value;
}
}
/// <summary>
/// An <see cref="IAsyncResult"/> implementation that wraps another.
/// </summary>
private sealed class AsyncResultWrapper : IAsyncResult
{
private readonly IAsyncResult _inner;
private readonly object _asyncState;
public AsyncResultWrapper(IAsyncResult inner, object asyncState)
{
_inner = inner;
_asyncState = asyncState;
}
public IAsyncResult InnerResult
{
get { return _inner; }
}
public bool IsCompleted
{
get { return _inner.IsCompleted; }
}
public WaitHandle AsyncWaitHandle
{
get { return _inner.AsyncWaitHandle; }
}
public object AsyncState
{
get { return _asyncState; }
}
public bool CompletedSynchronously
{
get { return _inner.CompletedSynchronously; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
public class EditorDummy
{
// from http://www.dotnetperls.com/word-count
public static int CountWords1(string s)
{
MatchCollection collection = Regex.Matches(s, @"[\S]+");
return collection.Count;
}
public static int CountWords2(string s)
{
int c = 0;
for (int i = 1; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i - 1]) == true)
{
if (char.IsLetterOrDigit(s[i]) == true ||
char.IsPunctuation(s[i]))
{
c++;
}
}
}
if (s.Length > 2)
{
c++;
}
return c;
}
// from http://www.dotnetperls.com/array-optimization
const int _max = 100000000;
public static void ArrayOptimization()
{
int[] array = new int[12];
Method1(array);
Method2(array);
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1(array);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method2(array);
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.Read();
}
static void Method1(int[] array)
{
// Initialize each element in for-loop.
for (int i = 0; i < array.Length; i++)
{
array[i] = 1;
}
}
static void Method2(int[] array)
{
// Initialize each element in separate statement with no enclosing loop.
array[0] = 1;
array[1] = 1;
array[2] = 1;
array[3] = 1;
array[4] = 1;
array[5] = 1;
array[6] = 1;
array[7] = 1;
array[8] = 1;
array[9] = 1;
array[10] = 1;
array[11] = 1;
}
// from http://www.dotnetperls.com/dictionary
public static void Dictionary1()
{
// Example Dictionary again.
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
// Loop over pairs with foreach.
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
// Use var keyword to enumerate dictionary.
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
}
public static void Dictionary2()
{
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
// Store keys in a List
List<string> list = new List<string>(d.Keys);
// Loop through list
foreach (string k in list)
{
Console.WriteLine("{0}, {1}",
k,
d[k]);
}
}
// from: http://www.dotnetperls.com/format
public static void Format1()
{
// Declare three variables.
// ... The values they have are not important.
string value1 = "Dot Net Perls";
int value2 = 10000;
DateTime value3 = new DateTime(2015, 11, 1);
// Use string.Format method with four arguments.
// ... The first argument is the formatting string.
// ... It specifies how the next arguments are formatted.
string result = string.Format("{0}: {1:0.0} - {2:yyyy}",
value1,
value2,
value3);
// Write the result.
Console.WriteLine(result);
}
public static void Format2()
{
// Format a ratio as a percentage string.
// ... You must specify the percentage symbol.
// ... It will multiply the value by 100.
double ratio = 0.73;
string result = string.Format("string = {0:0.0%}",
ratio);
Console.WriteLine(result);
}
public static void Format3()
{
// The constant formatting string.
// ... It specifies the padding.
// ... A negative number means to left-align.
// ... A positive number means to right-align.
const string format = "{0,-10} {1,10}";
// Construct the strings.
string line1 = string.Format(format,
100,
5);
string line2 = string.Format(format,
"Carrot",
"Giraffe");
// Write the formatted strings.
Console.WriteLine(line1);
Console.WriteLine(line2);
}
public static void Format4()
{
int value1 = 10995;
// Write number in hex format.
Console.WriteLine("{0:x}", value1);
Console.WriteLine("{0:x8}", value1);
Console.WriteLine("{0:X}", value1);
Console.WriteLine("{0:X8}", value1);
// Convert to hex.
string hex = value1.ToString("X8");
// Convert from hex to integer.
int value2 = int.Parse(hex, NumberStyles.AllowHexSpecifier);
Console.WriteLine(value1 == value2);
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestHelper
{
/// <summary>
/// Superclass of all Unit Tests for DiagnosticAnalyzers
/// </summary>
public abstract partial class DiagnosticVerifier
{
#region To be implemented by Test classes
/// <summary>
/// Get the CSharp analyzer being tested - to be implemented in non-abstract class
/// </summary>
protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return null;
}
/// <summary>
/// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class
/// </summary>
protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return null;
}
#endregion
#region Verifier wrappers
/// <summary>
/// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
/// Note: input a DiagnosticResult for each Diagnostic expected
/// </summary>
/// <param name="source">A class in the form of a string to run the analyzer on</param>
/// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param>
protected void VerifyCommandLineDiagnostic(string source, params DiagnosticResult[] expected)
{
VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected);
}
/// <summary>
/// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
/// then verifies each of them.
/// </summary>
/// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
/// <param name="language">The language of the classes represented by the source strings</param>
/// <param name="analyzer">The analyzer to be run on the source code</param>
/// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param>
private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected)
{
var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
VerifyDiagnosticResults(diagnostics, analyzer, expected);
}
#endregion
#region Actual comparisons and verifications
/// <summary>
/// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results.
/// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic.
/// </summary>
/// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param>
/// <param name="analyzer">The analyzer that was being run on the sources</param>
/// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
{
int expectedCount = expectedResults.Count();
int actualCount = actualResults.Count();
if (expectedCount != actualCount)
{
string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE.";
Assert.IsTrue(false,
string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
}
expectedResults = expectedResults.OrderBy(x => x.Id).ToArray();
actualResults = actualResults.OrderBy(x => x.Id);
for (int i = 0; i < expectedResults.Length; i++)
{
var actual = actualResults.ElementAt(i);
var expected = expectedResults[i];
if (expected.Line == -1 && expected.Column == -1)
{
if (actual.Location != Location.None)
{
Assert.IsTrue(false,
string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
FormatDiagnostics(analyzer, actual)));
}
}
else
{
VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First());
var additionalLocations = actual.AdditionalLocations.ToArray();
if (additionalLocations.Length != expected.Locations.Length - 1)
{
Assert.IsTrue(false,
string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
expected.Locations.Length - 1, additionalLocations.Length,
FormatDiagnostics(analyzer, actual)));
}
for (int j = 0; j < additionalLocations.Length; ++j)
{
VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
}
}
if (actual.Id != expected.Id)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
}
if (actual.Severity != expected.Severity)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)));
}
if (actual.GetMessage() != expected.Message)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)));
}
}
}
/// <summary>
/// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult.
/// </summary>
/// <param name="analyzer">The analyzer that was being run on the sources</param>
/// <param name="diagnostic">The diagnostic that was found in the code</param>
/// <param name="actual">The Location of the Diagnostic found in the code</param>
/// <param name="expected">The DiagnosticResultLocation that should have been found</param>
private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected)
{
var actualSpan = actual.GetLineSpan();
Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")),
string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));
var actualLinePosition = actualSpan.StartLinePosition;
// Only check line position if there is an actual line in the real diagnostic
if (actualLinePosition.Line > 0)
{
if (actualLinePosition.Line + 1 != expected.Line)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
// Only check column position if there is an actual column position in the real diagnostic
if (actualLinePosition.Character > 0)
{
if (actualLinePosition.Character + 1 != expected.Column)
{
Assert.IsTrue(false,
string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
}
#endregion
#region Formatting Diagnostics
/// <summary>
/// Helper method to format a Diagnostic into an easily readable string
/// </summary>
/// <param name="analyzer">The analyzer that this verifier tests</param>
/// <param name="diagnostics">The Diagnostics to be formatted</param>
/// <returns>The Diagnostics formatted as a string</returns>
private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics)
{
var builder = new StringBuilder();
for (int i = 0; i < diagnostics.Length; ++i)
{
builder.AppendLine("// " + diagnostics[i].ToString());
var analyzerType = analyzer.GetType();
var rules = analyzer.SupportedDiagnostics;
foreach (var rule in rules)
{
if (rule != null && rule.Id == diagnostics[i].Id)
{
var location = diagnostics[i].Location;
if (location == Location.None)
{
builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
}
else
{
Assert.IsTrue(location.IsInSource,
$"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");
string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;
builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
resultMethodName,
linePosition.Line + 1,
linePosition.Character + 1,
analyzerType.Name,
rule.Id);
}
if (i != diagnostics.Length - 1)
{
builder.Append(',');
}
builder.AppendLine();
break;
}
}
}
return builder.ToString();
}
#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 Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PoolOperations operations.
/// </summary>
public partial interface IPoolOperations
{
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the
/// response includes all pools that existed in the account in the time
/// range of the returned aggregation intervals. If you do not specify
/// a $filter clause including a startTime or endTime these filters
/// default to the start and end times of the last aggregation interval
/// currently available; that is, only the last aggregation interval is
/// returned.
/// </remarks>
/// <param name='poolListUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListUsageMetricsHeaders>> ListUsageMetricsWithHttpMessagesAsync(PoolListUsageMetricsOptions poolListUsageMetricsOptions = default(PoolListUsageMetricsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the
/// specified account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed
/// in the account, from account creation to the last update time of
/// the statistics.
/// </remarks>
/// <param name='poolGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PoolStatistics,PoolGetAllLifetimeStatisticsHeaders>> GetAllLifetimeStatisticsWithHttpMessagesAsync(PoolGetAllLifetimeStatisticsOptions poolGetAllLifetimeStatisticsOptions = default(PoolGetAllLifetimeStatisticsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <remarks>
/// When naming pools, avoid including sensitive information such as
/// user names or secret project names. This information may appear in
/// telemetry logs accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolAddHeaders>> AddWithHttpMessagesAsync(PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>> ListWithHttpMessagesAsync(PoolListOptions poolListOptions = default(PoolListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <remarks>
/// When you request that a pool be deleted, the following actions
/// occur: the pool state is set to deleting; any ongoing resize
/// operation on the pool are stopped; the Batch service starts
/// resizing the pool to zero nodes; any tasks running on existing
/// nodes are terminated and requeued (as if a resize pool operation
/// had been requested with the default requeue option); finally, the
/// pool is removed from the system. Because running tasks are
/// requeued, the user can rerun these tasks by updating their job to
/// target a different pool. The tasks can then run on the new pool. If
/// you want to override the requeue behavior, then you should call
/// resize pool explicitly to shrink the pool to zero size before
/// deleting the pool. If you call an Update, Patch or Delete API on a
/// pool in the deleting state, it will fail with HTTP status code 409
/// with error code PoolBeingDeleted.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolDeleteHeaders>> DeleteWithHttpMessagesAsync(string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<bool,PoolExistsHeaders>> ExistsWithHttpMessagesAsync(string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CloudPool,PoolGetHeaders>> GetWithHttpMessagesAsync(string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This only replaces the pool properties specified in the request.
/// For example, if the pool has a start task associated with it, and a
/// request does not specify a start task element, then the pool keeps
/// the existing start task.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolPatchHeaders>> PatchWithHttpMessagesAsync(string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolDisableAutoScaleHeaders>> DisableAutoScaleWithHttpMessagesAsync(string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <remarks>
/// You cannot enable automatic scaling on a pool if a resize operation
/// is in progress on the pool. If automatic scaling of the pool is
/// currently disabled, you must specify a valid autoscale formula as
/// part of the request. If automatic scaling of the pool is already
/// enabled, you may specify a new autoscale formula and/or a new
/// evaluation interval. You cannot call this API for the same pool
/// more than once every 30 seconds.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolEnableAutoScaleHeaders>> EnableAutoScaleWithHttpMessagesAsync(string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the
/// pool.
/// </summary>
/// <remarks>
/// This API is primarily for validating an autoscale formula, as it
/// simply returns the result without applying the formula to the pool.
/// The pool must have auto scaling enabled in order to evaluate a
/// formula.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool on which to evaluate the automatic scaling
/// formula.
/// </param>
/// <param name='autoScaleFormula'>
/// The formula for the desired number of compute nodes in the pool.
/// The formula is validated and its results calculated, but it is not
/// applied to the pool. To apply the formula to the pool, 'Enable
/// automatic scaling on a pool'. For more information about specifying
/// this formula, see Automatically scale compute nodes in an Azure
/// Batch pool
/// (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling).
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<AutoScaleRun,PoolEvaluateAutoScaleHeaders>> EvaluateAutoScaleWithHttpMessagesAsync(string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <remarks>
/// You can only resize a pool when its allocation state is steady. If
/// the pool is already resizing, the request fails with status code
/// 409. When you resize a pool, the pool's allocation state changes
/// from steady to resizing. You cannot resize pools which are
/// configured for automatic scaling. If you try to do this, the Batch
/// service returns an error 409. If you resize a pool downwards, the
/// Batch service chooses which nodes to remove. To remove specific
/// nodes, use the pool remove nodes API instead.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolResizeHeaders>> ResizeWithHttpMessagesAsync(string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the
/// resize operation: it only stops any further changes being made, and
/// the pool maintains its current state. After stopping, the pool
/// stabilizes at the number of nodes it was at when the stop operation
/// was done. During the stop operation, the pool allocation state
/// changes first to stopping and then to steady. A resize operation
/// need not be an explicit resize pool request; this API can also be
/// used to halt the initial sizing of the pool when it is created.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolStopResizeHeaders>> StopResizeWithHttpMessagesAsync(string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the pool. For
/// example, if the pool has a start task associated with it and if
/// start task is not specified with this request, then the Batch
/// service will remove the existing start task.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolUpdatePropertiesHeaders>> UpdatePropertiesWithHttpMessagesAsync(string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <remarks>
/// During an upgrade, the Batch service upgrades each compute node in
/// the pool. When a compute node is chosen for upgrade, any tasks
/// running on that node are removed from the node and returned to the
/// queue to be rerun later (or on a different compute node). The node
/// will be unavailable until the upgrade is complete. This operation
/// results in temporarily reduced pool capacity as nodes are taken out
/// of service to be upgraded. Although the Batch service tries to
/// avoid upgrading all compute nodes at the same time, it does not
/// guarantee to do this (particularly on small pools); therefore, the
/// pool may be temporarily unavailable to run tasks. When this
/// operation runs, the pool state changes to upgrading. When all
/// compute nodes have finished upgrading, the pool state returns to
/// active. While the upgrade is in progress, the pool's
/// currentOSVersion reflects the OS version that nodes are upgrading
/// from, and targetOSVersion reflects the OS version that nodes are
/// upgrading to. Once the upgrade is complete, currentOSVersion is
/// updated to reflect the OS version now running on all nodes. This
/// operation can only be invoked on pools created with the
/// cloudServiceConfiguration property.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines
/// in the pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolUpgradeOSHeaders>> UpgradeOSWithHttpMessagesAsync(string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <remarks>
/// This operation can only run when the allocation state of the pool
/// is steady. When this operation runs, the allocation state changes
/// from steady to resizing.
/// </remarks>
/// <param name='poolId'>
/// The ID of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<PoolRemoveNodesHeaders>> RemoveNodesWithHttpMessagesAsync(string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the
/// response includes all pools that existed in the account in the time
/// range of the returned aggregation intervals. If you do not specify
/// a $filter clause including a startTime or endTime these filters
/// default to the start and end times of the last aggregation interval
/// currently available; that is, only the last aggregation interval is
/// returned.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<PoolUsageMetrics>,PoolListUsageMetricsHeaders>> ListUsageMetricsNextWithHttpMessagesAsync(string nextPageLink, PoolListUsageMetricsNextOptions poolListUsageMetricsNextOptions = default(PoolListUsageMetricsNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudPool>,PoolListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using System.Collections;
using VolumetricLines.Utils;
namespace VolumetricLines
{
/// <summary>
/// Render a line strip of volumetric lines
///
/// Based on the Volumetric lines algorithm by Sebastien Hillaire
/// http://sebastien.hillaire.free.fr/index.php?option=com_content&view=article&id=57&Itemid=74
///
/// Thread in the Unity3D Forum:
/// http://forum.unity3d.com/threads/181618-Volumetric-lines
///
/// Unity3D port by Johannes Unterguggenberger
/// johannes.unterguggenberger@gmail.com
///
/// Thanks to Michael Probst for support during development.
///
/// Thanks for bugfixes and improvements to Unity Forum User "Mistale"
/// http://forum.unity3d.com/members/102350-Mistale
///
/// /// Shader code optimization and cleanup by Lex Darlog (aka DRL)
/// http://forum.unity3d.com/members/lex-drl.67487/
///
/// </summary>
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(Renderer))]
[ExecuteInEditMode]
public class VolumetricLineStripBehavior : MonoBehaviour
{
#region private variables
/// <summary>
/// Template material to be used
/// </summary>
[SerializeField]
public Material m_templateMaterial;
/// <summary>
/// Set to false in order to change the material's properties as specified in this script.
/// Set to true in order to *initially* leave the material's properties as they are in the template material.
/// </summary>
[SerializeField]
private bool m_doNotOverwriteTemplateMaterialProperties;
/// <summary>
/// Line Color
/// </summary>
[SerializeField]
private Color m_lineColor;
/// <summary>
/// The width of the line
/// </summary>
[SerializeField]
private float m_lineWidth;
/// <summary>
/// Light saber factor
/// </summary>
[SerializeField]
[Range(0.0f, 1.0f)]
private float m_lightSaberFactor;
/// <summary>
/// This GameObject's specific material
/// </summary>
private Material m_material;
/// <summary>
/// This GameObject's mesh filter
/// </summary>
private MeshFilter m_meshFilter;
/// <summary>
/// The vertices of the line
/// </summary>
[SerializeField]
private Vector3[] m_lineVertices;
#endregion
#region properties
/// <summary>
/// Gets or sets the tmplate material.
/// Setting this will only have an impact once.
/// Subsequent changes will be ignored.
/// </summary>
public Material TemplateMaterial
{
get { return m_templateMaterial; }
set { m_templateMaterial = value; }
}
/// <summary>
/// Gets or sets whether or not the template material properties
/// should be used (false) or if the properties of this MonoBehavior
/// instance should be used (true, default).
/// Setting this will only have an impact once, and then only if it
/// is set before TemplateMaterial has been assigned.
/// </summary>
public bool DoNotOverwriteTemplateMaterialProperties
{
get { return m_doNotOverwriteTemplateMaterialProperties; }
set { m_doNotOverwriteTemplateMaterialProperties = value; }
}
/// <summary>
/// Get or set the line color of this volumetric line's material
/// </summary>
public Color LineColor
{
get { return m_lineColor; }
set
{
CreateMaterial();
if (null != m_material)
{
m_lineColor = value;
m_material.color = m_lineColor;
}
}
}
/// <summary>
/// Get or set the line width of this volumetric line's material
/// </summary>
public float LineWidth
{
get { return m_lineWidth; }
set
{
CreateMaterial();
if (null != m_material)
{
m_lineWidth = value;
m_material.SetFloat("_LineWidth", m_lineWidth);
}
}
}
/// <summary>
/// Get or set the light saber factor of this volumetric line's material
/// </summary>
public float LightSaberFactor
{
get { return m_lightSaberFactor; }
set
{
CreateMaterial();
if (null != m_material)
{
m_lightSaberFactor = value;
m_material.SetFloat("_LightSaberFactor", m_lightSaberFactor);
}
}
}
/// <summary>
/// Gets the vertices of this line strip
/// </summary>
public Vector3[] LineVertices
{
get { return m_lineVertices; }
}
#endregion
#region methods
/// <summary>
/// Creates a copy of the template material for this instance
/// </summary>
private void CreateMaterial()
{
if (null != m_templateMaterial && null == m_material)
{
m_material = Material.Instantiate(m_templateMaterial);
GetComponent<MeshRenderer>().sharedMaterial = m_material;
SetAllMaterialProperties();
}
}
/// <summary>
/// Destroys the copy of the template material which was used for this instance
/// </summary>
private void DestroyMaterial()
{
if (null != m_material)
{
DestroyImmediate(m_material);
m_material = null;
}
}
/// <summary>
/// Sets all material properties (color, width, start-, endpos)
/// </summary>
private void SetAllMaterialProperties()
{
UpdateLineVertices(m_lineVertices);
if (null != m_material)
{
if (!m_doNotOverwriteTemplateMaterialProperties)
{
m_material.color = m_lineColor;
m_material.SetFloat("_LineWidth", m_lineWidth);
m_material.SetFloat("_LightSaberFactor", m_lightSaberFactor);
}
m_material.SetFloat("_LineScale", transform.GetGlobalUniformScaleForLineWidth());
}
}
/// <summary>
/// Updates the vertices of this VolumetricLineStrip.
/// This is an expensive operation.
/// </summary>
/// <param name="m_newSetOfVertices">M_new set of vertices.</param>
public void UpdateLineVertices(Vector3[] m_newSetOfVertices)
{
if (null == m_newSetOfVertices)
{
return;
}
if (m_newSetOfVertices.Length < 3)
{
Debug.LogError("Add at least 3 vertices to the VolumetricLineStrip");
return;
}
m_lineVertices = m_newSetOfVertices;
// fill vertex positions, and indices
// 2 for each position, + 2 for the start, + 2 for the end
Vector3[] vertexPositions = new Vector3[m_lineVertices.Length * 2 + 4];
// there are #vertices - 2 faces, and 3 indices each
int[] indices = new int[(m_lineVertices.Length * 2 + 2) * 3];
int v = 0;
int x = 0;
vertexPositions[v++] = m_lineVertices[0];
vertexPositions[v++] = m_lineVertices[0];
for (int i = 0; i < m_lineVertices.Length; ++i)
{
vertexPositions[v++] = m_lineVertices[i];
vertexPositions[v++] = m_lineVertices[i];
indices[x++] = v - 2;
indices[x++] = v - 3;
indices[x++] = v - 4;
indices[x++] = v - 1;
indices[x++] = v - 2;
indices[x++] = v - 3;
}
vertexPositions[v++] = m_lineVertices[m_lineVertices.Length - 1];
vertexPositions[v++] = m_lineVertices[m_lineVertices.Length - 1];
indices[x++] = v - 2;
indices[x++] = v - 3;
indices[x++] = v - 4;
indices[x++] = v - 1;
indices[x++] = v - 2;
indices[x++] = v - 3;
// fill texture coordinates and vertex offsets
Vector2[] texCoords = new Vector2[vertexPositions.Length];
Vector2[] vertexOffsets = new Vector2[vertexPositions.Length];
int t = 0;
int o = 0;
texCoords[t++] = new Vector2(1.0f, 0.0f);
texCoords[t++] = new Vector2(1.0f, 1.0f);
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
vertexOffsets[o++] = new Vector2(1.0f, -1.0f);
vertexOffsets[o++] = new Vector2(1.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
for (int i = 1; i < m_lineVertices.Length - 1; ++i)
{
if ((i & 0x1) == 0x1)
{
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
}
else
{
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
}
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
}
texCoords[t++] = new Vector2(0.5f, 0.0f);
texCoords[t++] = new Vector2(0.5f, 1.0f);
texCoords[t++] = new Vector2(0.0f, 0.0f);
texCoords[t++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, 1.0f);
vertexOffsets[o++] = new Vector2(0.0f, -1.0f);
vertexOffsets[o++] = new Vector2(1.0f, 1.0f);
vertexOffsets[o++] = new Vector2(1.0f, -1.0f);
// fill previous and next positions
Vector3[] prevPositions = new Vector3[vertexPositions.Length];
Vector4[] nextPositions = new Vector4[vertexPositions.Length];
int p = 0;
int n = 0;
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
prevPositions[p++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
nextPositions[n++] = m_lineVertices[1];
for (int i = 1; i < m_lineVertices.Length - 1; ++i)
{
prevPositions[p++] = m_lineVertices[i - 1];
prevPositions[p++] = m_lineVertices[i - 1];
nextPositions[n++] = m_lineVertices[i + 1];
nextPositions[n++] = m_lineVertices[i + 1];
}
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
prevPositions[p++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
nextPositions[n++] = m_lineVertices[m_lineVertices.Length - 2];
// Need to set vertices before assigning new Mesh to the MeshFilter's mesh property
Mesh mesh = new Mesh();
mesh.vertices = vertexPositions;
mesh.normals = prevPositions;
mesh.tangents = nextPositions;
mesh.uv = texCoords;
mesh.uv2 = vertexOffsets;
mesh.SetIndices(indices, MeshTopology.Triangles, 0);
mesh.RecalculateBounds();
GetComponent<MeshFilter>().mesh = mesh;
}
#endregion
#region event functions
void Start ()
{
UpdateLineVertices(m_lineVertices);
CreateMaterial();
}
void OnDestroy()
{
DestroyMaterial();
}
void Update()
{
if (transform.hasChanged && null != m_material)
{
m_material.SetFloat("_LineScale", transform.GetGlobalUniformScaleForLineWidth());
}
}
void OnValidate()
{
// This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
// => make sure, everything stays up-to-date
CreateMaterial();
SetAllMaterialProperties();
}
void OnDrawGizmos()
{
Gizmos.color = Color.green;
for (int i=0; i < m_lineVertices.Length - 1; ++i)
{
Gizmos.DrawLine(gameObject.transform.TransformPoint(m_lineVertices[i]), gameObject.transform.TransformPoint(m_lineVertices[i+1]));
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace AspxCommerce.USPS
{
public class USPSPackage
{ //MailType =packagetype
public USPSPackage()
{
AddressServiceRequested = false;
SeparateReceiptPage = false;
// _labelType = LabelType.FullLabel;
// _labelImageType = LabelImageType.TIF;
// _serviceType = ServiceType.ALL;
}
private LabelType _labelType;
public LabelType LabelType
{
get { return _labelType; }
set { _labelType = value; }
}
private DestinationAddress _shipToAddress = new DestinationAddress();
public DestinationAddress ShipToAddress
{
get { return _shipToAddress; }
set { _shipToAddress = value; }
}
private string _serviceType = "ALL";
public string ServiceType
{
get { return _serviceType; }
set { _serviceType = value; }
}
public bool SeparateReceiptPage { get; set; }
private LabelImageType _labelImageType = LabelImageType.PDF;
public LabelImageType LabelImageType
{
get { return _labelImageType; }
set { _labelImageType = value; }
}
private DateTime _shipDate = DateTime.Now;
public DateTime ShipDate
{
get { return _shipDate; }
set { _shipDate = value; }
}
private string _referenceNumber = "";
public string ReferenceNumber
{
get { return _referenceNumber; }
set { _referenceNumber = value; }
}
public bool AddressServiceRequested { get; set; }
public byte[] ShippingLabel { get; set; }
public PackageType PackageType { get; set; }
private PackageSize _packageSize = PackageSize.Regular;
public PackageSize PackageSize
{
get { return _packageSize; }
set { _packageSize = value; }
}
public decimal ValueOfContents { get; set; }
// <Pounds>0</Pounds> <Ounces>3</Ounces>
// <Width/> <Length/> <Height/> <Girth/>
public bool Machinable { get; set; }
private Container _container = Container.NONE;
public Container Container
{
get { return _container; }
set { _container = value; }
}
public string WeightUnit { get; set; }
public decimal WeightValue { get; set; }
public decimal Width { get; set; }
public decimal Height { get; set; }
public decimal Length { get; set; }
public int Girth { get; set; }
public decimal Pounds { get; set; }
public int Quantity { get; set; }
private GiftFlag _giftFlag = GiftFlag.N;
public GiftFlag GiftFlag
{
get { return _giftFlag; }
set { _giftFlag = value; }
}
private PoBoxFlag _poBoxFlag = PoBoxFlag.N;
public PoBoxFlag PoBoxFlag
{
get { return _poBoxFlag; }
set { _poBoxFlag = value; }
}
private CommercialFlag _commercialFlag = CommercialFlag.N;
public CommercialFlag CommercialFlag
{
get { return _commercialFlag; }
set { _commercialFlag = value; }
}
private Size _size = Size.REGULAR;
public Size Size
{
get { return _size; }
set { _size = value; }
}
private MailType _mailType = MailType.Package;
public MailType MailType
{
get { return _mailType; }
set { _mailType = value; }
}
}
public enum PackageType { None, Flat_Rate_Envelope, Flat_Rate_Box };
public enum PackageSize { None, Regular, Large, Oversize };
public enum LabelImageType { TIF, PDF, None };
public enum ServiceType
{
Express, Priority, First_Class, Parcel_Post, Media_Mail, Library_Mail
//FIRST_CLASS,
//FIRST_CLASS_COMMERCIAL,
//FIRST_CLASS_HFP_COMMERCIAL,
//PRIORITY,
//PRIORITY_COMMERCIAL,
//PRIORITY_HFP_COMMERCIAL,
//EXPRESS,
//EXPRESS_COMMERCIAL,
//EXPRESS_SH,
//EXPRESS_SH_COMMERCIAL,
//EXPRESS_HFP,
//EXPRESS_HFP_COMMERCIAL,
//PARCEL,
//MEDIA,
//LIBRARY,
//ALL,
//ONLINE,
};
public enum LabelType { FullLabel = 1, DeliveryConfirmationBarcode = 2 };
public enum Container
{
VARIABLE, FLAT_RATE_ENVELOPE,
PADDED_FLAT_RATE_ENVELOPE,
LEGAL_FLAT_RATE_ENVELOPE,
SM_FLAT_RATE_ENVELOPE,
WINDOW_FLAT_RATE_ENVELOPE,
GIFT_CARD_FLAT_RATE_ENVELOPE,
FLAT_RATE_BOX,
SM_FLAT_RATE_BOX,
MD_FLAT_RATE_BOX,
LG_FLAT_RATE_BOX,
REGIONALRATEBOXA,
REGIONALRATEBOXB,
RECTANGULAR,
NONRECTANGULAR,
NONE
};
public enum WeightUnits
{
KGS,
LBS,
POUNDS,
OUNCES,
};
public enum POBoxFlag
{
Y, N,
};
public enum MailType
{
Package,
Postcards,
aerogrammes,
Envelope,
LargeEnvelope,
FlatRate,
};
public enum ImageLayout
{
ONEPERFILE,
ALLINONEFILE,
TRIMONEPERFILE,
TRIMALLINONEFILE
}
public enum ImageType
{
PDF,
TIF
};
public enum PoBoxFlag
{
Y,
N
} ;
public enum GiftFlag
{
Y,
N
} ;
public enum CommercialFlag
{
Y,
N
} ;
public enum Size
{
REGULAR,
LARGE
} ;
public enum FirstClassMailType
{
PARCEL,
LETTER,
FLAT
}
public enum NonDeliveryOption
{
ABANDON,
RETURN,
REDIRECT
}
public enum ContentType
{
MERCHANDISE,
SAMPLE,
GIFT,
DOCUMENTS,
RETURN,
OTHER
} ;
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System.Collections.Generic;
using System.Threading;
using MindTouch.Deki.UserSubscription;
using MindTouch.Dream;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Deki.Tests.ChangeSubscriptionTests {
[TestFixture]
public class SubscriptionManagerTests {
private static readonly log4net.ILog _log = LogUtils.CreateLog();
[Test]
public void SubscriptionManager_with_initial_subscriptions() {
List<Tuplet<string, List<XDoc>>> subs = new List<Tuplet<string, List<XDoc>>>();
List<XDoc> x = new List<XDoc>();
Tuplet<string, List<XDoc>> xSubs = new Tuplet<string, List<XDoc>>("x", x);
subs.Add(xSubs);
x.Add(new XDoc("user")
.Attr("userid", 1)
.Elem("email", "foo")
.Start("subscription.page").Attr("id", 1).Attr("depth", 0).End());
x.Add(new XDoc("user")
.Attr("userid", 2)
.Elem("email", "foo")
.Start("subscription.page").Attr("id", 1).Attr("depth", 0).End()
.Start("subscription.page").Attr("id", 2).Attr("depth", 0).End());
x.Add(new XDoc("user")
.Attr("userid", 3)
.Elem("email", "foo")
.Start("subscription.page").Attr("id", 2).Attr("depth", 0).End());
List<XDoc> y = new List<XDoc>();
Tuplet<string, List<XDoc>> ySubs = new Tuplet<string, List<XDoc>>("y", y);
subs.Add(ySubs);
y.Add(new XDoc("user")
.Attr("userid", 10)
.Elem("email", "foo")
.Start("subscription.page").Attr("id", 1).Attr("depth", 0).End());
SubscriptionManager subscriptionManager = new SubscriptionManager(new XUri("test://"), subs);
List<XDoc> subscriptions = new List<XDoc>(subscriptionManager.Subscriptions);
Assert.AreEqual(3, subscriptions.Count);
bool foundXa = false;
bool foundXb = false;
bool foundYa = false;
foreach(XDoc sub in subscriptions) {
switch(sub["channel"].AsText) {
case "event://x/deki/pages/create":
switch(sub["uri.resource"].AsText) {
case "deki://x/pages/1#depth=0":
Assert.AreEqual(2, sub["recipient"].ListLength);
foundXa = true;
break;
case "deki://x/pages/2#depth=0":
Assert.AreEqual(2, sub["recipient"].ListLength);
foundXb = true;
break;
default:
Assert.Fail("bad resource for deki X");
break;
}
break;
case "event://y/deki/pages/create":
if(sub["uri.resource"].AsText != "deki://y/pages/1#depth=0") {
Assert.Fail("bad resource for deki Y");
}
XDoc recipient = sub["recipient"];
Assert.AreEqual(1, recipient.ListLength);
Assert.AreEqual("10", recipient["@userid"].AsText);
foundYa = true;
break;
}
}
Assert.IsTrue(foundXa);
Assert.IsTrue(foundXb);
Assert.IsTrue(foundYa);
Assert.IsNotNull(subscriptionManager.GetUser("x", 1, false));
Assert.IsNotNull(subscriptionManager.GetUser("x", 2, false));
Assert.IsNotNull(subscriptionManager.GetUser("x", 3, false));
Assert.IsNull(subscriptionManager.GetUser("x", 10, false));
Assert.IsNotNull(subscriptionManager.GetUser("y", 10, false));
}
[Test]
public void SubscriptionManager_collapses_subscriptions_to_favor_infinite_depth() {
SubscriptionManager subscriptionManager = new SubscriptionManager(null, null);
UserInfo userInfo = subscriptionManager.GetUser("a", 1, true);
userInfo.AddResource(1, "0");
userInfo.AddResource(1, "infinity");
List<XDoc> subscriptions = new List<XDoc>(subscriptionManager.Subscriptions);
Assert.AreEqual(1, subscriptions.Count);
Assert.AreEqual("deki://a/pages/1#depth=infinity", subscriptions[0]["uri.resource"].AsText);
}
[Test]
public void SubscriptionManager_user_subscription_management() {
var subscriptionManager = new SubscriptionManager(null, null);
var recordEvents = new List<RecordEventArgs>();
var recordsEvent = new ManualResetEvent(false);
subscriptionManager.RecordsChanged += delegate(object sender, RecordEventArgs e) {
recordEvents.Add(e);
recordsEvent.Set();
};
SubscriptionEventArgs subscriptionEventArgs = null;
var subscriptionsFired = 0;
var subscriptionsEvent = new ManualResetEvent(false);
subscriptionManager.SubscriptionsChanged += delegate(object sender, SubscriptionEventArgs e) {
subscriptionEventArgs = e;
subscriptionsFired++;
subscriptionsEvent.Set();
};
_log.Debug("adding resource 1 to user 1");
recordsEvent.Reset();
subscriptionsEvent.Reset();
UserInfo userInfo1 = subscriptionManager.GetUser("a", 1, true);
userInfo1.AddResource(1, "0");
userInfo1.Save();
_log.Debug("waiting on events");
Assert.IsTrue(recordsEvent.WaitOne(2000, true));
Assert.IsTrue(subscriptionsEvent.WaitOne(2000, true));
Assert.IsNotNull(subscriptionManager.GetUser("a", 1, false));
Assert.AreEqual(1, recordEvents.Count);
Assert.AreEqual(1, subscriptionsFired);
Assert.AreEqual("a", recordEvents[0].WikiId);
Assert.AreEqual(1, recordEvents[0].User.Id);
Assert.AreEqual(1, subscriptionEventArgs.Subscriptions.Length);
Assert.AreEqual("deki://a/pages/1#depth=0", subscriptionEventArgs.Subscriptions[0]["uri.resource"].AsText);
_log.Debug("adding resource 1 to user 2");
recordsEvent.Reset();
subscriptionsEvent.Reset();
UserInfo userInfo2 = subscriptionManager.GetUser("a", 2, true);
userInfo2.AddResource(1, "0");
userInfo2.Save();
_log.Debug("waiting on events");
Assert.IsTrue(recordsEvent.WaitOne(2000, true));
Assert.IsTrue(subscriptionsEvent.WaitOne(2000, true));
Assert.IsNotNull(subscriptionManager.GetUser("a", 2, false));
Assert.AreEqual(2, recordEvents.Count);
Assert.AreEqual(2, subscriptionsFired);
Assert.AreEqual("a", recordEvents[1].WikiId);
Assert.AreEqual(2, recordEvents[1].User.Id);
Assert.AreEqual(1, subscriptionEventArgs.Subscriptions.Length);
Assert.AreEqual("deki://a/pages/1#depth=0", subscriptionEventArgs.Subscriptions[0]["uri.resource"].AsText);
Assert.AreEqual(2, subscriptionEventArgs.Subscriptions[0]["recipient"].ListLength);
_log.Debug("adding resource 2 to user 2");
recordsEvent.Reset();
subscriptionsEvent.Reset();
UserInfo userInfo2a = subscriptionManager.GetUser("a", 2, false);
userInfo2a.AddResource(2, "0");
userInfo2a.Save();
_log.Debug("waiting on events");
Assert.IsTrue(recordsEvent.WaitOne(2000, true));
Assert.IsTrue(subscriptionsEvent.WaitOne(2000, true));
UserInfo userInfo = subscriptionManager.GetUser("a", 2, false);
Assert.AreEqual(2, userInfo.Resources.Length);
Assert.AreEqual(3, recordEvents.Count);
Assert.AreEqual(3, subscriptionsFired);
Assert.AreEqual("a", recordEvents[2].WikiId);
Assert.AreEqual(2, recordEvents[2].User.Id);
Assert.AreEqual(2, subscriptionEventArgs.Subscriptions.Length);
Assert.AreEqual("deki://a/pages/2#depth=0", subscriptionEventArgs.Subscriptions[1]["uri.resource"].AsText);
Assert.AreEqual(1, subscriptionEventArgs.Subscriptions[1]["recipient"].ListLength);
_log.Debug("removing resource 1 from user 1");
recordsEvent.Reset();
subscriptionsEvent.Reset();
UserInfo userInfo1a = subscriptionManager.GetUser("a", 1, false);
userInfo1a.RemoveResource(1);
userInfo1a.Save();
_log.Debug("waiting on events");
Assert.IsTrue(recordsEvent.WaitOne(2000, true));
Assert.IsTrue(subscriptionsEvent.WaitOne(2000, true));
Assert.IsNull(subscriptionManager.GetUser("a", 1, false));
Assert.AreEqual(4, subscriptionsFired);
Assert.AreEqual(4, recordEvents.Count);
Assert.AreEqual("a", recordEvents[3].WikiId);
Assert.AreEqual(1, recordEvents[3].User.Id);
Assert.AreEqual(2, subscriptionEventArgs.Subscriptions.Length);
Assert.AreEqual("deki://a/pages/1#depth=0", subscriptionEventArgs.Subscriptions[0]["uri.resource"].AsText);
Assert.AreEqual(1, subscriptionEventArgs.Subscriptions[0]["recipient"].ListLength);
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Axiom.Animating;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
using Multiverse.Serialization.Collada;
namespace Multiverse.Serialization
{
/// <summary>
/// This is a collection of methods that help with accessing Axiom
/// hardware buffers.
/// </summary>
public class HardwareBufferHelper
{
Mesh m_AxiomMesh;
readonly log4net.ILog m_Log;
internal HardwareBufferHelper( Mesh axiomMesh, log4net.ILog log )
{
m_AxiomMesh = axiomMesh;
m_Log = log;
}
internal VertexDataEntry ExtractData( VertexElementSemantic semantic,
int vertexCount, InputSource source,
List<PointComponents> indexSets, int accessIndex )
{
float[ , ] fdata = null;
uint[ , ] idata = null;
switch( semantic )
{
case VertexElementSemantic.Diffuse:
idata = new uint[ vertexCount, 1 ];
for( int i = 0; i < vertexCount; ++i )
{
PointComponents components = indexSets[ i ];
int inputIndex = components[ accessIndex ];
ColorEx color = ColorEx.Black;
color.r = (float) source.Accessor.GetParam( "R", inputIndex );
color.g = (float) source.Accessor.GetParam( "G", inputIndex );
color.b = (float) source.Accessor.GetParam( "B", inputIndex );
if( source.Accessor.ContainsParam( "A" ) )
color.a = (float) source.Accessor.GetParam( "A", inputIndex );
idata[ i, 0 ] = Root.Instance.RenderSystem.ConvertColor( color );
}
break;
case VertexElementSemantic.TexCoords:
fdata = new float[ vertexCount, 2 ];
for( int i = 0; i < vertexCount; ++i )
{
PointComponents components = indexSets[ i ];
int inputIndex = components[ accessIndex ];
// S,T or U,V ?
if( source.Accessor.ContainsParam( "S" ) )
{
fdata[ i, 0 ] = (float) source.Accessor.GetParam( "S", inputIndex );
fdata[ i, 1 ] = 1.0f - (float) source.Accessor.GetParam( "T", inputIndex );
}
else if( source.Accessor.ContainsParam( "U" ) )
{
fdata[ i, 0 ] = (float) source.Accessor.GetParam( "U", inputIndex );
fdata[ i, 1 ] = 1.0f - (float) source.Accessor.GetParam( "V", inputIndex );
}
else
{
Debug.Assert( false, "Invalid param names" );
}
}
break;
case VertexElementSemantic.Position:
case VertexElementSemantic.Normal:
case VertexElementSemantic.Tangent:
case VertexElementSemantic.Binormal:
fdata = new float[ vertexCount, 3 ];
for( int i = 0; i < vertexCount; ++i )
{
PointComponents components = indexSets[ i ];
int inputIndex = components[ accessIndex ];
Vector3 tmp = Vector3.Zero;
tmp.x = (float) source.Accessor.GetParam( "X", inputIndex );
tmp.y = (float) source.Accessor.GetParam( "Y", inputIndex );
tmp.z = (float) source.Accessor.GetParam( "Z", inputIndex );
for( int j = 0; j < 3; ++j )
fdata[ i, j ] = tmp[ j ];
}
break;
default:
m_Log.InfoFormat( "Unknown semantic: {0}", semantic );
return null;
}
if( fdata == null && idata == null )
return null;
VertexDataEntry vde = new VertexDataEntry();
vde.semantic = semantic;
vde.fdata = fdata;
vde.idata = idata;
return vde;
}
#region Allocation methods
/// <summary>
/// Adds a vertex element to the vertexData and allocates the vertex
/// buffer and populates it with the information in the data array.
/// This variant uses the data in the mesh to determine appropriate
/// settings for the vertexBufferUsage and useVertexShadowBuffer
/// parameters.
/// </summary>
/// <param name="vertexData">
/// the vertex data object whose vertex declaration and buffer
/// bindings must be modified to include the reference to the new
/// buffer
/// </param>
/// <param name="bindIdx">the index that will be used for this buffer</param>
/// <param name="dataList">the list containing information about each elements being added</param>
internal void AllocateBuffer( VertexData vertexData, ushort bindIdx, List<VertexDataEntry> dataList )
{
AllocateBuffer( vertexData, bindIdx, dataList,
m_AxiomMesh.VertexBufferUsage,
m_AxiomMesh.UseVertexShadowBuffer );
}
/// <summary>
/// Adds a vertex element to the vertexData and allocates the vertex
/// buffer and populates it with the information in the data array.
/// </summary>
/// <param name="vertexData">
/// the vertex data object whose vertex declaration and buffer
/// bindings must be modified to include the reference to the new
/// buffer
/// </param>
/// <param name="bindIdx">the index that will be used for this buffer</param>
/// <param name="dataList">the list of raw data that will be used to populate the buffer</param>
/// <param name="vertexBufferUsage"></param>
/// <param name="useVertexShadowBuffer"></param>
internal static void AllocateBuffer( VertexData vertexData,
ushort bindIdx,
List<VertexDataEntry> dataList,
BufferUsage vertexBufferUsage,
bool useVertexShadowBuffer )
{
// vertex buffers
int offset = 0;
List<int> offsets = new List<int>();
foreach( VertexDataEntry vde in dataList )
{
VertexElementType type = vde.GetVertexElementType();
vertexData.vertexDeclaration.AddElement( bindIdx, offset, type, vde.semantic, vde.textureIndex );
offsets.Add( offset );
offset += VertexElement.GetTypeSize( type );
}
int vertexSize = vertexData.vertexDeclaration.GetVertexSize( bindIdx );
int vertexCount = vertexData.vertexCount;
HardwareVertexBuffer vBuffer =
HardwareBufferManager.Instance.CreateVertexBuffer( vertexSize,
vertexCount, vertexBufferUsage, useVertexShadowBuffer );
for( int i = 0; i < dataList.Count; ++i )
{
int vertexOffset = offsets[ i ];
if( dataList[ i ].fdata != null )
FillBuffer( vBuffer, vertexCount, vertexSize, vertexOffset, vertexSize, dataList[ i ].fdata );
else if( dataList[ i ].idata != null )
FillBuffer( vBuffer, vertexCount, vertexSize, vertexOffset, vertexSize, dataList[ i ].idata );
else
throw new Exception( "Invalid data element with no data" );
}
// bind the data
vertexData.vertexBufferBinding.SetBinding( bindIdx, vBuffer );
}
/// <summary>
/// Adds a vertex element to the vertexData and allocates the vertex
/// buffer and populates it with the information in the data array.
/// This variant uses the data in the mesh to determine appropriate
/// settings for the vertexBufferUsage and useVertexShadowBuffer
/// parameters.
/// </summary>
/// <param name="vertexData">
/// the vertex data object whose vertex declaration and buffer
/// bindings must be modified to include the reference to the new
/// buffer
/// </param>
/// <param name="type">the type of vertex element being added</param>
/// <param name="semantic">the semantic of the element being added</param>
/// <param name="bindIdx">the index that will be used for this buffer</param>
/// <param name="index">the texture index to which this buffer will apply (or 0)</param>
/// <param name="data">the raw data that will be used to populate the buffer</param>
internal void AllocateBuffer( VertexData vertexData, VertexElementType type,
VertexElementSemantic semantic,
ushort bindIdx, int index, int[] data )
{
AllocateBuffer( vertexData, type, semantic,
bindIdx, index, data,
m_AxiomMesh.VertexBufferUsage,
m_AxiomMesh.UseVertexShadowBuffer );
}
/// <summary>
/// Adds a vertex element to the vertexData and allocates the vertex
/// buffer and populates it with the information in the data array.
/// </summary>
/// <param name="vertexData">
/// the vertex data object whose vertex declaration and buffer
/// bindings must be modified to include the reference to the new
/// buffer
/// </param>
/// <param name="type">the type of vertex element being added</param>
/// <param name="semantic">the semantic of the element being added</param>
/// <param name="bindIdx">the index that will be used for this buffer</param>
/// <param name="index">the texture index to which this buffer will apply (or 0)</param>
/// <param name="data">the raw data that will be used to populate the buffer</param>
/// <param name="vertexBufferUsage"></param>
/// <param name="useVertexShadowBuffer"></param>
internal static void AllocateBuffer( VertexData vertexData, VertexElementType type,
VertexElementSemantic semantic,
ushort bindIdx, int index, int[] data,
BufferUsage vertexBufferUsage,
bool useVertexShadowBuffer )
{
// vertex buffers
vertexData.vertexDeclaration.AddElement( bindIdx, 0, type, semantic, index );
int vertexSize = vertexData.vertexDeclaration.GetVertexSize( bindIdx );
int vertexCount = vertexData.vertexCount;
HardwareVertexBuffer vBuffer =
HardwareBufferManager.Instance.CreateVertexBuffer( vertexSize,
vertexCount, vertexBufferUsage, useVertexShadowBuffer );
FillBuffer( vBuffer, vertexCount, vertexSize, data );
// bind the data
vertexData.vertexBufferBinding.SetBinding( bindIdx, vBuffer );
}
#endregion Allocation methods
#region Fill Buffer methods
/// <summary>
/// Fill a vertex buffer with the contents of a two dimensional
/// float array
/// </summary>
/// <param name="vBuffer">HardwareVertexBuffer to populate</param>
/// <param name="vertexCount">the number of vertices</param>
/// <param name="vertexSize">the size of each vertex</param>
/// <param name="data">the array of data to put in the buffer</param>
internal static void FillBuffer( HardwareVertexBuffer vBuffer, int vertexCount, int vertexSize, float[ , ] data )
{
FillBuffer( vBuffer, vertexCount, vertexSize, 0, sizeof( float ) * data.GetLength( 1 ), data );
}
/// <summary>
/// Fill a vertex buffer with the contents of a two dimensional
/// float array
/// </summary>
/// <param name="vBuffer">HardwareVertexBuffer to populate</param>
/// <param name="vertexCount">the number of vertices</param>
/// <param name="vertexSize">the size of each vertex</param>
/// <param name="vertexOffset">the offset (in bytes) of this element in the vertex buffer</param>
/// <param name="vertexStride">the stride (in bytes) between vertices</param>
/// <param name="data">the array of data to put in the buffer</param>
internal static void FillBuffer( HardwareVertexBuffer vBuffer, int vertexCount, int vertexSize,
int vertexOffset, int vertexStride, float[ , ] data )
{
int count = data.GetLength( 1 );
IntPtr bufData = vBuffer.Lock( BufferLocking.Discard );
int floatStride = vertexStride / sizeof( float );
int floatOffset = vertexOffset / sizeof( float );
unsafe
{
float* pFloats = (float*) bufData.ToPointer();
for( int i = 0; i < vertexCount; ++i )
for( int j = 0; j < count; ++j )
{
Debug.Assert( sizeof( float ) * (i * floatStride + floatOffset + j) < vertexCount * vertexSize,
"Wrote off end of vertex buffer" );
pFloats[ i * floatStride + floatOffset + j ] = data[ i, j ];
}
}
// unlock the buffer
vBuffer.Unlock();
}
/// <summary>
/// Fill a vertex buffer with the contents of a two dimensional
/// float array
/// </summary>
/// <param name="vBuffer">HardwareVertexBuffer to populate</param>
/// <param name="vertexCount">the number of vertices</param>
/// <param name="vertexSize">the size of each vertex</param>
/// <param name="vertexOffset">the offset (in bytes) of this element in the vertex buffer</param>
/// <param name="vertexStride">the stride (in bytes) between vertices</param>
/// <param name="data">the array of data to put in the buffer</param>
internal static void FillBuffer( HardwareVertexBuffer vBuffer, int vertexCount, int vertexSize,
int vertexOffset, int vertexStride, uint[ , ] data )
{
int count = data.GetLength( 1 );
IntPtr bufData = vBuffer.Lock( BufferLocking.Discard );
int uintStride = vertexStride / sizeof( uint );
int uintOffset = vertexOffset / sizeof( uint );
unsafe
{
uint* pUints = (uint*) bufData.ToPointer();
for( int i = 0; i < vertexCount; ++i )
for( int j = 0; j < count; ++j )
{
Debug.Assert( sizeof( uint ) * (i * uintStride + uintOffset + j) < vertexCount * vertexSize,
"Wrote off end of vertex buffer" );
pUints[ i * uintStride + uintOffset + j ] = data[ i, j ];
}
}
// unlock the buffer
vBuffer.Unlock();
}
/// <summary>
/// Fill a vertex buffer with the contents of a one dimensional
/// integer array
/// </summary>
/// <param name="vBuffer">HardwareVertexBuffer to populate</param>
/// <param name="vertexCount">the number of vertices</param>
/// <param name="vertexSize">the size of each vertex</param>
/// <param name="data">the array of data to put in the buffer</param>
internal static void FillBuffer( HardwareVertexBuffer vBuffer, int vertexCount, int vertexSize, int[] data )
{
IntPtr bufData = vBuffer.Lock( BufferLocking.Discard );
unsafe
{
int* pInts = (int*) bufData.ToPointer();
for( int i = 0; i < vertexCount; ++i )
{
Debug.Assert( sizeof( int ) * i < vertexCount * vertexSize,
"Wrote off end of vertex buffer" );
pInts[ i ] = data[ i ];
}
}
// unlock the buffer
vBuffer.Unlock();
}
/// <summary>
/// Populate the index buffer with the information in the data array
/// </summary>
/// <param name="idxBuffer">HardwareIndexBuffer to populate</param>
/// <param name="indexCount">the number of indices</param>
/// <param name="indexType">the type of index (e.g. IndexType.Size16)</param>
/// <param name="data">the data to fill the buffer</param>
internal void FillBuffer( HardwareIndexBuffer idxBuffer, int indexCount, IndexType indexType, int[ , ] data )
{
int faceCount = data.GetLength( 0 );
int count = data.GetLength( 1 );
IntPtr indices = idxBuffer.Lock( BufferLocking.Discard );
if( indexType == IndexType.Size32 )
{
// read the ints into the buffer data
unsafe
{
int* pInts = (int*) indices.ToPointer();
for( int i = 0; i < faceCount; ++i )
for( int j = 0; j < count; ++j )
{
Debug.Assert( i * count + j < indexCount, "Wrote off end of index buffer" );
pInts[ i * count + j ] = data[ i, j ];
}
}
}
else
{
// read the shorts into the buffer data
unsafe
{
short* pShorts = (short*) indices.ToPointer();
for( int i = 0; i < faceCount; ++i )
for( int j = 0; j < count; ++j )
{
Debug.Assert( i * count + j < indexCount, "Wrote off end of index buffer" );
pShorts[ i * count + j ] = (short) data[ i, j ];
}
}
}
// unlock the buffer to commit
idxBuffer.Unlock();
}
#endregion Fill Buffer methods
/// <summary>
/// Utility method to pull a bunch of floats out of a vertex buffer.
/// </summary>
/// <param name="data"></param>
/// <param name="vBuffer"></param>
/// <param name="elem"></param>
public static void ReadBuffer( float[ , ] data, HardwareVertexBuffer vBuffer, VertexElement elem )
{
int count = data.GetLength( 1 );
IntPtr bufData = vBuffer.Lock( BufferLocking.ReadOnly );
Debug.Assert( vBuffer.VertexSize % sizeof( float ) == 0 );
Debug.Assert( elem.Offset % sizeof( float ) == 0 );
int vertexCount = vBuffer.VertexCount;
int vertexSpan = vBuffer.VertexSize / sizeof( float );
int offset = elem.Offset / sizeof( float );
unsafe
{
float* pFloats = (float*) bufData.ToPointer();
for( int i = 0; i < vertexCount; ++i )
{
for( int j = 0; j < count; ++j )
{
Debug.Assert( ((offset + i * vertexSpan + j) * sizeof( float )) < (vertexCount * vBuffer.VertexSize),
"Read off end of vertex buffer" );
data[ i, j ] = pFloats[ offset + i * vertexSpan + j ];
}
}
}
// unlock the buffer
vBuffer.Unlock();
}
#if NOT
/// <summary>
/// Fetch the data from the vBuffer into the data array
/// </summary>
/// <remarks>the data field that will be populated by this call should
/// already have the correct dimensions</remarks>
/// <param name="vBuffer">the vertex buffer with the data</param>
/// <param name="vertexCount">the number of vertices</param>
/// <param name="vertexSize">the size of each vertex</param>
/// <param name="data">the array to fill</param>
internal void GetBuffer(HardwareVertexBuffer vBuffer, int vertexCount, int vertexSize, float[,] data) {
int count = data.GetLength(1);
IntPtr bufData = vBuffer.Lock(BufferLocking.Discard);
unsafe {
float* pFloats = (float*)bufData.ToPointer();
for (int i = 0; i < vertexCount; ++i)
for (int j = 0; j < count; ++j) {
Debug.Assert(sizeof(float) * (i * count + j) < vertexCount * vertexSize,
"Read off end of index buffer");
data[i, j] = pFloats[i * count + j];
}
}
// unlock the buffer
vBuffer.Unlock();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Controllers;
using Dks.SimpleToken.Core;
using Dks.SimpleToken.Validation.WebAPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dks.SimpleToken.WebAPI.Tests
{
[TestClass]
public class WebApiValidationFilterTest
{
private const string MatchingParameter = "testParam";
private ISecureTokenProvider _securityTokenProvider;
[TestInitialize]
public void Initialize()
{
_securityTokenProvider = new DummyTokenProvider();
}
[TestMethod]
public void ShouldDetectValidToken_InWebApiFilter()
{
//Token generation
var token = _securityTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60);
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext(token);
actionContext.ActionArguments.Add(MatchingParameter, "value");
//Executing filter action
filter.OnActionExecuting(actionContext);
}
[TestMethod]
public void ShouldDetectMissingToken_InWebApiFilter()
{
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext();
actionContext.ActionArguments.Add(MatchingParameter, "value");
try
{
//Executing filter action
filter.OnActionExecuting(actionContext);
}
catch (HttpResponseException ex)
{
Assert.AreEqual(HttpStatusCode.Unauthorized, ex.Response.StatusCode);
return;
}
Assert.Fail();
}
[TestMethod]
public void ShouldDetectEmptyToken_InWebApiFilter()
{
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext(" ");
actionContext.ActionArguments.Add(MatchingParameter, "value");
try
{
//Executing filter action
filter.OnActionExecuting(actionContext);
}
catch (HttpResponseException ex)
{
Assert.AreEqual(HttpStatusCode.Unauthorized, ex.Response.StatusCode);
return;
}
Assert.Fail();
}
[TestMethod]
public void ShouldDetectInvalidToken_InWebApiFilter()
{
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext("RANDOMSTRING");
actionContext.ActionArguments.Add(MatchingParameter, "value");
try
{
//Executing filter action
filter.OnActionExecuting(actionContext);
}
catch (HttpResponseException ex)
{
Assert.AreEqual(HttpStatusCode.Unauthorized, ex.Response.StatusCode);
return;
}
Assert.Fail();
}
[TestMethod]
public void ShouldDetectExpiredToken_InWebApiFilter()
{
//Token generation
var token = _securityTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 1);
//Waiting for token to expire
Thread.Sleep(1500);
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext(token);
actionContext.ActionArguments.Add(MatchingParameter, "value");
try
{
//Executing filter action
filter.OnActionExecuting(actionContext);
}
catch (HttpResponseException ex)
{
Assert.AreEqual(HttpStatusCode.Unauthorized, ex.Response.StatusCode);
return;
}
Assert.Fail();
}
[TestMethod]
public void ShouldDetectMismatchingParametersToken_InWebApiFilter()
{
//Token generation
var token = _securityTokenProvider.GenerateToken(new Dictionary<string, string> { { MatchingParameter, "value" } }, 60);
//Filter creation
var filter = new ValidateToken(MatchingParameter);
//Filter context initialization
var actionContext = CraftFakeActionContext(token);
actionContext.ActionArguments.Add(MatchingParameter, "anothervalue");
try
{
//Executing filter action
filter.OnActionExecuting(actionContext);
}
catch (HttpResponseException ex)
{
Assert.AreEqual(HttpStatusCode.Forbidden, ex.Response.StatusCode);
return;
}
Assert.Fail();
}
private HttpActionContext CraftFakeActionContext(string token = null)
{
var config = new HttpConfiguration();
var ctx = new HttpControllerContext
{
Request = new HttpRequestMessage(
HttpMethod.Get,
"http://test" + (token == null ? null : "?token=" + token)
),
Configuration = config
};
ctx.Request.SetConfiguration(config);
config.AddCustomSecureTokenProvider(_securityTokenProvider);
return new HttpActionContext(ctx, new ReflectedHttpActionDescriptor());
}
private class DummyTokenProvider : DefaultSecureTokenProvider
{
public DummyTokenProvider() : base(new DummyTokenSerializer(), new DummyTokenProtector())
{ }
private class DummyTokenProtector : ISecureTokenProtector
{
private static readonly byte[] DummyPreamble = Encoding.UTF8.GetBytes("DUMMY::__");
public byte[] ProtectData(byte[] unprotectedData)
{
return DummyPreamble.Concat(unprotectedData).ToArray();
}
public byte[] UnprotectData(byte[] protectedData)
{
if (protectedData.Length >= DummyPreamble.Length)
{
if (protectedData.Take(DummyPreamble.Length).SequenceEqual(DummyPreamble))
{
return protectedData.Skip(DummyPreamble.Length).ToArray();
}
}
throw new ApplicationException();
}
}
private class DummyTokenSerializer : ISecureTokenSerializer
{
public byte[] SerializeToken(SecureToken token)
{
return
Encoding.UTF8.GetBytes(
$"{token.Issued:O}:::{token.Expire:O}:::{string.Join("&&&", token.Data.Select(kvp => $"{kvp.Key}==={kvp.Value}"))}"
);
}
public SecureToken DeserializeToken(byte[] serialized)
{
var str = Encoding.UTF8.GetString(serialized).Split(new[] { ":::" }, StringSplitOptions.None);
var issued = DateTimeOffset.Parse(str[0]);
var expire = DateTimeOffset.Parse(str[1]);
var dict = str[2]
.Split(new[] { "&&&" }, StringSplitOptions.None)
.Select(p => p.Split(new[] { "===" }, StringSplitOptions.None))
.ToDictionary(pa => pa[0], pa => pa[1]);
return SecureToken.Create(issued, expire, dict);
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Net;
using System.Windows.Forms;
using CookComputing.XmlRpc;
namespace WindowsApplication4
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtStateNumber;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button butGetStateName;
private System.Windows.Forms.Label labStateName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txtStateNumber1;
private System.Windows.Forms.TextBox txtStateNumber2;
private System.Windows.Forms.Button butGetStateNames;
private System.Windows.Forms.TextBox txtStateNumber3;
private System.Windows.Forms.Label labStateNames1;
private System.Windows.Forms.Label labStateNames2;
private System.Windows.Forms.Label labStateNames3;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labStateName = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.butGetStateName = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.labStateNames3 = new System.Windows.Forms.Label();
this.labStateNames2 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.txtStateNumber3 = new System.Windows.Forms.TextBox();
this.txtStateNumber2 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtStateNumber1 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.labStateNames1 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.butGetStateNames = new System.Windows.Forms.Button();
this.txtStateNumber = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// labStateName
//
this.labStateName.Location = new System.Drawing.Point(105, 48);
this.labStateName.Name = "labStateName";
this.labStateName.Size = new System.Drawing.Size(113, 16);
this.labStateName.TabIndex = 1;
//
// groupBox1
//
this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.butGetStateName,
this.labStateName,
this.label2,
this.label1});
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(247, 73);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "examples.getStateName";
//
// butGetStateName
//
this.butGetStateName.Location = new System.Drawing.Point(167, 21);
this.butGetStateName.Name = "butGetStateName";
this.butGetStateName.Size = new System.Drawing.Size(68, 21);
this.butGetStateName.TabIndex = 2;
this.butGetStateName.Text = "Get Name";
this.butGetStateName.Click += new System.EventHandler(this.butGetStateName_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 16);
this.label2.TabIndex = 0;
this.label2.Text = "State Name:";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 0;
this.label1.Text = "State Number:";
//
// groupBox2
//
this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
this.labStateNames3,
this.labStateNames2,
this.label5,
this.txtStateNumber3,
this.txtStateNumber2,
this.label4,
this.txtStateNumber1,
this.label3,
this.labStateNames1,
this.label6,
this.butGetStateNames});
this.groupBox2.Location = new System.Drawing.Point(13, 95);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(241, 193);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "examples.getStateStruct";
//
// labStateNames3
//
this.labStateNames3.Location = new System.Drawing.Point(98, 164);
this.labStateNames3.Name = "labStateNames3";
this.labStateNames3.Size = new System.Drawing.Size(113, 16);
this.labStateNames3.TabIndex = 1;
//
// labStateNames2
//
this.labStateNames2.Location = new System.Drawing.Point(100, 140);
this.labStateNames2.Name = "labStateNames2";
this.labStateNames2.Size = new System.Drawing.Size(111, 16);
this.labStateNames2.TabIndex = 1;
//
// label5
//
this.label5.Location = new System.Drawing.Point(5, 87);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(88, 16);
this.label5.TabIndex = 0;
this.label5.Text = "State Number 3:";
//
// txtStateNumber3
//
this.txtStateNumber3.Location = new System.Drawing.Point(99, 85);
this.txtStateNumber3.Name = "txtStateNumber3";
this.txtStateNumber3.Size = new System.Drawing.Size(48, 20);
this.txtStateNumber3.TabIndex = 5;
this.txtStateNumber3.Text = "";
//
// txtStateNumber2
//
this.txtStateNumber2.Location = new System.Drawing.Point(99, 58);
this.txtStateNumber2.Name = "txtStateNumber2";
this.txtStateNumber2.Size = new System.Drawing.Size(48, 20);
this.txtStateNumber2.TabIndex = 4;
this.txtStateNumber2.Text = "";
//
// label4
//
this.label4.Location = new System.Drawing.Point(4, 60);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(89, 16);
this.label4.TabIndex = 0;
this.label4.Text = "State Number 2:";
//
// txtStateNumber1
//
this.txtStateNumber1.Location = new System.Drawing.Point(99, 29);
this.txtStateNumber1.Name = "txtStateNumber1";
this.txtStateNumber1.Size = new System.Drawing.Size(48, 20);
this.txtStateNumber1.TabIndex = 3;
this.txtStateNumber1.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(3, 31);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(91, 16);
this.label3.TabIndex = 0;
this.label3.Text = "State Number 1:";
//
// labStateNames1
//
this.labStateNames1.Location = new System.Drawing.Point(99, 114);
this.labStateNames1.Name = "labStateNames1";
this.labStateNames1.Size = new System.Drawing.Size(113, 16);
this.labStateNames1.TabIndex = 1;
//
// label6
//
this.label6.Location = new System.Drawing.Point(6, 114);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(80, 16);
this.label6.TabIndex = 0;
this.label6.Text = "State Names:";
//
// butGetStateNames
//
this.butGetStateNames.Location = new System.Drawing.Point(163, 33);
this.butGetStateNames.Name = "butGetStateNames";
this.butGetStateNames.Size = new System.Drawing.Size(71, 21);
this.butGetStateNames.TabIndex = 6;
this.butGetStateNames.Text = "Get Names";
this.butGetStateNames.Click += new System.EventHandler(this.butGetStateNames_Click);
//
// txtStateNumber
//
this.txtStateNumber.Location = new System.Drawing.Point(111, 30);
this.txtStateNumber.Name = "txtStateNumber";
this.txtStateNumber.Size = new System.Drawing.Size(48, 20);
this.txtStateNumber.TabIndex = 0;
this.txtStateNumber.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(262, 295);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.groupBox2,
this.txtStateNumber,
this.groupBox1});
this.Name = "Form1";
this.Text = "BettyApp";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void butGetStateName_Click(object sender, System.EventArgs e)
{
labStateName.Text = "";
IStateName betty = XmlRpcProxyGen.Create<IStateName>();
betty.AttachLogger(new XmlRpcDebugLogger());
Cursor = Cursors.WaitCursor;
try
{
int num = Convert.ToInt32(txtStateNumber.Text);
labStateName.Text = betty.GetStateName(num);
}
catch (Exception ex)
{
HandleException(ex);
}
Cursor = Cursors.Default;
}
private void butGetStateNames_Click(object sender, System.EventArgs e)
{
labStateNames1.Text = labStateNames2.Text = labStateNames3.Text = "";
IStateName betty = (IStateName)XmlRpcProxyGen.Create(typeof(IStateName));
betty.AttachLogger(new XmlRpcDebugLogger());
StateStructRequest request;
string retstr = "";
Cursor = Cursors.WaitCursor;
try
{
request.state1 = Convert.ToInt32(txtStateNumber1.Text);
request.state2 = Convert.ToInt32(txtStateNumber2.Text);
request.state3 = Convert.ToInt32(txtStateNumber3.Text);
retstr = betty.GetStateNames(request);
String[] names = retstr.Split(',');
if (names.Length > 2)
labStateNames3.Text = names[2];
if (names.Length > 1)
labStateNames2.Text = names[1];
if (names.Length > 0)
labStateNames1.Text = names[0];
}
catch (Exception ex)
{
HandleException(ex);
}
Cursor = Cursors.Default;
}
private void HandleException(Exception ex)
{
string msgBoxTitle = "Error";
try
{
throw ex;
}
catch(XmlRpcFaultException fex)
{
MessageBox.Show("Fault Response: " + fex.FaultCode + " "
+ fex.FaultString, msgBoxTitle,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(WebException webEx)
{
MessageBox.Show("WebException: " + webEx.Message, msgBoxTitle,
MessageBoxButtons.OK, MessageBoxIcon.Error);
if (webEx.Response != null)
webEx.Response.Close();
}
catch(Exception excep)
{
MessageBox.Show(excep.Message, msgBoxTitle,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class CartonType : IEquatable<CartonType>
{
/// <summary>
/// Initializes a new instance of the <see cref="CartonType" /> class.
/// Initializes a new instance of the <see cref="CartonType" />class.
/// </summary>
/// <param name="Abbreviation">Abbreviation (required).</param>
/// <param name="Name">Name (required).</param>
/// <param name="LengthIn">LengthIn (required).</param>
/// <param name="WidthIn">WidthIn (required).</param>
/// <param name="HeightIn">HeightIn (required).</param>
/// <param name="InnerLengthIn">InnerLengthIn (required).</param>
/// <param name="InnerWidthIn">InnerWidthIn (required).</param>
/// <param name="InnerHeightIn">InnerHeightIn (required).</param>
/// <param name="WeightLbs">WeightLbs.</param>
/// <param name="LobId">LobId (required).</param>
/// <param name="IsActive">IsActive (required) (default to false).</param>
/// <param name="PredefinedPackageTypeId">PredefinedPackageTypeId.</param>
/// <param name="CustomFields">CustomFields.</param>
public CartonType(string Abbreviation = null, string Name = null, double? LengthIn = null, double? WidthIn = null, double? HeightIn = null, double? InnerLengthIn = null, double? InnerWidthIn = null, double? InnerHeightIn = null, double? WeightLbs = null, int? LobId = null, bool? IsActive = null, int? PredefinedPackageTypeId = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "Abbreviation" is required (not null)
if (Abbreviation == null)
{
throw new InvalidDataException("Abbreviation is a required property for CartonType and cannot be null");
}
else
{
this.Abbreviation = Abbreviation;
}
// to ensure "Name" is required (not null)
if (Name == null)
{
throw new InvalidDataException("Name is a required property for CartonType and cannot be null");
}
else
{
this.Name = Name;
}
// to ensure "LengthIn" is required (not null)
if (LengthIn == null)
{
throw new InvalidDataException("LengthIn is a required property for CartonType and cannot be null");
}
else
{
this.LengthIn = LengthIn;
}
// to ensure "WidthIn" is required (not null)
if (WidthIn == null)
{
throw new InvalidDataException("WidthIn is a required property for CartonType and cannot be null");
}
else
{
this.WidthIn = WidthIn;
}
// to ensure "HeightIn" is required (not null)
if (HeightIn == null)
{
throw new InvalidDataException("HeightIn is a required property for CartonType and cannot be null");
}
else
{
this.HeightIn = HeightIn;
}
// to ensure "InnerLengthIn" is required (not null)
if (InnerLengthIn == null)
{
throw new InvalidDataException("InnerLengthIn is a required property for CartonType and cannot be null");
}
else
{
this.InnerLengthIn = InnerLengthIn;
}
// to ensure "InnerWidthIn" is required (not null)
if (InnerWidthIn == null)
{
throw new InvalidDataException("InnerWidthIn is a required property for CartonType and cannot be null");
}
else
{
this.InnerWidthIn = InnerWidthIn;
}
// to ensure "InnerHeightIn" is required (not null)
if (InnerHeightIn == null)
{
throw new InvalidDataException("InnerHeightIn is a required property for CartonType and cannot be null");
}
else
{
this.InnerHeightIn = InnerHeightIn;
}
// to ensure "LobId" is required (not null)
if (LobId == null)
{
throw new InvalidDataException("LobId is a required property for CartonType and cannot be null");
}
else
{
this.LobId = LobId;
}
// to ensure "IsActive" is required (not null)
if (IsActive == null)
{
throw new InvalidDataException("IsActive is a required property for CartonType and cannot be null");
}
else
{
this.IsActive = IsActive;
}
this.WeightLbs = WeightLbs;
this.PredefinedPackageTypeId = PredefinedPackageTypeId;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets Abbreviation
/// </summary>
[DataMember(Name="abbreviation", EmitDefaultValue=false)]
public string Abbreviation { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets LengthIn
/// </summary>
[DataMember(Name="lengthIn", EmitDefaultValue=false)]
public double? LengthIn { get; set; }
/// <summary>
/// Gets or Sets WidthIn
/// </summary>
[DataMember(Name="widthIn", EmitDefaultValue=false)]
public double? WidthIn { get; set; }
/// <summary>
/// Gets or Sets HeightIn
/// </summary>
[DataMember(Name="heightIn", EmitDefaultValue=false)]
public double? HeightIn { get; set; }
/// <summary>
/// Gets or Sets InnerLengthIn
/// </summary>
[DataMember(Name="innerLengthIn", EmitDefaultValue=false)]
public double? InnerLengthIn { get; set; }
/// <summary>
/// Gets or Sets InnerWidthIn
/// </summary>
[DataMember(Name="innerWidthIn", EmitDefaultValue=false)]
public double? InnerWidthIn { get; set; }
/// <summary>
/// Gets or Sets InnerHeightIn
/// </summary>
[DataMember(Name="innerHeightIn", EmitDefaultValue=false)]
public double? InnerHeightIn { get; set; }
/// <summary>
/// Gets or Sets WeightLbs
/// </summary>
[DataMember(Name="weightLbs", EmitDefaultValue=false)]
public double? WeightLbs { get; set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets IsActive
/// </summary>
[DataMember(Name="isActive", EmitDefaultValue=false)]
public bool? IsActive { get; set; }
/// <summary>
/// Gets or Sets PredefinedPackageTypeId
/// </summary>
[DataMember(Name="predefinedPackageTypeId", EmitDefaultValue=false)]
public int? PredefinedPackageTypeId { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CartonType {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Abbreviation: ").Append(Abbreviation).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" LengthIn: ").Append(LengthIn).Append("\n");
sb.Append(" WidthIn: ").Append(WidthIn).Append("\n");
sb.Append(" HeightIn: ").Append(HeightIn).Append("\n");
sb.Append(" InnerLengthIn: ").Append(InnerLengthIn).Append("\n");
sb.Append(" InnerWidthIn: ").Append(InnerWidthIn).Append("\n");
sb.Append(" InnerHeightIn: ").Append(InnerHeightIn).Append("\n");
sb.Append(" WeightLbs: ").Append(WeightLbs).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" IsActive: ").Append(IsActive).Append("\n");
sb.Append(" PredefinedPackageTypeId: ").Append(PredefinedPackageTypeId).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CartonType);
}
/// <summary>
/// Returns true if CartonType instances are equal
/// </summary>
/// <param name="other">Instance of CartonType to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartonType other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Abbreviation == other.Abbreviation ||
this.Abbreviation != null &&
this.Abbreviation.Equals(other.Abbreviation)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.LengthIn == other.LengthIn ||
this.LengthIn != null &&
this.LengthIn.Equals(other.LengthIn)
) &&
(
this.WidthIn == other.WidthIn ||
this.WidthIn != null &&
this.WidthIn.Equals(other.WidthIn)
) &&
(
this.HeightIn == other.HeightIn ||
this.HeightIn != null &&
this.HeightIn.Equals(other.HeightIn)
) &&
(
this.InnerLengthIn == other.InnerLengthIn ||
this.InnerLengthIn != null &&
this.InnerLengthIn.Equals(other.InnerLengthIn)
) &&
(
this.InnerWidthIn == other.InnerWidthIn ||
this.InnerWidthIn != null &&
this.InnerWidthIn.Equals(other.InnerWidthIn)
) &&
(
this.InnerHeightIn == other.InnerHeightIn ||
this.InnerHeightIn != null &&
this.InnerHeightIn.Equals(other.InnerHeightIn)
) &&
(
this.WeightLbs == other.WeightLbs ||
this.WeightLbs != null &&
this.WeightLbs.Equals(other.WeightLbs)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.IsActive == other.IsActive ||
this.IsActive != null &&
this.IsActive.Equals(other.IsActive)
) &&
(
this.PredefinedPackageTypeId == other.PredefinedPackageTypeId ||
this.PredefinedPackageTypeId != null &&
this.PredefinedPackageTypeId.Equals(other.PredefinedPackageTypeId)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Abbreviation != null)
hash = hash * 59 + this.Abbreviation.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.LengthIn != null)
hash = hash * 59 + this.LengthIn.GetHashCode();
if (this.WidthIn != null)
hash = hash * 59 + this.WidthIn.GetHashCode();
if (this.HeightIn != null)
hash = hash * 59 + this.HeightIn.GetHashCode();
if (this.InnerLengthIn != null)
hash = hash * 59 + this.InnerLengthIn.GetHashCode();
if (this.InnerWidthIn != null)
hash = hash * 59 + this.InnerWidthIn.GetHashCode();
if (this.InnerHeightIn != null)
hash = hash * 59 + this.InnerHeightIn.GetHashCode();
if (this.WeightLbs != null)
hash = hash * 59 + this.WeightLbs.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.IsActive != null)
hash = hash * 59 + this.IsActive.GetHashCode();
if (this.PredefinedPackageTypeId != null)
hash = hash * 59 + this.PredefinedPackageTypeId.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace FlatBuffers.Test
{
[FlatBuffersTestClass]
public class FlatBuffersFuzzTests
{
private readonly Lcg _lcg = new Lcg();
[FlatBuffersTestMethod]
public void TestObjects()
{
CheckObjects(11, 100);
}
[FlatBuffersTestMethod]
public void TestNumbers()
{
var builder = new FlatBufferBuilder(1);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddBool(true);
Assert.ArrayEqual(new byte[] { 1 }, builder.DataBuffer.ToFullArray());
builder.AddSbyte(-127);
Assert.ArrayEqual(new byte[] { 129, 1 }, builder.DataBuffer.ToFullArray());
builder.AddByte(255);
Assert.ArrayEqual(new byte[] { 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // First pad
builder.AddShort(-32222);
Assert.ArrayEqual(new byte[] { 0, 0, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // Second pad
builder.AddUshort(0xFEEE);
Assert.ArrayEqual(new byte[] { 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // no pad
builder.AddInt(-53687092);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // third pad
builder.AddUint(0x98765432);
Assert.ArrayEqual(new byte[] { 0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // no pad
}
[FlatBuffersTestMethod]
public void TestNumbers64()
{
var builder = new FlatBufferBuilder(1);
builder.AddUlong(0x1122334455667788);
Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.ToFullArray());
builder = new FlatBufferBuilder(1);
builder.AddLong(0x1122334455667788);
Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVector_1xUInt8()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(byte), 1, 1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.AddByte(1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.EndVector();
Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVector_2xUint8()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(byte), 2, 1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.AddByte(1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 1, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.AddByte(2);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.EndVector();
Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVector_1xUInt16()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(ushort), 1, 1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.AddUshort(1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.EndVector();
Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVector_2xUInt16()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(ushort), 2, 1);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray());
builder.AddUshort(0xABCD);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray());
builder.AddUshort(0xDCBA);
Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray());
builder.EndVector();
Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestCreateAsciiString()
{
var builder = new FlatBufferBuilder(1);
builder.CreateString("foo");
Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray());
builder.CreateString("moop");
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
4, 0, 0, 0,
(byte)'m', (byte)'o', (byte)'o', (byte)'p',
0, 0, 0, 0, // zero terminator with 3 byte pad
3, 0, 0, 0,
(byte)'f', (byte)'o', (byte)'o', 0
}, builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestCreateArbitarytring()
{
var builder = new FlatBufferBuilder(1);
builder.CreateString("\x01\x02\x03");
Assert.ArrayEqual(new byte[]
{
3, 0, 0, 0,
0x01, 0x02, 0x03, 0
}, builder.DataBuffer.ToFullArray()); // No padding
builder.CreateString("\x04\x05\x06\x07");
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
4, 0, 0, 0,
0x04, 0x05, 0x06, 0x07,
0, 0, 0, 0, // zero terminator with 3 byte pad
3, 0, 0, 0,
0x01, 0x02, 0x03, 0
}, builder.DataBuffer.ToFullArray()); // No padding
}
[FlatBuffersTestMethod]
public void TestEmptyVTable()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(0);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
4, 0, 4, 0,
4, 0, 0, 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithOneBool()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(1);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddBool(0, true, false);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, // padding to 16 bytes
6, 0, // vtable bytes
8, 0, // object length inc vtable offset
7, 0, // start of bool value
6, 0, 0, 0, // int32 offset for start of vtable
0, 0, 0, // padding
1, // value 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithOneBool_DefaultValue()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(1);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddBool(0, false, false);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
// No padding.
4, 0, // vtable bytes
4, 0, // end of object from here
// entry 0 is not stored (trimmed end of vtable)
4, 0, 0, 0, // int32 offset for start of vtable
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithOneInt16()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(1);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddShort(0, 0x789A, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, // padding to 16 bytes
6, 0, // vtable bytes
8, 0, // object length inc vtable offset
6, 0, // start of int16 value
6, 0, 0, 0, // int32 offset for start of vtable
0, 0, // padding
0x9A, 0x78, //value 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithTwoInt16()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(2);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddShort(0, 0x3456, 0);
builder.AddShort(1, 0x789A, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
8, 0, // vtable bytes
8, 0, // object length inc vtable offset
6, 0, // start of int16 value 0
4, 0, // start of int16 value 1
8, 0, 0, 0, // int32 offset for start of vtable
0x9A, 0x78, // value 1
0x56, 0x34, // value 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithInt16AndBool()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(2);
Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray());
builder.AddShort(0, 0x3456, 0);
builder.AddBool(1, true, false);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
8, 0, // vtable bytes
8, 0, // object length inc vtable offset
6, 0, // start of int16 value 0
5, 0, // start of bool value 1
8, 0, 0, 0, // int32 offset for start of vtable
0, 1, // padding + value 1
0x56, 0x34, // value 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithEmptyVector()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(byte), 0, 1);
var vecEnd = builder.EndVector();
builder.StartObject(1);
builder.AddOffset(0, vecEnd.Value, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
8, 0, // object length inc vtable offset
4, 0, // start of vector offset value 0
6, 0, 0, 0, // int32 offset for start of vtable
4, 0, 0, 0,
0, 0, 0, 0,
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithEmptyVectorAndScalars()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(byte), 0, 1);
var vecEnd = builder.EndVector();
builder.StartObject(2);
builder.AddShort(0, 55, 0);
builder.AddOffset(1, vecEnd.Value, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0, // Padding to 32 bytes
8, 0, // vtable bytes
12, 0, // object length inc vtable offset
10, 0, // offset to int16 value 0
4, 0, // start of vector offset value 1
8, 0, 0, 0, // int32 offset for start of vtable
8, 0, 0, 0, // value 1
0, 0, 55, 0, // value 0
0, 0, 0, 0, // length of vector (not in sctruc)
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWith_1xInt16_and_Vector_or_2xInt16()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(short), 2, 1);
builder.AddShort(0x1234);
builder.AddShort(0x5678);
var vecEnd = builder.EndVector();
builder.StartObject(2);
builder.AddOffset(1, vecEnd.Value, 0);
builder.AddShort(0, 55, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0, // Padding to 32 bytes
8, 0, // vtable bytes
12, 0, // object length
6, 0, // start of value 0 from end of vtable
8, 0, // start of value 1 from end of buffer
8, 0, 0, 0, // int32 offset for start of vtable
0, 0, 55, 0, // padding + value 0
4, 0, 0, 0, // position of vector from here
2, 0, 0, 0, // length of vector
0x78, 0x56, // vector value 0
0x34, 0x12, // vector value 1
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithAStruct_of_int8_int16_int32()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(1);
builder.Prep(4+4+4, 0);
builder.AddSbyte(55);
builder.Pad(3);
builder.AddShort(0x1234);
builder.Pad(2);
builder.AddInt(0x12345678);
var structStart = builder.Offset;
builder.AddStruct(0, structStart, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
16, 0, // object length
4, 0, // start of struct from here
6, 0, 0, 0, // int32 offset for start of vtable
0x78, 0x56, 0x34, 0x12, // struct value 2
0x00, 0x00, 0x34, 0x12, // struct value 1
0x00, 0x00, 0x00, 55, // struct value 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithAVectorOf_2xStructOf_2xInt8()
{
var builder = new FlatBufferBuilder(1);
builder.StartVector(sizeof(byte)*2, 2, 1);
builder.AddByte(33);
builder.AddByte(44);
builder.AddByte(55);
builder.AddByte(66);
var vecEnd = builder.EndVector();
builder.StartObject(1);
builder.AddOffset(0, vecEnd.Value, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, // Padding to 32 bytes
6, 0, // vtable bytes
8, 0, // object length
4, 0, // offset of vector offset
6, 0, 0, 0, // int32 offset for start of vtable
4, 0, 0, 0, // Vector start offset
2, 0, 0, 0, // Vector len
66, // vector 1, 1
55, // vector 1, 0
44, // vector 0, 1
33, // vector 0, 0
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestVTableWithSomeElements()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(2);
builder.AddByte(0, 33, 0);
builder.AddShort(1, 66, 0);
var off = builder.EndObject();
builder.Finish(off);
byte[] padded = new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, //Padding to 32 bytes
12, 0, 0, 0, // root of table, pointing to vtable offset
8, 0, // vtable bytes
8, 0, // object length
7, 0, // start of value 0
4, 0, // start of value 1
8, 0, 0, 0, // int32 offset for start of vtable
66, 0, // value 1
0, 33, // value 0
};
Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray());
// no padding in sized array
byte[] unpadded = new byte[padded.Length - 12];
Buffer.BlockCopy(padded, 12, unpadded, 0, unpadded.Length);
Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray());
}
[FlatBuffersTestMethod]
public void TestTwoFinishTable()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(2);
builder.AddByte(0, 33, 0);
builder.AddByte(1, 44, 0);
var off0 = builder.EndObject();
builder.Finish(off0);
builder.StartObject(3);
builder.AddByte(0, 55, 0);
builder.AddByte(1, 66, 0);
builder.AddByte(2, 77, 0);
var off1 = builder.EndObject();
builder.Finish(off1);
Assert.ArrayEqual(new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // padding to 64 bytes
16, 0, 0, 0, // root of table, pointing to vtable offset (obj1)
0, 0, // padding
10, 0, // vtable bytes
8, 0, // object length
7, 0, // start of value 0
6, 0, // start of value 1
5, 0, // start of value 2
10, 0, 0, 0, // int32 offset for start of vtable
0, // pad
77, // values 2, 1, 0
66,
55,
12, 0, 0, 0, // root of table, pointing to vtable offset (obj0)
8, 0, // vtable bytes
8, 0, // object length
7, 0, // start of value 0
6, 0, // start of value 1
8, 0, 0, 0, // int32 offset for start of vtable
0, 0, // pad
44, // value 1, 0
33,
},
builder.DataBuffer.ToFullArray());
}
[FlatBuffersTestMethod]
public void TestBunchOfBools()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(8);
for (var i = 0; i < 8; i++)
{
builder.AddBool(i, true, false);
}
var off = builder.EndObject();
builder.Finish(off);
byte[] padded = new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // padding to 64 bytes
24, 0, 0, 0, // root of table, pointing to vtable offset (obj0)
20, 0, // vtable bytes
12, 0, // object length
11, 0, // start of value 0
10, 0, // start of value 1
9, 0, // start of value 2
8, 0, // start of value 3
7, 0, // start of value 4
6, 0, // start of value 5
5, 0, // start of value 6
4, 0, // start of value 7
20, 0, 0, 0, // int32 offset for start of vtable
1, 1, 1, 1, // values
1, 1, 1, 1,
};
Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray());
// no padding in sized array
byte[] unpadded = new byte[padded.Length - 28];
Buffer.BlockCopy(padded, 28, unpadded, 0, unpadded.Length);
Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray());
}
[FlatBuffersTestMethod]
public void TestBunchOfBoolsSizePrefixed()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(8);
for (var i = 0; i < 8; i++)
{
builder.AddBool(i, true, false);
}
var off = builder.EndObject();
builder.FinishSizePrefixed(off);
byte[] padded = new byte[]
{
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, // padding to 64 bytes
36, 0, 0, 0, // size prefix
24, 0, 0, 0, // root of table, pointing to vtable offset (obj0)
20, 0, // vtable bytes
12, 0, // object length
11, 0, // start of value 0
10, 0, // start of value 1
9, 0, // start of value 2
8, 0, // start of value 3
7, 0, // start of value 4
6, 0, // start of value 5
5, 0, // start of value 6
4, 0, // start of value 7
20, 0, 0, 0, // int32 offset for start of vtable
1, 1, 1, 1, // values
1, 1, 1, 1,
};
Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray());
// no padding in sized array
byte[] unpadded = new byte[padded.Length - 24];
Buffer.BlockCopy(padded, 24, unpadded, 0, unpadded.Length);
Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray());
}
[FlatBuffersTestMethod]
public void TestWithFloat()
{
var builder = new FlatBufferBuilder(1);
builder.StartObject(1);
builder.AddFloat(0, 1, 0);
builder.EndObject();
Assert.ArrayEqual(new byte[]
{
0, 0,
6, 0, // vtable bytes
8, 0, // object length
4, 0, // start of value 0
6, 0, 0, 0, // int32 offset for start of vtable
0, 0, 128, 63, // value
},
builder.DataBuffer.ToFullArray());
}
private void CheckObjects(int fieldCount, int objectCount)
{
_lcg.Reset();
const int testValuesMax = 11;
var builder = new FlatBufferBuilder(1);
var objects = new int[objectCount];
for (var i = 0; i < objectCount; ++i)
{
builder.StartObject(fieldCount);
for (var j = 0; j < fieldCount; ++j)
{
var fieldType = _lcg.Next()%testValuesMax;
switch (fieldType)
{
case 0:
{
builder.AddBool(j, FuzzTestData.BoolValue, false);
break;
}
case 1:
{
builder.AddSbyte(j, FuzzTestData.Int8Value, 0);
break;
}
case 2:
{
builder.AddByte(j, FuzzTestData.UInt8Value, 0);
break;
}
case 3:
{
builder.AddShort(j, FuzzTestData.Int16Value, 0);
break;
}
case 4:
{
builder.AddUshort(j, FuzzTestData.UInt16Value, 0);
break;
}
case 5:
{
builder.AddInt(j, FuzzTestData.Int32Value, 0);
break;
}
case 6:
{
builder.AddUint(j, FuzzTestData.UInt32Value, 0);
break;
}
case 7:
{
builder.AddLong(j, FuzzTestData.Int64Value, 0);
break;
}
case 8:
{
builder.AddUlong(j, FuzzTestData.UInt64Value, 0);
break;
}
case 9:
{
builder.AddFloat(j, FuzzTestData.Float32Value, 0);
break;
}
case 10:
{
builder.AddDouble(j, FuzzTestData.Float64Value, 0);
break;
}
default:
throw new Exception("Unreachable");
}
}
var offset = builder.EndObject();
// Store the object offset
objects[i] = offset;
}
_lcg.Reset();
// Test all objects are readable and return expected values...
for (var i = 0; i < objectCount; ++i)
{
var table = new TestTable(builder.DataBuffer, builder.DataBuffer.Length - objects[i]);
for (var j = 0; j < fieldCount; ++j)
{
var fieldType = _lcg.Next() % testValuesMax;
var fc = 2 + j; // 2 == VtableMetadataFields
var f = fc * 2;
switch (fieldType)
{
case 0:
{
Assert.AreEqual(FuzzTestData.BoolValue, table.GetSlot(f, false));
break;
}
case 1:
{
Assert.AreEqual(FuzzTestData.Int8Value, table.GetSlot(f, (sbyte)0));
break;
}
case 2:
{
Assert.AreEqual(FuzzTestData.UInt8Value, table.GetSlot(f, (byte)0));
break;
}
case 3:
{
Assert.AreEqual(FuzzTestData.Int16Value, table.GetSlot(f, (short)0));
break;
}
case 4:
{
Assert.AreEqual(FuzzTestData.UInt16Value, table.GetSlot(f, (ushort)0));
break;
}
case 5:
{
Assert.AreEqual(FuzzTestData.Int32Value, table.GetSlot(f, (int)0));
break;
}
case 6:
{
Assert.AreEqual(FuzzTestData.UInt32Value, table.GetSlot(f, (uint)0));
break;
}
case 7:
{
Assert.AreEqual(FuzzTestData.Int64Value, table.GetSlot(f, (long)0));
break;
}
case 8:
{
Assert.AreEqual(FuzzTestData.UInt64Value, table.GetSlot(f, (ulong)0));
break;
}
case 9:
{
Assert.AreEqual(FuzzTestData.Float32Value, table.GetSlot(f, (float)0));
break;
}
case 10:
{
Assert.AreEqual(FuzzTestData.Float64Value, table.GetSlot(f, (double)0));
break;
}
default:
throw new Exception("Unreachable");
}
}
}
}
}
}
| |
using System.Collections.Immutable;
using System.Text.Json;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Queries.Internal;
using JsonApiDotNetCore.Queries.Internal.Parsing;
using JsonApiDotNetCore.QueryStrings;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCore.Serialization.Response;
using JsonApiDotNetCoreTests.UnitTests.Serialization.Response.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.UnitTests.Serialization.Response;
public sealed class ResponseModelAdapterTests
{
[Fact]
public void Resources_in_deeply_nested_circular_chain_are_written_in_relationship_declaration_order()
{
// Arrange
var fakers = new ResponseSerializationFakers();
Article article = fakers.Article.Generate();
article.Author = fakers.Person.Generate();
article.Author.Blogs = fakers.Blog.Generate(2).ToHashSet();
article.Author.Blogs.ElementAt(0).Reviewer = article.Author;
article.Author.Blogs.ElementAt(1).Reviewer = fakers.Person.Generate();
article.Author.FavoriteFood = fakers.Food.Generate();
article.Author.Blogs.ElementAt(1).Reviewer.FavoriteFood = fakers.Food.Generate();
IJsonApiOptions options = new JsonApiOptions();
ResponseModelAdapter responseModelAdapter = CreateAdapter(options, article.StringId, "author.blogs.reviewer.favoriteFood");
// Act
Document document = responseModelAdapter.Convert(article);
// Assert
string text = JsonSerializer.Serialize(document, new JsonSerializerOptions(options.SerializerWriteOptions));
text.Should().BeJson(@"{
""data"": {
""type"": ""articles"",
""id"": ""1"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""author"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
},
""included"": [
{
""type"": ""people"",
""id"": ""2"",
""attributes"": {
""name"": ""Ernestine Runte""
},
""relationships"": {
""blogs"": {
""data"": [
{
""type"": ""blogs"",
""id"": ""3""
},
{
""type"": ""blogs"",
""id"": ""4""
}
]
},
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""6""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""3"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""4"",
""attributes"": {
""title"": ""I'll connect the mobile ADP card, that should card the ADP card!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""5""
}
}
}
},
{
""type"": ""people"",
""id"": ""5"",
""attributes"": {
""name"": ""Doug Shields""
},
""relationships"": {
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""7""
}
}
}
},
{
""type"": ""foods"",
""id"": ""7"",
""attributes"": {
""dish"": ""Nostrum totam harum totam voluptatibus.""
}
},
{
""type"": ""foods"",
""id"": ""6"",
""attributes"": {
""dish"": ""Illum assumenda iste quia natus et dignissimos reiciendis.""
}
}
]
}");
}
[Fact]
public void Resources_in_deeply_nested_circular_chains_are_written_in_relationship_declaration_order_without_duplicates()
{
// Arrange
var fakers = new ResponseSerializationFakers();
Article article1 = fakers.Article.Generate();
article1.Author = fakers.Person.Generate();
article1.Author.Blogs = fakers.Blog.Generate(2).ToHashSet();
article1.Author.Blogs.ElementAt(0).Reviewer = article1.Author;
article1.Author.Blogs.ElementAt(1).Reviewer = fakers.Person.Generate();
article1.Author.FavoriteFood = fakers.Food.Generate();
article1.Author.Blogs.ElementAt(1).Reviewer.FavoriteFood = fakers.Food.Generate();
Article article2 = fakers.Article.Generate();
article2.Author = article1.Author;
IJsonApiOptions options = new JsonApiOptions();
ResponseModelAdapter responseModelAdapter = CreateAdapter(options, article1.StringId, "author.blogs.reviewer.favoriteFood");
// Act
Document document = responseModelAdapter.Convert(new[]
{
article1,
article2
});
// Assert
string text = JsonSerializer.Serialize(document, new JsonSerializerOptions(options.SerializerWriteOptions));
text.Should().BeJson(@"{
""data"": [
{
""type"": ""articles"",
""id"": ""1"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""author"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
},
{
""type"": ""articles"",
""id"": ""8"",
""attributes"": {
""title"": ""I'll connect the mobile ADP card, that should card the ADP card!""
},
""relationships"": {
""author"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
}
],
""included"": [
{
""type"": ""people"",
""id"": ""2"",
""attributes"": {
""name"": ""Ernestine Runte""
},
""relationships"": {
""blogs"": {
""data"": [
{
""type"": ""blogs"",
""id"": ""3""
},
{
""type"": ""blogs"",
""id"": ""4""
}
]
},
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""6""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""3"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""4"",
""attributes"": {
""title"": ""I'll connect the mobile ADP card, that should card the ADP card!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""5""
}
}
}
},
{
""type"": ""people"",
""id"": ""5"",
""attributes"": {
""name"": ""Doug Shields""
},
""relationships"": {
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""7""
}
}
}
},
{
""type"": ""foods"",
""id"": ""7"",
""attributes"": {
""dish"": ""Nostrum totam harum totam voluptatibus.""
}
},
{
""type"": ""foods"",
""id"": ""6"",
""attributes"": {
""dish"": ""Illum assumenda iste quia natus et dignissimos reiciendis.""
}
}
]
}");
}
[Fact]
public void Resources_in_overlapping_deeply_nested_circular_chains_are_written_in_relationship_declaration_order()
{
// Arrange
var fakers = new ResponseSerializationFakers();
Article article = fakers.Article.Generate();
article.Author = fakers.Person.Generate();
article.Author.Blogs = fakers.Blog.Generate(2).ToHashSet();
article.Author.Blogs.ElementAt(0).Reviewer = article.Author;
article.Author.Blogs.ElementAt(1).Reviewer = fakers.Person.Generate();
article.Author.FavoriteFood = fakers.Food.Generate();
article.Author.Blogs.ElementAt(1).Reviewer.FavoriteFood = fakers.Food.Generate();
article.Reviewer = fakers.Person.Generate();
article.Reviewer.Blogs = fakers.Blog.Generate(1).ToHashSet();
article.Reviewer.Blogs.Add(article.Author.Blogs.ElementAt(0));
article.Reviewer.Blogs.ElementAt(0).Author = article.Reviewer;
article.Reviewer.Blogs.ElementAt(1).Author = article.Author.Blogs.ElementAt(1).Reviewer;
article.Author.Blogs.ElementAt(1).Reviewer.FavoriteSong = fakers.Song.Generate();
article.Reviewer.FavoriteSong = fakers.Song.Generate();
IJsonApiOptions options = new JsonApiOptions();
ResponseModelAdapter responseModelAdapter =
CreateAdapter(options, article.StringId, "author.blogs.reviewer.favoriteFood,reviewer.blogs.author.favoriteSong");
// Act
Document document = responseModelAdapter.Convert(article);
// Assert
string text = JsonSerializer.Serialize(document, new JsonSerializerOptions(options.SerializerWriteOptions));
text.Should().BeJson(@"{
""data"": {
""type"": ""articles"",
""id"": ""1"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""8""
}
},
""author"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
}
}
},
""included"": [
{
""type"": ""people"",
""id"": ""8"",
""attributes"": {
""name"": ""Nettie Howell""
},
""relationships"": {
""blogs"": {
""data"": [
{
""type"": ""blogs"",
""id"": ""9""
},
{
""type"": ""blogs"",
""id"": ""3""
}
]
},
""favoriteSong"": {
""data"": {
""type"": ""songs"",
""id"": ""11""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""9"",
""attributes"": {
""title"": ""The RSS bus is down, parse the mobile bus so we can parse the RSS bus!""
},
""relationships"": {
""author"": {
""data"": {
""type"": ""people"",
""id"": ""8""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""3"",
""attributes"": {
""title"": ""The SAS microchip is down, quantify the 1080p microchip so we can quantify the SAS microchip!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""2""
}
},
""author"": {
""data"": {
""type"": ""people"",
""id"": ""5""
}
}
}
},
{
""type"": ""people"",
""id"": ""2"",
""attributes"": {
""name"": ""Ernestine Runte""
},
""relationships"": {
""blogs"": {
""data"": [
{
""type"": ""blogs"",
""id"": ""3""
},
{
""type"": ""blogs"",
""id"": ""4""
}
]
},
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""6""
}
}
}
},
{
""type"": ""blogs"",
""id"": ""4"",
""attributes"": {
""title"": ""I'll connect the mobile ADP card, that should card the ADP card!""
},
""relationships"": {
""reviewer"": {
""data"": {
""type"": ""people"",
""id"": ""5""
}
}
}
},
{
""type"": ""people"",
""id"": ""5"",
""attributes"": {
""name"": ""Doug Shields""
},
""relationships"": {
""favoriteFood"": {
""data"": {
""type"": ""foods"",
""id"": ""7""
}
},
""favoriteSong"": {
""data"": {
""type"": ""songs"",
""id"": ""10""
}
}
}
},
{
""type"": ""foods"",
""id"": ""7"",
""attributes"": {
""dish"": ""Nostrum totam harum totam voluptatibus.""
}
},
{
""type"": ""songs"",
""id"": ""10"",
""attributes"": {
""title"": ""Illum assumenda iste quia natus et dignissimos reiciendis.""
}
},
{
""type"": ""foods"",
""id"": ""6"",
""attributes"": {
""dish"": ""Illum assumenda iste quia natus et dignissimos reiciendis.""
}
},
{
""type"": ""songs"",
""id"": ""11"",
""attributes"": {
""title"": ""Nostrum totam harum totam voluptatibus.""
}
}
]
}");
}
[Fact]
public void Duplicate_children_in_multiple_chains_occur_once_in_output()
{
// Arrange
var fakers = new ResponseSerializationFakers();
Person person = fakers.Person.Generate();
List<Article> articles = fakers.Article.Generate(5);
articles.ForEach(article => article.Author = person);
articles.ForEach(article => article.Reviewer = person);
IJsonApiOptions options = new JsonApiOptions();
ResponseModelAdapter responseModelAdapter = CreateAdapter(options, null, "author,reviewer");
// Act
Document document = responseModelAdapter.Convert(articles);
// Assert
document.Included.ShouldHaveCount(1);
document.Included[0].Attributes.ShouldContainKey("name").With(value => value.Should().Be(person.Name));
document.Included[0].Id.Should().Be(person.StringId);
}
private ResponseModelAdapter CreateAdapter(IJsonApiOptions options, string? primaryId, string includeChains)
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
IResourceGraph resourceGraph = new ResourceGraphBuilder(options, NullLoggerFactory.Instance)
.Add<Article, int>()
.Add<Person, int>()
.Add<Blog, int>()
.Add<Food, int>()
.Add<Song, int>()
.Build();
// @formatter:wrap_chained_method_calls restore
// @formatter:keep_existing_linebreaks restore
var request = new JsonApiRequest
{
Kind = EndpointKind.Primary,
PrimaryResourceType = resourceGraph.GetResourceType<Article>(),
PrimaryId = primaryId
};
var evaluatedIncludeCache = new EvaluatedIncludeCache();
var linkBuilder = new FakeLinkBuilder();
var metaBuilder = new FakeMetaBuilder();
var resourceDefinitionAccessor = new FakeResourceDefinitionAccessor();
var sparseFieldSetCache = new SparseFieldSetCache(Array.Empty<IQueryConstraintProvider>(), resourceDefinitionAccessor);
var requestQueryStringAccessor = new FakeRequestQueryStringAccessor();
var parser = new IncludeParser();
IncludeExpression include = parser.Parse(includeChains, request.PrimaryResourceType, null);
evaluatedIncludeCache.Set(include);
return new ResponseModelAdapter(request, options, linkBuilder, metaBuilder, resourceDefinitionAccessor, evaluatedIncludeCache, sparseFieldSetCache,
requestQueryStringAccessor);
}
private sealed class FakeLinkBuilder : ILinkBuilder
{
public TopLevelLinks? GetTopLevelLinks()
{
return null;
}
public ResourceLinks? GetResourceLinks(ResourceType resourceType, IIdentifiable resource)
{
return null;
}
public RelationshipLinks? GetRelationshipLinks(RelationshipAttribute relationship, IIdentifiable leftResource)
{
return null;
}
}
private sealed class FakeMetaBuilder : IMetaBuilder
{
public void Add(IReadOnlyDictionary<string, object?> values)
{
}
public IDictionary<string, object?>? Build()
{
return null;
}
}
private sealed class FakeResourceDefinitionAccessor : IResourceDefinitionAccessor
{
public IImmutableSet<IncludeElementExpression> OnApplyIncludes(ResourceType resourceType, IImmutableSet<IncludeElementExpression> existingIncludes)
{
return existingIncludes;
}
public FilterExpression? OnApplyFilter(ResourceType resourceType, FilterExpression? existingFilter)
{
return existingFilter;
}
public SortExpression? OnApplySort(ResourceType resourceType, SortExpression? existingSort)
{
return existingSort;
}
public PaginationExpression? OnApplyPagination(ResourceType resourceType, PaginationExpression? existingPagination)
{
return existingPagination;
}
public SparseFieldSetExpression? OnApplySparseFieldSet(ResourceType resourceType, SparseFieldSetExpression? existingSparseFieldSet)
{
return existingSparseFieldSet;
}
public object? GetQueryableHandlerForQueryStringParameter(Type resourceClrType, string parameterName)
{
return null;
}
public IDictionary<string, object?>? GetMeta(ResourceType resourceType, IIdentifiable resourceInstance)
{
return null;
}
public Task OnPrepareWriteAsync<TResource>(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.CompletedTask;
}
public Task<IIdentifiable?> OnSetToOneRelationshipAsync<TResource>(TResource leftResource, HasOneAttribute hasOneRelationship,
IIdentifiable? rightResourceId, WriteOperationKind writeOperation, CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.FromResult(rightResourceId);
}
public Task OnSetToManyRelationshipAsync<TResource>(TResource leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
WriteOperationKind writeOperation, CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.CompletedTask;
}
public Task OnAddToRelationshipAsync<TResource, TId>(TId leftResourceId, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
where TResource : class, IIdentifiable<TId>
{
return Task.CompletedTask;
}
public Task OnRemoveFromRelationshipAsync<TResource>(TResource leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.CompletedTask;
}
public Task OnWritingAsync<TResource>(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.CompletedTask;
}
public Task OnWriteSucceededAsync<TResource>(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken)
where TResource : class, IIdentifiable
{
return Task.CompletedTask;
}
public void OnDeserialize(IIdentifiable resource)
{
}
public void OnSerialize(IIdentifiable resource)
{
}
}
private sealed class FakeRequestQueryStringAccessor : IRequestQueryStringAccessor
{
public IQueryCollection Query { get; } = new QueryCollection(0);
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UnsafeKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
// This will be fixed once we have accessibility for members
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
{
await VerifyAbsenceAsync(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAbstract()
{
await VerifyKeywordAsync(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafe()
{
await VerifyAbsenceAsync(@"unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticUnsafe()
{
await VerifyAbsenceAsync(@"static unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafeStatic()
{
await VerifyAbsenceAsync(@"unsafe static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterSealed()
{
await VerifyKeywordAsync(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatic()
{
await VerifyKeywordAsync(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInUsingDirective()
{
await VerifyAbsenceAsync(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
{
await VerifyAbsenceAsync(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
{
await VerifyAbsenceAsync(@"delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedVirtual()
{
await VerifyKeywordAsync(
@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideSwitchBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (E) {
case 0:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUnsafe_InMethod()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"unsafe $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInterfaceModifiers()
{
await VerifyKeywordAsync(
@"public $$ interface IBinaryDocumentMemoryBlock {");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EasyNetQ
{
/// <summary>
/// Collection of precondition methods for qualifying method arguments.
/// </summary>
internal static class Preconditions
{
/// <summary>
/// Ensures that <paramref name="value"/> is not null.
/// </summary>
/// <param name="value">
/// The value to check, must not be null.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="name"/> is blank.
/// </exception>
public static void CheckNotNull<T>(T value, string name)
{
CheckNotNull(value, name, string.Format("{0} must not be null", name));
}
/// <summary>
/// Ensures that <paramref name="value"/> is not null.
/// </summary>
/// <param name="value">
/// The value to check, must not be null.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="value"/>
/// is null, must not be blank.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="name"/> or <paramref name="message"/> are
/// blank.
/// </exception>
public static void CheckNotNull<T>(T value, string name, string message)
{
if (value == null)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentNullException(name, message);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is not blank.
/// </summary>
/// <param name="value">
/// The value to check, must not be blank.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="value"/>
/// is blank, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/>, <paramref name="name"/>, or
/// <paramref name="message"/> are blank.
/// </exception>
public static void CheckNotBlank(string value, string name, string message)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("name must not be blank", "name");
}
if (string.IsNullOrWhiteSpace(message))
{
throw new ArgumentException("message must not be blank", "message");
}
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is not blank.
/// </summary>
/// <param name="value">
/// The value to check, must not be blank.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> or <paramref name="name"/> are
/// blank.
/// </exception>
public static void CheckNotBlank(string value, string name)
{
CheckNotBlank(value, name, string.Format("{0} must not be blank", name));
}
/// <summary>
/// Ensures that <paramref name="collection"/> contains at least one
/// item.
/// </summary>
/// <param name="collection">
/// The collection to check, must not be null or empty.
/// </param>
/// <param name="name">
/// The name of the parameter the collection is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is empty, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="collection"/> is empty, or if
/// <paramref name="value"/> or <paramref name="name"/> are blank.
/// </exception>
public static void CheckAny<T>(IEnumerable<T> collection, string name, string message)
{
if (collection == null || !collection.Any())
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is true.
/// </summary>
/// <param name="value">
/// The value to check, must be true.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is false, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> is false, or if <paramref name="name"/>
/// or <paramref name="message"/> are blank.
/// </exception>
public static void CheckTrue(bool value, string name, string message)
{
if (!value)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
/// <summary>
/// Ensures that <paramref name="value"/> is false.
/// </summary>
/// <param name="value">
/// The value to check, must be false.
/// </param>
/// <param name="name">
/// The name of the parameter the value is taken from, must not be
/// blank.
/// </param>
/// <param name="message">
/// The message to provide to the exception if <paramref name="collection"/>
/// is true, must not be blank.
/// </param>
/// <exception cref="ArgumentException">
/// Thrown if <paramref name="value"/> is true, or if <paramref name="name"/>
/// or <paramref name="message"/> are blank.
/// </exception>
public static void CheckFalse(bool value, string name, string message)
{
if (value)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
public static void CheckShortString(string value, string name)
{
CheckNotNull(value, name);
if (value.Length > 255)
{
throw new ArgumentException(string.Format("Argument '{0}' must be less than or equal to 255 characters.", name));
}
}
public static void CheckTypeMatches(Type expectedType, object value, string name, string message)
{
bool assignable = expectedType.IsAssignableFrom(value.GetType());
if (!assignable)
{
CheckNotBlank(name, "name", "name must not be blank");
CheckNotBlank(message, "message", "message must not be blank");
throw new ArgumentException(message, name);
}
}
public static void CheckLess(TimeSpan value, TimeSpan maxValue, string name)
{
if (value < maxValue)
return;
throw new ArgumentOutOfRangeException(name, string.Format("Arguments {0} must be less than maxValue", name));
}
public static void CheckNull<T>(T value, string name)
{
if (value == null)
return;
throw new ArgumentException(string.Format("{0} must not be null", name), name);
}
}
}
| |
using System;
using System.Collections.Generic;
using AutoMapper.Mappers;
using Should;
using Xunit;
using System.Reflection;
using System.Linq;
namespace AutoMapper.UnitTests
{
namespace MemberResolution
{
public class When_mapping_derived_classes_in_arrays : AutoMapperSpecBase
{
private DtoObject[] _result;
public class ModelObject
{
public string BaseString { get; set; }
}
public class ModelSubObject : ModelObject
{
public string SubString { get; set; }
}
public class DtoObject
{
public string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new[]
{
new ModelObject {BaseString = "Base1"},
new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
cfg.CreateMap<ModelSubObject, DtoSubObject>();
});
_result = (DtoObject[]) Mapper.Map(model, typeof (ModelObject[]), typeof (DtoObject[]));
}
[Fact]
public void Should_map_both_the_base_and_sub_objects()
{
_result.Length.ShouldEqual(2);
_result[0].BaseString.ShouldEqual("Base1");
_result[1].BaseString.ShouldEqual("Base2");
}
[Fact]
public void Should_map_to_the_correct_respective_dto_types()
{
_result[0].ShouldBeType(typeof (DtoObject));
_result[1].ShouldBeType(typeof (DtoSubObject));
}
}
public class When_mapping_derived_classes : AutoMapperSpecBase
{
private DtoObject _result;
public class ModelObject
{
public string BaseString { get; set; }
}
public class ModelSubObject : ModelObject
{
public string SubString { get; set; }
}
public class DtoObject
{
public string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
cfg.CreateMap<ModelSubObject, DtoSubObject>();
});
}
protected override void Because_of()
{
var model = new ModelSubObject { BaseString = "Base2", SubString = "Sub2" };
_result = Mapper.Map<ModelObject, DtoObject>(model);
}
[Fact]
public void Should_map_to_the_correct_dto_types()
{
_result.ShouldBeType(typeof(DtoSubObject));
}
}
public class When_mapping_derived_classes_from_intefaces_to_abstract : AutoMapperSpecBase
{
private DtoObject[] _result;
public interface IModelObject
{
string BaseString { get; set; }
}
public class ModelSubObject : IModelObject
{
public string SubString { get; set; }
public string BaseString { get; set; }
}
public abstract class DtoObject
{
public virtual string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new IModelObject[]
{
new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
Mapper.Initialize(cfg =>
{
cfg.CreateMap<IModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
cfg.CreateMap<ModelSubObject, DtoSubObject>();
});
_result = (DtoObject[]) Mapper.Map(model, typeof (IModelObject[]), typeof (DtoObject[]));
}
[Fact]
public void Should_map_both_the_base_and_sub_objects()
{
_result.Length.ShouldEqual(1);
_result[0].BaseString.ShouldEqual("Base2");
}
[Fact]
public void Should_map_to_the_correct_respective_dto_types()
{
_result[0].ShouldBeType(typeof (DtoSubObject));
((DtoSubObject) _result[0]).SubString.ShouldEqual("Sub2");
}
}
public class When_mapping_derived_classes_as_property_of_top_object : AutoMapperSpecBase
{
private DtoModel _result;
public class Model
{
public IModelObject Object { get; set; }
}
public interface IModelObject
{
string BaseString { get; set; }
}
public class ModelSubObject : IModelObject
{
public string SubString { get; set; }
public string BaseString { get; set; }
}
public class DtoModel
{
public DtoObject Object { get; set; }
}
public abstract class DtoObject
{
public virtual string BaseString { get; set; }
}
public class DtoSubObject : DtoObject
{
public string SubString { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Model, DtoModel>();
cfg.CreateMap<IModelObject, DtoObject>()
.Include<ModelSubObject, DtoSubObject>();
cfg.CreateMap<ModelSubObject, DtoSubObject>();
});
}
[Fact]
public void Should_map_object_to_sub_object()
{
var model = new Model
{
Object = new ModelSubObject {BaseString = "Base2", SubString = "Sub2"}
};
_result = Mapper.Map<Model, DtoModel>(model);
_result.Object.ShouldNotBeNull();
_result.Object.ShouldBeType<DtoSubObject>();
_result.Object.ShouldBeType<DtoSubObject>();
_result.Object.BaseString.ShouldEqual("Base2");
((DtoSubObject) _result.Object).SubString.ShouldEqual("Sub2");
}
}
public class When_mapping_dto_with_only_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate { get; set; }
public ModelSubObject Sub { get; set; }
public ModelSubObject Sub2 { get; set; }
public ModelSubObject SubWithExtraName { get; set; }
public ModelSubObject SubMissing { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set; }
public ModelSubSubObject SubSub { get; set; }
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set; }
}
public class ModelDto
{
public DateTime BaseDate { get; set; }
public string SubProperName { get; set; }
public string Sub2ProperName { get; set; }
public string SubWithExtraNameProperName { get; set; }
public string SubSubSubIAmACoolProperty { get; set; }
public string SubMissingSubSubIAmACoolProperty { get; set; }
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Fact]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Fact]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Fact]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Fact]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_mapping_dto_with_only_fields : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate;
public ModelSubObject Sub;
public ModelSubObject Sub2;
public ModelSubObject SubWithExtraName;
public ModelSubObject SubMissing;
}
public class ModelSubObject
{
public string ProperName;
public ModelSubSubObject SubSub;
}
public class ModelSubSubObject
{
public string IAmACoolProperty;
}
public class ModelDto
{
public DateTime BaseDate;
public string SubProperName;
public string Sub2ProperName;
public string SubWithExtraNameProperName;
public string SubSubSubIAmACoolProperty;
public string SubMissingSubSubIAmACoolProperty;
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Fact]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Fact]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Fact]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Fact]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_mapping_dto_with_fields_and_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public DateTime BaseDate { get; set;}
public ModelSubObject Sub;
public ModelSubObject Sub2 { get; set;}
public ModelSubObject SubWithExtraName;
public ModelSubObject SubMissing { get; set; }
}
public class ModelSubObject
{
public string ProperName { get; set;}
public ModelSubSubObject SubSub;
}
public class ModelSubSubObject
{
public string IAmACoolProperty { get; set;}
}
public class ModelDto
{
public DateTime BaseDate;
public string SubProperName;
public string Sub2ProperName { get; set;}
public string SubWithExtraNameProperName;
public string SubSubSubIAmACoolProperty;
public string SubMissingSubSubIAmACoolProperty { get; set;}
}
protected override void Establish_context()
{
Mapper.Reset();
var model = new ModelObject
{
BaseDate = new DateTime(2007, 4, 5),
Sub = new ModelSubObject
{
ProperName = "Some name",
SubSub = new ModelSubSubObject
{
IAmACoolProperty = "Cool daddy-o"
}
},
Sub2 = new ModelSubObject
{
ProperName = "Sub 2 name"
},
SubWithExtraName = new ModelSubObject
{
ProperName = "Some other name"
},
SubMissing = new ModelSubObject
{
ProperName = "I have a missing sub sub object"
}
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_item_in_first_level_of_hierarchy()
{
_result.BaseDate.ShouldEqual(new DateTime(2007, 4, 5));
}
[Fact]
public void Should_map_a_member_with_a_number()
{
_result.Sub2ProperName.ShouldEqual("Sub 2 name");
}
[Fact]
public void Should_map_item_in_second_level_of_hierarchy()
{
_result.SubProperName.ShouldEqual("Some name");
}
[Fact]
public void Should_map_item_with_more_items_in_property_name()
{
_result.SubWithExtraNameProperName.ShouldEqual("Some other name");
}
[Fact]
public void Should_map_item_in_any_level_of_depth_in_the_hierarchy()
{
_result.SubSubSubIAmACoolProperty.ShouldEqual("Cool daddy-o");
}
}
public class When_ignoring_a_dto_property_during_configuration : AutoMapperSpecBase
{
private TypeMap[] _allTypeMaps;
private Source _source;
public class Source
{
public string Value { get; set; }
}
public class Destination
{
public bool Ignored
{
get { return true; }
}
public string Value { get; set; }
}
[Fact]
public void Should_not_report_it_as_unmapped()
{
_allTypeMaps.AsEnumerable().ForEach(t => t.GetUnmappedPropertyNames().ShouldBeOfLength(0));
}
[Fact]
public void Should_map_successfully()
{
var destination = Mapper.Map<Source, Destination>(_source);
destination.Value.ShouldEqual("foo");
destination.Ignored.ShouldBeTrue();
}
[Fact]
public void Should_succeed_configration_check()
{
Mapper.AssertConfigurationIsValid();
}
protected override void Establish_context()
{
_source = new Source {Value = "foo"};
Mapper.CreateMap<Source, Destination>()
.ForMember(x => x.Ignored, opt => opt.Ignore());
_allTypeMaps = Mapper.GetAllTypeMaps();
}
}
public class When_mapping_dto_with_get_methods : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public string GetSomeCoolValue()
{
return "Cool value";
}
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string GetSomeOtherCoolValue()
{
return "Even cooler";
}
}
public class ModelDto
{
public string SomeCoolValue { get; set; }
public string SubSomeOtherCoolValue { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Sub = new ModelSubObject()
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_base_method_value()
{
_result.SomeCoolValue.ShouldEqual("Cool value");
}
[Fact]
public void Should_map_second_level_method_value_off_of_property()
{
_result.SubSomeOtherCoolValue.ShouldEqual("Even cooler");
}
}
public class When_mapping_a_dto_with_names_matching_properties : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public string SomeCoolValue()
{
return "Cool value";
}
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string SomeOtherCoolValue()
{
return "Even cooler";
}
}
public class ModelDto
{
public string SomeCoolValue { get; set; }
public string SubSomeOtherCoolValue { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Sub = new ModelSubObject()
};
Mapper.CreateMap<ModelObject, ModelDto>();
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_base_method_value()
{
_result.SomeCoolValue.ShouldEqual("Cool value");
}
[Fact]
public void Should_map_second_level_method_value_off_of_property()
{
_result.SubSomeOtherCoolValue.ShouldEqual("Even cooler");
}
}
public class When_mapping_with_a_dto_subtype : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public ModelSubObject Sub { get; set; }
}
public class ModelSubObject
{
public string SomeValue { get; set; }
}
public class ModelDto
{
public ModelSubDto Sub { get; set; }
}
public class ModelSubDto
{
public string SomeValue { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>();
Mapper.CreateMap<ModelSubObject, ModelSubDto>();
var model = new ModelObject
{
Sub = new ModelSubObject
{
SomeValue = "Some value"
}
};
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_the_model_sub_type_to_the_dto_sub_type()
{
_result.Sub.ShouldNotBeNull();
_result.Sub.SomeValue.ShouldEqual("Some value");
}
}
public class When_mapping_a_dto_with_a_set_only_property_and_a_get_method : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelDto
{
public int SomeValue { get; set; }
}
public class ModelObject
{
private int _someValue;
public int SomeValue
{
set { _someValue = value; }
}
public int GetSomeValue()
{
return _someValue;
}
}
protected override void Establish_context()
{
Mapper.CreateMap<ModelObject, ModelDto>();
var model = new ModelObject();
model.SomeValue = 46;
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_map_the_get_method_to_the_dto()
{
_result.SomeValue.ShouldEqual(46);
}
}
public class When_mapping_using_a_custom_member_mappings : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public int Blarg { get; set; }
public string MoreBlarg { get; set; }
public int SomeMethodToGetMoreBlarg()
{
return 45;
}
public string SomeValue { get; set; }
public ModelSubObject SomeWeirdSubObject { get; set; }
public string IAmSomeMethod()
{
return "I am some method";
}
}
public class ModelSubObject
{
public int Narf { get; set; }
public ModelSubSubObject SubSub { get; set; }
public string SomeSubValue()
{
return "I am some sub value";
}
}
public class ModelSubSubObject
{
public int Norf { get; set; }
public string SomeSubSubValue()
{
return "I am some sub sub value";
}
}
public class ModelDto
{
public int Splorg { get; set; }
public string SomeValue { get; set; }
public string SomeMethod { get; set; }
public int SubNarf { get; set; }
public string SubValue { get; set; }
public int GrandChildInt { get; set; }
public string GrandChildString { get; set; }
public int BlargPlus3 { get; set; }
public int BlargMinus2 { get; set; }
public int MoreBlarg { get; set; }
}
protected override void Establish_context()
{
var model = new ModelObject
{
Blarg = 10,
SomeValue = "Some value",
SomeWeirdSubObject = new ModelSubObject
{
Narf = 5,
SubSub = new ModelSubSubObject
{
Norf = 15
}
},
MoreBlarg = "adsfdsaf"
};
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Splorg, opt => opt.MapFrom(m => m.Blarg))
.ForMember(dto => dto.SomeMethod, opt => opt.MapFrom(m => m.IAmSomeMethod()))
.ForMember(dto => dto.SubNarf, opt => opt.MapFrom(m => m.SomeWeirdSubObject.Narf))
.ForMember(dto => dto.SubValue, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SomeSubValue()))
.ForMember(dto => dto.GrandChildInt, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.Norf))
.ForMember(dto => dto.GrandChildString, opt => opt.MapFrom(m => m.SomeWeirdSubObject.SubSub.SomeSubSubValue()))
.ForMember(dto => dto.MoreBlarg, opt => opt.MapFrom(m => m.SomeMethodToGetMoreBlarg()))
.ForMember(dto => dto.BlargPlus3, opt => opt.MapFrom(m => m.Blarg.Plus(3)))
.ForMember(dto => dto.BlargMinus2, opt => opt.MapFrom(m => m.Blarg - 2));
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Fact]
public void Should_preserve_the_existing_mapping()
{
_result.SomeValue.ShouldEqual("Some value");
}
[Fact]
public void Should_map_top_level_properties()
{
_result.Splorg.ShouldEqual(10);
}
[Fact]
public void Should_map_methods_results()
{
_result.SomeMethod.ShouldEqual("I am some method");
}
[Fact]
public void Should_map_children_properties()
{
_result.SubNarf.ShouldEqual(5);
}
[Fact]
public void Should_map_children_methods()
{
_result.SubValue.ShouldEqual("I am some sub value");
}
[Fact]
public void Should_map_grandchildren_properties()
{
_result.GrandChildInt.ShouldEqual(15);
}
[Fact]
public void Should_map_grandchildren_methods()
{
_result.GrandChildString.ShouldEqual("I am some sub sub value");
}
[Fact]
public void Should_map_blarg_plus_three_using_extension_method()
{
_result.BlargPlus3.ShouldEqual(13);
}
[Fact]
public void Should_map_blarg_minus_2_using_lambda()
{
_result.BlargMinus2.ShouldEqual(8);
}
[Fact]
public void Should_override_existing_matches_for_new_mappings()
{
_result.MoreBlarg.ShouldEqual(45);
}
}
public class When_mapping_using_custom_member_mappings_without_generics : AutoMapperSpecBase
{
private OrderDTO _result;
public class Order
{
public int Id { get; set; }
public string Status { get; set; }
public string Customer { get; set; }
public string ShippingCode { get; set; }
public string Zip { get; set; }
}
public class OrderDTO
{
public int Id { get; set; }
public string CurrentState { get; set; }
public string Contact { get; set; }
public string Tracking { get; set; }
public string Postal { get; set; }
}
public class StringCAPS : ValueResolver<string, string>
{
protected override string ResolveCore(string source)
{
return source.ToUpper();
}
}
public class StringLower : ValueResolver<string, string>
{
protected override string ResolveCore(string source)
{
return source.ToLower();
}
}
public class StringPadder : ValueResolver<string, string>
{
private readonly int _desiredLength;
public StringPadder(int desiredLength)
{
_desiredLength = desiredLength;
}
protected override string ResolveCore(string source)
{
return source.PadLeft(_desiredLength);
}
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap(typeof (Order), typeof (OrderDTO))
.ForMember("CurrentState", map => map.MapFrom("Status"))
.ForMember("Contact", map => map.ResolveUsing(new StringCAPS()).FromMember("Customer"))
.ForMember("Tracking", map => map.ResolveUsing(typeof(StringLower)).FromMember("ShippingCode"))
.ForMember("Postal", map => map.ResolveUsing<StringPadder>().ConstructedBy(() => new StringPadder(6)).FromMember("Zip"));
});
var order = new Order
{
Id = 7,
Status = "Pending",
Customer = "Buster",
ShippingCode = "AbcxY23",
Zip = "XYZ"
};
_result = Mapper.Map<Order, OrderDTO>(order);
}
[Fact]
public void Should_preserve_existing_mapping()
{
_result.Id.ShouldEqual(7);
}
[Fact]
public void Should_support_custom_source_member()
{
_result.CurrentState.ShouldEqual("Pending");
}
[Fact]
public void Should_support_custom_resolver_on_custom_source_member()
{
_result.Contact.ShouldEqual("BUSTER");
}
[Fact]
public void Should_support_custom_resolver_by_type_on_custom_source_member()
{
_result.Tracking.ShouldEqual("abcxy23");
}
[Fact]
public void Should_support_custom_resolver_by_generic_type_with_constructor_on_custom_source_member()
{
_result.Postal.ShouldEqual(" XYZ");
}
}
public class When_mapping_to_a_top_level_camelCased_destination_member : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int SomeValueWithPascalName { get; set; }
}
public class Destination
{
public int someValueWithPascalName { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
var source = new Source {SomeValueWithPascalName = 5};
_result = Mapper.Map<Source, Destination>(source);
}
[Fact]
public void Should_match_to_PascalCased_source_member()
{
_result.someValueWithPascalName.ShouldEqual(5);
}
[Fact]
public void Should_pass_configuration_check()
{
Mapper.AssertConfigurationIsValid();
}
}
public class When_mapping_to_a_self_referential_object : AutoMapperSpecBase
{
private CategoryDto _result;
public class Category
{
public string Name { get; set; }
public IList<Category> Children { get; set; }
}
public class CategoryDto
{
public string Name { get; set; }
public CategoryDto[] Children { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Category, CategoryDto>();
}
protected override void Because_of()
{
var category = new Category
{
Name = "Grandparent",
Children = new List<Category>()
{
new Category { Name = "Parent 1", Children = new List<Category>()
{
new Category { Name = "Child 1"},
new Category { Name = "Child 2"},
new Category { Name = "Child 3"},
}},
new Category { Name = "Parent 2", Children = new List<Category>()
{
new Category { Name = "Child 4"},
new Category { Name = "Child 5"},
new Category { Name = "Child 6"},
new Category { Name = "Child 7"},
}},
}
};
_result = Mapper.Map<Category, CategoryDto>(category);
}
[Fact]
public void Should_pass_configuration_check()
{
Mapper.AssertConfigurationIsValid();
}
[Fact]
public void Should_resolve_any_level_of_hierarchies()
{
_result.Name.ShouldEqual("Grandparent");
_result.Children.Length.ShouldEqual(2);
_result.Children[0].Children.Length.ShouldEqual(3);
_result.Children[1].Children.Length.ShouldEqual(4);
}
}
public class When_mapping_to_types_in_a_non_generic_manner : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap(typeof (Source), typeof (Destination));
}
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Fact]
public void Should_allow_for_basic_mapping()
{
_result.Value.ShouldEqual(5);
}
}
public class When_matching_source_and_destination_members_with_underscored_members : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public SubSource some_source { get; set; }
}
public class SubSource
{
public int value { get; set; }
}
public class Destination
{
public int some_source_value { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {some_source = new SubSource {value = 8}});
}
[Fact]
public void Should_use_underscores_as_tokenizers_to_flatten()
{
_destination.some_source_value.ShouldEqual(8);
}
}
public class When_source_members_contain_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int FooValue { get; set; }
public int GetOtherValue()
{
return 10;
}
}
public class Destination
{
public int Value { get; set; }
public int OtherValue { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizePrefixes("Foo");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {FooValue = 5});
}
[Fact]
public void Registered_prefixes_ignored()
{
_destination.Value.ShouldEqual(5);
}
[Fact]
public void Default_prefix_included()
{
_destination.OtherValue.ShouldEqual(10);
}
}
public class When_source_members_contain_postfixes_and_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int FooValueBar { get; set; }
public int GetOtherValue()
{
return 10;
}
}
public class Destination
{
public int Value { get; set; }
public int OtherValue { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizePrefixes("Foo");
cfg.RecognizePostfixes("Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { FooValueBar = 5 });
}
[Fact]
public void Registered_prefixes_ignored()
{
_destination.Value.ShouldEqual(5);
}
[Fact]
public void Default_prefix_included()
{
_destination.OtherValue.ShouldEqual(10);
}
}
public class When_source_member_names_match_with_underscores : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int I_amaCraAZZEE____Name { get; set; }
}
public class Destination
{
public int I_amaCraAZZEE____Name { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
_destination = Mapper.Map<Source, Destination>(new Source {I_amaCraAZZEE____Name = 5});
}
[Fact]
public void Should_match_based_on_name()
{
_destination.I_amaCraAZZEE____Name.ShouldEqual(5);
}
}
public class When_recognizing_explicit_member_aliases : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Foo { get; set; }
}
public class Destination
{
public int Bar { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizeAlias("Foo", "Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Foo = 5});
}
[Fact]
public void Members_that_match_alias_should_be_matched()
{
_destination.Bar.ShouldEqual(5);
}
}
public class When_destination_members_contain_prefixes : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int FooValue { get; set; }
public int BarValue2 { get; set; }
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.RecognizeDestinationPrefixes("Foo","Bar");
cfg.CreateMap<Source, Destination>();
});
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Value = 5, Value2 = 10 });
}
[Fact]
public void Registered_prefixes_ignored()
{
_destination.FooValue.ShouldEqual(5);
_destination.BarValue2.ShouldEqual(10);
}
}
}
#if !SILVERLIGHT
public class When_destination_type_has_private_members : AutoMapperSpecBase
{
private IDestination _destination;
public class Source
{
public int Value { get; set; }
}
public interface IDestination
{
int Value { get; }
}
public class Destination : IDestination
{
public Destination(int value)
{
Value = value;
}
private Destination()
{
}
public int Value { get; private set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Fact]
public void Should_use_private_accessors_and_constructors()
{
_destination.Value.ShouldEqual(5);
}
}
#endif
public static class MapFromExtensions
{
public static int Plus(this int left, int right)
{
return left + right;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 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.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Execution;
#if !PORTABLE && !NETSTANDARD1_6
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Security.Principal;
using NUnit.Compatibility;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Helper class used to save and restore certain static or
/// singleton settings in the environment that affect tests
/// or which might be changed by the user tests.
/// </summary>
public class TestExecutionContext
#if !PORTABLE && !NETSTANDARD1_6
: LongLivedMarshalByRefObject, ILogicalThreadAffinative
#endif
{
// NOTE: Be very careful when modifying this class. It uses
// conditional compilation extensively and you must give
// thought to whether any new features will be supported
// on each platform. In particular, instance fields,
// properties, initialization and restoration must all
// use the same conditions for each feature.
#region Instance Fields
/// <summary>
/// Link to a prior saved context
/// </summary>
private TestExecutionContext _priorContext;
/// <summary>
/// Indicates that a stop has been requested
/// </summary>
private TestExecutionStatus _executionStatus;
/// <summary>
/// The event listener currently receiving notifications
/// </summary>
private ITestListener _listener = TestListener.NULL;
/// <summary>
/// The number of assertions for the current test
/// </summary>
private int _assertCount;
private Randomizer _randomGenerator;
/// <summary>
/// The current culture
/// </summary>
private CultureInfo _currentCulture;
/// <summary>
/// The current UI culture
/// </summary>
private CultureInfo _currentUICulture;
/// <summary>
/// The current test result
/// </summary>
private TestResult _currentResult;
#if !PORTABLE && !NETSTANDARD1_6
/// <summary>
/// The current Principal.
/// </summary>
private IPrincipal _currentPrincipal;
#endif
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
public TestExecutionContext()
{
_priorContext = null;
TestCaseTimeout = 0;
UpstreamActions = new List<ITestAction>();
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !PORTABLE && !NETSTANDARD1_6
_currentPrincipal = Thread.CurrentPrincipal;
#endif
CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val);
IsSingleThreaded = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="TestExecutionContext"/> class.
/// </summary>
/// <param name="other">An existing instance of TestExecutionContext.</param>
public TestExecutionContext(TestExecutionContext other)
{
_priorContext = other;
CurrentTest = other.CurrentTest;
CurrentResult = other.CurrentResult;
TestObject = other.TestObject;
_listener = other._listener;
StopOnError = other.StopOnError;
TestCaseTimeout = other.TestCaseTimeout;
UpstreamActions = new List<ITestAction>(other.UpstreamActions);
_currentCulture = other.CurrentCulture;
_currentUICulture = other.CurrentUICulture;
#if !PORTABLE && !NETSTANDARD1_6
_currentPrincipal = other.CurrentPrincipal;
#endif
CurrentValueFormatter = other.CurrentValueFormatter;
Dispatcher = other.Dispatcher;
ParallelScope = other.ParallelScope;
IsSingleThreaded = other.IsSingleThreaded;
}
#endregion
#region CurrentContext Instance
// NOTE: We use different implementations for various platforms.
#if NETSTANDARD1_6
private static readonly AsyncLocal<TestExecutionContext> _currentContext = new AsyncLocal<TestExecutionContext>();
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
get
{
return _currentContext.Value;
}
private set
{
_currentContext.Value = value;
}
}
#elif PORTABLE
// The portable build only supports a single thread of
// execution, so we can use a simple static field to
// hold the current TestExecutionContext.
private static TestExecutionContext _currentContext;
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
get { return _currentContext; }
private set { _currentContext = value; }
}
#else
// In all other builds, we use the CallContext
private static readonly string CONTEXT_KEY = "NUnit.Framework.TestContext";
/// <summary>
/// Gets and sets the current context.
/// </summary>
public static TestExecutionContext CurrentContext
{
// This getter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class.
// Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute'
// rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers.
[SecuritySafeCritical]
get
{
return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;
}
// This setter invokes security critical members on the 'System.Runtime.Remoting.Messaging.CallContext' class.
// Callers of this method have no influence on how these methods are used so we define a 'SecuritySafeCriticalAttribute'
// rather than a 'SecurityCriticalAttribute' to enable use by security transparent callers.
[SecuritySafeCritical]
private set
{
if (value == null)
CallContext.FreeNamedDataSlot(CONTEXT_KEY);
else
CallContext.SetData(CONTEXT_KEY, value);
}
}
#endif
#endregion
#region Properties
/// <summary>
/// Gets or sets the current test
/// </summary>
public Test CurrentTest { get; set; }
/// <summary>
/// The time the current test started execution
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// The time the current test started in Ticks
/// </summary>
public long StartTicks { get; set; }
/// <summary>
/// Gets or sets the current test result
/// </summary>
public TestResult CurrentResult
{
get { return _currentResult; }
set
{
_currentResult = value;
if (value != null)
OutWriter = value.OutWriter;
}
}
/// <summary>
/// Gets a TextWriter that will send output to the current test result.
/// </summary>
public TextWriter OutWriter { get; private set; }
/// <summary>
/// The current test object - that is the user fixture
/// object on which tests are being executed.
/// </summary>
public object TestObject { get; set; }
/// <summary>
/// Get or set indicator that run should stop on the first error
/// </summary>
public bool StopOnError { get; set; }
/// <summary>
/// Gets an enum indicating whether a stop has been requested.
/// </summary>
public TestExecutionStatus ExecutionStatus
{
get
{
// ExecutionStatus may have been set to StopRequested or AbortRequested
// in a prior context. If so, reflect the same setting in this context.
if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)
_executionStatus = _priorContext.ExecutionStatus;
return _executionStatus;
}
set
{
_executionStatus = value;
// Push the same setting up to all prior contexts
if (_priorContext != null)
_priorContext.ExecutionStatus = value;
}
}
/// <summary>
/// The current test event listener
/// </summary>
internal ITestListener Listener
{
get { return _listener; }
set { _listener = value; }
}
/// <summary>
/// The current WorkItemDispatcher. Made public for
/// use by nunitlite.tests
/// </summary>
public IWorkItemDispatcher Dispatcher { get; set; }
/// <summary>
/// The ParallelScope to be used by tests running in this context.
/// For builds with out the parallel feature, it has no effect.
/// </summary>
public ParallelScope ParallelScope { get; set; }
#if PARALLEL
/// <summary>
/// The worker that spawned the context.
/// For builds without the parallel feature, it is null.
/// </summary>
public TestWorker TestWorker {get; internal set;}
#endif
/// <summary>
/// Gets the RandomGenerator specific to this Test
/// </summary>
public Randomizer RandomGenerator
{
get
{
if (_randomGenerator == null)
_randomGenerator = new Randomizer(CurrentTest.Seed);
return _randomGenerator;
}
}
/// <summary>
/// Gets the assert count.
/// </summary>
/// <value>The assert count.</value>
internal int AssertCount
{
get { return _assertCount; }
}
/// <summary>
/// The current nesting level of multiple assert blocks
/// </summary>
internal int MultipleAssertLevel { get; set; }
/// <summary>
/// Gets or sets the test case timeout value
/// </summary>
public int TestCaseTimeout { get; set; }
/// <summary>
/// Gets a list of ITestActions set by upstream tests
/// </summary>
public List<ITestAction> UpstreamActions { get; private set; }
// TODO: Put in checks on all of these settings
// with side effects so we only change them
// if the value is different
/// <summary>
/// Saves or restores the CurrentCulture
/// </summary>
public CultureInfo CurrentCulture
{
get { return _currentCulture; }
set
{
_currentCulture = value;
#if !PORTABLE && !NETSTANDARD1_6
Thread.CurrentThread.CurrentCulture = _currentCulture;
#endif
}
}
/// <summary>
/// Saves or restores the CurrentUICulture
/// </summary>
public CultureInfo CurrentUICulture
{
get { return _currentUICulture; }
set
{
_currentUICulture = value;
#if !PORTABLE && !NETSTANDARD1_6
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
#endif
}
}
#if !PORTABLE && !NETSTANDARD1_6
/// <summary>
/// Gets or sets the current <see cref="IPrincipal"/> for the Thread.
/// </summary>
public IPrincipal CurrentPrincipal
{
get { return _currentPrincipal; }
set
{
_currentPrincipal = value;
Thread.CurrentPrincipal = _currentPrincipal;
}
}
#endif
/// <summary>
/// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter
/// </summary>
public ValueFormatter CurrentValueFormatter { get; private set; }
/// <summary>
/// If true, all tests must run on the same thread. No new thread may be spawned.
/// </summary>
public bool IsSingleThreaded { get; set; }
#endregion
#region Instance Methods
/// <summary>
/// Record any changes in the environment made by
/// the test code in the execution context so it
/// will be passed on to lower level tests.
/// </summary>
public void UpdateContextFromEnvironment()
{
_currentCulture = CultureInfo.CurrentCulture;
_currentUICulture = CultureInfo.CurrentUICulture;
#if !PORTABLE && !NETSTANDARD1_6
_currentPrincipal = Thread.CurrentPrincipal;
#endif
}
/// <summary>
/// Set up the execution environment to match a context.
/// Note that we may be running on the same thread where the
/// context was initially created or on a different thread.
/// </summary>
public void EstablishExecutionEnvironment()
{
#if !PORTABLE && !NETSTANDARD1_6
Thread.CurrentThread.CurrentCulture = _currentCulture;
Thread.CurrentThread.CurrentUICulture = _currentUICulture;
Thread.CurrentPrincipal = _currentPrincipal;
#endif
CurrentContext = this;
}
/// <summary>
/// Increments the assert count by one.
/// </summary>
public void IncrementAssertCount()
{
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Increments the assert count by a specified amount.
/// </summary>
public void IncrementAssertCount(int count)
{
// TODO: Temporary implementation
while (count-- > 0)
Interlocked.Increment(ref _assertCount);
}
/// <summary>
/// Adds a new ValueFormatterFactory to the chain of formatters
/// </summary>
/// <param name="formatterFactory">The new factory</param>
public void AddFormatter(ValueFormatterFactory formatterFactory)
{
CurrentValueFormatter = formatterFactory(CurrentValueFormatter);
}
private TestExecutionContext CreateIsolatedContext()
{
var context = new TestExecutionContext(this);
if (context.CurrentTest != null)
context.CurrentResult = context.CurrentTest.MakeTestResult();
return context;
}
#endregion
#region InitializeLifetimeService
#if !PORTABLE && !NETSTANDARD1_6
/// <summary>
/// Obtain lifetime service object
/// </summary>
/// <returns></returns>
[SecurityCritical] // Override of security critical method must be security critical itself
public override object InitializeLifetimeService()
{
return null;
}
#endif
#endregion
#region Nested IsolatedContext Class
/// <summary>
/// An IsolatedContext is used when running code
/// that may effect the current result in ways that
/// should not impact the final result of the test.
/// A new TestExecutionContext is created with an
/// initially clear result, which is discarded on
/// exiting the context.
/// </summary>
/// <example>
/// using (new TestExecutionContext.IsolatedContext())
/// {
/// // Code that should not impact the result
/// }
/// </example>
public class IsolatedContext : IDisposable
{
private TestExecutionContext _originalContext;
/// <summary>
/// Save the original current TestExecutionContext and
/// make a new isolated context current.
/// </summary>
public IsolatedContext()
{
_originalContext = CurrentContext;
CurrentContext = _originalContext.CreateIsolatedContext();
}
/// <summary>
/// Restore the original TestExecutionContext.
/// </summary>
public void Dispose()
{
CurrentContext = _originalContext;
}
}
#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.IO;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== Initialize =====================
public class TCInitialize : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCInitialize(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void InitializeShouldResetIDConstraints()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS);
XmlSchemaInfo info = new XmlSchemaInfo();
for (int i = 0; i < 2; i++)
{
val.Initialize();
val.ValidateElement("rootIDs", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("foo", "", info);
val.ValidateAttribute("attr", "", StringGetter("a1"), info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateEndElement(info);
val.EndValidation();
}
return;
}
[Fact]
public void InitializeShouldNotResetLineInfoProvider()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
CDummyLineInfo LineInfo = new CDummyLineInfo(10, 10);
val.Initialize();
val.LineInfoProvider = LineInfo;
val.EndValidation();
val.Initialize();
Assert.Equal(LineInfo, val.LineInfoProvider);
return;
}
[Fact]
public void InitializeShouldNotResetSourceUri()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
Uri srcUri = new Uri("urn:foo.bar");
val.Initialize();
val.SourceUri = srcUri;
val.EndValidation();
val.Initialize();
Assert.Equal(srcUri, val.SourceUri);
return;
}
[Fact]
public void InitializeShouldNotResetValidationEventSender()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
CDummyLineInfo LineInfo = new CDummyLineInfo(10, 10);
val.Initialize();
val.ValidationEventSender = LineInfo;
val.EndValidation();
val.Initialize();
Assert.Equal(LineInfo, val.ValidationEventSender);
return;
}
[Fact]
public void InitializeShouldNotResetInternalSchemaSet()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.AddSchema(XmlSchema.Read(XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:element name=\"root\" type=\"xs:string\" />\n" +
"</xs:schema>")), null));
val.EndValidation();
val.Initialize();
val.ValidateElement("root", "", info);
Assert.True(info.SchemaElement != null);
return;
}
[Fact]
public void InitializeShouldNotResetXmlResolver()
{
XmlSchemaInfo info = new XmlSchemaInfo();
CXmlTestResolver res = new CXmlTestResolver();
CResolverHolder holder = new CResolverHolder();
res.CalledResolveUri += new XmlTestResolverEventHandler(holder.CallBackResolveUri);
res.CalledGetEntity += new XmlTestResolverEventHandler(holder.CallBackGetEntity);
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
val.XmlResolver = res;
val.EndValidation();
val.Initialize();
val.ValidateElement("foo", "", info, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE));
val.ValidateEndOfAttributes(null);
val.ValidateElement("bar", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(holder.IsCalledResolveUri);
return;
}
// Second overload
//(BUG #306951)
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
try
{
val.Initialize(null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void InitializeWithElementValidateSameElement()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalElements[new XmlQualifiedName("PartialElement")]);
val.ValidateElement("PartialElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("123"));
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.SchemaElement.Name, "PartialElement");
return;
}
[Theory]
[InlineData("other")]
[InlineData("type")]
[InlineData("attribute")]
public void InitializeWithElementValidate_OtherElement_Type_Attribute(String typeToValidate)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalElements[new XmlQualifiedName("PartialElement")]);
try
{
switch (typeToValidate)
{
case "other":
val.ValidateElement("PartialElement2", "", info);
break;
case "type":
val.ValidateElement("foo", "", info, "PartialType", null, null, null);
break;
case "attribute":
val.ValidateAttribute("PartialAttribute", "", StringGetter("123"), info);
break;
default:
Assert.True(false);
break;
}
}
catch (XmlSchemaValidationException e)
{
switch (typeToValidate)
{
case "other":
_exVerifier.IsExceptionOk(e, "Sch_SchemaElementNameMismatch", new string[] { "PartialElement2", "PartialElement" });
break;
case "type":
_exVerifier.IsExceptionOk(e, "Sch_SchemaElementNameMismatch", new string[] { "foo", "PartialElement" });
break;
case "attribute":
_exVerifier.IsExceptionOk(e, "Sch_ValidateAttributeInvalidCall");
break;
default:
Assert.True(false);
break;
}
return;
}
Assert.True(false);
}
[Fact]
public void InitializeWithTypeValidateSameType()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalTypes[new XmlQualifiedName("PartialType")]);
val.ValidateElement("foo", "", info, "PartialType", null, null, null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.SchemaType.Name, "PartialType");
return;
}
[Theory]
[InlineData("other")]
[InlineData("attribute")]
public void InitializeWithTypeValidate_OtherType_Attribute(String typeToValidate)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalTypes[new XmlQualifiedName("PartialType")]);
try
{
switch (typeToValidate)
{
case "other":
val.ValidateElement("foo", "", info, "PartialType2", null, null, null);
break;
case "attribute":
val.ValidateAttribute("PartialAttribute", "", StringGetter("123"), info);
break;
default:
Assert.True(false);
break;
}
}
catch (XmlSchemaValidationException e)
{
switch (typeToValidate)
{
case "other":
_exVerifier.IsExceptionOk(e, "Sch_XsiTypeBlockedEx", new string[] { "PartialType2", "foo" });
break;
case "attribute":
_exVerifier.IsExceptionOk(e, "Sch_ValidateAttributeInvalidCall");
break;
default:
Assert.True(false);
break;
}
return;
}
Assert.True(false);
}
[Fact]
public void InitializeWithTypeValidateElement()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalTypes[new XmlQualifiedName("PartialType")]);
try
{
val.ValidateElement("PartialElement", "", info);
}
catch (XmlSchemaValidationException)
{
Assert.True(false);
}
return;
}
[Fact]
public void InitializeWithAttributeValidateSameAttribute()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalAttributes[new XmlQualifiedName("PartialAttribute")]);
val.ValidateAttribute("PartialAttribute", "", StringGetter("123"), info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
Assert.Equal(info.SchemaAttribute.Name, "PartialAttribute");
return;
}
[Theory]
[InlineData("other")]
[InlineData("element")]
[InlineData("type")]
public void InitializeWithAttributeValidate_OtherAttribute_Element_Type(String typeToValidate)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalAttributes[new XmlQualifiedName("PartialAttribute")]);
try
{
switch (typeToValidate)
{
case "other":
val.ValidateAttribute("PartialAttribute2", "", StringGetter("123"), info);
break;
case "element":
val.ValidateElement("PartialElement", "", info);
break;
case "type":
val.ValidateElement("foo", "", info, "PartialType", null, null, null);
break;
default:
Assert.True(false);
break;
}
}
catch (XmlSchemaValidationException e)
{
switch (typeToValidate)
{
case "other":
_exVerifier.IsExceptionOk(e, "Sch_SchemaAttributeNameMismatch", new string[] { "PartialAttribute2", "PartialAttribute" });
break;
case "element":
_exVerifier.IsExceptionOk(e, "Sch_ValidateElementInvalidCall");
break;
case "type":
_exVerifier.IsExceptionOk(e, "Sch_ValidateElementInvalidCall");
break;
default:
Assert.True(false);
break;
}
return;
}
Assert.True(false);
}
[Theory]
[InlineData("annotation")]
[InlineData("group")]
[InlineData("any")]
public void Pass_XmlSchemaAnnotation_XmlSchemaGroup_XmlSchemaAny_Invalid(String TypeToPass)
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
XmlSchemaObject obj = new XmlSchemaAnnotation();
switch (TypeToPass)
{
case "annotation":
obj = new XmlSchemaAnnotation();
break;
case "group":
obj = new XmlSchemaGroup();
break;
case "any":
obj = new XmlSchemaAny();
break;
default:
Assert.True(false);
break;
}
try
{
val.Initialize(obj);
}
catch (ArgumentException)
{
return;
}
Assert.True(false);
}
[Theory]
[InlineData("text")]
[InlineData("whitespace")]
public void SetPartiaValidationAndCallValidate_Text_WhiteSpace_Valid(String typeToValidate)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", Path.Combine(TestData, XSDFILE_PARTIAL_VALIDATION));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize(schemas.GlobalElements[new XmlQualifiedName("PartialElement")]);
if (typeToValidate == "text")
val.ValidateText(StringGetter("foo"));
else
val.ValidateWhitespace(StringGetter(Environment.NewLine + "\t "));
return;
}
}
// ===================== EndValidation =====================
public class TCEndValidation : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCEndValidation(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void CallWithoutAnyValidation__AfterInitialize()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
val.EndValidation();
return;
}
[Theory]
[InlineData("valid")]
[InlineData("missing")]
[InlineData("ignore")]
public void TestForRootLevelIdentityConstraints_Valid_IDREFMissingInvalid_IgnoreIdentityConstraintsIsSetInvalid(String validity)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
string[] keys = new string[] { };
string[] keyrefs = new string[] { };
switch (validity)
{
case "valid":
keys = new string[] { "a1", "a2" };
keyrefs = new string[] { "a1", "a1", "a2" };
break;
case "missing":
keys = new string[] { "a1", "a2" };
keyrefs = new string[] { "a1", "a1", "a3" };
break;
case "ignore":
keys = new string[] { "a1", "a1" };
keyrefs = new string[] { "a2", "a2" };
break;
default:
Assert.True(false);
break;
}
if (validity == "ignore")
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS, "", XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema);
else
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS);
val.Initialize();
val.ValidateElement("rootIDREFs", "", info);
val.ValidateEndOfAttributes(null);
foreach (string str in keyrefs)
{
val.ValidateElement("foo", "", info);
val.ValidateAttribute("attr", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
val.ValidateElement("rootIDs", "", info);
val.ValidateEndOfAttributes(null);
foreach (string str in keys)
{
val.ValidateElement("foo", "", info);
val.ValidateAttribute("attr", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
if (validity == "missing")
{
try
{
val.EndValidation();
Assert.True(false);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_UndeclaredId", new string[] { "a3" });
return;
}
}
else
val.EndValidation();
return;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Transform3DGroup.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Media3D
{
sealed partial class Transform3DGroup : Transform3D
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new Transform3DGroup Clone()
{
return (Transform3DGroup)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new Transform3DGroup CloneCurrentValue()
{
return (Transform3DGroup)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void ChildrenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
Transform3DGroup target = ((Transform3DGroup) d);
// If this is both non-null and mutable, we need to unhook the Changed event.
Transform3DCollection oldCollection = null;
Transform3DCollection newCollection = null;
if ((e.OldValueSource != BaseValueSourceInternal.Default) || e.IsOldValueModified)
{
oldCollection = (Transform3DCollection) e.OldValue;
if ((oldCollection != null) && !oldCollection.IsFrozen)
{
oldCollection.ItemRemoved -= target.ChildrenItemRemoved;
oldCollection.ItemInserted -= target.ChildrenItemInserted;
}
}
// If this is both non-null and mutable, we need to hook the Changed event.
if ((e.NewValueSource != BaseValueSourceInternal.Default) || e.IsNewValueModified)
{
newCollection = (Transform3DCollection) e.NewValue;
if ((newCollection != null) && !newCollection.IsFrozen)
{
newCollection.ItemInserted += target.ChildrenItemInserted;
newCollection.ItemRemoved += target.ChildrenItemRemoved;
}
}
if (oldCollection != newCollection && target.Dispatcher != null)
{
using (CompositionEngineLock.Acquire())
{
DUCE.IResource targetResource = (DUCE.IResource)target;
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
// resource shouldn't be null because
// 1) If the field is one of our collections, we don't allow null elements
// 2) Codegen already made sure the collection contains DUCE.IResources
// ... so we'll Assert it
if (newCollection != null)
{
int count = newCollection.Count;
for (int i = 0; i < count; i++)
{
DUCE.IResource resource = newCollection.Internal_GetItem(i) as DUCE.IResource;
Debug.Assert(resource != null);
resource.AddRefOnChannel(channel);
}
}
if (oldCollection != null)
{
int count = oldCollection.Count;
for (int i = 0; i < count; i++)
{
DUCE.IResource resource = oldCollection.Internal_GetItem(i) as DUCE.IResource;
Debug.Assert(resource != null);
resource.ReleaseOnChannel(channel);
}
}
}
}
}
target.PropertyChanged(ChildrenProperty);
}
#region Public Properties
/// <summary>
/// Children - Transform3DCollection. Default value is new FreezableDefaultValueFactory(Transform3DCollection.Empty).
/// </summary>
public Transform3DCollection Children
{
get
{
return (Transform3DCollection) GetValue(ChildrenProperty);
}
set
{
SetValueInternal(ChildrenProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Transform3DGroup();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Transform3DCollection vChildren = Children;
// Store the count of this resource's contained collections in local variables.
int ChildrenCount = (vChildren == null) ? 0 : vChildren.Count;
// Pack & send command packet
DUCE.MILCMD_TRANSFORM3DGROUP data;
unsafe
{
data.Type = MILCMD.MilCmdTransform3DGroup;
data.Handle = _duceResource.GetHandle(channel);
data.ChildrenSize = (uint)(sizeof(DUCE.ResourceHandle) * ChildrenCount);
channel.BeginCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_TRANSFORM3DGROUP),
(int)(data.ChildrenSize)
);
// Copy this collection's elements (or their handles) to reserved data
for(int i = 0; i < ChildrenCount; i++)
{
DUCE.ResourceHandle resource = ((DUCE.IResource)vChildren.Internal_GetItem(i)).GetHandle(channel);;
channel.AppendCommandData(
(byte*)&resource,
sizeof(DUCE.ResourceHandle)
);
}
channel.EndCommand();
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_TRANSFORM3DGROUP))
{
Transform3DCollection vChildren = Children;
if (vChildren != null)
{
int count = vChildren.Count;
for (int i = 0; i < count; i++)
{
((DUCE.IResource) vChildren.Internal_GetItem(i)).AddRefOnChannel(channel);
}
}
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform3DCollection vChildren = Children;
if (vChildren != null)
{
int count = vChildren.Count;
for (int i = 0; i < count; i++)
{
((DUCE.IResource) vChildren.Internal_GetItem(i)).ReleaseOnChannel(channel);
}
}
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
private void ChildrenItemInserted(object sender, object item)
{
if (this.Dispatcher != null)
{
DUCE.IResource thisResource = (DUCE.IResource)this;
using (CompositionEngineLock.Acquire())
{
int channelCount = thisResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = thisResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!thisResource.GetHandle(channel).IsNull);
// We're on a channel, which means our dependents are also on the channel.
DUCE.IResource addResource = item as DUCE.IResource;
if (addResource != null)
{
addResource.AddRefOnChannel(channel);
}
UpdateResource(channel, true /* skip on channel check */);
}
}
}
}
private void ChildrenItemRemoved(object sender, object item)
{
if (this.Dispatcher != null)
{
DUCE.IResource thisResource = (DUCE.IResource)this;
using (CompositionEngineLock.Acquire())
{
int channelCount = thisResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = thisResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!thisResource.GetHandle(channel).IsNull);
UpdateResource(channel, true /* is on channel check */);
// We're on a channel, which means our dependents are also on the channel.
DUCE.IResource releaseResource = item as DUCE.IResource;
if (releaseResource != null)
{
releaseResource.ReleaseOnChannel(channel);
}
}
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
//
// This property finds the correct initial size for the _effectiveValues store on the
// current DependencyObject as a performance optimization
//
// This includes:
// Children
//
internal override int EffectiveValuesInitialSize
{
get
{
return 1;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the Transform3DGroup.Children property.
/// </summary>
public static readonly DependencyProperty ChildrenProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal static Transform3DCollection s_Children = Transform3DCollection.Empty;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static Transform3DGroup()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
Debug.Assert(s_Children == null || s_Children.IsFrozen,
"Detected context bound default value Transform3DGroup.s_Children (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(Transform3DGroup);
ChildrenProperty =
RegisterProperty("Children",
typeof(Transform3DCollection),
typeofThis,
new FreezableDefaultValueFactory(Transform3DCollection.Empty),
new PropertyChangedCallback(ChildrenPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// This RegexWriter class is internal to the Regex package.
// It builds a block of regular expression codes (RegexCode)
// from a RegexTree parse tree.
// Implementation notes:
//
// This step is as simple as walking the tree and emitting
// sequences of codes.
//
using System.Collections.Generic;
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal sealed class RegexWriter
{
private int[] _intStack;
private int _depth;
private int[] _emitted;
private int _curpos;
private readonly Dictionary<string, int> _stringhash;
private readonly List<String> _stringtable;
private bool _counting;
private int _count;
private int _trackcount;
private Dictionary<Int32, Int32> _caps;
private const int BeforeChild = 64;
private const int AfterChild = 128;
/// <summary>
/// This is the only function that should be called from outside.
/// It takes a RegexTree and creates a corresponding RegexCode.
/// </summary>
internal static RegexCode Write(RegexTree t)
{
RegexWriter w = new RegexWriter();
RegexCode retval = w.RegexCodeFromRegexTree(t);
#if DEBUG
if (t.Debug)
{
t.Dump();
retval.Dump();
}
#endif
return retval;
}
// Private constructor; can't be created outside
private RegexWriter()
{
_intStack = new int[32];
_emitted = new int[32];
_stringhash = new Dictionary<string, int>();
_stringtable = new List<String>();
}
/// <summary>
/// To avoid recursion, we use a simple integer stack.
/// This is the push.
/// </summary>
private void PushInt(int i)
{
if (_depth >= _intStack.Length)
{
int[] expanded = new int[_depth * 2];
Array.Copy(_intStack, 0, expanded, 0, _depth);
_intStack = expanded;
}
_intStack[_depth++] = i;
}
/// <summary>
/// <c>true</c> if the stack is empty.
/// </summary>
private bool EmptyStack()
{
return _depth == 0;
}
/// <summary>
/// This is the pop.
/// </summary>
private int PopInt()
{
return _intStack[--_depth];
}
/// <summary>
/// Returns the current position in the emitted code.
/// </summary>
private int CurPos()
{
return _curpos;
}
/// <summary>
/// Fixes up a jump instruction at the specified offset
/// so that it jumps to the specified jumpDest.
/// </summary>
private void PatchJump(int offset, int jumpDest)
{
_emitted[offset + 1] = jumpDest;
}
/// <summary>
/// Emits a zero-argument operation. Note that the emit
/// functions all run in two modes: they can emit code, or
/// they can just count the size of the code.
/// </summary>
private void Emit(int op)
{
if (_counting)
{
_count += 1;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
}
/// <summary>
/// Emits a one-argument operation.
/// </summary>
private void Emit(int op, int opd1)
{
if (_counting)
{
_count += 2;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
_emitted[_curpos++] = opd1;
}
/// <summary>
/// Emits a two-argument operation.
/// </summary>
private void Emit(int op, int opd1, int opd2)
{
if (_counting)
{
_count += 3;
if (RegexCode.OpcodeBacktracks(op))
_trackcount += 1;
return;
}
_emitted[_curpos++] = op;
_emitted[_curpos++] = opd1;
_emitted[_curpos++] = opd2;
}
/// <summary>
/// Returns an index in the string table for a string;
/// uses a hashtable to eliminate duplicates.
/// </summary>
private int StringCode(String str)
{
if (_counting)
return 0;
if (str == null)
str = String.Empty;
Int32 i;
if (!_stringhash.TryGetValue(str, out i))
{
i = _stringtable.Count;
_stringhash[str] = i;
_stringtable.Add(str);
}
return i;
}
/// <summary>
/// When generating code on a regex that uses a sparse set
/// of capture slots, we hash them to a dense set of indices
/// for an array of capture slots. Instead of doing the hash
/// at match time, it's done at compile time, here.
/// </summary>
private int MapCapnum(int capnum)
{
if (capnum == -1)
return -1;
if (_caps != null)
return _caps[capnum];
else
return capnum;
}
/// <summary>
/// The top level RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
///
/// It runs two passes, first to count the size of the generated
/// code, and second to generate the code.
///
/// We should time it against the alternative, which is
/// to just generate the code and grow the array as we go.
/// </summary>
private RegexCode RegexCodeFromRegexTree(RegexTree tree)
{
RegexNode curNode;
int curChild;
int capsize;
RegexPrefix fcPrefix;
RegexPrefix prefix;
int anchors;
RegexBoyerMoore bmPrefix;
bool rtl;
// construct sparse capnum mapping if some numbers are unused
if (tree._capnumlist == null || tree._captop == tree._capnumlist.Length)
{
capsize = tree._captop;
_caps = null;
}
else
{
capsize = tree._capnumlist.Length;
_caps = tree._caps;
for (int i = 0; i < tree._capnumlist.Length; i++)
_caps[tree._capnumlist[i]] = i;
}
_counting = true;
for (; ;)
{
if (!_counting)
_emitted = new int[_count];
curNode = tree._root;
curChild = 0;
Emit(RegexCode.Lazybranch, 0);
for (; ;)
{
if (curNode._children == null)
{
EmitFragment(curNode._type, curNode, 0);
}
else if (curChild < curNode._children.Count)
{
EmitFragment(curNode._type | BeforeChild, curNode, curChild);
curNode = (RegexNode)curNode._children[curChild];
PushInt(curChild);
curChild = 0;
continue;
}
if (EmptyStack())
break;
curChild = PopInt();
curNode = curNode._next;
EmitFragment(curNode._type | AfterChild, curNode, curChild);
curChild++;
}
PatchJump(0, CurPos());
Emit(RegexCode.Stop);
if (!_counting)
break;
_counting = false;
}
fcPrefix = RegexFCD.FirstChars(tree);
prefix = RegexFCD.Prefix(tree);
rtl = ((tree._options & RegexOptions.RightToLeft) != 0);
CultureInfo culture = (tree._options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
if (prefix != null && prefix.Prefix.Length > 0)
bmPrefix = new RegexBoyerMoore(prefix.Prefix, prefix.CaseInsensitive, rtl, culture);
else
bmPrefix = null;
anchors = RegexFCD.Anchors(tree);
return new RegexCode(_emitted, _stringtable, _trackcount, _caps, capsize, bmPrefix, fcPrefix, anchors, rtl);
}
/// <summary>
/// The main RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
/// </summary>
private void EmitFragment(int nodetype, RegexNode node, int curIndex)
{
int bits = 0;
if (nodetype <= RegexNode.Ref)
{
if (node.UseOptionR())
bits |= RegexCode.Rtl;
if ((node._options & RegexOptions.IgnoreCase) != 0)
bits |= RegexCode.Ci;
}
switch (nodetype)
{
case RegexNode.Concatenate | BeforeChild:
case RegexNode.Concatenate | AfterChild:
case RegexNode.Empty:
break;
case RegexNode.Alternate | BeforeChild:
if (curIndex < node._children.Count - 1)
{
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
}
break;
case RegexNode.Alternate | AfterChild:
{
if (curIndex < node._children.Count - 1)
{
int LBPos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(LBPos, CurPos());
}
else
{
int I;
for (I = 0; I < curIndex; I++)
{
PatchJump(PopInt(), CurPos());
}
}
break;
}
case RegexNode.Testref | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
Emit(RegexCode.Testref, MapCapnum(node._m));
Emit(RegexCode.Forejump);
break;
}
break;
case RegexNode.Testref | AfterChild:
switch (curIndex)
{
case 0:
{
int Branchpos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, CurPos());
Emit(RegexCode.Forejump);
if (node._children.Count > 1)
break;
// else fallthrough
goto case 1;
}
case 1:
PatchJump(PopInt(), CurPos());
break;
}
break;
case RegexNode.Testgroup | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
break;
}
break;
case RegexNode.Testgroup | AfterChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
break;
case 1:
int Branchpos = PopInt();
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, CurPos());
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
if (node._children.Count > 2)
break;
// else fallthrough
goto case 2;
case 2:
PatchJump(PopInt(), CurPos());
break;
}
break;
case RegexNode.Loop | BeforeChild:
case RegexNode.Lazyloop | BeforeChild:
if (node._n < Int32.MaxValue || node._m > 1)
Emit(node._m == 0 ? RegexCode.Nullcount : RegexCode.Setcount, node._m == 0 ? 0 : 1 - node._m);
else
Emit(node._m == 0 ? RegexCode.Nullmark : RegexCode.Setmark);
if (node._m == 0)
{
PushInt(CurPos());
Emit(RegexCode.Goto, 0);
}
PushInt(CurPos());
break;
case RegexNode.Loop | AfterChild:
case RegexNode.Lazyloop | AfterChild:
{
int StartJumpPos = CurPos();
int Lazy = (nodetype - (RegexNode.Loop | AfterChild));
if (node._n < Int32.MaxValue || node._m > 1)
Emit(RegexCode.Branchcount + Lazy, PopInt(), node._n == Int32.MaxValue ? Int32.MaxValue : node._n - node._m);
else
Emit(RegexCode.Branchmark + Lazy, PopInt());
if (node._m == 0)
PatchJump(PopInt(), StartJumpPos);
}
break;
case RegexNode.Group | BeforeChild:
case RegexNode.Group | AfterChild:
break;
case RegexNode.Capture | BeforeChild:
Emit(RegexCode.Setmark);
break;
case RegexNode.Capture | AfterChild:
Emit(RegexCode.Capturemark, MapCapnum(node._m), MapCapnum(node._n));
break;
case RegexNode.Require | BeforeChild:
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
break;
case RegexNode.Require | AfterChild:
Emit(RegexCode.Getmark);
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Forejump);
break;
case RegexNode.Prevent | BeforeChild:
Emit(RegexCode.Setjump);
PushInt(CurPos());
Emit(RegexCode.Lazybranch, 0);
break;
case RegexNode.Prevent | AfterChild:
Emit(RegexCode.Backjump);
PatchJump(PopInt(), CurPos());
Emit(RegexCode.Forejump);
break;
case RegexNode.Greedy | BeforeChild:
Emit(RegexCode.Setjump);
break;
case RegexNode.Greedy | AfterChild:
Emit(RegexCode.Forejump);
break;
case RegexNode.One:
case RegexNode.Notone:
Emit(node._type | bits, (int)node._ch);
break;
case RegexNode.Notoneloop:
case RegexNode.Notonelazy:
case RegexNode.Oneloop:
case RegexNode.Onelazy:
if (node._m > 0)
Emit(((node._type == RegexNode.Oneloop || node._type == RegexNode.Onelazy) ?
RegexCode.Onerep : RegexCode.Notonerep) | bits, (int)node._ch, node._m);
if (node._n > node._m)
Emit(node._type | bits, (int)node._ch, node._n == Int32.MaxValue ?
Int32.MaxValue : node._n - node._m);
break;
case RegexNode.Setloop:
case RegexNode.Setlazy:
if (node._m > 0)
Emit(RegexCode.Setrep | bits, StringCode(node._str), node._m);
if (node._n > node._m)
Emit(node._type | bits, StringCode(node._str),
(node._n == Int32.MaxValue) ? Int32.MaxValue : node._n - node._m);
break;
case RegexNode.Multi:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Set:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Ref:
Emit(node._type | bits, MapCapnum(node._m));
break;
case RegexNode.Nothing:
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.Nonboundary:
case RegexNode.ECMABoundary:
case RegexNode.NonECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
Emit(node._type);
break;
default:
throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString(CultureInfo.CurrentCulture)));
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ServiceObject.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the ServiceObject class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.ObjectModel;
/// <summary>
/// Represents the base abstract class for all item and folder types.
/// </summary>
public abstract class ServiceObject
{
private object lockObject = new object();
private ExchangeService service;
private PropertyBag propertyBag;
private string xmlElementName;
/// <summary>
/// Triggers dispatch of the change event.
/// </summary>
internal void Changed()
{
if (this.OnChange != null)
{
this.OnChange(this);
}
}
/// <summary>
/// Throws exception if this is a new service object.
/// </summary>
internal void ThrowIfThisIsNew()
{
if (this.IsNew)
{
throw new InvalidOperationException(Strings.ServiceObjectDoesNotHaveId);
}
}
/// <summary>
/// Throws exception if this is not a new service object.
/// </summary>
internal void ThrowIfThisIsNotNew()
{
if (!this.IsNew)
{
throw new InvalidOperationException(Strings.ServiceObjectAlreadyHasId);
}
}
/// <summary>
/// This methods lets subclasses of ServiceObject override the default mechanism
/// by which the XML element name associated with their type is retrieved.
/// </summary>
/// <returns>
/// The XML element name associated with this type.
/// If this method returns null or empty, the XML element name associated with this
/// type is determined by the EwsObjectDefinition attribute that decorates the type,
/// if present.
/// </returns>
/// <remarks>
/// Item and folder classes that can be returned by EWS MUST rely on the EwsObjectDefinition
/// attribute for XML element name determination.
/// </remarks>
internal virtual string GetXmlElementNameOverride()
{
return null;
}
/// <summary>
/// GetXmlElementName retrieves the XmlElementName of this type based on the
/// EwsObjectDefinition attribute that decorates it, if present.
/// </summary>
/// <returns>The XML element name associated with this type.</returns>
internal string GetXmlElementName()
{
if (string.IsNullOrEmpty(this.xmlElementName))
{
this.xmlElementName = this.GetXmlElementNameOverride();
if (string.IsNullOrEmpty(this.xmlElementName))
{
lock (this.lockObject)
{
foreach (Attribute attribute in this.GetType().GetCustomAttributes(false))
{
ServiceObjectDefinitionAttribute definitionAttribute = attribute as ServiceObjectDefinitionAttribute;
if (definitionAttribute != null)
{
this.xmlElementName = definitionAttribute.XmlElementName;
}
}
}
}
}
EwsUtilities.Assert(
!string.IsNullOrEmpty(this.xmlElementName),
"EwsObject.GetXmlElementName",
string.Format("The class {0} does not have an associated XML element name.", this.GetType().Name));
return this.xmlElementName;
}
/// <summary>
/// Gets the name of the change XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal virtual string GetChangeXmlElementName()
{
return XmlElementNames.ItemChange;
}
/// <summary>
/// Gets the name of the set field XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal virtual string GetSetFieldXmlElementName()
{
return XmlElementNames.SetItemField;
}
/// <summary>
/// Gets the name of the delete field XML element.
/// </summary>
/// <returns>XML element name,</returns>
internal virtual string GetDeleteFieldXmlElementName()
{
return XmlElementNames.DeleteItemField;
}
/// <summary>
/// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem
/// or UpdateItem request so this item can be property saved or updated.
/// </summary>
/// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param>
/// <returns><c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.</returns>
internal virtual bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation)
{
return false;
}
/// <summary>
/// Determines whether properties defined with ScopedDateTimePropertyDefinition require custom time zone scoping.
/// </summary>
/// <returns>
/// <c>true</c> if this item type requires custom scoping for scoped date/time properties; otherwise, <c>false</c>.
/// </returns>
internal virtual bool GetIsCustomDateTimeScopingRequired()
{
return false;
}
/// <summary>
/// The property bag holding property values for this object.
/// </summary>
internal PropertyBag PropertyBag
{
get { return this.propertyBag; }
}
/// <summary>
/// Internal constructor.
/// </summary>
/// <param name="service">EWS service to which this object belongs.</param>
internal ServiceObject(ExchangeService service)
{
EwsUtilities.ValidateParam(service, "service");
EwsUtilities.ValidateServiceObjectVersion(this, service.RequestedServerVersion);
this.service = service;
this.propertyBag = new PropertyBag(this);
}
/// <summary>
/// Gets the schema associated with this type of object.
/// </summary>
public ServiceObjectSchema Schema
{
get { return this.GetSchema(); }
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal abstract ServiceObjectSchema GetSchema();
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal abstract ExchangeVersion GetMinimumRequiredServerVersion();
/// <summary>
/// Loads service object from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
internal void LoadFromXml(EwsServiceXmlReader reader, bool clearPropertyBag)
{
this.PropertyBag.LoadFromXml(
reader,
clearPropertyBag,
null, /* propertySet */
false); /* summaryPropertiesOnly */
}
/// <summary>
/// Validates this instance.
/// </summary>
internal virtual void Validate()
{
this.PropertyBag.Validate();
}
/// <summary>
/// Loads service object from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
/// <param name="requestedPropertySet">The property set.</param>
/// <param name="summaryPropertiesOnly">if set to <c>true</c> [summary props only].</param>
internal void LoadFromXml(
EwsServiceXmlReader reader,
bool clearPropertyBag,
PropertySet requestedPropertySet,
bool summaryPropertiesOnly)
{
this.PropertyBag.LoadFromXml(
reader,
clearPropertyBag,
requestedPropertySet,
summaryPropertiesOnly);
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonServiceObject">The json service object.</param>
/// <param name="service">The service.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
/// <param name="requestedPropertySet">The requested property set.</param>
/// <param name="summaryPropertiesOnly">if set to <c>true</c> [summary properties only].</param>
internal void LoadFromJson(JsonObject jsonServiceObject, ExchangeService service, bool clearPropertyBag, PropertySet requestedPropertySet, bool summaryPropertiesOnly)
{
this.PropertyBag.LoadFromJson(
jsonServiceObject,
service,
clearPropertyBag,
requestedPropertySet,
summaryPropertiesOnly);
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonObject">The json object.</param>
/// <param name="service">The service.</param>
/// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param>
internal void LoadFromJson(JsonObject jsonObject, ExchangeService service, bool clearPropertyBag)
{
this.PropertyBag.LoadFromJson(
jsonObject,
service,
clearPropertyBag,
null, /* propertySet */
false); /* summaryPropertiesOnly */
}
/// <summary>
/// Clears the object's change log.
/// </summary>
internal void ClearChangeLog()
{
this.PropertyBag.ClearChangeLog();
}
/// <summary>
/// Writes service object as XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal void WriteToXml(EwsServiceXmlWriter writer)
{
this.PropertyBag.WriteToXml(writer);
}
/// <summary>
/// Creates a JSON representation of this object.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="isUpdateOperation">if set to <c>true</c> [is update operation].</param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
internal object ToJson(ExchangeService service, bool isUpdateOperation)
{
return this.PropertyBag.ToJson(service, isUpdateOperation);
}
/// <summary>
/// Writes service object for update as XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal void WriteToXmlForUpdate(EwsServiceXmlWriter writer)
{
this.PropertyBag.WriteToXmlForUpdate(writer);
}
/// <summary>
/// Writes service object for update as Json.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
internal object WriteToJsonForUpdate(ExchangeService service)
{
return this.PropertyBag.ToJson(service, true);
}
/// <summary>
/// Loads the specified set of properties on the object.
/// </summary>
/// <param name="propertySet">The properties to load.</param>
internal abstract void InternalLoad(PropertySet propertySet);
/// <summary>
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
internal abstract void InternalDelete(
DeleteMode deleteMode,
SendCancellationsMode? sendCancellationsMode,
AffectedTaskOccurrence? affectedTaskOccurrences);
/// <summary>
/// Loads the specified set of properties. Calling this method results in a call to EWS.
/// </summary>
/// <param name="propertySet">The properties to load.</param>
public void Load(PropertySet propertySet)
{
this.InternalLoad(propertySet);
}
/// <summary>
/// Loads the first class properties. Calling this method results in a call to EWS.
/// </summary>
public void Load()
{
this.InternalLoad(PropertySet.FirstClassProperties);
}
/// <summary>
/// Gets the value of specified property in this instance.
/// </summary>
/// <param name="propertyDefinition">Definition of the property to get.</param>
/// <exception cref="ServiceVersionException">Raised if this property requires a later version of Exchange.</exception>
/// <exception cref="PropertyException">Raised if this property hasn't been assigned or loaded. Raised for set if property cannot be updated or deleted.</exception>
public object this[PropertyDefinitionBase propertyDefinition]
{
get
{
object propertyValue;
PropertyDefinition propDef = propertyDefinition as PropertyDefinition;
if (propDef != null)
{
return this.PropertyBag[propDef];
}
else
{
ExtendedPropertyDefinition extendedPropDef = propertyDefinition as ExtendedPropertyDefinition;
if (extendedPropDef != null)
{
if (this.TryGetExtendedProperty(extendedPropDef, out propertyValue))
{
return propertyValue;
}
else
{
throw new ServiceObjectPropertyException(Strings.MustLoadOrAssignPropertyBeforeAccess, propertyDefinition);
}
}
else
{
// Other subclasses of PropertyDefinitionBase are not supported.
throw new NotSupportedException(string.Format(
Strings.OperationNotSupportedForPropertyDefinitionType,
propertyDefinition.GetType().Name));
}
}
}
}
/// <summary>
/// Try to get the value of a specified extended property in this instance.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="propertyValue">The property value.</param>
/// <typeparam name="T">Type of expected property value.</typeparam>
/// <returns>True if property retrieved, false otherwise.</returns>
internal bool TryGetExtendedProperty<T>(ExtendedPropertyDefinition propertyDefinition, out T propertyValue)
{
ExtendedPropertyCollection propertyCollection = this.GetExtendedProperties();
if ((propertyCollection != null) &&
propertyCollection.TryGetValue<T>(propertyDefinition, out propertyValue))
{
return true;
}
else
{
propertyValue = default(T);
return false;
}
}
/// <summary>
/// Try to get the value of a specified property in this instance.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="propertyValue">The property value.</param>
/// <returns>True if property retrieved, false otherwise.</returns>
public bool TryGetProperty(PropertyDefinitionBase propertyDefinition, out object propertyValue)
{
return this.TryGetProperty<object>(propertyDefinition, out propertyValue);
}
/// <summary>
/// Try to get the value of a specified property in this instance.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="propertyValue">The property value.</param>
/// <typeparam name="T">Type of expected property value.</typeparam>
/// <returns>True if property retrieved, false otherwise.</returns>
public bool TryGetProperty<T>(PropertyDefinitionBase propertyDefinition, out T propertyValue)
{
PropertyDefinition propDef = propertyDefinition as PropertyDefinition;
if (propDef != null)
{
return this.PropertyBag.TryGetProperty<T>(propDef, out propertyValue);
}
else
{
ExtendedPropertyDefinition extPropDef = propertyDefinition as ExtendedPropertyDefinition;
if (extPropDef != null)
{
return this.TryGetExtendedProperty<T>(extPropDef, out propertyValue);
}
else
{
// Other subclasses of PropertyDefinitionBase are not supported.
throw new NotSupportedException(string.Format(
Strings.OperationNotSupportedForPropertyDefinitionType,
propertyDefinition.GetType().Name));
}
}
}
/// <summary>
/// Gets the collection of loaded property definitions.
/// </summary>
/// <returns>Collection of property definitions.</returns>
public Collection<PropertyDefinitionBase> GetLoadedPropertyDefinitions()
{
Collection<PropertyDefinitionBase> propDefs = new Collection<PropertyDefinitionBase>();
foreach (PropertyDefinition propDef in this.PropertyBag.Properties.Keys)
{
propDefs.Add(propDef);
}
if (this.GetExtendedProperties() != null)
{
foreach (ExtendedProperty extProp in this.GetExtendedProperties())
{
propDefs.Add(extProp.PropertyDefinition);
}
}
return propDefs;
}
/// <summary>
/// Gets the ExchangeService the object is bound to.
/// </summary>
public ExchangeService Service
{
get { return this.service; }
internal set { this.service = value; }
}
/// <summary>
/// The property definition for the Id of this object.
/// </summary>
/// <returns>A PropertyDefinition instance.</returns>
internal virtual PropertyDefinition GetIdPropertyDefinition()
{
return null;
}
/// <summary>
/// The unique Id of this object.
/// </summary>
/// <returns>A ServiceId instance.</returns>
internal ServiceId GetId()
{
PropertyDefinition idPropertyDefinition = this.GetIdPropertyDefinition();
object serviceId = null;
if (idPropertyDefinition != null)
{
this.PropertyBag.TryGetValue(idPropertyDefinition, out serviceId);
}
return (ServiceId)serviceId;
}
/// <summary>
/// Indicates whether this object is a real store item, or if it's a local object
/// that has yet to be saved.
/// </summary>
public virtual bool IsNew
{
get
{
ServiceId id = this.GetId();
return id == null ? true : !id.IsValid;
}
}
/// <summary>
/// Gets a value indicating whether the object has been modified and should be saved.
/// </summary>
public bool IsDirty
{
get { return this.PropertyBag.IsDirty; }
}
/// <summary>
/// Gets the extended properties collection.
/// </summary>
/// <returns>Extended properties collection.</returns>
internal virtual ExtendedPropertyCollection GetExtendedProperties()
{
return null;
}
/// <summary>
/// Defines an event that is triggered when the service object changes.
/// </summary>
internal event ServiceObjectChangedDelegate OnChange;
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CustomerLabelServiceClient"/> instances.</summary>
public sealed partial class CustomerLabelServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerLabelServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerLabelServiceSettings"/>.</returns>
public static CustomerLabelServiceSettings GetDefault() => new CustomerLabelServiceSettings();
/// <summary>Constructs a new <see cref="CustomerLabelServiceSettings"/> object with default settings.</summary>
public CustomerLabelServiceSettings()
{
}
private CustomerLabelServiceSettings(CustomerLabelServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerLabelSettings = existing.GetCustomerLabelSettings;
MutateCustomerLabelsSettings = existing.MutateCustomerLabelsSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerLabelServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerLabelServiceClient.GetCustomerLabel</c> and <c>CustomerLabelServiceClient.GetCustomerLabelAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerLabelServiceClient.MutateCustomerLabels</c> and
/// <c>CustomerLabelServiceClient.MutateCustomerLabelsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerLabelServiceSettings"/> object.</returns>
public CustomerLabelServiceSettings Clone() => new CustomerLabelServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerLabelServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CustomerLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerLabelServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerLabelServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerLabelServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerLabelServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerLabelServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerLabelServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerLabelServiceClient Build()
{
CustomerLabelServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerLabelServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerLabelServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerLabelServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerLabelServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerLabelServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerLabelServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerLabelServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerLabelService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on customers.
/// </remarks>
public abstract partial class CustomerLabelServiceClient
{
/// <summary>
/// The default endpoint for the CustomerLabelService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerLabelService scopes.</summary>
/// <remarks>
/// The default CustomerLabelService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerLabelServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerLabelServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerLabelServiceClient"/>.</returns>
public static stt::Task<CustomerLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerLabelServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerLabelServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CustomerLabelServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerLabelServiceClient"/>.</returns>
public static CustomerLabelServiceClient Create() => new CustomerLabelServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerLabelServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerLabelServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerLabelServiceClient"/>.</returns>
internal static CustomerLabelServiceClient Create(grpccore::CallInvoker callInvoker, CustomerLabelServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerLabelService.CustomerLabelServiceClient grpcClient = new CustomerLabelService.CustomerLabelServiceClient(callInvoker);
return new CustomerLabelServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerLabelService client</summary>
public virtual CustomerLabelService.CustomerLabelServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabel(new GetCustomerLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabelAsync(new GetCustomerLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerLabel GetCustomerLabel(gagvr::CustomerLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabel(new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(gagvr::CustomerLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerLabelAsync(new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer-label relationship to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(gagvr::CustomerLabelName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerLabelsResponse MutateCustomerLabels(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerLabelsResponse MutateCustomerLabels(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerLabels(new MutateCustomerLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerLabelsAsync(new MutateCustomerLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose customer-label relationships are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on customer-label relationships.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(string customerId, scg::IEnumerable<CustomerLabelOperation> operations, st::CancellationToken cancellationToken) =>
MutateCustomerLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerLabelService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on customers.
/// </remarks>
public sealed partial class CustomerLabelServiceClientImpl : CustomerLabelServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel> _callGetCustomerLabel;
private readonly gaxgrpc::ApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse> _callMutateCustomerLabels;
/// <summary>
/// Constructs a client wrapper for the CustomerLabelService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CustomerLabelServiceSettings"/> used within this client.</param>
public CustomerLabelServiceClientImpl(CustomerLabelService.CustomerLabelServiceClient grpcClient, CustomerLabelServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerLabelServiceSettings effectiveSettings = settings ?? CustomerLabelServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerLabel = clientHelper.BuildApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel>(grpcClient.GetCustomerLabelAsync, grpcClient.GetCustomerLabel, effectiveSettings.GetCustomerLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerLabel);
Modify_GetCustomerLabelApiCall(ref _callGetCustomerLabel);
_callMutateCustomerLabels = clientHelper.BuildApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse>(grpcClient.MutateCustomerLabelsAsync, grpcClient.MutateCustomerLabels, effectiveSettings.MutateCustomerLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerLabels);
Modify_MutateCustomerLabelsApiCall(ref _callMutateCustomerLabels);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerLabelApiCall(ref gaxgrpc::ApiCall<GetCustomerLabelRequest, gagvr::CustomerLabel> call);
partial void Modify_MutateCustomerLabelsApiCall(ref gaxgrpc::ApiCall<MutateCustomerLabelsRequest, MutateCustomerLabelsResponse> call);
partial void OnConstruction(CustomerLabelService.CustomerLabelServiceClient grpcClient, CustomerLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerLabelService client</summary>
public override CustomerLabelService.CustomerLabelServiceClient GrpcClient { get; }
partial void Modify_GetCustomerLabelRequest(ref GetCustomerLabelRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerLabelsRequest(ref MutateCustomerLabelsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CustomerLabel GetCustomerLabel(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerLabelRequest(ref request, ref callSettings);
return _callGetCustomerLabel.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested customer-label relationship in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CustomerLabel> GetCustomerLabelAsync(GetCustomerLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerLabelRequest(ref request, ref callSettings);
return _callGetCustomerLabel.Async(request, callSettings);
}
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerLabelsResponse MutateCustomerLabels(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerLabelsRequest(ref request, ref callSettings);
return _callMutateCustomerLabels.Sync(request, callSettings);
}
/// <summary>
/// Creates and removes customer-label relationships.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [LabelError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerLabelsResponse> MutateCustomerLabelsAsync(MutateCustomerLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerLabelsRequest(ref request, ref callSettings);
return _callMutateCustomerLabels.Async(request, callSettings);
}
}
}
| |
//
// ContentDisposition.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2015 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
#if PORTABLE
using Encoding = Portable.Text.Encoding;
#endif
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A class representing a Content-Disposition header value.
/// </summary>
/// <remarks>
/// The Content-Disposition header is a way for the originating client to
/// suggest to the receiving client whether to present the part to the user
/// as an attachment or as part of the content (inline).
/// </remarks>
public class ContentDisposition
{
/// <summary>
/// The attachment disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be treated as an attachment.
/// </remarks>
public const string Attachment = "attachment";
/// <summary>
/// The form-data disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be treated as form data.
/// </remarks>
public const string FormData = "form-data";
/// <summary>
/// The inline disposition.
/// </summary>
/// <remarks>
/// Indicates that the <see cref="MimePart"/> should be rendered inline.
/// </remarks>
public const string Inline = "inline";
static readonly StringComparer icase = StringComparer.OrdinalIgnoreCase;
ParameterList parameters;
string disposition;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// The disposition should either be <see cref="ContentDisposition.Attachment"/>
/// or <see cref="ContentDisposition.Inline"/>.
/// </remarks>
/// <param name="disposition">The disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="disposition"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="disposition"/> is not <c>"attachment"</c> or <c>"inline"</c>.
/// </exception>
public ContentDisposition (string disposition)
{
Parameters = new ParameterList ();
Disposition = disposition;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// This is identical to <see cref="ContentDisposition(string)"/> with a disposition
/// value of <see cref="ContentDisposition.Attachment"/>.
/// </remarks>
public ContentDisposition () : this (Attachment)
{
}
static bool IsAsciiAtom (byte c)
{
return c.IsAsciiAtom ();
}
/// <summary>
/// Gets or sets the disposition.
/// </summary>
/// <remarks>
/// The disposition is typically either <c>"attachment"</c> or <c>"inline"</c>.
/// </remarks>
/// <value>The disposition.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is an invalid disposition value.
/// </exception>
public string Disposition {
get { return disposition; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("The disposition is not allowed to be empty.", "value");
for (int i = 0; i < value.Length; i++) {
if (value[i] >= 127 || !IsAsciiAtom ((byte) value[i]))
throw new ArgumentException ("Illegal characters in disposition value.", "value");
}
if (disposition == value)
return;
disposition = value;
OnChanged ();
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="MimePart"/> is an attachment.
/// </summary>
/// <remarks>
/// A convenience property to determine if the entity should be considered an attachment or not.
/// </remarks>
/// <value><c>true</c> if the <see cref="MimePart"/> is an attachment; otherwise, <c>false</c>.</value>
public bool IsAttachment {
get { return icase.Compare (disposition, Attachment) == 0; }
set { disposition = value ? Attachment : Inline; }
}
/// <summary>
/// Gets the parameters.
/// </summary>
/// <remarks>
/// In addition to specifying whether the entity should be treated as an
/// attachment vs displayed inline, the Content-Disposition header may also
/// contain parameters to provide further information to the receiving client
/// such as the file attributes.
/// </remarks>
/// <value>The parameters.</value>
public ParameterList Parameters {
get { return parameters; }
private set {
if (parameters != null)
parameters.Changed -= OnParametersChanged;
value.Changed += OnParametersChanged;
parameters = value;
}
}
/// <summary>
/// Gets or sets the name of the file.
/// </summary>
/// <remarks>
/// When set, this can provide a useful hint for a default file name for the
/// content when the user decides to save it to disk.
/// </remarks>
/// <value>The name of the file.</value>
public string FileName {
get { return Parameters["filename"]; }
set {
if (value != null)
Parameters["filename"] = value;
else
Parameters.Remove ("filename");
}
}
static bool IsNullOrWhiteSpace (string value)
{
if (string.IsNullOrEmpty (value))
return true;
for (int i = 0; i < value.Length; i++) {
if (!char.IsWhiteSpace (value[i]))
return false;
}
return true;
}
/// <summary>
/// Gets or sets the creation-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was created on the
/// originating system. This parameter serves little purpose and is
/// typically not used by mail clients.
/// </remarks>
/// <value>The creation date.</value>
public DateTimeOffset? CreationDate {
get {
var value = Parameters["creation-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset ctime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out ctime))
return null;
return ctime;
}
set {
if (value.HasValue)
Parameters["creation-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("creation-date");
}
}
/// <summary>
/// Gets or sets the modification-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was last modified on
/// the originating system. This parameter serves little purpose and is
/// typically not used by mail clients.
/// </remarks>
/// <value>The modification date.</value>
public DateTimeOffset? ModificationDate {
get {
var value = Parameters["modification-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset mtime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out mtime))
return null;
return mtime;
}
set {
if (value.HasValue)
Parameters["modification-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("modification-date");
}
}
/// <summary>
/// Gets or sets the read-date parameter.
/// </summary>
/// <remarks>
/// Refers to the date and time that the content file was last read on the
/// originating system. This parameter serves little purpose and is typically
/// not used by mail clients.
/// </remarks>
/// <value>The read date.</value>
public DateTimeOffset? ReadDate {
get {
var value = Parameters["read-date"];
if (IsNullOrWhiteSpace (value))
return null;
var buffer = Encoding.UTF8.GetBytes (value);
DateTimeOffset atime;
if (!DateUtils.TryParse (buffer, 0, buffer.Length, out atime))
return null;
return atime;
}
set {
if (value.HasValue)
Parameters["read-date"] = DateUtils.FormatDate (value.Value);
else
Parameters.Remove ("read-date");
}
}
/// <summary>
/// Gets or sets the size parameter.
/// </summary>
/// <remarks>
/// When set, the size parameter typically refers to the original size of the
/// content on disk. This parameter is rarely used by mail clients as it serves
/// little purpose.
/// </remarks>
/// <value>The size.</value>
public long? Size {
get {
var value = Parameters["size"];
if (IsNullOrWhiteSpace (value))
return null;
long size;
if (!long.TryParse (value, out size))
return null;
return size;
}
set {
if (value.HasValue)
Parameters["size"] = value.Value.ToString ();
else
Parameters.Remove ("size");
}
}
internal string Encode (FormatOptions options, Encoding charset)
{
int lineLength = "Content-Disposition: ".Length;
var value = new StringBuilder (" ");
value.Append (disposition);
Parameters.Encode (options, value, ref lineLength, charset);
value.Append (options.NewLine);
return value.ToString ();
}
/// <summary>
/// Serializes the <see cref="MimeKit.ContentDisposition"/> to a string,
/// optionally encoding the parameters.
/// </summary>
/// <remarks>
/// Creates a string-representation of the <see cref="ContentDisposition"/>,
/// optionally encoding the parameters as they would be encoded for trabsport.
/// </remarks>
/// <returns>The serialized string.</returns>
/// <param name="charset">The charset to be used when encoding the parameter values.</param>
/// <param name="encode">If set to <c>true</c>, the parameter values will be encoded.</param>
public string ToString (Encoding charset, bool encode)
{
if (charset == null)
throw new ArgumentNullException ("charset");
var value = new StringBuilder ("Content-Disposition: ");
value.Append (disposition);
if (encode) {
var options = FormatOptions.GetDefault ();
int lineLength = value.Length;
Parameters.Encode (options, value, ref lineLength, charset);
} else {
value.Append (Parameters.ToString ());
}
return value.ToString ();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ContentDisposition"/>.
/// </summary>
/// <remarks>
/// Creates a string-representation of the <see cref="ContentDisposition"/>.
/// </remarks>
/// <returns>A <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ContentDisposition"/>.</returns>
public override string ToString ()
{
return ToString (Encoding.UTF8, false);
}
internal event EventHandler Changed;
void OnParametersChanged (object sender, EventArgs e)
{
OnChanged ();
}
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentDisposition disposition)
{
string type;
int atom;
disposition = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
atom = index;
if (!ParseUtils.SkipAtom (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format ("Invalid atom token at position {0}", atom), atom, index);
return false;
}
type = Encoding.ASCII.GetString (text, atom, index - atom);
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
disposition = new ContentDisposition ();
disposition.disposition = type;
if (index >= endIndex)
return true;
if (text[index] != (byte) ';') {
if (throwOnError)
throw new ParseException (string.Format ("Expected ';' at position {0}", index), index, index);
return false;
}
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex)
return true;
ParameterList parameters;
if (!ParameterList.TryParse (options, text, ref index, endIndex, throwOnError, out parameters))
return false;
disposition.Parameters = parameters;
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out ContentDisposition disposition)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (buffer.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
int index = startIndex;
return TryParse (options, buffer, ref index, startIndex + length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out ContentDisposition disposition)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex >= buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
int index = startIndex;
return TryParse (options, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out ContentDisposition disposition)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
int index = 0;
return TryParse (options, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified buffer.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out ContentDisposition disposition)
{
return TryParse (ParserOptions.Default, buffer, out disposition);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.ContentDisposition"/> instance.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied text.
/// </remarks>
/// <returns><c>true</c>, if the disposition was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="disposition">The parsed disposition.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out ContentDisposition disposition)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
int index = 0;
return TryParse (ParserOptions.Default, buffer, ref index, buffer.Length, false, out disposition);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <param name="length">The length of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || length > (buffer.Length - startIndex))
throw new ArgumentOutOfRangeException ("length");
ContentDisposition disposition;
int index = startIndex;
TryParse (options, buffer, ref index, startIndex + length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the given index
/// and spanning across the specified number of bytes.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <param name="length">The length of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer, int startIndex)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
ContentDisposition disposition;
int index = startIndex;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer starting at the specified index.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The start index of the buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, byte[] buffer)
{
if (options == null)
throw new ArgumentNullException ("options");
if (buffer == null)
throw new ArgumentNullException ("buffer");
ContentDisposition disposition;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the supplied buffer.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="buffer"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parse the specified text into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="options">The parser options.</param>
/// <param name="text">The input text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="text"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (ParserOptions options, string text)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
ContentDisposition disposition;
int index = 0;
TryParse (options, buffer, ref index, buffer.Length, true, out disposition);
return disposition;
}
/// <summary>
/// Parse the specified text into a new instance of the <see cref="MimeKit.ContentDisposition"/> class.
/// </summary>
/// <remarks>
/// Parses a Content-Disposition value from the specified text.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.ContentDisposition"/>.</returns>
/// <param name="text">The input text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// The <paramref name="text"/> could not be parsed.
/// </exception>
public static ContentDisposition Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Python.LanguageServer;
using Microsoft.PythonTools.Editor;
using Microsoft.PythonTools.Editor.Core;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
namespace Microsoft.PythonTools.Intellisense {
/// <summary>
/// Provides various completion services after the text around the current location has been
/// processed. The completion services are specific to the current context
/// </summary>
internal class CompletionAnalysis {
internal const long TooMuchTime = 50;
private static readonly Stopwatch _stopwatch = MakeStopWatch();
private readonly PythonEditorServices _services;
private readonly ICompletionSession _session;
private readonly ITextView _view;
private readonly ITextBuffer _textBuffer;
private readonly ITextSnapshot _snapshot;
private readonly ITrackingPoint _point;
private readonly CompletionOptions _options;
private ITrackingSpan _span;
internal static CompletionAnalysis EmptyCompletionContext = new CompletionAnalysis(null, null, null, null, null, null);
internal CompletionAnalysis(PythonEditorServices services, ICompletionSession session, ITextView view, ITextSnapshot snapshot, ITrackingPoint point, CompletionOptions options) {
_session = session;
_view = view;
_services = services;
_snapshot = snapshot;
_textBuffer = snapshot?.TextBuffer;
_point = point;
_options = options == null ? new CompletionOptions() : options.Clone();
}
public CompletionSet GetCompletions(IGlyphService glyphService) {
if (_snapshot == null) {
return null;
}
var start = _stopwatch.ElapsedMilliseconds;
var interactiveWindow = _snapshot.TextBuffer.GetInteractiveWindow();
var pyReplEval = interactiveWindow?.Evaluator as IPythonInteractiveIntellisense;
var bufferInfo = PythonTextBufferInfo.TryGetForBuffer(_textBuffer);
Debug.Assert(bufferInfo != null, "Getting completions from uninitialized buffer " + _textBuffer);
var analysis = bufferInfo?.AnalysisEntry;
var analyzer = analysis?.Analyzer;
if (analyzer == null) {
return null;
}
var point = _point.GetPoint(bufferInfo.CurrentSnapshot);
var location = VsProjectAnalyzer.TranslateIndex(
point.Position,
point.Snapshot,
analysis
);
var triggerChar = _session.GetTriggerCharacter();
var completions = analyzer.WaitForRequest(analyzer.GetCompletionsAsync(
analysis,
location,
_options.MemberOptions,
triggerChar == '\0' ? CompletionTriggerKind.Invoked : CompletionTriggerKind.TriggerCharacter,
triggerChar == '\0' ? null : triggerChar.ToString()
), "GetCompletions.GetMembers", null, pyReplEval?.Analyzer == null ? 1 : 5);
if (completions == null) {
return null;
}
var snapshotSpan = completions._applicableSpan.HasValue
? ((SourceSpan)completions._applicableSpan.Value).ToSnapshotSpan(_snapshot)
: new SnapshotSpan(point, 0);
_span = bufferInfo.CurrentSnapshot.CreateTrackingSpan(snapshotSpan, SpanTrackingMode.EdgeInclusive);
var members = completions.items.MaybeEnumerate().Select(c => new CompletionResult(
// if a method stub generation (best guess by comparing length),
// merge entry based on label, for everything else, use insertion text
c.filterText ?? (c.insertText != null && c.insertText.Length <= c.label.Length ? c.insertText : c.label),
c.label,
c.insertText ?? c.label,
c.documentation?.value,
Enum.TryParse(c._kind, true, out PythonMemberType mt) ? mt : PythonMemberType.Unknown,
null
));
if (pyReplEval?.Analyzer != null && (string.IsNullOrEmpty(completions._expr) || pyReplEval.Analyzer.ShouldEvaluateForCompletion(completions._expr))) {
var replMembers = pyReplEval.GetMemberNames(completions._expr ?? "");
if (_services.Python.InteractiveOptions.LiveCompletionsOnly) {
members = replMembers ?? Array.Empty<CompletionResult>();
} else if (replMembers != null) {
members = members.Union(replMembers, CompletionMergeKeyComparer.Instance);
}
}
if (pyReplEval == null && (completions._allowSnippet ?? false)) {
var expansions = analyzer.WaitForRequest(_services.Python?.GetExpansionCompletionsAsync(), "GetCompletions.GetExpansions", null, 5);
if (expansions != null) {
// Expansions should come first, so that they replace our keyword
// completions with the more detailed snippets.
members = expansions.Union(members, CompletionMergeKeyComparer.Instance);
}
}
var end = _stopwatch.ElapsedMilliseconds;
if (/*Logging &&*/ (end - start) > TooMuchTime) {
var memberArray = members.ToArray();
members = memberArray;
Trace.WriteLine($"{this} lookup time {end - start} for {memberArray.Length} members");
}
start = _stopwatch.ElapsedMilliseconds;
var result = new FuzzyCompletionSet(
"Python",
"Python",
_span,
members.Select(m => PythonCompletion(glyphService, m)),
_options,
CompletionComparer.UnderscoresLast,
matchInsertionText: true
) {
CommitByDefault = completions._commitByDefault ?? true
};
end = _stopwatch.ElapsedMilliseconds;
if (/*Logging &&*/ (end - start) > TooMuchTime) {
Trace.WriteLine($"{this} completion set time {end - start} total time {end - start}");
}
return result;
}
internal DynamicallyVisibleCompletion PythonCompletion(IGlyphService service, CompletionResult memberResult) {
var insert = memberResult.Completion;
if (insert.IndexOf('\t') >= 0 && _view.Options.IsConvertTabsToSpacesEnabled()) {
insert = insert.Replace("\t", new string(' ', _view.Options.GetIndentSize()));
}
return new DynamicallyVisibleCompletion(memberResult.Name,
insert,
() => memberResult.Documentation,
() => service.GetGlyph(memberResult.MemberType.ToGlyphGroup(), StandardGlyphItem.GlyphItemPublic),
Enum.GetName(typeof(PythonMemberType), memberResult.MemberType)
);
}
internal static DynamicallyVisibleCompletion PythonCompletion(IGlyphService service, string name, string tooltip, StandardGlyphGroup group) {
var icon = new IconDescription(group, StandardGlyphItem.GlyphItemPublic);
var result = new DynamicallyVisibleCompletion(name,
name,
tooltip,
service.GetGlyph(group, StandardGlyphItem.GlyphItemPublic),
Enum.GetName(typeof(StandardGlyphGroup), group));
result.Properties.AddProperty(typeof(IconDescription), icon);
return result;
}
internal static DynamicallyVisibleCompletion PythonCompletion(IGlyphService service, string name, string completion, string tooltip, StandardGlyphGroup group) {
var icon = new IconDescription(group, StandardGlyphItem.GlyphItemPublic);
var result = new DynamicallyVisibleCompletion(name,
completion,
tooltip,
service.GetGlyph(group, StandardGlyphItem.GlyphItemPublic),
Enum.GetName(typeof(StandardGlyphGroup), group));
result.Properties.AddProperty(typeof(IconDescription), icon);
return result;
}
private static Stopwatch MakeStopWatch() {
var res = new Stopwatch();
res.Start();
return res;
}
public override string ToString() {
if (_span == null) {
return "CompletionContext.EmptyCompletionContext";
}
var snapSpan = _span.GetSpan(_textBuffer.CurrentSnapshot);
return String.Format("CompletionContext({0}): {1} @{2}", GetType().Name, snapSpan.GetText(), snapSpan.Span);
}
}
}
| |
using J2N.Text;
using System;
using System.Text;
namespace YAF.Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
/// <summary>
/// A <see cref="Term"/> represents a word from text. This is the unit of search. It is
/// composed of two elements, the text of the word, as a string, and the name of
/// the field that the text occurred in.
/// <para/>
/// Note that terms may represent more than words from text fields, but also
/// things like dates, email addresses, urls, etc.
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public sealed class Term : IComparable<Term>, IEquatable<Term> // LUCENENET specific - class implements IEquatable<T>
{
/// <summary>
/// Constructs a <see cref="Term"/> with the given field and bytes.
/// <para/>Note that a null field or null bytes value results in undefined
/// behavior for most Lucene APIs that accept a Term parameter.
///
/// <para/>WARNING: the provided <see cref="BytesRef"/> is not copied, but used directly.
/// Therefore the bytes should not be modified after construction, for
/// example, you should clone a copy by <see cref="BytesRef.DeepCopyOf(BytesRef)"/>
/// rather than pass reused bytes from a <see cref="TermsEnum"/>.
/// </summary>
public Term(string fld, BytesRef bytes)
{
Field = fld;
Bytes = bytes;
}
/// <summary>
/// Constructs a <see cref="Term"/> with the given field and text.
/// <para/>Note that a <c>null</c> field or null text value results in undefined
/// behavior for most Lucene APIs that accept a <see cref="Term"/> parameter.
/// </summary>
public Term(string fld, string text)
: this(fld, new BytesRef(text))
{
}
/// <summary>
/// Constructs a <see cref="Term"/> with the given field and empty text.
/// this serves two purposes: 1) reuse of a <see cref="Term"/> with the same field.
/// 2) pattern for a query.
/// </summary>
/// <param name="fld"> field's name </param>
public Term(string fld)
: this(fld, new BytesRef())
{
}
/// <summary>
/// Returns the field of this term. The field indicates
/// the part of a document which this term came from.
/// </summary>
public string Field { get; internal set; }
/// <summary>
/// Returns the text of this term. In the case of words, this is simply the
/// text of the word. In the case of dates and other types, this is an
/// encoding of the object as a string.
/// </summary>
public string Text()
{
return ToString(Bytes);
}
/// <summary>
/// Returns human-readable form of the term text. If the term is not unicode,
/// the raw bytes will be printed instead.
/// </summary>
public static string ToString(BytesRef termText)
{
// the term might not be text, but usually is. so we make a best effort
Encoding decoder = new UTF8Encoding(false, true);
try
{
return decoder.GetString(termText.Bytes, termText.Offset, termText.Length);
}
catch
{
return termText.ToString();
}
}
/// <summary>
/// Returns the bytes of this term.
/// </summary>
public BytesRef Bytes { get; internal set; }
public override bool Equals(object obj)
{
Term t = obj as Term;
return this.Equals(t);
}
public override int GetHashCode()
{
const int prime = 31;
int result = 1;
result = prime * result + ((Field == null) ? 0 : Field.GetHashCode());
result = prime * result + ((Bytes == null) ? 0 : Bytes.GetHashCode());
return result;
}
/// <summary>
/// Compares two terms, returning a negative integer if this
/// term belongs before the argument, zero if this term is equal to the
/// argument, and a positive integer if this term belongs after the argument.
/// <para/>
/// The ordering of terms is first by field, then by text.
/// </summary>
public int CompareTo(Term other)
{
int compare = Field.CompareToOrdinal(other.Field);
if (compare == 0)
{
return Bytes.CompareTo(other.Bytes);
}
else
{
return compare;
}
}
/// <summary>
/// Resets the field and text of a <see cref="Term"/>.
/// <para/>WARNING: the provided <see cref="BytesRef"/> is not copied, but used directly.
/// Therefore the bytes should not be modified after construction, for
/// example, you should clone a copy rather than pass reused bytes from
/// a TermsEnum.
/// </summary>
internal void Set(string fld, BytesRef bytes)
{
Field = fld;
this.Bytes = bytes;
}
public bool Equals(Term other)
{
if (object.ReferenceEquals(null, other))
{
return object.ReferenceEquals(null, this);
}
if (object.ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
if (string.Compare(this.Field, other.Field, StringComparison.Ordinal) != 0)
{
return false;
}
if (Bytes == null)
{
if (other.Bytes != null)
{
return false;
}
}
else if (!Bytes.Equals(other.Bytes))
{
return false;
}
return true;
}
public override string ToString()
{
return Field + ":" + Text();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
/// <summary>Characters that can't be used in a pipe's name.</summary>
private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>Characters that can't be used in an absolute path pipe's name.</summary>
private static readonly char[] s_invalidPathNameChars = Path.GetInvalidPathChars();
/// <summary>Prefix to prepend to all pipe names.</summary>
private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_");
internal static string GetPipePath(string serverName, string pipeName)
{
if (serverName != "." && serverName != Interop.Sys.GetHostName())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
}
if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
// Match Windows constraint
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
// Since pipes are stored as files in the system we support either an absolute path to a file name
// or a file name. The support of absolute path was added to allow working around the limited
// length available for the pipe name when concatenated with the temp path, while being
// cross-platform with Windows (which has only '\' as an invalid char).
if (Path.IsPathRooted(pipeName))
{
if (pipeName.IndexOfAny(s_invalidPathNameChars) >= 0 || pipeName[pipeName.Length - 1] == Path.DirectorySeparatorChar)
throw new PlatformNotSupportedException(SR.PlatformNotSupported_InvalidPipeNameChars);
// Caller is in full control of file location.
return pipeName;
}
if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_InvalidPipeNameChars);
}
// The pipe is created directly under Path.GetTempPath() with "CoreFXPipe_" prefix.
//
// We previously didn't put it into a subdirectory because it only existed on disk for the duration
// between when the server started listening in WaitForConnection and when the client
// connected, after which the pipe was deleted. We now create the pipe when the
// server stream is created, which leaves it on disk longer, but we can't change the
// naming scheme used as that breaks the ability for code running on an older
// runtime to connect to code running on the newer runtime. That means we're stuck
// with a tmp file for the lifetime of the server stream.
return s_pipePrefix + pipeName;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
if (safePipeHandle.NamedPipeSocket == null)
{
Interop.Sys.FileStatus status;
int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
(status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
internal virtual void DisposeCore(bool disposing)
{
// nop
}
private unsafe int ReadCore(Span<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, receive on the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Read syscall as is done
// for reading an anonymous pipe. However, for a non-blocking socket, Read could
// end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case
// is already handled by Socket.Receive, so we use it here.
try
{
return socket.Receive(buffer, SocketFlags.None);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, read from the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length));
Debug.Assert(result <= buffer.Length);
return result;
}
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, send to the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Write syscall as is done
// for writing to anonymous pipe. However, for a non-blocking socket, Write could
// end up returning EWOULDBLOCK rather than blocking waiting for space available.
// Such a case is already handled by Socket.Send, so we use it here.
try
{
while (buffer.Length > 0)
{
int bytesWritten = socket.Send(buffer, SocketFlags.None);
buffer = buffer.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, write the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
while (buffer.Length > 0)
{
int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length));
buffer = buffer.Slice(bytesWritten);
}
}
}
private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
Socket socket = InternalHandle.NamedPipeSocket;
try
{
// TODO #22608:
// Remove all of this cancellation workaround once Socket.ReceiveAsync
// that accepts a CancellationToken is available.
// If a cancelable token is used and there's no data, issue a zero-length read so that
// we're asynchronously notified when data is available, and concurrently monitor the
// supplied cancellation token. If cancellation is requested, we will end up "leaking"
// the zero-length read until data becomes available, at which point it'll be satisfied.
// But it's very rare to reuse a stream after an operation has been canceled, so even if
// we do incur such a situation, it's likely to be very short lived.
if (cancellationToken.CanBeCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
if (socket.Available == 0)
{
Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None);
if (!t.IsCompletedSuccessfully)
{
var cancelTcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs))
{
if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false))
{
t.GetAwaiter().GetResult(); // propagate any failure
}
cancellationToken.ThrowIfCancellationRequested();
// At this point there was data available. In the rare case where multiple concurrent
// ReadAsyncs are issued against the PipeStream, worst case is the reads that lose
// the race condition for the data will end up in a non-cancelable state as part of
// the actual async receive operation.
}
}
}
}
// Issue the asynchronous read.
return await (MemoryMarshal.TryGetArray(destination, out ArraySegment<byte> buffer) ?
socket.ReceiveAsync(buffer, SocketFlags.None) :
socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
// TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync
// accepts a Memory<T> in the near future.
byte[] buffer;
int offset, count;
if (MemoryMarshal.TryGetArray(source, out ArraySegment<byte> segment))
{
buffer = segment.Array;
offset = segment.Offset;
count = segment.Count;
}
else
{
buffer = source.ToArray();
offset = 0;
count = buffer.Length;
}
while (count > 0)
{
// cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if
// cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and
// most writes will complete immediately as they simply store data into the socket's buffer. The only time we end
// up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation.
cancellationToken.ThrowIfCancellationRequested();
int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
Debug.Assert(bytesWritten <= count);
count -= bytesWritten;
offset += bytesWritten;
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private IOException GetIOExceptionForSocketException(SocketException e)
{
if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
{
State = PipeState.Broken;
}
return new IOException(e.Message, e);
}
// Blocks until the other end of the pipe has read in all written buffer.
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// For named pipes on sockets, we could potentially partially implement this
// via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However,
// that would require polling, and it wouldn't actually mean that the other
// end has read all of the data, just that the data has left this end's buffer.
throw new PlatformNotSupportedException(); // not fully implementable on unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static void CreateDirectory(string directoryPath)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(
HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe
int* fds = stackalloc int[2];
CreateAnonymousPipe(inheritability, fds);
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
internal int CheckPipeCall(int result)
{
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException(); // OS does not support getting pipe size
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, just return the buffer size that was passed to the constructor.
return _handle != null ?
CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
_outBufferSize;
}
internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
{
var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
Interop.Sys.PipeFlags.O_CLOEXEC : 0;
Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags));
}
internal static void ConfigureSocket(
Socket s, SafePipeHandle pipeHandle,
PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
{
if (inBufferSize > 0)
{
s.ReceiveBufferSize = inBufferSize;
}
if (outBufferSize > 0)
{
s.SendBufferSize = outBufferSize;
}
if (inheritability != HandleInheritability.Inheritable)
{
Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt
}
switch (direction)
{
case PipeDirection.In:
s.Shutdown(SocketShutdown.Send);
break;
case PipeDirection.Out:
s.Shutdown(SocketShutdown.Receive);
break;
}
}
internal static Exception CreateExceptionForLastError(string pipeName = null)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
return error.Error == Interop.Error.ENOTSUP ?
new PlatformNotSupportedException(SR.Format(SR.PlatformNotSupported_OperatingSystemError, nameof(Interop.Error.ENOTSUP))) :
Interop.GetExceptionForIoErrno(error, pipeName);
}
}
}
| |
// Lucene version compatibility level 4.8.1
using J2N;
using YAF.Lucene.Net.Analysis.TokenAttributes;
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace YAF.Lucene.Net.Analysis.Cjk
{
/*
* 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>
/// CJKTokenizer is designed for Chinese, Japanese, and Korean languages.
/// <para>
/// The tokens returned are every two adjacent characters with overlap match.
/// </para>
/// <para>
/// Example: "java C1C2C3C4" will be segmented to: "java" "C1C2" "C2C3" "C3C4".
/// </para>
/// Additionally, the following is applied to Latin text (such as English):
/// <list type="bullet">
/// <item><description>Text is converted to lowercase.</description></item>
/// <item><description>Numeric digits, '+', '#', and '_' are tokenized as letters.</description></item>
/// <item><description>Full-width forms are converted to half-width forms.</description></item>
/// </list>
/// For more info on Asian language (Chinese, Japanese, and Korean) text segmentation:
/// please search <a
/// href="http://www.google.com/search?q=word+chinese+segment">google</a>
/// </summary>
/// @deprecated Use StandardTokenizer, CJKWidthFilter, CJKBigramFilter, and LowerCaseFilter instead.
[Obsolete("Use StandardTokenizer, CJKWidthFilter, CJKBigramFilter, and LowerCaseFilter instead.")]
public sealed class CJKTokenizer : Tokenizer
{
//~ Static fields/initializers ---------------------------------------------
/// <summary>
/// Word token type </summary>
internal const int WORD_TYPE = 0;
/// <summary>
/// Single byte token type </summary>
internal const int SINGLE_TOKEN_TYPE = 1;
/// <summary>
/// Double byte token type </summary>
internal const int DOUBLE_TOKEN_TYPE = 2;
/// <summary>
/// Names for token types </summary>
internal static readonly string[] TOKEN_TYPE_NAMES = new string[] { "word", "single", "double" };
/// <summary>
/// Max word length </summary>
private const int MAX_WORD_LEN = 255;
/// <summary>
/// buffer size: </summary>
private const int IO_BUFFER_SIZE = 256;
/// <summary>
/// Regular expression for testing Unicode character class <c>\p{IsHalfwidthandFullwidthForms}</c>.</summary>
// LUCENENET specific
private static readonly Regex HALFWIDTH_AND_FULLWIDTH_FORMS = new Regex(@"\p{IsHalfwidthandFullwidthForms}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// Regular expression for testing Unicode character class <c>\p{IsBasicLatin}</c>.</summary>
// LUCENENET specific
private static readonly Regex BASIC_LATIN = new Regex(@"\p{IsBasicLatin}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
//~ Instance fields --------------------------------------------------------
/// <summary>
/// word offset, used to imply which character(in ) is parsed </summary>
private int offset = 0;
/// <summary>
/// the index used only for ioBuffer </summary>
private int bufferIndex = 0;
/// <summary>
/// data length </summary>
private int dataLen = 0;
/// <summary>
/// character buffer, store the characters which are used to compose
/// the returned Token
/// </summary>
private readonly char[] buffer = new char[MAX_WORD_LEN];
/// <summary>
/// I/O buffer, used to store the content of the input(one of the
/// members of Tokenizer)
/// </summary>
private readonly char[] ioBuffer = new char[IO_BUFFER_SIZE];
/// <summary>
/// word type: single=>ASCII double=>non-ASCII word=>default </summary>
private int tokenType = WORD_TYPE;
/// <summary>
/// tag: previous character is a cached double-byte character "C1C2C3C4"
/// ----(set the C1 isTokened) C1C2 "C2C3C4" ----(set the C2 isTokened)
/// C1C2 C2C3 "C3C4" ----(set the C3 isTokened) "C1C2 C2C3 C3C4"
/// </summary>
private bool preIsTokened = false;
private ICharTermAttribute termAtt;
private IOffsetAttribute offsetAtt;
private ITypeAttribute typeAtt;
//~ Constructors -----------------------------------------------------------
/// <summary>
/// Construct a token stream processing the given input.
/// </summary>
/// <param name="in"> I/O reader </param>
public CJKTokenizer(TextReader @in)
: base(@in)
{
Init();
}
public CJKTokenizer(AttributeFactory factory, TextReader @in)
: base(factory, @in)
{
Init();
}
private void Init()
{
termAtt = AddAttribute<ICharTermAttribute>();
offsetAtt = AddAttribute<IOffsetAttribute>();
typeAtt = AddAttribute<ITypeAttribute>();
}
//~ Methods ----------------------------------------------------------------
/// <summary>
/// Returns true for the next token in the stream, or false at EOS.
/// See http://java.sun.com/j2se/1.3/docs/api/java/lang/Character.UnicodeBlock.html
/// for detail.
/// </summary>
/// <returns> false for end of stream, true otherwise
/// </returns>
/// <exception cref="IOException"> when read error
/// happened in the InputStream
/// </exception>
public override bool IncrementToken()
{
ClearAttributes();
// how many character(s) has been stored in buffer
while (true) // loop until we find a non-empty token
{
int length = 0;
// the position used to create Token
int start = offset;
while (true) // loop until we've found a full token
{
// current character
char c;
offset++;
if (bufferIndex >= dataLen)
{
dataLen = m_input.Read(ioBuffer, 0, ioBuffer.Length);
bufferIndex = 0;
}
if (dataLen <= 0)
{
if (length > 0)
{
if (preIsTokened == true)
{
length = 0;
preIsTokened = false;
}
else
{
offset--;
}
break;
}
else
{
offset--;
return false;
}
}
else
{
//get current character
c = ioBuffer[bufferIndex++];
}
//if the current character is ASCII or Extend ASCII
// LUCENENET Port Reference: https://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedNamedBlocks
string charAsString = c + "";
bool isHalfwidthAndFullwidthForms = false;
// LUCENENET: This condition only works because the ranges of BASIC_LATIN and HALFWIDTH_AND_FULLWIDTH_FORMS do not overlap
if (BASIC_LATIN.IsMatch(charAsString) || (isHalfwidthAndFullwidthForms = HALFWIDTH_AND_FULLWIDTH_FORMS.IsMatch(charAsString)))
{
if (isHalfwidthAndFullwidthForms)
{
int i = (int)c;
if (i >= 65281 && i <= 65374)
{
// convert certain HALFWIDTH_AND_FULLWIDTH_FORMS to BASIC_LATIN
i = i - 65248;
c = (char)i;
}
}
// if the current character is a letter or "_" "+" "#"
if (char.IsLetterOrDigit(c) || ((c == '_') || (c == '+') || (c == '#')))
{
if (length == 0)
{
// "javaC1C2C3C4linux" <br>
// ^--: the current character begin to token the ASCII
// letter
start = offset - 1;
}
else if (tokenType == DOUBLE_TOKEN_TYPE)
{
// "javaC1C2C3C4linux" <br>
// ^--: the previous non-ASCII
// : the current character
offset--;
bufferIndex--;
if (preIsTokened == true)
{
// there is only one non-ASCII has been stored
length = 0;
preIsTokened = false;
break;
}
else
{
break;
}
}
// store the LowerCase(c) in the buffer
buffer[length++] = char.ToLowerInvariant(c);
tokenType = SINGLE_TOKEN_TYPE;
// break the procedure if buffer overflowed!
if (length == MAX_WORD_LEN)
{
break;
}
}
else if (length > 0)
{
if (preIsTokened == true)
{
length = 0;
preIsTokened = false;
}
else
{
break;
}
}
}
else
{
// non-ASCII letter, e.g."C1C2C3C4"
if (Character.IsLetter(c))
{
if (length == 0)
{
start = offset - 1;
buffer[length++] = c;
tokenType = DOUBLE_TOKEN_TYPE;
}
else
{
if (tokenType == SINGLE_TOKEN_TYPE)
{
offset--;
bufferIndex--;
//return the previous ASCII characters
break;
}
else
{
buffer[length++] = c;
tokenType = DOUBLE_TOKEN_TYPE;
if (length == 2)
{
offset--;
bufferIndex--;
preIsTokened = true;
break;
}
}
}
}
else if (length > 0)
{
if (preIsTokened == true)
{
// empty the buffer
length = 0;
preIsTokened = false;
}
else
{
break;
}
}
}
}
if (length > 0)
{
termAtt.CopyBuffer(buffer, 0, length);
offsetAtt.SetOffset(CorrectOffset(start), CorrectOffset(start + length));
typeAtt.Type = TOKEN_TYPE_NAMES[tokenType];
return true;
}
else if (dataLen <= 0)
{
offset--;
return false;
}
// Cycle back and try for the next token (don't
// return an empty string)
}
}
public override sealed void End()
{
base.End();
// set final offset
int finalOffset = CorrectOffset(offset);
this.offsetAtt.SetOffset(finalOffset, finalOffset);
}
public override void Reset()
{
base.Reset();
offset = bufferIndex = dataLen = 0;
preIsTokened = false;
tokenType = WORD_TYPE;
}
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_View.vbgen
'
' The supporting base class OleDbEntity is in the
' Architecture directory in "dOOdads".
'===============================================================================
*/
// Generated by MyGeneration Version # (1.1.3.5)
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace MyGeneration.dOOdads.Tests.Access
{
public abstract class _FullNameView : OleDbEntity
{
public _FullNameView()
{
this.QuerySource = "FullNameView";
this.MappingName = "FullNameView";
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
return base.Query.Load();
}
public override void FlushData()
{
this._whereClause = null;
this._aggregateClause = null;
base.FlushData();
}
#region Parameters
protected class Parameters
{
public static OleDbParameter FullName
{
get
{
return new OleDbParameter("@FullName", OleDbType.VarWChar, 255);
}
}
public static OleDbParameter DepartmentID
{
get
{
return new OleDbParameter("@DepartmentID", OleDbType.Numeric, 0);
}
}
public static OleDbParameter HireDate
{
get
{
return new OleDbParameter("@HireDate", OleDbType.Date, 0);
}
}
public static OleDbParameter Salary
{
get
{
return new OleDbParameter("@Salary", OleDbType.Double, 0);
}
}
public static OleDbParameter IsActive
{
get
{
return new OleDbParameter("@IsActive", OleDbType.Boolean, 2);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string FullName = "FullName";
public const string DepartmentID = "DepartmentID";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[FullName] = _FullNameView.PropertyNames.FullName;
ht[DepartmentID] = _FullNameView.PropertyNames.DepartmentID;
ht[HireDate] = _FullNameView.PropertyNames.HireDate;
ht[Salary] = _FullNameView.PropertyNames.Salary;
ht[IsActive] = _FullNameView.PropertyNames.IsActive;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string FullName = "FullName";
public const string DepartmentID = "DepartmentID";
public const string HireDate = "HireDate";
public const string Salary = "Salary";
public const string IsActive = "IsActive";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[FullName] = _FullNameView.ColumnNames.FullName;
ht[DepartmentID] = _FullNameView.ColumnNames.DepartmentID;
ht[HireDate] = _FullNameView.ColumnNames.HireDate;
ht[Salary] = _FullNameView.ColumnNames.Salary;
ht[IsActive] = _FullNameView.ColumnNames.IsActive;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string FullName = "s_FullName";
public const string DepartmentID = "s_DepartmentID";
public const string HireDate = "s_HireDate";
public const string Salary = "s_Salary";
public const string IsActive = "s_IsActive";
}
#endregion
#region Properties
public virtual string FullName
{
get
{
return base.Getstring(ColumnNames.FullName);
}
set
{
base.Setstring(ColumnNames.FullName, value);
}
}
public virtual int DepartmentID
{
get
{
return base.Getint(ColumnNames.DepartmentID);
}
set
{
base.Setint(ColumnNames.DepartmentID, value);
}
}
public virtual DateTime HireDate
{
get
{
return base.GetDateTime(ColumnNames.HireDate);
}
set
{
base.SetDateTime(ColumnNames.HireDate, value);
}
}
public virtual double Salary
{
get
{
return base.Getdouble(ColumnNames.Salary);
}
set
{
base.Setdouble(ColumnNames.Salary, value);
}
}
public virtual bool IsActive
{
get
{
return base.Getbool(ColumnNames.IsActive);
}
set
{
base.Setbool(ColumnNames.IsActive, value);
}
}
#endregion
#region String Properties
public virtual string s_FullName
{
get
{
return this.IsColumnNull(ColumnNames.FullName) ? string.Empty : base.GetstringAsString(ColumnNames.FullName);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.FullName);
else
this.FullName = base.SetstringAsString(ColumnNames.FullName, value);
}
}
public virtual string s_DepartmentID
{
get
{
return this.IsColumnNull(ColumnNames.DepartmentID) ? string.Empty : base.GetintAsString(ColumnNames.DepartmentID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.DepartmentID);
else
this.DepartmentID = base.SetintAsString(ColumnNames.DepartmentID, value);
}
}
public virtual string s_HireDate
{
get
{
return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.HireDate);
else
this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value);
}
}
public virtual string s_Salary
{
get
{
return this.IsColumnNull(ColumnNames.Salary) ? string.Empty : base.GetdoubleAsString(ColumnNames.Salary);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.Salary);
else
this.Salary = base.SetdoubleAsString(ColumnNames.Salary, value);
}
}
public virtual string s_IsActive
{
get
{
return this.IsColumnNull(ColumnNames.IsActive) ? string.Empty : base.GetboolAsString(ColumnNames.IsActive);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.IsActive);
else
this.IsActive = base.SetboolAsString(ColumnNames.IsActive, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region WhereParameter TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter FullName
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.FullName, Parameters.FullName);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter DepartmentID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter HireDate
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter Salary
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter IsActive
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter FullName
{
get
{
if(_FullName_W == null)
{
_FullName_W = TearOff.FullName;
}
return _FullName_W;
}
}
public WhereParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public WhereParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public WhereParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public WhereParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private WhereParameter _FullName_W = null;
private WhereParameter _DepartmentID_W = null;
private WhereParameter _HireDate_W = null;
private WhereParameter _Salary_W = null;
private WhereParameter _IsActive_W = null;
public void WhereClauseReset()
{
_FullName_W = null;
_DepartmentID_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
#region Aggregate Clause
public class AggregateClause
{
public AggregateClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffAggregateParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffAggregateParameter(this);
}
return _tearOff;
}
}
#region AggregateParameter TearOff's
public class TearOffAggregateParameter
{
public TearOffAggregateParameter(AggregateClause clause)
{
this._clause = clause;
}
public AggregateParameter FullName
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.FullName, Parameters.FullName);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter DepartmentID
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.DepartmentID, Parameters.DepartmentID);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter HireDate
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.HireDate, Parameters.HireDate);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter Salary
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.Salary, Parameters.Salary);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
public AggregateParameter IsActive
{
get
{
AggregateParameter aggregate = new AggregateParameter(ColumnNames.IsActive, Parameters.IsActive);
this._clause._entity.Query.AddAggregateParameter(aggregate);
return aggregate;
}
}
private AggregateClause _clause;
}
#endregion
public AggregateParameter FullName
{
get
{
if(_FullName_W == null)
{
_FullName_W = TearOff.FullName;
}
return _FullName_W;
}
}
public AggregateParameter DepartmentID
{
get
{
if(_DepartmentID_W == null)
{
_DepartmentID_W = TearOff.DepartmentID;
}
return _DepartmentID_W;
}
}
public AggregateParameter HireDate
{
get
{
if(_HireDate_W == null)
{
_HireDate_W = TearOff.HireDate;
}
return _HireDate_W;
}
}
public AggregateParameter Salary
{
get
{
if(_Salary_W == null)
{
_Salary_W = TearOff.Salary;
}
return _Salary_W;
}
}
public AggregateParameter IsActive
{
get
{
if(_IsActive_W == null)
{
_IsActive_W = TearOff.IsActive;
}
return _IsActive_W;
}
}
private AggregateParameter _FullName_W = null;
private AggregateParameter _DepartmentID_W = null;
private AggregateParameter _HireDate_W = null;
private AggregateParameter _Salary_W = null;
private AggregateParameter _IsActive_W = null;
public void AggregateClauseReset()
{
_FullName_W = null;
_DepartmentID_W = null;
_HireDate_W = null;
_Salary_W = null;
_IsActive_W = null;
this._entity.Query.FlushAggregateParameters();
}
private BusinessEntity _entity;
private TearOffAggregateParameter _tearOff;
}
public AggregateClause Aggregate
{
get
{
if(_aggregateClause == null)
{
_aggregateClause = new AggregateClause(this);
}
return _aggregateClause;
}
}
private AggregateClause _aggregateClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
return null;
}
protected override IDbCommand GetUpdateCommand()
{
return null;
}
protected override IDbCommand GetDeleteCommand()
{
return null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Misc
{
/// <summary>
/// This class implements a priority queue (or heap).
/// It is a "semi-sorted" list which has the smallest element at the front.
/// </summary>
/// <remarks>
/// Based on BenDi's Priority Queue code at CodeProject.
/// (http://www.codeproject.com/csharp/priorityqueue.asp)
/// Also based on Vincente's Priority Queue code found in the Jad Engine
/// (http://www.codeplex.com/JADENGINE)
/// </remarks>
internal class PriorityQueue<T> : IPriorityQueue<T>
{
protected List<T> _heapList;
protected IComparer<T> _comparer;
public PriorityQueue()
: this(System.Collections.Generic.Comparer<T>.Default)
{ }
public PriorityQueue(IComparer<T> comparer)
{
_heapList = new List<T>();
_comparer = comparer;
}
public PriorityQueue(int Capacity)
: this(System.Collections.Generic.Comparer<T>.Default, Capacity)
{ }
public PriorityQueue(IComparer<T> comparer, int Capacity)
{
_heapList = new List<T>();
_comparer = comparer;
_heapList.Capacity = Capacity;
}
protected virtual void SwitchElements(int i, int j)
{
T h = _heapList[i];
_heapList[i] = _heapList[j];
_heapList[j] = h;
}
protected virtual int OnCompare(int i, int j)
{
return _comparer.Compare(_heapList[i], _heapList[j]);
}
#region IPriorityQueue<T> Members
public virtual int Push(T element)
{
int p = _heapList.Count, p2;
_heapList.Add(element); //E[p] = element
do
{
if (p == 0) //Element then has to be only element in list
{
break;
}
p2 = (p - 1) / 2;
if (OnCompare(p, p2) < 0) //E[p] less than E[p2]
{
SwitchElements(p, p2); //Order them
p = p2;
}
else
{
break; //Compared elements in order
}
} while (true);
return p;
}
public virtual T Pop()
{
T result = _heapList[0]; //First element
int p = 0, p1, p2, pn;
_heapList[0] = _heapList[_heapList.Count - 1]; //First element is now last element
_heapList.RemoveAt(_heapList.Count - 1); //Remove last element
do
{
pn = p;
p1 = 2 * p + 1;
p2 = 2 * p + 2;
if (_heapList.Count > p1 && OnCompare(p, p1) > 0) //Valid element AND E[p] greater than E[2p+1]
{
p = p1;
}
if (_heapList.Count > p2 && OnCompare(p, p2) > 0) ////Valid element AND E[p] greater than E[2p+2]
{
p = p2;
}
if (p == pn)
{
break;
}
SwitchElements(p, pn); //Swop E[p] and E[pn]
} while (true);
return result;
}
public virtual T Peek()
{
if (_heapList.Count > 0)
{
return _heapList[0];
}
return default(T);
}
public virtual void Update(int i)
{
int p = i, pn;
int p1, p2;
do
{
if (p == 0) //No elements "under" it to look at
{
break;
}
p2 = (p - 1) / 2;
if (OnCompare(p, p2) < 0) //E[p] less than E[(p-1)/2]
{
SwitchElements(p, p2);
p = p2;
}
else
{
break;
}
} while (true);
if (p < i)
{
return;
}
do
{
pn = p;
p1 = 2 * p + 1;
p2 = 2 * p + 2;
if (_heapList.Count > p1 && OnCompare(p, p1) > 0) //Valid element AND E[p] greater than E[2p+1]
{
p = p1;
}
if (_heapList.Count > p2 && OnCompare(p, p2) > 0) //Valid element AND E[p] greater than E[2p+2]
{
p = p2;
}
if (p == pn)
{
break;
}
SwitchElements(p, pn);
} while (true);
}
#endregion IPriorityQueue<T> Members
#region ICollection<T> Members
public void CopyTo(T[] array, int index)
{
_heapList.CopyTo(array, index);
}
public int Count
{
get { return _heapList.Count; }
}
#endregion ICollection<T> Members
#region IEnumerable<T> Members
IEnumerator IEnumerable.GetEnumerator()
{
return _heapList.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return _heapList.GetEnumerator();
}
#endregion IEnumerable<T> Members
#region IList<T> Members
public void Add(T value)
{
Push(value);
}
public void Clear()
{
_heapList.Clear();
}
public bool Contains(T value)
{
return _heapList.Contains(value);
}
public int IndexOf(T value)
{
return _heapList.IndexOf(value);
}
public void Insert(int index, T value)
{
throw new NotSupportedException();
}
public bool IsFixedSize
{
get { return false; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T value)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public T this[int index]
{
get { return _heapList[index]; }
set
{
_heapList[index] = value;
Update(index);
}
}
#endregion IList<T> Members
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
using System.Linq;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str
{
#region Utilities
public override string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName, "*");
}
public virtual string[] GetEntries(string dirName, string searchPattern)
{
return Directory.GetFileSystemEntries(dirName, searchPattern);
}
#endregion
#region UniversalTests
[Fact]
public void SearchPatternNull()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null));
}
[Fact]
public void SearchPatternEmpty()
{
// To avoid OS differences we have decided not to throw an argument exception when empty
// string passed. But we should return 0 items.
Assert.Empty(GetEntries(TestDirectory, string.Empty));
}
[Fact]
public void SearchPatternValid()
{
Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw
}
[Fact]
public void SearchPatternDotIsStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
{
string[] strArr = GetEntries(testDir.FullName, ".");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
}
}
[Fact]
public void SearchPatternWithTrailingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "Test1*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternWithLeadingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "*2");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*Dir*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternByExtension()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, "TestFile1.txt")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2.xxt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2.txt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2.txx")))
{
string[] strArr = GetEntries(testDir.FullName, "*.txt");
Assert.Equal(2, strArr.Length);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1.txt"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2.txt"), strArr);
}
}
}
[Fact]
public void SearchPatternExactMatch()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA"));
using (File.Create(Path.Combine(testDir.FullName, "AAABB")))
using (File.Create(Path.Combine(testDir.FullName, "AAABBC")))
using (File.Create(Path.Combine(testDir.FullName, "CAAABB")))
{
if (TestFiles)
{
string[] results = GetEntries(testDir.FullName, "AAABB");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results);
}
if (TestDirectories)
{
string[] results = GetEntries(testDir.FullName, "AAA");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results);
}
}
}
[Fact]
public void SearchPatternIgnoreSubDirectories()
{
// Shouldn't get files on full path by default
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*"));
if (TestDirectories && TestFiles)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Theory,
// '[' should not matter, but is special to Unix matching APIs
InlineData(
"[foo]",
new string[] { @"f", @"o", @"o", @"foo", @"[foo]" },
new string[] { @"[foo]" }),
]
public void PatternTests_UnixPatterns(string pattern, string[] sourceFiles, string[] expected)
{
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20779, TestPlatforms.AnyUnix)]
[Theory,
// Question marks collapse (right) to periods
InlineData(
"f???.txt",
new string[] { @"f.txt", @"foo.txt", @"foob.txt", @"fooba.txt", @"foobar.txt" },
new string[] { @"f.txt", @"foo.txt", @"foob.txt" }),
// Question marks don't collapse to !periods
InlineData(
"???b??.txt",
new string[] { @"f.txt", @"foo.txt", @"foob.txt", @"fooba.txt", @"foobar.txt" },
new string[] { @"foob.txt", @"fooba.txt", @"foobar.txt" }),
// Question marks collapse (right) to end
InlineData(
"foo.t??",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo.t", @"foo.tx", @"foo.txt" }),
]
public void PatternTests_DosQM(string pattern, string[] sourceFiles, string[] expected)
{
// Question marks always collapse right to periods or the end of the string if they are contiguous
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20779, TestPlatforms.AnyUnix)]
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
[Theory,
// Periods are optional if left of ? and end of match
InlineData(
"foo.???",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.???.?.?.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.?.??.???.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.??.???.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx" }),
// Periods are optional if left of * and end of match, question marks collapse (right) to end
InlineData(
"foo.*??",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
// Periods are optional if left of * and end of match, question marks collapse (right) to end
InlineData(
"foo.*??*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" })
]
public void PatternTests_DosDotQm(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for collapsing question marks and DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
[Theory,
// Periods are optional if left of * and end of match
InlineData(
"foo.*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
// Periods are optional if left of * and end of match
InlineData(
"foo.*.*.*.*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" })
]
public void PatternTests_DosDot(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
// Periods are optional if left of * or ? and end of match
InlineData(
"foo.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
InlineData(
"foo.*.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
InlineData(
"foo.?",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
InlineData(
"foo.?.?",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??.??",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
InlineData(
"foo.?.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
]
public void PatternTests_DosDotTrailingDot(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
[Theory,
InlineData(
"foo*.",
new string[] { @"foo", @"foobar", @"foo.bar" },
new string[] { @"foo", @"foobar" })
]
public void PatternTests_DosStar(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
InlineData(
"foo*.",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo..", @"foo...", @"foo .", @"foo. . .", @"foo. t" },
new string[] { @"foo", @"foo .", @"foo.", @"foo..", @"foo...", @"foo. . ." }),
InlineData(
"foodies*.",
new string[] { @"foodies.", @"foodies. ", @"foodies. " },
new string[] { @"foodies." }),
InlineData(
"foodies*.",
new string[] { @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { }),
InlineData(
"foooooo*.",
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " },
new string[] { @"foooooo." }),
InlineData(
"foooooo*.",
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " },
new string[] { }),
InlineData(
"foodies*.",
new string[] { @"foodies.", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { @"foodies." }),
InlineData(
"foodies*.",
new string[] { @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { }),
InlineData(
"foo*.",
new string[] { @"foo..", @"foo...", @"foo....", @"foo.....", @"foo......" },
new string[] { @"foo..", @"foo...", @"foo....", @"foo.....", @"foo......" }),
]
public void PatternTests_DosStarSpace(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *. These are the subset of tests
// with trailing spaces that work as documented.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[OuterLoop("These are pretty corner, don't need to run all the time.")]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
// "foo*." actually becomes "foo<" when passed to NT. It matches all characters up to, and including, the final period.
//
// There is a "bug" somewhere in the Windows stack where *some* files with trailing spaces after the final period will be returned when
// using "*." at the end of a string (which becomes "<"). According to the rules (and the actual pattern matcher used FsRtlIsNameInExpression)
// *nothing* should match after the final period.
//
// The results as passed to RtlIsNameInExpression (after changing *. to <) are in comments.
InlineData(
"foo*.",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo..", @"foo...", @"foo. ", @"foo. ", @"foo .", @"foo. . .", @"foo. t" },
// Really should be: new string[] { @"foo", @"foo.", @"foo..", @"foo...", @"foo .", @"foo. . ." }), but is
new string[] { @"foo", @"foo .", @"foo.", @"foo..", @"foo...", @"foo. ", @"foo. . ." }),
InlineData(
"*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"f*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo." },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo" },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"foo.", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"food", @"foo.", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo", @"food" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. ", @"food" }),
InlineData(
"fo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo.", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
// Really should be: new string[] { @"foo. .", @"foo. . ." }), but is
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . ." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." },
// Really should be: new string[] { @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." }), but is
new string[] { @"foo. ", @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
// Really should be: new string[] { @"foo. .", @"foo. . ."}), but is
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. " },
// Really should be: new string[] { @"food." }), but is
new string[] { @"food.", @"food. ", @"food. ", @"food. " }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. ", @"foodi." },
// Really should be: new string[] { @"food.", @"foodi." }), but is
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"foodi." }),
InlineData(
"foodi*.",
new string[] { @"foodi.", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. " },
// Really should be: new string[] { @"foodi." }), but is
new string[] { @"foodi.", @"foodi. ", @"foodi. ", @"foodi. " }),
InlineData(
"foodie*.",
new string[] { @"foodie.", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. " },
// Really should be: new string[] { @"foodie." }), but is
new string[] { @"foodie.", @"foodie. ", @"foodie. ", @"foodie. " }),
InlineData(
"fooooo*.",
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " },
// Really should be: new string[] { @"foooooo." }), but is
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " }),
InlineData(
"fooooo*.",
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " },
// Really should be: new string[] { }), but is
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo.." }),
]
public void PatternTests_DosStarOddSpace_Desktop(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *.
// These cases don't match documented behavior on Windows- matching *should* end at the final period.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[OuterLoop("These are pretty corner, don't need to run all the time.")]
[Theory,
// "foo*." actually becomes "foo<" when passed to NT. It matches all characters up to, and including, the final period.
//
// There is a "bug" somewhere in the Windows stack where *some* files with trailing spaces after the final period will be returned when
// using "*." at the end of a string (which becomes "<"). According to the rules (and the actual pattern matcher used FsRtlIsNameInExpression)
// *nothing* should match after the final period.
//
// We've made Core effectively call RtlIsNameInExpression directly, so this test validates the normally buggy cases. See the test above
// for what Windows really does. These are super obscure and the bug pattern isn't obvious so we're just going with "correct".
InlineData(
"foo*.",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo..", @"foo...", @"foo. ", @"foo. ", @"foo .", @"foo. . .", @"foo. t" },
new string[] { @"foo", @"foo.", @"foo..", @"foo...", @"foo .", @"foo. . ." }),
InlineData(
"*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
new string[] { @"foo.." }),
InlineData(
"f*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
new string[] { @"foo.." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
new string[] { @"foo.." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo." },
new string[] { @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo.", @"foo" }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo" },
new string[] { @"foo.", @"foo" }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"foo.", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo.", @"foo" }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"food", @"foo.", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo.", @"foo", @"food" }),
InlineData(
"fo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
new string[] { @"foo. .", @"foo. . ." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." },
new string[] { @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
new string[] { @"foo. .", @"foo. . ."}),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { @"foo." }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. " },
new string[] { @"food." }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. ", @"foodi." },
new string[] { @"food.", @"foodi." }),
InlineData(
"foodi*.",
new string[] { @"foodi.", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. " },
new string[] { @"foodi." }),
InlineData(
"foodie*.",
new string[] { @"foodie.", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. " },
new string[] { @"foodie." }),
InlineData(
"fooooo*.",
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " },
new string[] { @"foooooo." }),
InlineData(
"fooooo*.",
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " },
new string[] { }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
new string[] { }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t", @"foo. ", @"foo. " },
new string[] { @"foo.." }),
]
public void PatternTests_DosStarOddSpace_Core(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *.
// These cases don't match documented behavior on Windows- matching *should* end at the final period.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
private string PrepareDirectory(string[] sourceFiles, bool useExtendedPaths = false)
{
string testDir = Directory.CreateDirectory(GetTestFilePath()).FullName;
foreach (string file in sourceFiles)
CreateItem(useExtendedPaths && PlatformDetection.IsWindows
? @"\\?\" + Path.Combine(testDir, file)
: Path.Combine(testDir, file));
return testDir;
}
private void ValidatePatternMatch(string[] expected, string[] result)
{
Assert.Equal(expected.OrderBy(s => s), result.Select(Path.GetFileName).OrderBy(s => s));
}
#endregion
#region PlatformSpecific
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Theory,
InlineData(
@"foo\bar",
new string[] { @"foo", @"bar", @"foo\bar" },
new string[] { @"foo\bar" }),
]
public void PatternTests_UnixEscape(string pattern, string[] sourceFiles, string[] expected)
{
// We shouldn't be allowing escaping in Unix filename searches
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
// Long path segment in search pattern throws PathTooLongException on Desktop
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
}
else
{
GetEntries(testDir.FullName, longName);
}
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(32167, TargetFrameworkMonikers.NetFramework)]
public void SearchPatternLongPath()
{
// Create a destination path longer than the traditional Windows limit of 256 characters
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 254);
string longFullname = Path.Combine(testDir.FullName, longName);
if (TestFiles)
{
using (File.Create(longFullname)) { }
}
else
{
Directory.CreateDirectory(longFullname);
}
string[] results = GetEntries(testDir.FullName, longName);
Assert.Contains(longFullname, results);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsSearchPatternWithDoubleDots_Desktop()
{
// Search pattern with double dots throws ArgumentException
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void SearchPatternWithDoubleDots_Core()
{
// Search pattern with double dots no longer throws ArgumentException
string directory = Directory.CreateDirectory(GetTestFilePath()).FullName;
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(directory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
GetEntries(directory, "..");
GetEntries(directory, @".." + Path.DirectorySeparatorChar);
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(directory, Path.Combine("..ab ab.. .. abc..d", "abc", "..")));
GetEntries(directory, Path.Combine("..ab ab.. .. abc..d", "..", "abc"));
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(directory, Path.Combine("..", "..ab ab.. .. abc..d", "abc")));
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(directory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar));
}
private static char[] OldWildcards = new char[] { '*', '?' };
private static char[] NewWildcards = new char[] { '<', '>', '\"' };
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsSearchPatternInvalid_Desktop()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "|"));
Assert.All(Path.GetInvalidFileNameChars().Except(OldWildcards).Except(NewWildcards), invalidChar =>
{
switch (invalidChar)
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
//We don't throw in V1 too
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS
{
Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
}
else
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
}
break;
default:
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
}
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsSearchPatternInvalid_Core()
{
GetEntries(TestDirectory, "\0");
GetEntries(TestDirectory, "|");
Assert.All(Path.GetInvalidFileNameChars().Except(OldWildcards).Except(NewWildcards), invalidChar =>
{
switch (invalidChar)
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
default:
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
break;
}
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netcoreapp()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netfx()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-invalid search patterns throws no exception
public void UnixSearchPatternInvalid()
{
GetEntries(TestDirectory, "\0");
GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString()));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ? in search pattern returns results
public virtual void WindowsSearchPatternQuestionMarks()
{
string testDir1Str = GetTestFileName();
DirectoryInfo testDir = new DirectoryInfo(TestDirectory);
DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str);
using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length)));
if (TestFiles && TestDirectories)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in search pattern returns nothing
public void WindowsSearchPatternWhitespace()
{
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\n"));
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\t"));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void SearchPatternCaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void SearchPatternCaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "yZZz");
testDir.CreateSubdirectory(testBase + "yZZZ");
File.Create(Path.Combine(testDir.FullName, testBase + "YYYY")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "yYYy")).Dispose();
if (TestDirectories)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*ZZ*").Length);
}
if (TestFiles)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*YY*").Length);
}
}
[Theory,
InlineData(" "),
InlineData(" "),
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in file search patterns
public void UnixSearchPatternFileValidChar(string valid)
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Theory,
InlineData(" "),
InlineData(" "),
InlineData("\n"),
InlineData(">"),
InlineData("<"),
InlineData("\t")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in directory search patterns
public void UnixSearchPatternDirectoryValidChar(string valid)
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(valid);
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: FlowDocumentPageViewer.cs
//
// Description: FlowDocumentPageViewer provides a simple user experience for viewing
// one page of content at a time. The experience is optimized for
// FlowDocument scenarios, however any IDocumentPaginatorSource
// can be viewed using this control.
//
//---------------------------------------------------------------------------
using System.Collections.Generic; // Stack<T>
using System.Collections.ObjectModel; // ReadOnlyCollection<T>
using System.Windows.Automation.Peers; // AutomationPeer
using System.Windows.Documents; // IDocumentPaginatorSouce, ...
using System.Windows.Documents.Serialization; // WritingCompletedEventArgs
using System.Windows.Input; // UICommand
using System.Windows.Media; // VisualTreeHelper
using System.Windows.Controls.Primitives; // DocumentViewerBase, DocumentPageView
using System.Windows.Threading;
using MS.Internal; // Invariant, DoubleUtil
using MS.Internal.Commands; // CommandHelpers
using MS.Internal.Documents; // FindToolBar
using MS.Internal.KnownBoxes; // BooleanBoxes
using MS.Internal.PresentationFramework; // SecurityHelper
using MS.Internal.AppModel; // IJournalState
using System.Security; // SecurityCritical, SecurityTreatAsSafe
namespace System.Windows.Controls
{
/// <summary>
/// FlowDocumentPageViewer provides a simple user experience for viewing one page
/// of content at a time. The experience is optimized for FlowDocument scenarios,
/// however any IDocumentPaginatorSource can be viewed using this control.
/// </summary>
[TemplatePart(Name = "PART_FindToolBarHost", Type = typeof(Decorator))]
public class FlowDocumentPageViewer : DocumentViewerBase, IJournalState
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes class-wide settings.
/// </summary>
static FlowDocumentPageViewer()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(new ComponentResourceKey(typeof(PresentationUIStyleResources), "PUIFlowDocumentPageViewer")));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(FlowDocumentPageViewer));
TextBoxBase.SelectionBrushProperty.OverrideMetadata(typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(new PropertyChangedCallback(UpdateCaretElement)));
TextBoxBase.SelectionOpacityProperty.OverrideMetadata(typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(new PropertyChangedCallback(UpdateCaretElement)));
// Create our CommandBindings
CreateCommandBindings();
EventManager.RegisterClassHandler(typeof(FlowDocumentPageViewer), Keyboard.KeyDownEvent, new KeyEventHandler(KeyDownHandler), true);
}
/// <summary>
/// Instantiates a new instance of a FlowDocumentPageViewer.
/// </summary>
public FlowDocumentPageViewer()
: base()
{
this.LayoutUpdated += new EventHandler(HandleLayoutUpdated);
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Called when the Template's tree has been generated
/// </summary>
/// <returns>Whether Visuals were added to the tree.</returns>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Initialize FindTooBar host.
// If old FindToolBar is enabled, disable it first to ensure appropriate cleanup.
if (FindToolBar != null)
{
ToggleFindToolBar(false);
}
_findToolBarHost = GetTemplateChild(_findToolBarHostTemplateName) as Decorator;
}
/// <summary>
/// Increases the current zoom.
/// </summary>
public void IncreaseZoom()
{
OnIncreaseZoomCommand();
}
/// <summary>
/// Decreases the current zoom.
/// </summary>
public void DecreaseZoom()
{
OnDecreaseZoomCommand();
}
/// <summary>
/// Invokes the Find Toolbar. This is analogous to the ApplicationCommands.Find.
/// </summary>
public void Find()
{
OnFindCommand();
}
#endregion Public Methods
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
/// <summary>
/// Text Selection (readonly)
/// </summary>
public TextSelection Selection
{
get
{
ITextSelection textSelection = null;
FlowDocument flowDocument = Document as FlowDocument;
if (flowDocument != null)
{
textSelection = flowDocument.StructuralCache.TextContainer.TextSelection;
}
return textSelection as TextSelection;
}
}
/// <summary>
/// The Zoom applied to all pages; this value is 100-based.
/// </summary>
public double Zoom
{
get { return (double) GetValue(ZoomProperty); }
set { SetValue(ZoomProperty, value); }
}
/// <summary>
/// The maximum allowed value of the Zoom property.
/// </summary>
public double MaxZoom
{
get { return (double) GetValue(MaxZoomProperty); }
set { SetValue(MaxZoomProperty, value); }
}
/// <summary>
/// The minimum allowed value of the Zoom property.
/// </summary>
public double MinZoom
{
get { return (double) GetValue(MinZoomProperty); }
set { SetValue(MinZoomProperty, value); }
}
/// <summary>
/// The amount the Zoom property is incremented or decremented when
/// the IncreaseZoom or DecreaseZoom command is executed.
/// </summary>
public double ZoomIncrement
{
get { return (double) GetValue(ZoomIncrementProperty); }
set { SetValue(ZoomIncrementProperty, value); }
}
/// <summary>
/// Whether the viewer can increase the current zoom.
/// </summary>
public virtual bool CanIncreaseZoom
{
get { return (bool) GetValue(CanIncreaseZoomProperty); }
}
/// <summary>
/// Whether the viewer can decrease the current zoom.
/// </summary>
public virtual bool CanDecreaseZoom
{
get { return (bool) GetValue(CanDecreaseZoomProperty); }
}
/// <summary>
/// <see cref="TextBoxBase.SelectionBrushProperty" />
/// </summary>
public Brush SelectionBrush
{
get { return (Brush)GetValue(SelectionBrushProperty); }
set { SetValue(SelectionBrushProperty, value); }
}
/// <summary>
/// <see cref="TextBoxBase.SelectionOpacityProperty"/>
/// </summary>
public double SelectionOpacity
{
get { return (double)GetValue(SelectionOpacityProperty); }
set { SetValue(SelectionOpacityProperty, value); }
}
/// <summary>
/// <see cref="TextBoxBase.IsSelectionActive"/>
/// </summary>
public bool IsSelectionActive
{
get { return (bool)GetValue(IsSelectionActiveProperty); }
}
/// <summary>
/// <see cref="TextBoxBase.IsInactiveSelectionHighlightEnabled"/>
/// </summary>
public bool IsInactiveSelectionHighlightEnabled
{
get { return (bool)GetValue(IsInactiveSelectionHighlightEnabledProperty); }
set { SetValue(IsInactiveSelectionHighlightEnabledProperty, value); }
}
#region Public Dynamic Properties
/// <summary>
/// <see cref="Zoom"/>
/// </summary>
public static readonly DependencyProperty ZoomProperty =
DependencyProperty.Register(
"Zoom",
typeof(double),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(
100d,
new PropertyChangedCallback(ZoomChanged),
new CoerceValueCallback(CoerceZoom)),
new ValidateValueCallback(ZoomValidateValue));
/// <summary>
/// <see cref="MaxZoom"/>
/// </summary>
public static readonly DependencyProperty MaxZoomProperty =
DependencyProperty.Register(
"MaxZoom",
typeof(double),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(
200d,
new PropertyChangedCallback(MaxZoomChanged),
new CoerceValueCallback(CoerceMaxZoom)),
new ValidateValueCallback(ZoomValidateValue));
/// <summary>
/// <see cref="MinZoom"/>
/// </summary>
public static readonly DependencyProperty MinZoomProperty =
DependencyProperty.Register(
"MinZoom",
typeof(double),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(
80d,
new PropertyChangedCallback(MinZoomChanged)),
new ValidateValueCallback(ZoomValidateValue));
/// <summary>
/// <see cref="ZoomIncrement"/>
/// </summary>
public static readonly DependencyProperty ZoomIncrementProperty =
DependencyProperty.Register(
"ZoomIncrement",
typeof(double),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(10d),
new ValidateValueCallback(ZoomValidateValue));
/// <summary>
/// <see cref="CanIncreaseZoom"/>
/// </summary>
protected static readonly DependencyPropertyKey CanIncreaseZoomPropertyKey =
DependencyProperty.RegisterReadOnly(
"CanIncreaseZoom",
typeof(bool),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(true));
/// <summary>
/// <see cref="CanIncreaseZoom"/>
/// </summary>
public static readonly DependencyProperty CanIncreaseZoomProperty = CanIncreaseZoomPropertyKey.DependencyProperty;
/// <summary>
/// <see cref="CanDecreaseZoom"/>
/// </summary>
protected static readonly DependencyPropertyKey CanDecreaseZoomPropertyKey =
DependencyProperty.RegisterReadOnly(
"CanDecreaseZoom",
typeof(bool),
typeof(FlowDocumentPageViewer),
new FrameworkPropertyMetadata(true));
/// <summary>
/// <see cref="CanDecreaseZoom"/>
/// </summary>
public static readonly DependencyProperty CanDecreaseZoomProperty =
CanDecreaseZoomPropertyKey.DependencyProperty;
/// <summary>
/// <see cref="TextBoxBase.SelectionBrushProperty"/>
/// </summary>
public static readonly DependencyProperty SelectionBrushProperty =
TextBoxBase.SelectionBrushProperty.AddOwner(typeof(FlowDocumentPageViewer));
/// <summary>
/// <see cref="TextBoxBase.SelectionOpacityProperty"/>
/// </summary>
public static readonly DependencyProperty SelectionOpacityProperty =
TextBoxBase.SelectionOpacityProperty.AddOwner(typeof(FlowDocumentPageViewer));
/// <summary>
/// <see cref="TextBoxBase.IsSelectionActiveProperty"/>
/// </summary>
public static readonly DependencyProperty IsSelectionActiveProperty =
TextBoxBase.IsSelectionActiveProperty.AddOwner(typeof(FlowDocumentPageViewer));
/// <summary>
/// <see cref="TextBoxBase.IsInactiveSelectionHighlightEnabledProperty"/>
/// </summary>
public static readonly DependencyProperty IsInactiveSelectionHighlightEnabledProperty =
TextBoxBase.IsInactiveSelectionHighlightEnabledProperty.AddOwner(typeof(FlowDocumentPageViewer));
#endregion Public Dynamic Properties
#endregion Public Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new FlowDocumentPageViewerAutomationPeer(this);
}
/// <summary>
/// This is the method that responds to the KeyDown event.
/// </summary>
/// <param name="e">Event arguments</param>
/// <SecurityNote>
/// Critical: get_SearchUp is defined in a non-APTCA assembly.
/// TreatAsSafe: call to get_SearchUp does not entail any risk.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
protected override void OnKeyDown(KeyEventArgs e)
{
// Esc -- Close FindToolBar
if (e.Key == Key.Escape)
{
if (FindToolBar != null)
{
ToggleFindToolBar(false);
e.Handled = true;
}
}
// F3 -- Invoke Find
if (e.Key == Key.F3)
{
if (CanShowFindToolBar)
{
if (FindToolBar != null)
{
// If the Shift key is also pressed, then search up.
FindToolBar.SearchUp = ((e.KeyboardDevice.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift);
OnFindInvoked(this, EventArgs.Empty);
}
else
{
// Make the FindToolbar visible
ToggleFindToolBar(true);
}
e.Handled = true;
}
}
// If not handled, do default handling.
if (!e.Handled)
{
base.OnKeyDown(e);
}
}
/// <summary>
/// An event reporting a mouse wheel rotation.
/// </summary>
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
// [Mouse Wheel + Control] - zooming
// [Mouse Wheel] - page navigation
if (e.Delta != 0)
{
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
if (e.Delta > 0)
{
IncreaseZoom();
}
else
{
DecreaseZoom();
}
}
else
{
if (e.Delta > 0)
{
PreviousPage();
}
else
{
NextPage();
}
}
e.Handled = false;
}
// If not handled, do default handling.
if (!e.Handled)
{
base.OnMouseWheel(e);
}
}
/// <summary>
/// Called when ContextMenuOpening is raised on this element.
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnContextMenuOpening(ContextMenuEventArgs e)
{
base.OnContextMenuOpening(e);
DocumentViewerHelper.OnContextMenuOpening(Document as FlowDocument, this, e);
}
/// <summary>
/// Called when the PageViews collection is modified; this occurs when GetPageViewsCollection
/// returns True or if the control's template is modified.
/// </summary>
protected override void OnPageViewsChanged()
{
// Change of DocumentPageView collection resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
// Apply zoom value to new DocumentPageViews
ApplyZoom();
base.OnPageViewsChanged();
}
/// <summary>
/// Called when the Document property is changed.
/// </summary>
protected override void OnDocumentChanged()
{
// Document change resets current ContentPosition.
_contentPosition = null;
// _oldDocument is cached from previous document changed notification.
if (_oldDocument != null)
{
DynamicDocumentPaginator dynamicDocumentPaginator = _oldDocument.DocumentPaginator as DynamicDocumentPaginator;
if (dynamicDocumentPaginator != null)
{
dynamicDocumentPaginator.GetPageNumberCompleted -= new GetPageNumberCompletedEventHandler(HandleGetPageNumberCompleted);
}
FlowDocumentPaginator flowDocumentPaginator = _oldDocument.DocumentPaginator as FlowDocumentPaginator;
if (flowDocumentPaginator != null)
{
flowDocumentPaginator.BreakRecordTableInvalidated -= new BreakRecordTableInvalidatedEventHandler(HandleAllBreakRecordsInvalidated);
}
}
base.OnDocumentChanged();
_oldDocument = Document;
// Validate the new document type
if (Document != null && !(Document is FlowDocument))
{
// Undo new document assignment.
Document = null;
// Throw exception.
throw new NotSupportedException(SR.Get(SRID.FlowDocumentPageViewerOnlySupportsFlowDocument));
}
if(Document != null)
{
DynamicDocumentPaginator dynamicDocumentPaginator = Document.DocumentPaginator as DynamicDocumentPaginator;
if (dynamicDocumentPaginator != null)
{
dynamicDocumentPaginator.GetPageNumberCompleted += new GetPageNumberCompletedEventHandler(HandleGetPageNumberCompleted);
}
FlowDocumentPaginator flowDocumentPaginator = Document.DocumentPaginator as FlowDocumentPaginator;
if (flowDocumentPaginator != null)
{
flowDocumentPaginator.BreakRecordTableInvalidated += new BreakRecordTableInvalidatedEventHandler(HandleAllBreakRecordsInvalidated);
}
}
// Update the toolbar with our current document state.
if (!CanShowFindToolBar)
{
// Disable FindToolBar, if the content does not support it.
if (FindToolBar != null)
{
ToggleFindToolBar(false);
}
}
// Go to the first page of new content.
OnGoToPageCommand(1);
}
/// <summary>
/// Called when print has been completed.
/// </summary>
protected virtual void OnPrintCompleted()
{
ClearPrintingState();
}
/// <summary>
/// Handler for the PreviousPage command.
/// </summary>
protected override void OnPreviousPageCommand()
{
if (this.CanGoToPreviousPage)
{
// Page navigation resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
base.OnPreviousPageCommand();
}
}
/// <summary>
/// Handler for the NextPage command.
/// </summary>
protected override void OnNextPageCommand()
{
if (this.CanGoToNextPage)
{
// Page navigation resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
base.OnNextPageCommand();
}
}
/// <summary>
/// Handler for the FirstPage command.
/// </summary>
protected override void OnFirstPageCommand()
{
if (this.CanGoToPreviousPage)
{
// Page navigation resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
base.OnFirstPageCommand();
}
}
/// <summary>
/// Handler for the LastPage command.
/// </summary>
protected override void OnLastPageCommand()
{
if (this.CanGoToNextPage)
{
// Page navigation resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
base.OnLastPageCommand();
}
}
/// <summary>
/// Handler for the GoToPage command.
/// </summary>
protected override void OnGoToPageCommand(int pageNumber)
{
if (CanGoToPage(pageNumber) && this.MasterPageNumber != pageNumber)
{
// Page navigation resets current ContentPosition.
// This position is updated when layout process is done.
_contentPosition = null;
base.OnGoToPageCommand(pageNumber);
}
}
/// <summary>
/// Handler for the Find command.
/// </summary>
protected virtual void OnFindCommand()
{
if (CanShowFindToolBar)
{
// Toggle on the FindToolBar between visible and hidden state.
ToggleFindToolBar(FindToolBar == null);
}
}
/// <summary>
/// Handler for the Print command.
/// </summary>
protected override void OnPrintCommand()
{
#if !DONOTREFPRINTINGASMMETA
System.Windows.Xps.XpsDocumentWriter docWriter;
System.Printing.PrintDocumentImageableArea ia = null;
FlowDocumentPaginator paginator;
FlowDocument document = Document as FlowDocument;
Thickness pagePadding;
// Only one printing job is allowed.
if (_printingState != null)
{
return;
}
// If the document is FlowDocument, do custom printing. Otherwise go through default path.
if (document != null)
{
// Show print dialog.
docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia);
if (docWriter != null && ia != null)
{
// Store the current state of the document in the PrintingState
paginator = ((IDocumentPaginatorSource)document).DocumentPaginator as FlowDocumentPaginator;
_printingState = new FlowDocumentPrintingState();
_printingState.XpsDocumentWriter = docWriter;
_printingState.PageSize = paginator.PageSize;
_printingState.PagePadding = document.PagePadding;
_printingState.IsSelectionEnabled = IsSelectionEnabled;
// Since _printingState value is used to determine CanExecute state, we must invalidate that state.
CommandManager.InvalidateRequerySuggested();
// Register for XpsDocumentWriter events.
docWriter.WritingCompleted += new WritingCompletedEventHandler(HandlePrintCompleted);
docWriter.WritingCancelled += new WritingCancelledEventHandler(HandlePrintCancelled);
// Add PreviewCanExecute handler to have a chance to disable UI Commands during printing.
CommandManager.AddPreviewCanExecuteHandler(this, new CanExecuteRoutedEventHandler(PreviewCanExecuteRoutedEventHandler));
// Suspend layout on DocumentPageViews.
ReadOnlyCollection<DocumentPageView> pageViews = PageViews;
for (int index = 0; index < pageViews.Count; index++)
{
pageViews[index].SuspendLayout();
}
// Disable TextSelection, if currently enabled.
if (IsSelectionEnabled)
{
IsSelectionEnabled = false;
}
// Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
pagePadding = document.ComputePageMargin();
document.PagePadding = new Thickness(
Math.Max(ia.OriginWidth, pagePadding.Left),
Math.Max(ia.OriginHeight, pagePadding.Top),
Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),
Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));
// Send DocumentPaginator to the printer.
docWriter.WriteAsync(paginator);
}
}
else
{
base.OnPrintCommand();
}
#endif // DONOTREFPRINTINGASMMETA
}
/// <summary>
/// Handler for the CancelPrint command.
/// </summary>
protected override void OnCancelPrintCommand()
{
#if !DONOTREFPRINTINGASMMETA
if (_printingState != null)
{
_printingState.XpsDocumentWriter.CancelAsync();
}
else
{
base.OnCancelPrintCommand();
}
#endif // DONOTREFPRINTINGASMMETA
}
/// <summary>
/// Handler for the IncreaseZoom command.
/// </summary>
protected virtual void OnIncreaseZoomCommand()
{
// If can zoom in, increase zoom by the zoom increment value.
if (this.CanIncreaseZoom)
{
SetCurrentValueInternal(ZoomProperty, Math.Min(Zoom + ZoomIncrement, MaxZoom));
}
}
/// <summary>
/// Handler for the DecreaseZoom command.
/// </summary>
protected virtual void OnDecreaseZoomCommand()
{
// If can zoom out, decrease zoom by the zoom increment value.
if (this.CanDecreaseZoom)
{
SetCurrentValueInternal(ZoomProperty, Math.Max(Zoom - ZoomIncrement, MinZoom));
}
}
#endregion Protected Methods
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Allows FrameworkElement to augment the EventRoute.
/// </summary>
internal override bool BuildRouteCore(EventRoute route, RoutedEventArgs args)
{
// If FlowDocumentPageViewer is used as embedded viewer (in FlowDocumentReader),
// it is not part of logical tree, so default logic in FE to re-add logical
// tree from branched node does not work here.
// But before FlowDocumentPageViewer is added to the event route, logical
// ancestors up to Document need to be added to the route. Otherwise
// content will not have a chance to react to events first.
// This breaks navigation cursor management logic, because TextEditor attached
// to FlowDocumentPageViewer handles those events first.
DependencyObject document = this.Document as DependencyObject;
if (document != null && LogicalTreeHelper.GetParent(document) != this)
{
DependencyObject branchNode = route.PeekBranchNode() as DependencyObject;
if (branchNode != null && DocumentViewerHelper.IsLogicalDescendent(branchNode, document))
{
// Add intermediate ContentElements to the route.
FrameworkElement.AddIntermediateElementsToRoute(
LogicalTreeHelper.GetParent(document), route, args, LogicalTreeHelper.GetParent(branchNode));
}
}
return base.BuildRouteCore(route, args);
}
internal override bool InvalidateAutomationAncestorsCore(Stack<DependencyObject> branchNodeStack, out bool continuePastCoreTree)
{
bool continueInvalidation = true;
DependencyObject document = this.Document as DependencyObject;
if (document != null && LogicalTreeHelper.GetParent(document) != this)
{
DependencyObject branchNode = (branchNodeStack.Count > 0) ? branchNodeStack.Peek() : null;
if (branchNode != null && DocumentViewerHelper.IsLogicalDescendent(branchNode, document))
{
continueInvalidation = FrameworkElement.InvalidateAutomationIntermediateElements(LogicalTreeHelper.GetParent(document), LogicalTreeHelper.GetParent(branchNode));
}
}
continueInvalidation &= base.InvalidateAutomationAncestorsCore(branchNodeStack, out continuePastCoreTree);
return continueInvalidation;
}
/// <summary>
/// Brings specified point into view.
/// </summary>
/// <param name="point">Point in the viewer's coordinate system.</param>
/// <returns>Whether operation is pending or not.</returns>
/// <remarks>
/// It is guaranteed that Point is not over any existing pages.
/// </remarks>
internal bool BringPointIntoView(Point point)
{
int index;
Rect[] pageRects;
Rect pageRect;
ReadOnlyCollection<DocumentPageView> pageViews = this.PageViews;
bool bringIntoViewPending = false;
if (pageViews.Count > 0)
{
// Calculate rectangles for all pages.
pageRects = new Rect[pageViews.Count];
for (index = 0; index < pageViews.Count; index++)
{
pageRect = new Rect(pageViews[index].RenderSize);
pageRect = pageViews[index].TransformToAncestor(this).TransformBounds(pageRect);
pageRects[index] = pageRect;
}
// Try to find exact hit
for (index = 0; index < pageRects.Length; index++)
{
if (pageRects[index].Contains(point))
{
break;
}
}
if (index >= pageRects.Length)
{
// Union all rects.
pageRect = pageRects[0];
for (index = 1; index < pageRects.Length; index++)
{
pageRect.Union(pageRects[index]);
}
//
if (DoubleUtil.LessThan(point.X, pageRect.Left))
{
if (this.CanGoToPreviousPage)
{
OnPreviousPageCommand();
bringIntoViewPending = true;
}
}
else if (DoubleUtil.GreaterThan(point.X, pageRect.Right))
{
if (this.CanGoToNextPage)
{
OnNextPageCommand();
bringIntoViewPending = true;
}
}
else if (DoubleUtil.LessThan(point.Y, pageRect.Top))
{
if (this.CanGoToPreviousPage)
{
OnPreviousPageCommand();
bringIntoViewPending = true;
}
}
else if (DoubleUtil.GreaterThan(point.Y, pageRect.Bottom))
{
if (this.CanGoToNextPage)
{
OnNextPageCommand();
bringIntoViewPending = true;
}
}
}
}
return bringIntoViewPending;
}
/// <summary>
/// Bring specified content position into view.
/// </summary>
internal object BringContentPositionIntoView(object arg)
{
PrivateBringContentPositionIntoView(arg, false);
return null;
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// ContentPosition representing currently viewed content.
/// </summary>
internal ContentPosition ContentPosition
{
get { return _contentPosition; }
}
/// <summary>
/// Whether FindToolBar can be enabled.
/// </summary>
internal bool CanShowFindToolBar
{
get { return (_findToolBarHost != null && this.Document != null && this.TextEditor != null); }
}
/// <summary>
/// Whether currently printing the content.
/// </summary>
internal bool IsPrinting
{
get { return (_printingState != null); }
}
#endregion Internal Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Handler for LayoutUpdated event raised by the LayoutSystem.
/// </summary>
private void HandleLayoutUpdated(object sender, EventArgs e)
{
DocumentPageView masterPageView;
DynamicDocumentPaginator documentPaginator;
// Ignore LayoutUpdated during printing.
if (this.Document != null && _printingState == null)
{
documentPaginator = this.Document.DocumentPaginator as DynamicDocumentPaginator;
if (documentPaginator != null)
{
// Update ContentPosition, if not cached.
if (_contentPosition == null)
{
masterPageView = GetMasterPageView();
if (masterPageView != null && masterPageView.DocumentPage != null)
{
_contentPosition = documentPaginator.GetPagePosition(masterPageView.DocumentPage);
}
if (_contentPosition == ContentPosition.Missing)
{
_contentPosition = null;
}
}
// Otherwise bring this position into view.
else
{
PrivateBringContentPositionIntoView(_contentPosition, true);
}
}
}
}
/// <summary>
/// Handler for GetPageNumberCompleted event raised by the Document.
/// </summary>
private void HandleGetPageNumberCompleted(object sender, GetPageNumberCompletedEventArgs e)
{
if (Document != null && sender == Document.DocumentPaginator && e != null)
{
if (!e.Cancelled && e.Error == null && e.UserState == _bringContentPositionIntoViewToken)
{
int newMasterPageNumber = e.PageNumber + 1;
OnGoToPageCommand(newMasterPageNumber);
}
}
}
/// <summary>
/// Handler for BreakRecordTableInvalidated event raised by the Paginator.
/// </summary>
private void HandleAllBreakRecordsInvalidated(object sender, EventArgs e)
{
ReadOnlyCollection<DocumentPageView> pageViews = PageViews;
for (int index = 0; index < pageViews.Count; index++)
{
pageViews[index].DuplicateVisual();
}
}
/// <summary>
/// Handle the case when the position is no longer valid for the current document, conservatively returns true if
/// is uknown.
/// </summary>
private bool IsValidContentPositionForDocument(IDocumentPaginatorSource document, ContentPosition contentPosition)
{
FlowDocument flowDocument = document as FlowDocument;
TextPointer textPointer = contentPosition as TextPointer;
if(flowDocument != null && textPointer != null)
{
return flowDocument.ContentStart.TextContainer == textPointer.TextContainer;
}
return true;
}
/// <summary>
/// Bring specified content position into view. (If async, cancel any previous async request to bring into view.)
/// </summary>
private void PrivateBringContentPositionIntoView(object arg, bool isAsyncRequest)
{
ContentPosition contentPosition = arg as ContentPosition;
if (contentPosition != null && Document != null)
{
DynamicDocumentPaginator documentPaginator = this.Document.DocumentPaginator as DynamicDocumentPaginator;
if (documentPaginator != null && IsValidContentPositionForDocument(Document, contentPosition))
{
documentPaginator.CancelAsync(_bringContentPositionIntoViewToken);
if(isAsyncRequest)
{
documentPaginator.GetPageNumberAsync(contentPosition, _bringContentPositionIntoViewToken);
}
else
{
int newMasterPageNumber = documentPaginator.GetPageNumber(contentPosition) + 1;
OnGoToPageCommand(newMasterPageNumber);
}
_contentPosition = contentPosition;
}
}
}
/// <summary>
/// Called when WritingCompleted event raised by a DocumentWriter (during printing).
/// </summary>
/// <param name="sender">Sender of the event.</param>
/// <param name="e">Event arguments.</param>
private void HandlePrintCompleted(object sender, WritingCompletedEventArgs e)
{
OnPrintCompleted();
}
/// <summary>
/// Called when WritingCancelled event raised by a DocumentWriter (during printing).
/// </summary>
/// <param name="sender">Sender of the event.</param>
/// <param name="e">Event arguments.</param>
private void HandlePrintCancelled(object sender, WritingCancelledEventArgs e)
{
ClearPrintingState();
}
/// <summary>
/// Clears printing state.
/// </summary>
private void ClearPrintingState()
{
#if !DONOTREFPRINTINGASMMETA
if (_printingState != null)
{
// Resume layout on DocumentPageViews.
ReadOnlyCollection<DocumentPageView> pageViews = PageViews;
for (int index = 0; index < pageViews.Count; index++)
{
pageViews[index].ResumeLayout();
}
// Enable TextSelection, if it was previously enabled.
if (_printingState.IsSelectionEnabled)
{
IsSelectionEnabled = true;
}
// Remove PreviewCanExecute handler (added when Print command was executed).
CommandManager.RemovePreviewCanExecuteHandler(this, new CanExecuteRoutedEventHandler(PreviewCanExecuteRoutedEventHandler));
// Unregister for XpsDocumentWriter events.
_printingState.XpsDocumentWriter.WritingCompleted -= new WritingCompletedEventHandler(HandlePrintCompleted);
_printingState.XpsDocumentWriter.WritingCancelled -= new WritingCancelledEventHandler(HandlePrintCancelled);
// Restore old page metrics on FlowDocument.
((FlowDocument)Document).PagePadding = _printingState.PagePadding;
Document.DocumentPaginator.PageSize = _printingState.PageSize;
_printingState = null;
// Since _documentWriter value is used to determine CanExecute state, we must invalidate that state.
CommandManager.InvalidateRequerySuggested();
}
#endif // DONOTREFPRINTINGASMMETA
}
/// <summary>
/// Apply zoom value to all existing DocumentPageViews.
/// </summary>
private void ApplyZoom()
{
int index;
ReadOnlyCollection<DocumentPageView> pageViews;
// Apply zoom value to all DocumentPageViews.
pageViews = this.PageViews;
for (index = 0; index < pageViews.Count; index++)
{
pageViews[index].SetPageZoom(Zoom / 100.0);
}
}
/// <summary>
/// Enables/disables the FindToolbar.
/// </summary>
/// <param name="enable">Whether to enable/disable FindToolBar.</param>
private void ToggleFindToolBar(bool enable)
{
Invariant.Assert(enable == (FindToolBar == null));
DocumentViewerHelper.ToggleFindToolBar(_findToolBarHost, new EventHandler(OnFindInvoked), enable);
}
/// <summary>
/// Invoked when the "Find" button in the Find Toolbar is clicked.
/// This method invokes the actual Find process.
/// </summary>
/// <param name="sender">The object that sent this event</param>
/// <param name="e">The Click Events associated with this event</param>
private void OnFindInvoked(object sender, EventArgs e)
{
ITextRange findResult;
int newMasterPageNumber;
FindToolBar findToolBar = FindToolBar;
if (findToolBar != null && this.TextEditor != null)
{
// In order to show current text selection TextEditor requires Focus to be set on the UIScope.
// If there embedded controls, it may happen that embedded control currently has focus and find
// was invoked through hotkeys. To support this case we manually move focus to the appropriate element.
Focus();
findResult = Find(findToolBar);
// If we found something, bring it into the view. Otherwise alert the user.
if ((findResult != null) && (!findResult.IsEmpty))
{
if (findResult.Start is ContentPosition)
{
// Bring find result into view. Set also _contentPosition to the beginning of the
// result, so it is visible during resizing.
_contentPosition = (ContentPosition)findResult.Start;
newMasterPageNumber = ((DynamicDocumentPaginator)this.Document.DocumentPaginator).GetPageNumber(_contentPosition) + 1;
OnBringIntoView(this, Rect.Empty, newMasterPageNumber);
}
}
else
{
DocumentViewerHelper.ShowFindUnsuccessfulMessage(findToolBar);
}
}
}
/// <summary>
/// The Zoom has changed and needs to be updated.
/// </summary>
private void ZoomChanged(double oldValue, double newValue)
{
if (!DoubleUtil.AreClose(oldValue, newValue))
{
UpdateCanIncreaseZoom();
UpdateCanDecreaseZoom();
// Changes to Zoom may potentially cause content reflowing.
// In such case Paginator will notify DocumentViewerBase
// about content changes through PagesChanged event and viewer
// will invalidate appropriate properties.
// Hence there is no need to invalidate any properties on
// DocumentViewerBase right now.
ApplyZoom();
}
}
/// <summary>
/// Update CanIncreaseZoom property.
/// </summary>
private void UpdateCanIncreaseZoom()
{
SetValue(CanIncreaseZoomPropertyKey, BooleanBoxes.Box(DoubleUtil.GreaterThan(MaxZoom, Zoom)));
}
/// <summary>
/// Update CanDecreaseZoom property.
/// </summary>
private void UpdateCanDecreaseZoom()
{
SetValue(CanDecreaseZoomPropertyKey, BooleanBoxes.Box(DoubleUtil.LessThan(MinZoom, Zoom)));
}
/// <summary>
/// The MaxZoom has changed and needs to be updated.
/// </summary>
private void MaxZoomChanged(double oldValue, double newValue)
{
CoerceValue(ZoomProperty);
UpdateCanIncreaseZoom();
}
/// <summary>
/// The MinZoom has changed and needs to be updated.
/// </summary>
private void MinZoomChanged(double oldValue, double newValue)
{
CoerceValue(MaxZoomProperty);
CoerceValue(ZoomProperty);
UpdateCanIncreaseZoom();
UpdateCanDecreaseZoom();
}
#region Commands
/// <summary>
/// Set up Command and RoutedCommand bindings.
/// </summary>
private static void CreateCommandBindings()
{
ExecutedRoutedEventHandler executedHandler;
CanExecuteRoutedEventHandler canExecuteHandler;
// Create our generic ExecutedRoutedEventHandler.
executedHandler = new ExecutedRoutedEventHandler(ExecutedRoutedEventHandler);
// Create our generic CanExecuteRoutedEventHandler
canExecuteHandler = new CanExecuteRoutedEventHandler(CanExecuteRoutedEventHandler);
// Command: ApplicationCommands.Find
CommandHelpers.RegisterCommandHandler(typeof(FlowDocumentPageViewer), ApplicationCommands.Find,
executedHandler, canExecuteHandler);
// Command: NavigationCommands.IncreaseZoom
CommandHelpers.RegisterCommandHandler(typeof(FlowDocumentPageViewer), NavigationCommands.IncreaseZoom,
executedHandler, canExecuteHandler, new KeyGesture(Key.OemPlus, ModifierKeys.Control));
// Command: NavigationCommands.DecreaseZoom
CommandHelpers.RegisterCommandHandler(typeof(FlowDocumentPageViewer), NavigationCommands.DecreaseZoom,
executedHandler, canExecuteHandler, new KeyGesture(Key.OemMinus, ModifierKeys.Control));
// Register input bindings
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.PreviousPage, new KeyGesture(Key.Left)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.PreviousPage, new KeyGesture(Key.Up)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.PreviousPage, new KeyGesture(Key.PageUp)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.NextPage, new KeyGesture(Key.Right)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.NextPage, new KeyGesture(Key.Down)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.NextPage, new KeyGesture(Key.PageDown)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.FirstPage, new KeyGesture(Key.Home)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.FirstPage, new KeyGesture(Key.Home, ModifierKeys.Control)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.LastPage, new KeyGesture(Key.End)));
CommandManager.RegisterClassInputBinding(typeof(FlowDocumentPageViewer), new InputBinding(NavigationCommands.LastPage, new KeyGesture(Key.End, ModifierKeys.Control)));
}
/// <summary>
/// Central handler for CanExecuteRouted events fired by Commands directed at FlowDocumentPageViewer.
/// </summary>
/// <param name="target">The target of this Command, expected to be FlowDocumentPageViewer</param>
/// <param name="args">The event arguments for this event.</param>
private static void CanExecuteRoutedEventHandler(object target, CanExecuteRoutedEventArgs args)
{
FlowDocumentPageViewer fdpv = target as FlowDocumentPageViewer;
Invariant.Assert(fdpv != null, "Target of QueryEnabledEvent must be FlowDocumentPageViewer.");
Invariant.Assert(args != null, "args cannot be null.");
// DocumentViewerBase is capable of execution of the majority of its commands.
// Special rules:
// a) Find command is enabled when Document is attached and printing is not in progress.
if (args.Command == ApplicationCommands.Find)
{
args.CanExecute = fdpv.CanShowFindToolBar;
}
else
{
args.CanExecute = true;
}
}
/// <summary>
/// Central handler for all ExecutedRouted events fired by Commands directed at FlowDocumentPageViewer.
/// </summary>
/// <param name="target">The target of this Command, expected to be FlowDocumentPageViewer.</param>
/// <param name="args">The event arguments associated with this event.</param>
private static void ExecutedRoutedEventHandler(object target, ExecutedRoutedEventArgs args)
{
FlowDocumentPageViewer fdpv = target as FlowDocumentPageViewer;
Invariant.Assert(fdpv != null, "Target of ExecuteEvent must be FlowDocumentPageViewer.");
Invariant.Assert(args != null, "args cannot be null.");
// Now we execute the method corresponding to the Command that fired this event;
// each Command has its own protected virtual method that performs the operation
// corresponding to the Command.
if (args.Command == NavigationCommands.IncreaseZoom)
{
fdpv.OnIncreaseZoomCommand();
}
else if (args.Command == NavigationCommands.DecreaseZoom)
{
fdpv.OnDecreaseZoomCommand();
}
else if (args.Command == ApplicationCommands.Find)
{
fdpv.OnFindCommand();
}
else
{
Invariant.Assert(false, "Command not handled in ExecutedRoutedEventHandler.");
}
}
/// <summary>
/// Disable commands on DocumentViewerBase when this printing is in progress.
/// </summary>
private void PreviewCanExecuteRoutedEventHandler(object target, CanExecuteRoutedEventArgs args)
{
FlowDocumentPageViewer fdpv = target as FlowDocumentPageViewer;
Invariant.Assert(fdpv != null, "Target of PreviewCanExecuteRoutedEventHandler must be FlowDocumentPageViewer.");
Invariant.Assert(args != null, "args cannot be null.");
// Disable UI commands, if printing is in progress.
if (fdpv._printingState != null)
{
if (args.Command != ApplicationCommands.CancelPrint)
{
args.CanExecute = false;
args.Handled = true;
}
}
}
/// <summary>
/// Called when a key event occurs.
/// </summary>
private static void KeyDownHandler(object sender, KeyEventArgs e)
{
DocumentViewerHelper.KeyDownHelper(e, ((FlowDocumentPageViewer)sender)._findToolBarHost);
}
#endregion Commands
#region Static Methods
/// <summary>
/// Coerce the value for Zoom property.
/// </summary>
private static object CoerceZoom(DependencyObject d, object value)
{
Invariant.Assert(d != null && d is FlowDocumentPageViewer);
double maxZoom, minZoom;
FlowDocumentPageViewer v = (FlowDocumentPageViewer) d;
double zoom = (double)value;
maxZoom = v.MaxZoom;
if (DoubleUtil.LessThan(maxZoom, zoom))
{
return maxZoom;
}
minZoom = v.MinZoom;
if (DoubleUtil.GreaterThan(minZoom, zoom))
{
return minZoom;
}
return value;
}
/// <summary>
/// Coerce the value for MaxZoom property.
/// </summary>
private static object CoerceMaxZoom(DependencyObject d, object value)
{
Invariant.Assert(d != null && d is FlowDocumentPageViewer);
FlowDocumentPageViewer v = (FlowDocumentPageViewer) d;
double minZoom = v.MinZoom;
if (DoubleUtil.LessThan((double)value, minZoom))
{
return minZoom;
}
return value;
}
/// <summary>
/// The Zoom has changed and needs to be updated.
/// </summary>
private static void ZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Invariant.Assert(d != null && d is FlowDocumentPageViewer);
((FlowDocumentPageViewer)d).ZoomChanged((double) e.OldValue, (double) e.NewValue);
}
/// <summary>
/// The MaxZoom has changed and needs to be updated.
/// </summary>
private static void MaxZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Invariant.Assert(d != null && d is FlowDocumentPageViewer);
((FlowDocumentPageViewer)d).MaxZoomChanged((double) e.OldValue, (double) e.NewValue);
}
/// <summary>
/// The MinZoom has changed and needs to be updated.
/// </summary>
private static void MinZoomChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Invariant.Assert(d != null && d is FlowDocumentPageViewer);
((FlowDocumentPageViewer)d).MinZoomChanged((double) e.OldValue, (double) e.NewValue);
}
/// <summary>
/// Validate Zoom, MaxZoom, MinZoom and ZoomIncrement value.
/// </summary>
/// <param name="o">Value to validate.</param>
/// <returns>True if the value is valid, false otherwise.</returns>
private static bool ZoomValidateValue(object o)
{
double value = (double)o;
return (!Double.IsNaN(value) && !Double.IsInfinity(value) && DoubleUtil.GreaterThan(value, 0d));
}
/// <summary>
/// PropertyChanged callback for a property that affects the selection or caret rendering.
/// </summary>
private static void UpdateCaretElement(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FlowDocumentPageViewer viewer = (FlowDocumentPageViewer)d;
if (viewer.Selection != null)
{
CaretElement caretElement = viewer.Selection.CaretElement;
if (caretElement != null)
{
caretElement.InvalidateVisual();
}
}
}
#endregion Static Methods
#endregion Private Methods
//-------------------------------------------------------------------
//
// Private Properties
//
//-------------------------------------------------------------------
#region Private Properties
/// <summary>
/// Returns FindToolBar, if enabled.
/// </summary>
private FindToolBar FindToolBar
{
get { return (_findToolBarHost != null) ? _findToolBarHost.Child as FindToolBar : null; }
}
#endregion Private Properties
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
private Decorator _findToolBarHost; // Host for FindToolbar
private ContentPosition _contentPosition; // Current position to be maintained during zooming and resizing.
private FlowDocumentPrintingState _printingState; // Printing state
private IDocumentPaginatorSource _oldDocument; // IDocumentPaginatorSource representing Document. Cached separately from DocumentViewerBase
// due to lifetime issues.
private object _bringContentPositionIntoViewToken = new object(); // Bring content position into view user state
private const string _findToolBarHostTemplateName = "PART_FindToolBarHost"; //Name for the Find Toolbar host.
#endregion Private Fields
//-------------------------------------------------------------------
//
// IJournalState Members
//
//-------------------------------------------------------------------
#region IJournalState Members
[Serializable]
private class JournalState : CustomJournalStateInternal
{
public JournalState(int contentPosition, LogicalDirection contentPositionDirection, double zoom)
{
ContentPosition = contentPosition;
ContentPositionDirection = contentPositionDirection;
Zoom = zoom;
}
public int ContentPosition;
public LogicalDirection ContentPositionDirection;
public double Zoom;
}
/// <summary>
/// <see cref="IJournalState.GetJournalState"/>
/// </summary>
CustomJournalStateInternal IJournalState.GetJournalState(JournalReason journalReason)
{
int cp = -1;
LogicalDirection cpDirection = LogicalDirection.Forward;
TextPointer contentPosition = ContentPosition as TextPointer;
if (contentPosition != null)
{
cp = contentPosition.Offset;
cpDirection = contentPosition.LogicalDirection;
}
return new JournalState(cp, cpDirection, Zoom);
}
/// <summary>
/// <see cref="IJournalState.RestoreJournalState"/>
/// </summary>
void IJournalState.RestoreJournalState(CustomJournalStateInternal state)
{
JournalState viewerState = state as JournalState;
if (state != null)
{
SetCurrentValueInternal(ZoomProperty, viewerState.Zoom);
if (viewerState.ContentPosition != -1)
{
FlowDocument document = Document as FlowDocument;
if (document != null)
{
TextContainer textContainer = document.StructuralCache.TextContainer;
if (viewerState.ContentPosition <= textContainer.SymbolCount)
{
TextPointer contentPosition = textContainer.CreatePointerAtOffset(viewerState.ContentPosition, viewerState.ContentPositionDirection);
// This need be called because the UI may not be ready when Contentposition is set.
Dispatcher.BeginInvoke(DispatcherPriority.Input, new DispatcherOperationCallback(BringContentPositionIntoView), contentPosition);
}
}
}
}
}
#endregion IJournalState Members
//-------------------------------------------------------------------
//
// DTypeThemeStyleKey
//
//-------------------------------------------------------------------
#region DTypeThemeStyleKey
/// <summary>
/// Returns the DependencyObjectType for the registered ThemeStyleKey's default
/// value. Controls will override this method to return approriate types
/// </summary>
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
}
| |
using System;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;
using Rhino.Security.Impl.Util;
using Rhino.Security.Interfaces;
using Rhino.Security.Model;
using Rhino.Security.Properties;
namespace Rhino.Security.Services
{
/// <summary>
/// Answers authorization questions as well as enhance Criteria
/// queries
/// </summary>
public class AuthorizationService : IAuthorizationService
{
private readonly IAuthorizationRepository authorizationRepository;
private readonly IPermissionsService permissionsService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
/// </summary>
/// <param name="permissionsService">The permissions service.</param>
/// <param name="authorizationRepository">The authorization editing service.</param>
public AuthorizationService(IPermissionsService permissionsService,
IAuthorizationRepository authorizationRepository)
{
this.permissionsService = permissionsService;
this.authorizationRepository = authorizationRepository;
}
#region IAuthorizationService Members
/// <summary>
/// Adds the permissions to the criteria query.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="criteria">The criteria.</param>
/// <param name="operation">The operation.</param>
public void AddPermissionsToQuery(IUser user, string operation, ICriteria criteria)
{
ICriterion allowed = GetPermissionQueryInternal(user, operation, GetSecurityKeyProperty(criteria));
criteria.Add(allowed);
}
///<summary>
/// Adds the permissions to the criteria query for the given usersgroup
///</summary>
///<param name="usersgroup">The usersgroup. Only permissions directly related to this usergroup
/// are taken into account</param>
///<param name="operation">The operation</param>
///<param name="criteria">The criteria</param>
public void AddPermissionsToQuery(UsersGroup usersgroup,string operation, ICriteria criteria)
{
ICriterion allowed = GetPermissionQueryInternal(usersgroup, operation, GetSecurityKeyProperty(criteria));
criteria.Add(allowed);
}
/// <summary>
/// Adds the permissions to query.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="criteria">The criteria.</param>
/// <param name="operation">The operation.</param>
public void AddPermissionsToQuery(IUser user, string operation, DetachedCriteria criteria)
{
ICriterion allowed = GetPermissionQueryInternal(user, operation, GetSecurityKeyProperty(criteria));
criteria.Add(allowed);
}
///<summary>Adds the permissions to the criteria query for the given usersgroup
///</summary>
///<param name="usersgroup">The usersgroup. Only permissions directly related to this usergroup
/// are taken into account</param>
///<param name="operation">The operation</param>
///<param name="criteria">The criteria</param>
public void AddPermissionsToQuery(UsersGroup usersgroup, string operation, DetachedCriteria criteria)
{
ICriterion allowed = GetPermissionQueryInternal(usersgroup, operation, GetSecurityKeyProperty(criteria));
criteria.Add(allowed);
}
/// <summary>
/// Determines whether the specified user is allowed to perform the specified
/// operation on the entity
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="user">The user.</param>
/// <param name="entity">The entity.</param>
/// <param name="operation">The operation.</param>
/// <returns>
/// <c>true</c> if the specified user is allowed; otherwise, <c>false</c>.
/// </returns>
public bool IsAllowed<TEntity>(IUser user, TEntity entity, string operation) where TEntity : class
{
Permission[] permissions = permissionsService.GetPermissionsFor(user, entity, operation);
if (permissions.Length == 0)
return false;
return permissions[0].Allow;
}
/// <summary>
/// Determines whether the specified user is allowed to perform the
/// specified operation on the entity.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="operation">The operation.</param>
/// <returns>
/// <c>true</c> if the specified user is allowed; otherwise, <c>false</c>.
/// </returns>
public bool IsAllowed(IUser user, string operation)
{
Permission[] permissions = permissionsService.GetGlobalPermissionsFor(user, operation);
if (permissions.Length == 0)
return false;
return permissions[0].Allow;
}
/// <summary>
/// Gets the authorization information for the specified user and operation,
/// allows to easily understand why a given operation was granted / denied.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="operation">The operation.</param>
/// <returns></returns>
public AuthorizationInformation GetAuthorizationInformation(IUser user, string operation)
{
AuthorizationInformation info;
if (InitializeAuthorizationInfo(operation, out info))
return info;
Permission[] permissions = permissionsService.GetGlobalPermissionsFor(user, operation);
AddPermissionDescriptionToAuthorizationInformation<object>(operation, info, user, permissions, null);
return info;
}
/// <summary>
/// Gets the authorization information for the specified user and operation on the
/// given entity, allows to easily understand why a given operation was granted / denied.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="user">The user.</param>
/// <param name="entity">The entity.</param>
/// <param name="operation">The operation.</param>
/// <returns></returns>
public AuthorizationInformation GetAuthorizationInformation<TEntity>(IUser user, TEntity entity,
string operation) where TEntity : class
{
AuthorizationInformation info;
if (InitializeAuthorizationInfo(operation, out info))
return info;
Permission[] permissions = permissionsService.GetPermissionsFor(user, entity, operation);
AddPermissionDescriptionToAuthorizationInformation(operation, info, user, permissions, entity);
return info;
}
#endregion
private static ICriterion GetPermissionQueryInternal(IUser user, string operation, string securityKeyProperty)
{
string[] operationNames = Strings.GetHierarchicalOperationNames(operation);
DetachedCriteria criteria = DetachedCriteria.For<Permission>("permission")
.CreateAlias("Operation", "op")
.CreateAlias("EntitiesGroup", "entityGroup", JoinType.LeftOuterJoin)
.CreateAlias("entityGroup.Entities", "entityKey", JoinType.LeftOuterJoin)
.SetProjection(Projections.Property("Allow"))
.Add(Restrictions.In("op.Name", operationNames))
.Add(Restrictions.Eq("User", user)
|| Subqueries.PropertyIn("UsersGroup.Id",
SecurityCriterions.AllGroups(user).SetProjection(Projections.Id())))
.Add(
Property.ForName(securityKeyProperty).EqProperty("permission.EntitySecurityKey") ||
Property.ForName(securityKeyProperty).EqProperty("entityKey.EntitySecurityKey") ||
(
Restrictions.IsNull("permission.EntitySecurityKey") &&
Restrictions.IsNull("permission.EntitiesGroup")
)
)
.SetMaxResults(1)
.AddOrder(Order.Desc("Level"))
.AddOrder(Order.Asc("Allow"));
return Subqueries.Eq(true, criteria);
}
private ICriterion GetPermissionQueryInternal(UsersGroup usersgroup, string operation, string securityKeyProperty)
{
string[] operationNames = Strings.GetHierarchicalOperationNames(operation);
DetachedCriteria criteria = DetachedCriteria.For<Permission>("permission")
.CreateAlias("Operation", "op")
.CreateAlias("EntitiesGroup", "entityGroup", JoinType.LeftOuterJoin)
.CreateAlias("entityGroup.Entities", "entityKey", JoinType.LeftOuterJoin)
.SetProjection(Projections.Property("Allow"))
.Add(Expression.In("op.Name", operationNames))
.Add(Expression.Eq("UsersGroup", usersgroup))
.Add(
Property.ForName(securityKeyProperty).EqProperty("permission.EntitySecurityKey") ||
Property.ForName(securityKeyProperty).EqProperty("entityKey.EntitySecurityKey") ||
(
Expression.IsNull("permission.EntitySecurityKey") &&
Expression.IsNull("permission.EntitiesGroup")
)
)
.SetMaxResults(1)
.AddOrder(Order.Desc("Level"))
.AddOrder(Order.Asc("Allow"));
return Subqueries.Eq(true, criteria);
}
private string GetSecurityKeyProperty(DetachedCriteria criteria)
{
Type rootType = criteria.GetRootEntityTypeIfAvailable();
return criteria.Alias + "." + Security.GetSecurityKeyProperty(rootType);
}
private string GetSecurityKeyProperty(ICriteria criteria)
{
Type rootType = criteria.GetRootEntityTypeIfAvailable();
return criteria.Alias + "." + Security.GetSecurityKeyProperty(rootType);
}
private void AddPermissionDescriptionToAuthorizationInformation<TEntity>(string operation,
AuthorizationInformation info,
IUser user, Permission[] permissions,
TEntity entity)
where TEntity : class
{
string entityDescription = "";
string entitiesGroupsDescription = "";
if (entity != null)
{
EntitiesGroup[] entitiesGroups = authorizationRepository.GetAssociatedEntitiesGroupsFor(entity);
entityDescription = Security.GetDescription(entity);
entitiesGroupsDescription = Strings.Join(entitiesGroups);
}
if (permissions.Length == 0)
{
UsersGroup[] usersGroups = authorizationRepository.GetAssociatedUsersGroupFor(user);
if (entity == null) //not on specific entity
{
info.AddDeny(Resources.PermissionForOperationNotGrantedToUser,
operation,
user.SecurityInfo.Name,
Strings.Join(usersGroups)
);
}
else
{
info.AddDeny(Resources.PermissionForOperationNotGrantedToUserOnEntity,
operation,
user.SecurityInfo.Name,
Strings.Join(usersGroups),
entityDescription,
entitiesGroupsDescription);
}
return;
}
foreach (Permission permission in permissions)
{
AddUserLevelPermissionMessage(operation, info, user, permission, entityDescription,
entitiesGroupsDescription);
AddUserGroupLevelPermissionMessage(operation, info, user, permission, entityDescription,
entitiesGroupsDescription);
}
}
private bool InitializeAuthorizationInfo(string operation, out AuthorizationInformation info)
{
info = new AuthorizationInformation();
Operation op = authorizationRepository.GetOperationByName(operation);
if (op == null)
{
info.AddDeny(Resources.OperationNotDefined, operation);
return true;
}
return false;
}
private void AddUserGroupLevelPermissionMessage(string operation, AuthorizationInformation info,
IUser user, Permission permission,
string entityDescription,
string entitiesGroupsDescription)
{
if (permission.UsersGroup != null)
{
UsersGroup[] ancestryAssociation =
authorizationRepository.GetAncestryAssociation(user, permission.UsersGroup.Name);
string groupAncestry = Strings.Join(ancestryAssociation, " -> ");
if (permission.Allow)
{
info.AddAllow(Resources.PermissionGrantedForUsersGroup,
operation,
permission.UsersGroup.Name,
GetPermissionTarget(permission, entityDescription, entitiesGroupsDescription),
user.SecurityInfo.Name,
permission.Level,
groupAncestry);
}
else
{
info.AddDeny(Resources.PermissionDeniedForUsersGroup,
operation,
permission.UsersGroup.Name,
GetPermissionTarget(permission, entityDescription, entitiesGroupsDescription),
user.SecurityInfo.Name,
permission.Level,
groupAncestry);
}
}
}
private static void AddUserLevelPermissionMessage(
string operation,
AuthorizationInformation info,
IUser user,
Permission permission,
string entityDescription,
string entitiesGroupsDescription)
{
if (permission.User != null)
{
string target = GetPermissionTarget(permission, entityDescription, entitiesGroupsDescription);
if (permission.Allow)
{
info.AddAllow(Resources.PermissionGrantedForUser,
operation,
user.SecurityInfo.Name,
target,
permission.Level);
}
else
{
info.AddDeny(Resources.PermissionDeniedForUser,
operation,
user.SecurityInfo.Name,
target,
permission.Level);
}
}
}
private static string GetPermissionTarget(Permission permission, string entityDescription,
string entitiesGroupsDescription)
{
if (permission.EntitiesGroup != null)
{
if (string.IsNullOrEmpty(entitiesGroupsDescription) == false)
{
return string.Format(Resources.EntityWithGroups,
permission.EntitiesGroup.Name,
entityDescription, entitiesGroupsDescription);
}
else
{
return permission.EntitiesGroup.Name;
}
}
if (permission.EntitySecurityKey != null)
return entityDescription;
return Resources.Everything;
}
}
}
| |
//
// 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.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Microsoft.WindowsAzure;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ServerOperationsExtensions
{
/// <summary>
/// Creates a new Azure SQL Database server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// database.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static ServerGetResponse CreateOrUpdate(this IServerOperations operations, string resourceGroupName, string serverName, ServerCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure SQL Database server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// database.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static Task<ServerGetResponse> CreateOrUpdateAsync(this IServerOperations operations, string resourceGroupName, string serverName, ServerCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, parameters, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this IServerOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).DeleteAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this IServerOperations operations, string resourceGroupName, string serverName)
{
return operations.DeleteAsync(resourceGroupName, serverName, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to retrieve.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static ServerGetResponse Get(this IServerOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).GetAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the server to retrieve.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static Task<ServerGetResponse> GetAsync(this IServerOperations operations, string resourceGroupName, string serverName)
{
return operations.GetAsync(resourceGroupName, serverName, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static ServerListResponse List(this IServerOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Server.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Sql.IServerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <returns>
/// Represents the response to a Get Database request.
/// </returns>
public static Task<ServerListResponse> ListAsync(this IServerOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This RegexInterpreter class is internal to the RegularExpression package.
// It executes a block of regular expression codes while consuming
// input.
using System;
using System.Diagnostics;
using System.Globalization;
namespace Flatbox.RegularExpressions
{
internal sealed class RegexInterpreter : RegexRunner
{
private readonly RegexCode _code;
private readonly CultureInfo _culture;
private int _operator;
private int _codepos;
private bool _rightToLeft;
private bool _caseInsensitive;
internal RegexInterpreter(RegexCode code, CultureInfo culture)
{
Debug.Assert(code != null, "code cannot be null.");
Debug.Assert(culture != null, "culture cannot be null.");
_code = code;
_culture = culture;
}
protected override void InitTrackCount()
{
runtrackcount = _code._trackcount;
}
private void Advance()
{
Advance(0);
}
private void Advance(int i)
{
_codepos += (i + 1);
SetOperator(_code._codes[_codepos]);
}
private void Goto(int newpos)
{
// when branching backward, ensure storage
if (newpos < _codepos)
EnsureStorage();
SetOperator(_code._codes[newpos]);
_codepos = newpos;
}
private void Textto(int newpos)
{
runtextpos = newpos;
}
private void Trackto(int newpos)
{
runtrackpos = runtrack.Length - newpos;
}
private int Textstart()
{
return runtextstart;
}
private int Textpos()
{
return runtextpos;
}
// push onto the backtracking stack
private int Trackpos()
{
return runtrack.Length - runtrackpos;
}
private void TrackPush()
{
runtrack[--runtrackpos] = _codepos;
}
private void TrackPush(int I1)
{
runtrack[--runtrackpos] = I1;
runtrack[--runtrackpos] = _codepos;
}
private void TrackPush(int I1, int I2)
{
runtrack[--runtrackpos] = I1;
runtrack[--runtrackpos] = I2;
runtrack[--runtrackpos] = _codepos;
}
private void TrackPush(int I1, int I2, int I3)
{
runtrack[--runtrackpos] = I1;
runtrack[--runtrackpos] = I2;
runtrack[--runtrackpos] = I3;
runtrack[--runtrackpos] = _codepos;
}
private void TrackPush2(int I1)
{
runtrack[--runtrackpos] = I1;
runtrack[--runtrackpos] = -_codepos;
}
private void TrackPush2(int I1, int I2)
{
runtrack[--runtrackpos] = I1;
runtrack[--runtrackpos] = I2;
runtrack[--runtrackpos] = -_codepos;
}
private void Backtrack()
{
int newpos = runtrack[runtrackpos++];
#if DEBUG
if (runmatch.Debug)
{
if (newpos < 0)
Debug.WriteLine(" Backtracking (back2) to code position " + (-newpos));
else
Debug.WriteLine(" Backtracking to code position " + newpos);
}
#endif
if (newpos < 0)
{
newpos = -newpos;
SetOperator(_code._codes[newpos] | RegexCode.Back2);
}
else
{
SetOperator(_code._codes[newpos] | RegexCode.Back);
}
// When branching backward, ensure storage
if (newpos < _codepos)
EnsureStorage();
_codepos = newpos;
}
private void SetOperator(int op)
{
_caseInsensitive = (0 != (op & RegexCode.Ci));
_rightToLeft = (0 != (op & RegexCode.Rtl));
_operator = op & ~(RegexCode.Rtl | RegexCode.Ci);
}
private void TrackPop()
{
runtrackpos++;
}
// pop framesize items from the backtracking stack
private void TrackPop(int framesize)
{
runtrackpos += framesize;
}
// Technically we are actually peeking at items already popped. So if you want to
// get and pop the top item from the stack, you do
// TrackPop();
// TrackPeek();
private int TrackPeek()
{
return runtrack[runtrackpos - 1];
}
// get the ith element down on the backtracking stack
private int TrackPeek(int i)
{
return runtrack[runtrackpos - i - 1];
}
// Push onto the grouping stack
private void StackPush(int I1)
{
runstack[--runstackpos] = I1;
}
private void StackPush(int I1, int I2)
{
runstack[--runstackpos] = I1;
runstack[--runstackpos] = I2;
}
private void StackPop()
{
runstackpos++;
}
// pop framesize items from the grouping stack
private void StackPop(int framesize)
{
runstackpos += framesize;
}
// Technically we are actually peeking at items already popped. So if you want to
// get and pop the top item from the stack, you do
// StackPop();
// StackPeek();
private int StackPeek()
{
return runstack[runstackpos - 1];
}
// get the ith element down on the grouping stack
private int StackPeek(int i)
{
return runstack[runstackpos - i - 1];
}
private int Operator()
{
return _operator;
}
private int Operand(int i)
{
return _code._codes[_codepos + i + 1];
}
private int Leftchars()
{
return runtextpos - runtextbeg;
}
private int Rightchars()
{
return runtextend - runtextpos;
}
private int Bump()
{
return _rightToLeft ? -1 : 1;
}
private int Forwardchars()
{
return _rightToLeft ? runtextpos - runtextbeg : runtextend - runtextpos;
}
private char Forwardcharnext()
{
char ch = (_rightToLeft ? runtext[--runtextpos] : runtext[runtextpos++]);
return (_caseInsensitive ? _culture.TextInfo.ToLower(ch) : ch);
}
private bool Stringmatch(string str)
{
int c;
int pos;
if (!_rightToLeft)
{
if (runtextend - runtextpos < (c = str.Length))
return false;
pos = runtextpos + c;
}
else
{
if (runtextpos - runtextbeg < (c = str.Length))
return false;
pos = runtextpos;
}
if (!_caseInsensitive)
{
while (c != 0)
if (str[--c] != runtext[--pos])
return false;
}
else
{
while (c != 0)
if (str[--c] != _culture.TextInfo.ToLower(runtext[--pos]))
return false;
}
if (!_rightToLeft)
{
pos += str.Length;
}
runtextpos = pos;
return true;
}
private bool Refmatch(int index, int len)
{
int c;
int pos;
int cmpos;
if (!_rightToLeft)
{
if (runtextend - runtextpos < len)
return false;
pos = runtextpos + len;
}
else
{
if (runtextpos - runtextbeg < len)
return false;
pos = runtextpos;
}
cmpos = index + len;
c = len;
if (!_caseInsensitive)
{
while (c-- != 0)
if (runtext[--cmpos] != runtext[--pos])
return false;
}
else
{
while (c-- != 0)
if (_culture.TextInfo.ToLower(runtext[--cmpos]) != _culture.TextInfo.ToLower(runtext[--pos]))
return false;
}
if (!_rightToLeft)
{
pos += len;
}
runtextpos = pos;
return true;
}
private void Backwardnext()
{
runtextpos += _rightToLeft ? 1 : -1;
}
private char CharAt(int j)
{
return runtext[j];
}
protected override bool FindFirstChar()
{
int i;
string set;
if (0 != (_code._anchors & (RegexFCD.Beginning | RegexFCD.Start | RegexFCD.EndZ | RegexFCD.End)))
{
if (!_code._rightToLeft)
{
if ((0 != (_code._anchors & RegexFCD.Beginning) && runtextpos > runtextbeg) ||
(0 != (_code._anchors & RegexFCD.Start) && runtextpos > runtextstart))
{
runtextpos = runtextend;
return false;
}
if (0 != (_code._anchors & RegexFCD.EndZ) && runtextpos < runtextend - 1)
{
runtextpos = runtextend - 1;
}
else if (0 != (_code._anchors & RegexFCD.End) && runtextpos < runtextend)
{
runtextpos = runtextend;
}
}
else
{
if ((0 != (_code._anchors & RegexFCD.End) && runtextpos < runtextend) ||
(0 != (_code._anchors & RegexFCD.EndZ) && (runtextpos < runtextend - 1 ||
(runtextpos == runtextend - 1 && CharAt(runtextpos) != '\n'))) ||
(0 != (_code._anchors & RegexFCD.Start) && runtextpos < runtextstart))
{
runtextpos = runtextbeg;
return false;
}
if (0 != (_code._anchors & RegexFCD.Beginning) && runtextpos > runtextbeg)
{
runtextpos = runtextbeg;
}
}
if (_code._bmPrefix != null)
{
return _code._bmPrefix.IsMatch(runtext, runtextpos, runtextbeg, runtextend);
}
return true; // found a valid start or end anchor
}
else if (_code._bmPrefix != null)
{
runtextpos = _code._bmPrefix.Scan(runtext, runtextpos, runtextbeg, runtextend);
if (runtextpos == -1)
{
runtextpos = (_code._rightToLeft ? runtextbeg : runtextend);
return false;
}
return true;
}
else if (_code._fcPrefix == null)
{
return true;
}
_rightToLeft = _code._rightToLeft;
_caseInsensitive = _code._fcPrefix.CaseInsensitive;
set = _code._fcPrefix.Prefix;
if (RegexCharClass.IsSingleton(set))
{
char ch = RegexCharClass.SingletonChar(set);
for (i = Forwardchars(); i > 0; i--)
{
if (ch == Forwardcharnext())
{
Backwardnext();
return true;
}
}
}
else
{
for (i = Forwardchars(); i > 0; i--)
{
if (RegexCharClass.CharInClass(Forwardcharnext(), set))
{
Backwardnext();
return true;
}
}
}
return false;
}
protected override void Go()
{
Goto(0);
for (; ;)
{
#if DEBUG
if (runmatch.Debug)
{
DumpState();
}
#endif
CheckTimeout();
switch (Operator())
{
case RegexCode.Stop:
return;
case RegexCode.Nothing:
break;
case RegexCode.Goto:
Goto(Operand(0));
continue;
case RegexCode.Testref:
if (!IsMatched(Operand(0)))
break;
Advance(1);
continue;
case RegexCode.Lazybranch:
TrackPush(Textpos());
Advance(1);
continue;
case RegexCode.Lazybranch | RegexCode.Back:
TrackPop();
Textto(TrackPeek());
Goto(Operand(0));
continue;
case RegexCode.Setmark:
StackPush(Textpos());
TrackPush();
Advance();
continue;
case RegexCode.Nullmark:
StackPush(-1);
TrackPush();
Advance();
continue;
case RegexCode.Setmark | RegexCode.Back:
case RegexCode.Nullmark | RegexCode.Back:
StackPop();
break;
case RegexCode.Getmark:
StackPop();
TrackPush(StackPeek());
Textto(StackPeek());
Advance();
continue;
case RegexCode.Getmark | RegexCode.Back:
TrackPop();
StackPush(TrackPeek());
break;
case RegexCode.Capturemark:
if (Operand(1) != -1 && !IsMatched(Operand(1)))
break;
StackPop();
if (Operand(1) != -1)
TransferCapture(Operand(0), Operand(1), StackPeek(), Textpos());
else
Capture(Operand(0), StackPeek(), Textpos());
TrackPush(StackPeek());
Advance(2);
continue;
case RegexCode.Capturemark | RegexCode.Back:
TrackPop();
StackPush(TrackPeek());
Uncapture();
if (Operand(0) != -1 && Operand(1) != -1)
Uncapture();
break;
case RegexCode.Branchmark:
{
int matched;
StackPop();
matched = Textpos() - StackPeek();
if (matched != 0)
{ // Nonempty match -> loop now
TrackPush(StackPeek(), Textpos()); // Save old mark, textpos
StackPush(Textpos()); // Make new mark
Goto(Operand(0)); // Loop
}
else
{ // Empty match -> straight now
TrackPush2(StackPeek()); // Save old mark
Advance(1); // Straight
}
continue;
}
case RegexCode.Branchmark | RegexCode.Back:
TrackPop(2);
StackPop();
Textto(TrackPeek(1)); // Recall position
TrackPush2(TrackPeek()); // Save old mark
Advance(1); // Straight
continue;
case RegexCode.Branchmark | RegexCode.Back2:
TrackPop();
StackPush(TrackPeek()); // Recall old mark
break; // Backtrack
case RegexCode.Lazybranchmark:
{
// We hit this the first time through a lazy loop and after each
// successful match of the inner expression. It simply continues
// on and doesn't loop.
StackPop();
int oldMarkPos = StackPeek();
if (Textpos() != oldMarkPos)
{ // Nonempty match -> try to loop again by going to 'back' state
if (oldMarkPos != -1)
TrackPush(oldMarkPos, Textpos()); // Save old mark, textpos
else
TrackPush(Textpos(), Textpos());
}
else
{
// The inner expression found an empty match, so we'll go directly to 'back2' if we
// backtrack. In this case, we need to push something on the stack, since back2 pops.
// However, in the case of ()+? or similar, this empty match may be legitimate, so push the text
// position associated with that empty match.
StackPush(oldMarkPos);
TrackPush2(StackPeek()); // Save old mark
}
Advance(1);
continue;
}
case RegexCode.Lazybranchmark | RegexCode.Back:
{
// After the first time, Lazybranchmark | RegexCode.Back occurs
// with each iteration of the loop, and therefore with every attempted
// match of the inner expression. We'll try to match the inner expression,
// then go back to Lazybranchmark if successful. If the inner expression
// fails, we go to Lazybranchmark | RegexCode.Back2
int pos;
TrackPop(2);
pos = TrackPeek(1);
TrackPush2(TrackPeek()); // Save old mark
StackPush(pos); // Make new mark
Textto(pos); // Recall position
Goto(Operand(0)); // Loop
continue;
}
case RegexCode.Lazybranchmark | RegexCode.Back2:
// The lazy loop has failed. We'll do a true backtrack and
// start over before the lazy loop.
StackPop();
TrackPop();
StackPush(TrackPeek()); // Recall old mark
break;
case RegexCode.Setcount:
StackPush(Textpos(), Operand(0));
TrackPush();
Advance(1);
continue;
case RegexCode.Nullcount:
StackPush(-1, Operand(0));
TrackPush();
Advance(1);
continue;
case RegexCode.Setcount | RegexCode.Back:
StackPop(2);
break;
case RegexCode.Nullcount | RegexCode.Back:
StackPop(2);
break;
case RegexCode.Branchcount:
// StackPush:
// 0: Mark
// 1: Count
{
StackPop(2);
int mark = StackPeek();
int count = StackPeek(1);
int matched = Textpos() - mark;
if (count >= Operand(1) || (matched == 0 && count >= 0))
{ // Max loops or empty match -> straight now
TrackPush2(mark, count); // Save old mark, count
Advance(2); // Straight
}
else
{ // Nonempty match -> count+loop now
TrackPush(mark); // remember mark
StackPush(Textpos(), count + 1); // Make new mark, incr count
Goto(Operand(0)); // Loop
}
continue;
}
case RegexCode.Branchcount | RegexCode.Back:
// TrackPush:
// 0: Previous mark
// StackPush:
// 0: Mark (= current pos, discarded)
// 1: Count
TrackPop();
StackPop(2);
if (StackPeek(1) > 0)
{ // Positive -> can go straight
Textto(StackPeek()); // Zap to mark
TrackPush2(TrackPeek(), StackPeek(1) - 1); // Save old mark, old count
Advance(2); // Straight
continue;
}
StackPush(TrackPeek(), StackPeek(1) - 1); // recall old mark, old count
break;
case RegexCode.Branchcount | RegexCode.Back2:
// TrackPush:
// 0: Previous mark
// 1: Previous count
TrackPop(2);
StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, old count
break; // Backtrack
case RegexCode.Lazybranchcount:
// StackPush:
// 0: Mark
// 1: Count
{
StackPop(2);
int mark = StackPeek();
int count = StackPeek(1);
if (count < 0)
{ // Negative count -> loop now
TrackPush2(mark); // Save old mark
StackPush(Textpos(), count + 1); // Make new mark, incr count
Goto(Operand(0)); // Loop
}
else
{ // Nonneg count -> straight now
TrackPush(mark, count, Textpos()); // Save mark, count, position
Advance(2); // Straight
}
continue;
}
case RegexCode.Lazybranchcount | RegexCode.Back:
// TrackPush:
// 0: Mark
// 1: Count
// 2: Textpos
{
TrackPop(3);
int mark = TrackPeek();
int textpos = TrackPeek(2);
if (TrackPeek(1) < Operand(1) && textpos != mark)
{ // Under limit and not empty match -> loop
Textto(textpos); // Recall position
StackPush(textpos, TrackPeek(1) + 1); // Make new mark, incr count
TrackPush2(mark); // Save old mark
Goto(Operand(0)); // Loop
continue;
}
else
{ // Max loops or empty match -> backtrack
StackPush(TrackPeek(), TrackPeek(1)); // Recall old mark, count
break; // backtrack
}
}
case RegexCode.Lazybranchcount | RegexCode.Back2:
// TrackPush:
// 0: Previous mark
// StackPush:
// 0: Mark (== current pos, discarded)
// 1: Count
TrackPop();
StackPop(2);
StackPush(TrackPeek(), StackPeek(1) - 1); // Recall old mark, count
break; // Backtrack
case RegexCode.Setjump:
StackPush(Trackpos(), Crawlpos());
TrackPush();
Advance();
continue;
case RegexCode.Setjump | RegexCode.Back:
StackPop(2);
break;
case RegexCode.Backjump:
// StackPush:
// 0: Saved trackpos
// 1: Crawlpos
StackPop(2);
Trackto(StackPeek());
while (Crawlpos() != StackPeek(1))
Uncapture();
break;
case RegexCode.Forejump:
// StackPush:
// 0: Saved trackpos
// 1: Crawlpos
StackPop(2);
Trackto(StackPeek());
TrackPush(StackPeek(1));
Advance();
continue;
case RegexCode.Forejump | RegexCode.Back:
// TrackPush:
// 0: Crawlpos
TrackPop();
while (Crawlpos() != TrackPeek())
Uncapture();
break;
case RegexCode.Bol:
if (Leftchars() > 0 && CharAt(Textpos() - 1) != '\n')
break;
Advance();
continue;
case RegexCode.Eol:
if (Rightchars() > 0 && CharAt(Textpos()) != '\n')
break;
Advance();
continue;
case RegexCode.Boundary:
if (!IsBoundary(Textpos(), runtextbeg, runtextend))
break;
Advance();
continue;
case RegexCode.Nonboundary:
if (IsBoundary(Textpos(), runtextbeg, runtextend))
break;
Advance();
continue;
case RegexCode.ECMABoundary:
if (!IsECMABoundary(Textpos(), runtextbeg, runtextend))
break;
Advance();
continue;
case RegexCode.NonECMABoundary:
if (IsECMABoundary(Textpos(), runtextbeg, runtextend))
break;
Advance();
continue;
case RegexCode.Beginning:
if (Leftchars() > 0)
break;
Advance();
continue;
case RegexCode.Start:
if (Textpos() != Textstart())
break;
Advance();
continue;
case RegexCode.EndZ:
if (Rightchars() > 1 || Rightchars() == 1 && CharAt(Textpos()) != '\n')
break;
Advance();
continue;
case RegexCode.End:
if (Rightchars() > 0)
break;
Advance();
continue;
case RegexCode.One:
if (Forwardchars() < 1 || Forwardcharnext() != (char)Operand(0))
break;
Advance(1);
continue;
case RegexCode.Notone:
if (Forwardchars() < 1 || Forwardcharnext() == (char)Operand(0))
break;
Advance(1);
continue;
case RegexCode.Set:
if (Forwardchars() < 1 || !RegexCharClass.CharInClass(Forwardcharnext(), _code._strings[Operand(0)]))
break;
Advance(1);
continue;
case RegexCode.Multi:
{
if (!Stringmatch(_code._strings[Operand(0)]))
break;
Advance(1);
continue;
}
case RegexCode.Ref:
{
int capnum = Operand(0);
if (IsMatched(capnum))
{
if (!Refmatch(MatchIndex(capnum), MatchLength(capnum)))
break;
}
else
{
if ((runregex.roptions & RegexOptions.ECMAScript) == 0)
break;
}
Advance(1);
continue;
}
case RegexCode.Onerep:
{
int c = Operand(1);
if (Forwardchars() < c)
break;
char ch = (char)Operand(0);
while (c-- > 0)
if (Forwardcharnext() != ch)
goto BreakBackward;
Advance(2);
continue;
}
case RegexCode.Notonerep:
{
int c = Operand(1);
if (Forwardchars() < c)
break;
char ch = (char)Operand(0);
while (c-- > 0)
if (Forwardcharnext() == ch)
goto BreakBackward;
Advance(2);
continue;
}
case RegexCode.Setrep:
{
int c = Operand(1);
if (Forwardchars() < c)
break;
string set = _code._strings[Operand(0)];
while (c-- > 0)
if (!RegexCharClass.CharInClass(Forwardcharnext(), set))
goto BreakBackward;
Advance(2);
continue;
}
case RegexCode.Oneloop:
{
int c = Operand(1);
if (c > Forwardchars())
c = Forwardchars();
char ch = (char)Operand(0);
int i;
for (i = c; i > 0; i--)
{
if (Forwardcharnext() != ch)
{
Backwardnext();
break;
}
}
if (c > i)
TrackPush(c - i - 1, Textpos() - Bump());
Advance(2);
continue;
}
case RegexCode.Notoneloop:
{
int c = Operand(1);
if (c > Forwardchars())
c = Forwardchars();
char ch = (char)Operand(0);
int i;
for (i = c; i > 0; i--)
{
if (Forwardcharnext() == ch)
{
Backwardnext();
break;
}
}
if (c > i)
TrackPush(c - i - 1, Textpos() - Bump());
Advance(2);
continue;
}
case RegexCode.Setloop:
{
int c = Operand(1);
if (c > Forwardchars())
c = Forwardchars();
string set = _code._strings[Operand(0)];
int i;
for (i = c; i > 0; i--)
{
if (!RegexCharClass.CharInClass(Forwardcharnext(), set))
{
Backwardnext();
break;
}
}
if (c > i)
TrackPush(c - i - 1, Textpos() - Bump());
Advance(2);
continue;
}
case RegexCode.Oneloop | RegexCode.Back:
case RegexCode.Notoneloop | RegexCode.Back:
{
TrackPop(2);
int i = TrackPeek();
int pos = TrackPeek(1);
Textto(pos);
if (i > 0)
TrackPush(i - 1, pos - Bump());
Advance(2);
continue;
}
case RegexCode.Setloop | RegexCode.Back:
{
TrackPop(2);
int i = TrackPeek();
int pos = TrackPeek(1);
Textto(pos);
if (i > 0)
TrackPush(i - 1, pos - Bump());
Advance(2);
continue;
}
case RegexCode.Onelazy:
case RegexCode.Notonelazy:
{
int c = Operand(1);
if (c > Forwardchars())
c = Forwardchars();
if (c > 0)
TrackPush(c - 1, Textpos());
Advance(2);
continue;
}
case RegexCode.Setlazy:
{
int c = Operand(1);
if (c > Forwardchars())
c = Forwardchars();
if (c > 0)
TrackPush(c - 1, Textpos());
Advance(2);
continue;
}
case RegexCode.Onelazy | RegexCode.Back:
{
TrackPop(2);
int pos = TrackPeek(1);
Textto(pos);
if (Forwardcharnext() != (char)Operand(0))
break;
int i = TrackPeek();
if (i > 0)
TrackPush(i - 1, pos + Bump());
Advance(2);
continue;
}
case RegexCode.Notonelazy | RegexCode.Back:
{
TrackPop(2);
int pos = TrackPeek(1);
Textto(pos);
if (Forwardcharnext() == (char)Operand(0))
break;
int i = TrackPeek();
if (i > 0)
TrackPush(i - 1, pos + Bump());
Advance(2);
continue;
}
case RegexCode.Setlazy | RegexCode.Back:
{
TrackPop(2);
int pos = TrackPeek(1);
Textto(pos);
if (!RegexCharClass.CharInClass(Forwardcharnext(), _code._strings[Operand(0)]))
break;
int i = TrackPeek();
if (i > 0)
TrackPush(i - 1, pos + Bump());
Advance(2);
continue;
}
default:
throw new NotImplementedException("");
}
BreakBackward:
;
// "break Backward" comes here:
Backtrack();
}
}
#if DEBUG
internal override void DumpState()
{
base.DumpState();
Debug.WriteLine(" " + _code.OpcodeDescription(_codepos) +
((_operator & RegexCode.Back) != 0 ? " Back" : "") +
((_operator & RegexCode.Back2) != 0 ? " Back2" : ""));
Debug.WriteLine("");
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;
using System.DirectoryServices.Interop;
using System.ComponentModel;
using INTPTR_INTPTRCAST = System.IntPtr;
namespace System.DirectoryServices
{
/// <devdoc>
/// Performs queries against the Active Directory hierarchy.
/// </devdoc>
public class DirectorySearcher : Component
{
private DirectoryEntry _searchRoot;
private string _filter = defaultFilter;
private StringCollection _propertiesToLoad;
private bool _disposed = false;
private static readonly TimeSpan s_minusOneSecond = new TimeSpan(0, 0, -1);
// search preference variables
private SearchScope _scope = System.DirectoryServices.SearchScope.Subtree;
private bool _scopeSpecified = false;
private int _sizeLimit = 0;
private TimeSpan _serverTimeLimit = s_minusOneSecond;
private TimeSpan _clientTimeout = s_minusOneSecond;
private int _pageSize = 0;
private TimeSpan _serverPageTimeLimit = s_minusOneSecond;
private ReferralChasingOption _referralChasing = ReferralChasingOption.External;
private SortOption _sort = new SortOption();
private bool _cacheResults = true;
private bool _cacheResultsSpecified = false;
private bool _rootEntryAllocated = false; // true: if a temporary entry inside Searcher has been created
private string _assertDefaultNamingContext = null;
private string _attributeScopeQuery = "";
private bool _attributeScopeQuerySpecified = false;
private DereferenceAlias _derefAlias = DereferenceAlias.Never;
private SecurityMasks _securityMask = SecurityMasks.None;
private ExtendedDN _extendedDN = ExtendedDN.None;
private DirectorySynchronization _sync = null;
internal bool directorySynchronizationSpecified = false;
private DirectoryVirtualListView _vlv = null;
internal bool directoryVirtualListViewSpecified = false;
internal SearchResultCollection searchResult = null;
private const string defaultFilter = "(objectClass=*)";
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
/// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default values.
/// </devdoc>
public DirectorySearcher() : this(null, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
/// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to the given value.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot) : this(searchRoot, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
/// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter) : this(searchRoot, filter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to its default
/// value, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad) : this(searchRoot, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
/// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
/// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the given value.
/// </devdoc>
public DirectorySearcher(string filter) : this(null, filter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>
/// and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
/// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(string filter, string[] propertiesToLoad) : this(null, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to its default
/// value, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to the respective given values.</para>
/// </devdoc>
public DirectorySearcher(string filter, string[] propertiesToLoad, SearchScope scope) : this(null, filter, propertiesToLoad, scope)
{
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given
/// values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
{
_searchRoot = searchRoot;
_filter = filter;
if (propertiesToLoad != null)
PropertiesToLoad.AddRange(propertiesToLoad);
this.SearchScope = scope;
}
protected override void Dispose(bool disposing)
{
// safe to call while finalizing or disposing
//
if (!_disposed && disposing)
{
if (_rootEntryAllocated)
_searchRoot.Dispose();
_rootEntryAllocated = false;
_disposed = true;
}
base.Dispose(disposing);
}
/// <devdoc>
/// Gets or sets a value indicating whether the result should be cached on the
/// client machine.
/// </devdoc>
[DefaultValue(true)]
public bool CacheResults
{
get => _cacheResults;
set
{
// user explicitly set CacheResults to true and also want VLV
if (directoryVirtualListViewSpecified == true && value == true)
throw new ArgumentException(SR.DSBadCacheResultsVLV);
_cacheResults = value;
_cacheResultsSpecified = true;
}
}
/// <devdoc>
/// Gets or sets the maximum amount of time that the client waits for
/// the server to return results. If the server does not respond within this time,
/// the search is aborted, and no results are returned.</para>
/// </devdoc>
public TimeSpan ClientTimeout
{
get => _clientTimeout;
set
{
// prevent integer overflow
if (value.TotalSeconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
_clientTimeout = value;
}
}
/// <devdoc>
/// Gets or sets a value indicating whether the search should retrieve only the names of requested
/// properties or the names and values of requested properties.</para>
/// </devdoc>
[DefaultValue(false)]
public bool PropertyNamesOnly { get; set; }
/// <devdoc>
/// Gets or sets the Lightweight Directory Access Protocol (LDAP) filter string format.
/// </devdoc>
[
DefaultValue(defaultFilter),
// CoreFXPort - Remove design support
// TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string Filter
{
get => _filter;
set
{
if (value == null || value.Length == 0)
value = defaultFilter;
_filter = value;
}
}
/// <devdoc>
/// Gets or sets the page size in a paged search.
/// </devdoc>
[DefaultValue(0)]
public int PageSize
{
get => _pageSize;
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadPageSize);
// specify non-zero pagesize explicitly and also want dirsync
if (directorySynchronizationSpecified == true && value != 0)
throw new ArgumentException(SR.DSBadPageSizeDirsync);
_pageSize = value;
}
}
/// <devdoc>
/// Gets the set of properties retrieved during the search. By default, the <see cref='System.DirectoryServices.DirectoryEntry.Path'/>
/// and <see cref='System.DirectoryServices.DirectoryEntry.Name'/> properties are retrieved.
/// </devdoc>
public StringCollection PropertiesToLoad
{
get
{
if (_propertiesToLoad == null)
{
_propertiesToLoad = new StringCollection();
}
return _propertiesToLoad;
}
}
/// <devdoc>
/// Gets or sets how referrals are chased.
/// </devdoc>
[DefaultValue(ReferralChasingOption.External)]
public ReferralChasingOption ReferralChasing
{
get => _referralChasing;
set
{
if (value != ReferralChasingOption.None &&
value != ReferralChasingOption.Subordinate &&
value != ReferralChasingOption.External &&
value != ReferralChasingOption.All)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ReferralChasingOption));
_referralChasing = value;
}
}
/// <devdoc>
/// Gets or sets the scope of the search that should be observed by the server.
/// </devdoc>
[DefaultValue(SearchScope.Subtree)]
public SearchScope SearchScope
{
get => _scope;
set
{
if (value < SearchScope.Base || value > SearchScope.Subtree)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SearchScope));
// user explicitly set SearchScope to something other than Base and also want to do ASQ, it is not supported
if (_attributeScopeQuerySpecified == true && value != SearchScope.Base)
{
throw new ArgumentException(SR.DSBadASQSearchScope);
}
_scope = value;
_scopeSpecified = true;
}
}
/// <devdoc>
/// Gets or sets the time limit that the server should observe to search a page of results (as
/// opposed to the time limit for the entire search).
/// </devdoc>
public TimeSpan ServerPageTimeLimit
{
get => _serverPageTimeLimit;
set
{
// prevent integer overflow
if (value.TotalSeconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
_serverPageTimeLimit = value;
}
}
/// <devdoc>
/// Gets or sets the maximum amount of time the server spends searching. If the
/// time limit is reached, only entries found up to that point will be returned.
/// </devdoc>
public TimeSpan ServerTimeLimit
{
get => _serverTimeLimit;
set
{
// prevent integer overflow
if (value.TotalSeconds > int.MaxValue)
{
throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
_serverTimeLimit = value;
}
}
/// <devdoc>
/// Gets or sets the maximum number of objects that the
/// server should return in a search.
/// </devdoc>
[DefaultValue(0)]
public int SizeLimit
{
get => _sizeLimit;
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadSizeLimit);
_sizeLimit = value;
}
}
/// <devdoc>
/// Gets or sets the node in the Active Directory hierarchy
/// at which the search will start.
/// </devdoc>
[DefaultValue(null)]
public DirectoryEntry SearchRoot
{
get
{
if (_searchRoot == null && !DesignMode)
{
// get the default naming context. This should be the default root for the search.
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure);
//SECREVIEW: Searching the root of the DS will demand browse permissions
// on "*" or "LDAP://RootDSE".
string defaultNamingContext = (string)rootDSE.Properties["defaultNamingContext"][0];
rootDSE.Dispose();
_searchRoot = new DirectoryEntry("LDAP://" + defaultNamingContext, true, null, null, AuthenticationTypes.Secure);
_rootEntryAllocated = true;
_assertDefaultNamingContext = "LDAP://" + defaultNamingContext;
}
return _searchRoot;
}
set
{
if (_rootEntryAllocated)
_searchRoot.Dispose();
_rootEntryAllocated = false;
_assertDefaultNamingContext = null;
_searchRoot = value;
}
}
/// <devdoc>
/// Gets the property on which the results should be sorted.
/// </devdoc>
[TypeConverter(typeof(ExpandableObjectConverter))]
public SortOption Sort
{
get => _sort;
set => _sort = value ?? throw new ArgumentNullException(nameof(value));
}
/// <devdoc>
/// Gets or sets a value indicating whether searches should be carried out in an asynchronous
/// way.
/// </devdoc>
[DefaultValue(false)]
public bool Asynchronous { get; set; }
/// <devdoc>
/// Gets or sets a value indicating whether the search should also return deleted objects that match the search
/// filter.
/// </devdoc>
[DefaultValue(false)]
public bool Tombstone { get; set; }
/// <devdoc>
/// Gets or sets an attribute name to indicate that an attribute-scoped query search should be
/// performed.
/// </devdoc>
[
DefaultValue(""),
// CoreFXPort - Remove design support
// TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string AttributeScopeQuery
{
get => _attributeScopeQuery;
set
{
if (value == null)
value = "";
// user explicitly set AttributeScopeQuery and value is not null or empty string
if (value.Length != 0)
{
if (_scopeSpecified == true && SearchScope != SearchScope.Base)
{
throw new ArgumentException(SR.DSBadASQSearchScope);
}
// if user did not explicitly set search scope
_scope = SearchScope.Base;
_attributeScopeQuerySpecified = true;
}
else
// user explicitly sets the value to default one and doesn't want to do asq
{
_attributeScopeQuerySpecified = false;
}
_attributeScopeQuery = value;
}
}
/// <devdoc>
/// Gets or sets a value to indicate how the aliases of found objects are to be
/// resolved.
/// </devdoc>
[DefaultValue(DereferenceAlias.Never)]
public DereferenceAlias DerefAlias
{
get => _derefAlias;
set
{
if (value < DereferenceAlias.Never || value > DereferenceAlias.Always)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DereferenceAlias));
_derefAlias = value;
}
}
/// <devdoc>
/// Gets or sets a value to indicate the search should return security access information for the specified
/// attributes.
/// </devdoc>
[DefaultValue(SecurityMasks.None)]
public SecurityMasks SecurityMasks
{
get => _securityMask;
set
{
// make sure the behavior is consistent with native ADSI
if (value > (SecurityMasks.None | SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl))
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SecurityMasks));
_securityMask = value;
}
}
/// <devdoc>
/// Gets or sets a value to return extended DNs according to the requested
/// format.
/// </devdoc>
[DefaultValue(ExtendedDN.None)]
public ExtendedDN ExtendedDN
{
get => _extendedDN;
set
{
if (value < ExtendedDN.None || value > ExtendedDN.Standard)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ExtendedDN));
_extendedDN = value;
}
}
/// <devdoc>
/// Gets or sets a value to indicate a directory synchronization search, which returns all changes since a specified
/// state.
/// </devdoc>
[DefaultValue(null)]
public DirectorySynchronization DirectorySynchronization
{
get
{
// if user specifies dirsync search preference and search is executed
if (directorySynchronizationSpecified && searchResult != null)
{
_sync.ResetDirectorySynchronizationCookie(searchResult.DirsyncCookie);
}
return _sync;
}
set
{
// specify non-zero pagesize explicitly and also want dirsync
if (value != null)
{
if (PageSize != 0)
throw new ArgumentException(SR.DSBadPageSizeDirsync);
directorySynchronizationSpecified = true;
}
else
// user explicitly sets the value to default one and doesn't want to do dirsync
{
directorySynchronizationSpecified = false;
}
_sync = value;
}
}
/// <devdoc>
/// Gets or sets a value to indicate the search should use the LDAP virtual list view (VLV)
/// control.
/// </devdoc>
[DefaultValue(null)]
public DirectoryVirtualListView VirtualListView
{
get
{
// if user specifies dirsync search preference and search is executed
if (directoryVirtualListViewSpecified && searchResult != null)
{
DirectoryVirtualListView tempval = searchResult.VLVResponse;
_vlv.Offset = tempval.Offset;
_vlv.ApproximateTotal = tempval.ApproximateTotal;
_vlv.DirectoryVirtualListViewContext = tempval.DirectoryVirtualListViewContext;
if (_vlv.ApproximateTotal != 0)
_vlv.TargetPercentage = (int)((double)_vlv.Offset / _vlv.ApproximateTotal * 100);
else
_vlv.TargetPercentage = 0;
}
return _vlv;
}
set
{
// if user explicitly set CacheResults to true and also want to set VLV
if (value != null)
{
if (_cacheResultsSpecified == true && CacheResults == true)
throw new ArgumentException(SR.DSBadCacheResultsVLV);
directoryVirtualListViewSpecified = true;
// if user does not explicit specify cache results to true and also do vlv, then cache results is default to false
_cacheResults = false;
}
else
// user explicitly sets the value to default one and doesn't want to do vlv
{
directoryVirtualListViewSpecified = false;
}
_vlv = value;
}
}
/// <devdoc>
/// Executes the search and returns only the first entry that is found.
/// </devdoc>
public SearchResult FindOne()
{
DirectorySynchronization tempsync = null;
DirectoryVirtualListView tempvlv = null;
SearchResult resultEntry = null;
SearchResultCollection results = FindAll(false);
try
{
foreach (SearchResult entry in results)
{
// need to get the dirsync cookie
if (directorySynchronizationSpecified)
tempsync = DirectorySynchronization;
// need to get the vlv response
if (directoryVirtualListViewSpecified)
tempvlv = VirtualListView;
resultEntry = entry;
break;
}
}
finally
{
searchResult = null;
// still need to properly release the resource
results.Dispose();
}
return resultEntry;
}
/// <devdoc>
/// Executes the search and returns a collection of the entries that are found.
/// </devdoc>
public SearchResultCollection FindAll() => FindAll(true);
private SearchResultCollection FindAll(bool findMoreThanOne)
{
searchResult = null;
DirectoryEntry clonedRoot = null;
if (_assertDefaultNamingContext == null)
{
clonedRoot = SearchRoot.CloneBrowsable();
}
else
{
clonedRoot = SearchRoot.CloneBrowsable();
}
UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject;
if (!(adsObject is UnsafeNativeMethods.IDirectorySearch))
throw new NotSupportedException(SR.Format(SR.DSSearchUnsupported , SearchRoot.Path));
// this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than
// one reference count, one by SearchResultCollection object, one by DirectorySearcher object. In this way, when user calls
// Dispose on SearchResultCollection, the connection is still there instead of reference count dropping to zero and being closed.
// It is especially important for virtuallistview case, in order to reuse the vlv response, the search must be performed on the same ldap connection
// only do it when vlv is used
if (directoryVirtualListViewSpecified)
{
SearchRoot.Bind(true);
}
UnsafeNativeMethods.IDirectorySearch adsSearch = (UnsafeNativeMethods.IDirectorySearch)adsObject;
SetSearchPreferences(adsSearch, findMoreThanOne);
string[] properties = null;
if (PropertiesToLoad.Count > 0)
{
if (!PropertiesToLoad.Contains("ADsPath"))
{
// if we don't get this property, we won't be able to return a list of DirectoryEntry objects!
PropertiesToLoad.Add("ADsPath");
}
properties = new string[PropertiesToLoad.Count];
PropertiesToLoad.CopyTo(properties, 0);
}
IntPtr resultsHandle;
if (properties != null)
adsSearch.ExecuteSearch(Filter, properties, properties.Length, out resultsHandle);
else
{
adsSearch.ExecuteSearch(Filter, null, -1, out resultsHandle);
properties = Array.Empty<string>();
}
SearchResultCollection result = new SearchResultCollection(clonedRoot, resultsHandle, properties, this);
searchResult = result;
return result;
}
private unsafe void SetSearchPreferences(UnsafeNativeMethods.IDirectorySearch adsSearch, bool findMoreThanOne)
{
ArrayList prefList = new ArrayList();
AdsSearchPreferenceInfo info;
// search scope
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.SEARCH_SCOPE;
info.vValue = new AdsValueHelper((int)SearchScope).GetStruct();
prefList.Add(info);
// size limit
if (_sizeLimit != 0 || !findMoreThanOne)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.SIZE_LIMIT;
info.vValue = new AdsValueHelper(findMoreThanOne ? SizeLimit : 1).GetStruct();
prefList.Add(info);
}
// time limit
if (ServerTimeLimit >= new TimeSpan(0))
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.TIME_LIMIT;
info.vValue = new AdsValueHelper((int)ServerTimeLimit.TotalSeconds).GetStruct();
prefList.Add(info);
}
// propertyNamesOnly
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBTYPES_ONLY;
info.vValue = new AdsValueHelper(PropertyNamesOnly).GetStruct();
prefList.Add(info);
// Timeout
if (ClientTimeout >= new TimeSpan(0))
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.TIMEOUT;
info.vValue = new AdsValueHelper((int)ClientTimeout.TotalSeconds).GetStruct();
prefList.Add(info);
}
// page size
if (PageSize != 0)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.PAGESIZE;
info.vValue = new AdsValueHelper(PageSize).GetStruct();
prefList.Add(info);
}
// page time limit
if (ServerPageTimeLimit >= new TimeSpan(0))
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.PAGED_TIME_LIMIT;
info.vValue = new AdsValueHelper((int)ServerPageTimeLimit.TotalSeconds).GetStruct();
prefList.Add(info);
}
// chase referrals
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.CHASE_REFERRALS;
info.vValue = new AdsValueHelper((int)ReferralChasing).GetStruct();
prefList.Add(info);
// asynchronous
if (Asynchronous == true)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.ASYNCHRONOUS;
info.vValue = new AdsValueHelper(Asynchronous).GetStruct();
prefList.Add(info);
}
// tombstone
if (Tombstone == true)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.TOMBSTONE;
info.vValue = new AdsValueHelper(Tombstone).GetStruct();
prefList.Add(info);
}
// attributescopequery
if (_attributeScopeQuerySpecified)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.ATTRIBUTE_QUERY;
info.vValue = new AdsValueHelper(AttributeScopeQuery, AdsType.ADSTYPE_CASE_IGNORE_STRING).GetStruct();
prefList.Add(info);
}
// derefalias
if (DerefAlias != DereferenceAlias.Never)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.DEREF_ALIASES;
info.vValue = new AdsValueHelper((int)DerefAlias).GetStruct();
prefList.Add(info);
}
// securitymask
if (SecurityMasks != SecurityMasks.None)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.SECURITY_MASK;
info.vValue = new AdsValueHelper((int)SecurityMasks).GetStruct();
prefList.Add(info);
}
// extendeddn
if (ExtendedDN != ExtendedDN.None)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.EXTENDED_DN;
info.vValue = new AdsValueHelper((int)ExtendedDN).GetStruct();
prefList.Add(info);
}
// dirsync
if (directorySynchronizationSpecified)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC;
info.vValue = new AdsValueHelper(DirectorySynchronization.GetDirectorySynchronizationCookie(), AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct();
prefList.Add(info);
if (DirectorySynchronization.Option != DirectorySynchronizationOptions.None)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.DIRSYNC_FLAG;
info.vValue = new AdsValueHelper((int)DirectorySynchronization.Option).GetStruct();
prefList.Add(info);
}
}
IntPtr ptrToFree = (IntPtr)0;
IntPtr ptrVLVToFree = (IntPtr)0;
IntPtr ptrVLVContexToFree = (IntPtr)0;
try
{
// sort
if (Sort.PropertyName != null && Sort.PropertyName.Length > 0)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.SORT_ON;
AdsSortKey sortKey = new AdsSortKey();
sortKey.pszAttrType = Marshal.StringToCoTaskMemUni(Sort.PropertyName);
ptrToFree = sortKey.pszAttrType; // so we can free it later.
sortKey.pszReserved = (IntPtr)0;
sortKey.fReverseOrder = (Sort.Direction == SortDirection.Descending) ? -1 : 0;
byte[] sortKeyBytes = new byte[Marshal.SizeOf(sortKey)];
Marshal.Copy((INTPTR_INTPTRCAST)(&sortKey), sortKeyBytes, 0, sortKeyBytes.Length);
info.vValue = new AdsValueHelper(sortKeyBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct();
prefList.Add(info);
}
// vlv
if (directoryVirtualListViewSpecified)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.VLV;
AdsVLV vlvValue = new AdsVLV();
vlvValue.beforeCount = _vlv.BeforeCount;
vlvValue.afterCount = _vlv.AfterCount;
vlvValue.offset = _vlv.Offset;
//we need to treat the empty string as null here
if (_vlv.Target.Length != 0)
vlvValue.target = Marshal.StringToCoTaskMemUni(_vlv.Target);
else
vlvValue.target = IntPtr.Zero;
ptrVLVToFree = vlvValue.target;
if (_vlv.DirectoryVirtualListViewContext == null)
{
vlvValue.contextIDlength = 0;
vlvValue.contextID = (IntPtr)0;
}
else
{
vlvValue.contextIDlength = _vlv.DirectoryVirtualListViewContext._context.Length;
vlvValue.contextID = Marshal.AllocCoTaskMem(vlvValue.contextIDlength);
ptrVLVContexToFree = vlvValue.contextID;
Marshal.Copy(_vlv.DirectoryVirtualListViewContext._context, 0, vlvValue.contextID, vlvValue.contextIDlength);
}
IntPtr vlvPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(AdsVLV)));
byte[] vlvBytes = new byte[Marshal.SizeOf(vlvValue)];
try
{
Marshal.StructureToPtr(vlvValue, vlvPtr, false);
Marshal.Copy(vlvPtr, vlvBytes, 0, vlvBytes.Length);
}
finally
{
Marshal.FreeHGlobal(vlvPtr);
}
info.vValue = new AdsValueHelper(vlvBytes, AdsType.ADSTYPE_PROV_SPECIFIC).GetStruct();
prefList.Add(info);
}
// cacheResults
if (_cacheResultsSpecified)
{
info = new AdsSearchPreferenceInfo();
info.dwSearchPref = (int)AdsSearchPreferences.CACHE_RESULTS;
info.vValue = new AdsValueHelper(CacheResults).GetStruct();
prefList.Add(info);
}
//
// now make the call
//
AdsSearchPreferenceInfo[] prefs = new AdsSearchPreferenceInfo[prefList.Count];
for (int i = 0; i < prefList.Count; i++)
{
prefs[i] = (AdsSearchPreferenceInfo)prefList[i];
}
DoSetSearchPrefs(adsSearch, prefs);
}
finally
{
if (ptrToFree != (IntPtr)0)
Marshal.FreeCoTaskMem(ptrToFree);
if (ptrVLVToFree != (IntPtr)0)
Marshal.FreeCoTaskMem(ptrVLVToFree);
if (ptrVLVContexToFree != (IntPtr)0)
Marshal.FreeCoTaskMem(ptrVLVContexToFree);
}
}
private static void DoSetSearchPrefs(UnsafeNativeMethods.IDirectorySearch adsSearch, AdsSearchPreferenceInfo[] prefs)
{
int structSize = Marshal.SizeOf(typeof(AdsSearchPreferenceInfo));
IntPtr ptr = Marshal.AllocHGlobal((IntPtr)(structSize * prefs.Length));
try
{
IntPtr tempPtr = ptr;
for (int i = 0; i < prefs.Length; i++)
{
Marshal.StructureToPtr(prefs[i], tempPtr, false);
tempPtr = IntPtr.Add(tempPtr, structSize);
}
adsSearch.SetSearchPreference(ptr, prefs.Length);
// Check for the result status for all preferences
tempPtr = ptr;
for (int i = 0; i < prefs.Length; i++)
{
int status = Marshal.ReadInt32(tempPtr, 32);
if (status != 0)
{
int prefIndex = prefs[i].dwSearchPref;
string property = "";
switch (prefIndex)
{
case (int)AdsSearchPreferences.SEARCH_SCOPE:
property = "SearchScope";
break;
case (int)AdsSearchPreferences.SIZE_LIMIT:
property = "SizeLimit";
break;
case (int)AdsSearchPreferences.TIME_LIMIT:
property = "ServerTimeLimit";
break;
case (int)AdsSearchPreferences.ATTRIBTYPES_ONLY:
property = "PropertyNamesOnly";
break;
case (int)AdsSearchPreferences.TIMEOUT:
property = "ClientTimeout";
break;
case (int)AdsSearchPreferences.PAGESIZE:
property = "PageSize";
break;
case (int)AdsSearchPreferences.PAGED_TIME_LIMIT:
property = "ServerPageTimeLimit";
break;
case (int)AdsSearchPreferences.CHASE_REFERRALS:
property = "ReferralChasing";
break;
case (int)AdsSearchPreferences.SORT_ON:
property = "Sort";
break;
case (int)AdsSearchPreferences.CACHE_RESULTS:
property = "CacheResults";
break;
case (int)AdsSearchPreferences.ASYNCHRONOUS:
property = "Asynchronous";
break;
case (int)AdsSearchPreferences.TOMBSTONE:
property = "Tombstone";
break;
case (int)AdsSearchPreferences.ATTRIBUTE_QUERY:
property = "AttributeScopeQuery";
break;
case (int)AdsSearchPreferences.DEREF_ALIASES:
property = "DerefAlias";
break;
case (int)AdsSearchPreferences.SECURITY_MASK:
property = "SecurityMasks";
break;
case (int)AdsSearchPreferences.EXTENDED_DN:
property = "ExtendedDn";
break;
case (int)AdsSearchPreferences.DIRSYNC:
property = "DirectorySynchronization";
break;
case (int)AdsSearchPreferences.DIRSYNC_FLAG:
property = "DirectorySynchronizationFlag";
break;
case (int)AdsSearchPreferences.VLV:
property = "VirtualListView";
break;
}
throw new InvalidOperationException(SR.Format(SR.DSSearchPreferencesNotAccepted , property));
}
tempPtr = IntPtr.Add(tempPtr, structSize);
}
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.UserModel
{
using System;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Collections.Generic;
using System.Text;
using System.Xml;
/**
* Represents a Cell within a {@link XWPFTable}. The
* Cell is the thing that holds the actual content (paragraphs etc)
*/
public class XWPFTableCell : IBody, ICell
{
private CT_Tc ctTc;
protected List<XWPFParagraph> paragraphs = null;
protected List<XWPFTable> tables = null;
protected List<IBodyElement> bodyElements = null;
protected IBody part;
private XWPFTableRow tableRow = null;
// Create a map from this XWPF-level enum to the STVerticalJc.Enum values
public enum XWPFVertAlign { TOP, CENTER, BOTH, BOTTOM };
private static Dictionary<XWPFVertAlign, ST_VerticalJc> alignMap;
// Create a map from the STVerticalJc.Enum values to the XWPF-level enums
private static Dictionary<ST_VerticalJc, XWPFVertAlign> stVertAlignTypeMap;
static XWPFTableCell()
{
// populate enum maps
alignMap = new Dictionary<XWPFVertAlign, ST_VerticalJc>();
alignMap.Add(XWPFVertAlign.TOP, ST_VerticalJc.top);
alignMap.Add(XWPFVertAlign.CENTER, ST_VerticalJc.center);
alignMap.Add(XWPFVertAlign.BOTH, ST_VerticalJc.both);
alignMap.Add(XWPFVertAlign.BOTTOM, ST_VerticalJc.bottom);
stVertAlignTypeMap = new Dictionary<ST_VerticalJc, XWPFVertAlign>();
stVertAlignTypeMap.Add(ST_VerticalJc.top, XWPFVertAlign.TOP);
stVertAlignTypeMap.Add(ST_VerticalJc.center, XWPFVertAlign.CENTER);
stVertAlignTypeMap.Add(ST_VerticalJc.both, XWPFVertAlign.BOTH);
stVertAlignTypeMap.Add(ST_VerticalJc.bottom, XWPFVertAlign.BOTTOM);
}
/**
* If a table cell does not include at least one block-level element, then this document shall be considered corrupt
*/
public XWPFTableCell(CT_Tc cell, XWPFTableRow tableRow, IBody part)
{
this.ctTc = cell;
this.part = part;
this.tableRow = tableRow;
// NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt.
if(cell.GetPList().Count<1)
cell.AddNewP();
bodyElements = new List<IBodyElement>();
paragraphs = new List<XWPFParagraph>();
tables = new List<XWPFTable>();
foreach (object o in ctTc.Items)
{
if (o is CT_P)
{
XWPFParagraph p = new XWPFParagraph((CT_P)o, this);
paragraphs.Add(p);
bodyElements.Add(p);
}
if (o is CT_Tbl)
{
XWPFTable t = new XWPFTable((CT_Tbl)o, this);
tables.Add(t);
bodyElements.Add(t);
}
if (o is CT_SdtBlock)
{
XWPFSDT c = new XWPFSDT((CT_SdtBlock)o, this);
bodyElements.Add(c);
}
if (o is CT_SdtRun)
{
XWPFSDT c = new XWPFSDT((CT_SdtRun)o, this);
bodyElements.Add(c);
}
}
}
public CT_Tc GetCTTc()
{
return ctTc;
}
/**
* returns an Iterator with paragraphs and tables
* @see NPOI.XWPF.UserModel.IBody#getBodyElements()
*/
public IList<IBodyElement> BodyElements
{
get
{
return bodyElements.AsReadOnly();
}
}
public void SetParagraph(XWPFParagraph p)
{
if (ctTc.SizeOfPArray() == 0) {
ctTc.AddNewP();
}
ctTc.SetPArray(0, p.GetCTP());
}
/**
* returns a list of paragraphs
*/
public IList<XWPFParagraph> Paragraphs
{
get
{
return paragraphs;
}
}
/**
* Add a Paragraph to this Table Cell
* @return The paragraph which was Added
*/
public XWPFParagraph AddParagraph()
{
XWPFParagraph p = new XWPFParagraph(ctTc.AddNewP(), this);
AddParagraph(p);
return p;
}
/**
* add a Paragraph to this TableCell
* @param p the paragaph which has to be Added
*/
public void AddParagraph(XWPFParagraph p)
{
paragraphs.Add(p);
}
/**
* Removes a paragraph of this tablecell
* @param pos
*/
public void RemoveParagraph(int pos)
{
paragraphs.RemoveAt(pos);
ctTc.RemoveP(pos);
}
/**
* if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table
* the method will return this paragraph
* if there is no corresponding {@link XWPFParagraph} the method will return null
* @param p is instance of CTP and is searching for an XWPFParagraph
* @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table
* XWPFParagraph with the correspondig CTP p
*/
public XWPFParagraph GetParagraph(CT_P p)
{
foreach (XWPFParagraph paragraph in paragraphs) {
if(p.Equals(paragraph.GetCTP())){
return paragraph;
}
}
return null;
}
/// <summary>
/// Add bottom border to cell
/// </summary>
/// <param name="type">Border Style</param>
/// <param name="size">Border Width</param>
/// <param name="space">Border Spacing Measurement</param>
/// <param name="rgbColor">Border Color</param>
public void SetBorderBottom(XWPFTable.XWPFBorderType type, int size, int space, String rgbColor)
{
CT_TcPr ctTcPr = GetCTTc().IsSetTcPr() ? GetCTTc().tcPr : GetCTTc().AddNewTcPr();
CT_TcBorders borders = ctTcPr.tcBorders == null ? ctTcPr.AddNewTcBorders() : ctTcPr.tcBorders;
borders.bottom = CreateBorder(type, size, space, rgbColor);
}
/// <summary>
/// Add top border to cell
/// </summary>
/// <param name="type">Border Style</param>
/// <param name="size">Border Width</param>
/// <param name="space">Border Spacing Measurement</param>
/// <param name="rgbColor">Border Color</param>
public void SetBorderTop(XWPFTable.XWPFBorderType type, int size, int space, String rgbColor)
{
CT_TcPr ctTcPr = GetCTTc().IsSetTcPr() ? GetCTTc().tcPr : GetCTTc().AddNewTcPr();
CT_TcBorders borders = ctTcPr.tcBorders == null ? ctTcPr.AddNewTcBorders() : ctTcPr.tcBorders;
borders.top = CreateBorder(type, size, space, rgbColor);
}
/// <summary>
/// Add left border to cell
/// </summary>
/// <param name="type">Border Style</param>
/// <param name="size">Border Width</param>
/// <param name="space">Border Spacing Measurement</param>
/// <param name="rgbColor">Border Color</param>
public void SetBorderLeft(XWPFTable.XWPFBorderType type, int size, int space, String rgbColor)
{
CT_TcPr ctTcPr = GetCTTc().IsSetTcPr() ? GetCTTc().tcPr : GetCTTc().AddNewTcPr();
CT_TcBorders borders = ctTcPr.tcBorders == null ? ctTcPr.AddNewTcBorders() : ctTcPr.tcBorders;
borders.left = CreateBorder(type, size, space, rgbColor);
}
/// <summary>
/// Add right border to cell
/// </summary>
/// <param name="type">Border Style</param>
/// <param name="size">Border Width</param>
/// <param name="space"></param>
/// <param name="rgbColor">Border Color</param>
public void SetBorderRight(XWPFTable.XWPFBorderType type, int size, int space, String rgbColor)
{
CT_TcPr ctTcPr = GetCTTc().IsSetTcPr() ? GetCTTc().tcPr : GetCTTc().AddNewTcPr();
CT_TcBorders borders = ctTcPr.tcBorders == null ? ctTcPr.AddNewTcBorders() : ctTcPr.tcBorders;
borders.right = CreateBorder(type, size, space, rgbColor);
}
/// <summary>
/// Creates border with parameters
/// </summary>
/// <param name="type">Border Style</param>
/// <param name="size">Border Width</param>
/// <param name="space">Border Spacing Measurement</param>
/// <param name="rgbColor">Border Color</param>
/// <returns>CT_Border object</returns>
private static CT_Border CreateBorder(XWPFTable.XWPFBorderType type, int size, int space, string rgbColor)
{
CT_Border border = new CT_Border();
border.val = XWPFTable.xwpfBorderTypeMap[type];
border.sz = (ulong)size;
border.space = (ulong)space;
border.color = (rgbColor);
return border;
}
public void SetText(String text)
{
CT_P ctP = (ctTc.SizeOfPArray() == 0) ? ctTc.AddNewP() : ctTc.GetPArray(0);
XWPFParagraph par = new XWPFParagraph(ctP, this);
par.CreateRun().AppendText(text);
}
public XWPFTableRow GetTableRow()
{
return tableRow;
}
/**
* Set cell color. This sets some associated values; for finer control
* you may want to access these elements individually.
* @param rgbStr - the desired cell color, in the hex form "RRGGBB".
*/
public void SetColor(String rgbStr)
{
CT_TcPr tcpr = ctTc.IsSetTcPr() ? ctTc.tcPr : ctTc.AddNewTcPr();
CT_Shd ctshd = tcpr.IsSetShd() ? tcpr.shd : tcpr.AddNewShd();
ctshd.color = ("auto");
ctshd.val = (ST_Shd.clear);
ctshd.fill = (rgbStr);
}
/**
* Get cell color. Note that this method only returns the "fill" value.
* @return RGB string of cell color
*/
public String GetColor()
{
String color = null;
CT_TcPr tcpr = ctTc.tcPr;
if (tcpr != null)
{
CT_Shd ctshd = tcpr.shd;
if (ctshd != null)
{
color = ctshd.fill;
}
}
return color;
}
/**
* Set the vertical alignment of the cell.
* @param vAlign - the desired alignment enum value
*/
public void SetVerticalAlignment(XWPFVertAlign vAlign)
{
CT_TcPr tcpr = ctTc.IsSetTcPr() ? ctTc.tcPr : ctTc.AddNewTcPr();
CT_VerticalJc va = tcpr.AddNewVAlign();
va.val = (alignMap[(vAlign)]);
}
/**
* Get the vertical alignment of the cell.
* @return the cell alignment enum value or null if no vertical alignment is set
*/
public XWPFVertAlign? GetVerticalAlignment()
{
XWPFVertAlign? vAlign = null;
CT_TcPr tcpr = ctTc.tcPr;
if (tcpr != null)
{
CT_VerticalJc va = tcpr.vAlign;
if (va != null)
{
vAlign = stVertAlignTypeMap[va.val.Value];
}
else
{
vAlign = XWPFVertAlign.TOP;
}
if (va != null && va.val != null)
{
vAlign = stVertAlignTypeMap[va.val.Value];
}
}
return vAlign;
}
/**
* add a new paragraph at position of the cursor
* @param cursor
* @return the inserted paragraph
*/
public XWPFParagraph InsertNewParagraph(/*XmlCursor*/ XmlDocument cursor)
{
/*if(!isCursorInTableCell(cursor))
return null;
String uri = CTP.type.Name.NamespaceURI;
String localPart = "p";
cursor.BeginElement(localPart,uri);
cursor.ToParent();
CTP p = (CTP)cursor.Object;
XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null;
while(!(o is CTP)&&(cursor.ToPrevSibling())){
o = cursor.Object;
}
if((!(o is CTP)) || (CTP)o == p){
paragraphs.Add(0, newP);
}
else{
int pos = paragraphs.IndexOf(getParagraph((CTP)o))+1;
paragraphs.Add(pos,newP);
}
int i=0;
cursor.ToCursor(p.NewCursor());
while(cursor.ToPrevSibling()){
o =cursor.Object;
if(o is CTP || o is CTTbl)
i++;
}
bodyElements.Add(i, newP);
cursor.ToCursor(p.NewCursor());
cursor.ToEndToken();
return newP;*/
throw new NotImplementedException();
}
public XWPFTable InsertNewTbl(/*XmlCursor*/ XmlDocument cursor)
{
/*if(isCursorInTableCell(cursor)){
String uri = CTTbl.type.Name.NamespaceURI;
String localPart = "tbl";
cursor.BeginElement(localPart,uri);
cursor.ToParent();
CTTbl t = (CTTbl)cursor.Object;
XWPFTable newT = new XWPFTable(t, this);
cursor.RemoveXmlContents();
XmlObject o = null;
while(!(o is CTTbl)&&(cursor.ToPrevSibling())){
o = cursor.Object;
}
if(!(o is CTTbl)){
tables.Add(0, newT);
}
else{
int pos = tables.IndexOf(getTable((CTTbl)o))+1;
tables.Add(pos,newT);
}
int i=0;
cursor = t.NewCursor();
while(cursor.ToPrevSibling()){
o =cursor.Object;
if(o is CTP || o is CTTbl)
i++;
}
bodyElements.Add(i, newT);
cursor = t.NewCursor();
cursor.ToEndToken();
return newT;
}
return null;*/
throw new NotImplementedException();
}
/**
* verifies that cursor is on the right position
*/
private bool IsCursorInTableCell(/*XmlCursor*/XmlDocument cursor)
{
/*XmlCursor verify = cursor.NewCursor();
verify.ToParent();
if(verify.Object == this.ctTc){
return true;
}
return false;*/
throw new NotImplementedException();
}
/**
* @see NPOI.XWPF.UserModel.IBody#getParagraphArray(int)
*/
public XWPFParagraph GetParagraphArray(int pos)
{
if (pos >= 0 && pos < paragraphs.Count)
{
return paragraphs[(pos)];
}
return null;
}
/**
* Get the to which the TableCell belongs
*
* @see NPOI.XWPF.UserModel.IBody#getPart()
*/
public POIXMLDocumentPart Part
{
get
{
return tableRow.GetTable().Part;
}
}
/**
* @see NPOI.XWPF.UserModel.IBody#getPartType()
*/
public BodyType PartType
{
get
{
return BodyType.TABLECELL;
}
}
/**
* Get a table by its CTTbl-Object
* @see NPOI.XWPF.UserModel.IBody#getTable(org.Openxmlformats.schemas.wordProcessingml.x2006.main.CTTbl)
*/
public XWPFTable GetTable(CT_Tbl ctTable)
{
for(int i=0; i<tables.Count; i++){
if(this.Tables[(i)].GetCTTbl() == ctTable) return Tables[(i)];
}
return null;
}
/**
* @see NPOI.XWPF.UserModel.IBody#getTableArray(int)
*/
public XWPFTable GetTableArray(int pos)
{
if (pos >=0 && pos < tables.Count)
{
return tables[pos];
}
return null;
}
/**
* @see NPOI.XWPF.UserModel.IBody#getTables()
*/
public IList<XWPFTable> Tables
{
get
{
return tables.AsReadOnly();
}
}
/**
* inserts an existing XWPFTable to the arrays bodyElements and tables
* @see NPOI.XWPF.UserModel.IBody#insertTable(int, NPOI.XWPF.UserModel.XWPFTable)
*/
public void InsertTable(int pos, XWPFTable table)
{
bodyElements.Insert(pos, table);
int i;
for (i = 0; i < ctTc.GetTblList().Count; i++) {
CT_Tbl tbl = ctTc.GetTblArray(i);
if(tbl == table.GetCTTbl()){
break;
}
}
tables.Insert(i, table);
}
public String GetText()
{
StringBuilder text = new StringBuilder();
foreach (XWPFParagraph p in paragraphs)
{
text.Append(p.Text);
}
return text.ToString();
}
/**
* extracts all text recursively through embedded tables and embedded SDTs
*/
public String GetTextRecursively()
{
StringBuilder text = new StringBuilder();
for (int i = 0; i < bodyElements.Count; i++)
{
bool isLast = (i == bodyElements.Count - 1) ? true : false;
AppendBodyElementText(text, bodyElements[i], isLast);
}
return text.ToString();
}
private void AppendBodyElementText(StringBuilder text, IBodyElement e, bool isLast)
{
if (e is XWPFParagraph)
{
text.Append(((XWPFParagraph)e).Text);
if (isLast == false)
{
text.Append('\t');
}
}
else if (e is XWPFTable)
{
XWPFTable eTable = (XWPFTable)e;
foreach (XWPFTableRow row in eTable.Rows)
{
foreach (XWPFTableCell cell in row.GetTableCells())
{
IList<IBodyElement> localBodyElements = cell.BodyElements;
for (int i = 0; i < localBodyElements.Count; i++)
{
bool localIsLast = (i == localBodyElements.Count - 1) ? true : false;
AppendBodyElementText(text, localBodyElements[i], localIsLast);
}
}
}
if (isLast == false)
{
text.Append('\n');
}
}
else if (e is XWPFSDT)
{
text.Append(((XWPFSDT)e).Content.Text);
if (isLast == false)
{
text.Append('\t');
}
}
}
/**
* Get the TableCell which belongs to the TableCell
*/
public XWPFTableCell GetTableCell(CT_Tc cell)
{
if (!(cell.Parent is CT_Row))
return null;
CT_Row row = (CT_Row)cell.Parent;
if (!(row.Parent is CT_Tbl))
{
return null;
}
CT_Tbl tbl = (CT_Tbl)row.Parent;
XWPFTable table = GetTable(tbl);
if (table == null)
{
return null;
}
XWPFTableRow tr = table.GetRow(row);
if (tr == null)
{
return null;
}
return tr.GetTableCell(cell);
}
public XWPFDocument GetXWPFDocument()
{
return part.GetXWPFDocument();
}
}// end class
}
| |
using System.Collections.Generic;
using UnityEngine;
using SentinelMission;
namespace DarkMultiPlayer
{
public class AsteroidWorker
{
//How many asteroids to spawn into the server
public int maxNumberOfUntrackedAsteroids;
public bool workerEnabled;
//private state variables
private float lastAsteroidCheck;
private const float ASTEROID_CHECK_INTERVAL = 60f; // 1 minute
private ScenarioDiscoverableObjects scenario;
private bool initialized;
private List<string> serverAsteroids = new List<string>();
private Dictionary<string, string> serverAsteroidTrackStatus = new Dictionary<string, string>();
private object serverAsteroidListLock = new object();
//Services
private DMPGame dmpGame;
private LockSystem lockSystem;
private NetworkWorker networkWorker;
private VesselWorker vesselWorker;
public AsteroidWorker(DMPGame dmpGame, LockSystem lockSystem, NetworkWorker networkWorker, VesselWorker vesselWorker)
{
this.dmpGame = dmpGame;
this.lockSystem = lockSystem;
this.networkWorker = networkWorker;
this.vesselWorker = vesselWorker;
this.dmpGame.updateEvent.Add(Update);
GameEvents.onVesselCreate.Add(OnVesselCreate);
}
public void InitializeScenario()
{
foreach (ProtoScenarioModule psm in HighLogic.CurrentGame.scenarios)
{
if (psm != null && scenario == null && psm.moduleName.Contains("Discoverable"))
{
scenario = (ScenarioDiscoverableObjects)psm.moduleRef; // this is borked as of 1.3.0; maybe they'll fix it in the future?
}
}
if (scenario != null) scenario.spawnInterval = float.MaxValue;
// Disable the new Sentinel mechanic in KSP 1.3.0
SentinelUtilities.SpawnChance = 0f;
initialized = true;
}
public IEnumerable<Vessel> SpawnAsteroids(int quantity = 1)
{
System.Random random = new System.Random();
while (quantity-- > 0)
{
yield return SpawnAsteroid(random).vesselRef;
}
yield break;
}
public ProtoVessel SpawnAsteroid(System.Random random)
{
double baseDays = 21 + random.NextDouble() * 360;
Orbit orbit = Orbit.CreateRandomOrbitFlyBy(Planetarium.fetch.Home, baseDays);
ProtoVessel pv = DiscoverableObjectsUtil.SpawnAsteroid(
DiscoverableObjectsUtil.GenerateAsteroidName(),
orbit,
(uint)SentinelUtilities.RandomRange(random),
SentinelUtilities.WeightedAsteroidClass(random),
double.PositiveInfinity, double.PositiveInfinity);
return pv;
}
private void Update()
{
if (!workerEnabled) return;
if (Client.realtimeSinceStartup - lastAsteroidCheck < ASTEROID_CHECK_INTERVAL) return;
else lastAsteroidCheck = Client.realtimeSinceStartup;
if (!initialized) InitializeScenario();
//Try to acquire the asteroid-spawning lock if nobody else has it.
if (!lockSystem.LockExists("asteroid-spawning"))
{
lockSystem.AcquireLock("asteroid-spawning", false);
}
//We have the spawn lock, lets do stuff.
if (lockSystem.LockIsOurs("asteroid-spawning"))
{
if ((HighLogic.CurrentGame.flightState.protoVessels != null) && (FlightGlobals.fetch.vessels != null))
{
if ((HighLogic.CurrentGame.flightState.protoVessels.Count == 0) || (FlightGlobals.fetch.vessels.Count > 0))
{
int beforeSpawn = GetAsteroidCount();
int asteroidsToSpawn = maxNumberOfUntrackedAsteroids - beforeSpawn;
if (asteroidsToSpawn > 0)
{
foreach (Vessel asty in SpawnAsteroids(1)) // spawn 1 every ASTEROID_CHECK_INTERVAL seconds
DarkLog.Debug("Spawned asteroid " + asty.name + ", have " + (beforeSpawn) + ", need " + maxNumberOfUntrackedAsteroids);
}
}
}
}
//Check for changes to tracking
foreach (Vessel asteroid in GetCurrentAsteroids())
{
if (asteroid.state != Vessel.State.DEAD)
{
if (!serverAsteroidTrackStatus.ContainsKey(asteroid.id.ToString()))
{
serverAsteroidTrackStatus.Add(asteroid.id.ToString(), asteroid.DiscoveryInfo.trackingStatus.Value);
}
else
{
if (asteroid.DiscoveryInfo.trackingStatus.Value != serverAsteroidTrackStatus[asteroid.id.ToString()])
{
ProtoVessel pv = asteroid.BackupVessel();
DarkLog.Debug("Sending changed asteroid, new state: " + asteroid.DiscoveryInfo.trackingStatus.Value + "!");
serverAsteroidTrackStatus[asteroid.id.ToString()] = asteroid.DiscoveryInfo.trackingStatus.Value;
networkWorker.SendVesselProtoMessage(pv, false, false);
}
}
}
}
}
private void OnVesselCreate(Vessel checkVessel)
{
if (workerEnabled)
{
if (VesselIsAsteroid(checkVessel))
{
lock (serverAsteroidListLock)
{
if (lockSystem.LockIsOurs("asteroid-spawning"))
{
if (!serverAsteroids.Contains(checkVessel.id.ToString()))
{
if (GetAsteroidCount() <= maxNumberOfUntrackedAsteroids)
{
DarkLog.Debug("Spawned in new server asteroid!");
serverAsteroids.Add(checkVessel.id.ToString());
vesselWorker.RegisterServerVessel(checkVessel.id);
networkWorker.SendVesselProtoMessage(checkVessel.protoVessel, false, false);
}
else
{
DarkLog.Debug("Killing non-server asteroid " + checkVessel.id);
checkVessel.Die();
}
}
}
else
{
if (!serverAsteroids.Contains(checkVessel.id.ToString()))
{
DarkLog.Debug("Killing non-server asteroid " + checkVessel.id + ", we don't own the asteroid-spawning lock");
checkVessel.Die();
}
}
}
}
}
}
/// <summary>
/// Checks if the vessel is an asteroid.
/// </summary>
/// <returns><c>true</c> if the vessel is an asteroid, <c>false</c> otherwise.</returns>
/// <param name="checkVessel">The vessel to check</param>
public bool VesselIsAsteroid(Vessel checkVessel)
{
if (checkVessel != null)
{
if (!checkVessel.loaded)
{
return VesselIsAsteroid(checkVessel.protoVessel);
}
//Check the vessel has exactly one part.
if (checkVessel.parts != null ? (checkVessel.parts.Count == 1) : false)
{
if (checkVessel.parts[0].partName == "PotatoRoid")
{
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the vessel is an asteroid.
/// </summary>
/// <returns><c>true</c> if the vessel is an asteroid, <c>false</c> otherwise.</returns>
/// <param name="checkVessel">The vessel to check</param>
public bool VesselIsAsteroid(ProtoVessel checkVessel)
{
// Short circuit evaluation = faster
if (
checkVessel != null
&& checkVessel.protoPartSnapshots != null
&& checkVessel.protoPartSnapshots.Count == 1
&& checkVessel.protoPartSnapshots[0].partName == "PotatoRoid")
return true;
else
return false;
}
private Vessel[] GetCurrentAsteroids()
{
List<Vessel> currentAsteroids = new List<Vessel>();
foreach (Vessel checkVessel in FlightGlobals.fetch.vessels)
{
if (VesselIsAsteroid(checkVessel))
{
currentAsteroids.Add(checkVessel);
}
}
return currentAsteroids.ToArray();
}
private int GetAsteroidCount()
{
return GetCurrentAsteroids().Length;
}
/// <summary>
/// Registers the server asteroid - Prevents DMP from deleting it.
/// </summary>
/// <param name="asteroidID">Asteroid to register</param>
public void RegisterServerAsteroid(string asteroidID)
{
lock (serverAsteroidListLock)
{
if (!serverAsteroids.Contains(asteroidID))
{
serverAsteroids.Add(asteroidID);
}
//This will ignore status changes so we don't resend the asteroid.
if (serverAsteroidTrackStatus.ContainsKey(asteroidID))
{
serverAsteroidTrackStatus.Remove(asteroidID);
}
}
}
public void Stop()
{
dmpGame.updateEvent.Remove(Update);
GameEvents.onVesselCreate.Remove(OnVesselCreate);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartGridlinesFormatRequest.
/// </summary>
public partial class WorkbookChartGridlinesFormatRequest : BaseRequest, IWorkbookChartGridlinesFormatRequest
{
/// <summary>
/// Constructs a new WorkbookChartGridlinesFormatRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartGridlinesFormatRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartGridlinesFormat using POST.
/// </summary>
/// <param name="workbookChartGridlinesFormatToCreate">The WorkbookChartGridlinesFormat to create.</param>
/// <returns>The created WorkbookChartGridlinesFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> CreateAsync(WorkbookChartGridlinesFormat workbookChartGridlinesFormatToCreate)
{
return this.CreateAsync(workbookChartGridlinesFormatToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartGridlinesFormat using POST.
/// </summary>
/// <param name="workbookChartGridlinesFormatToCreate">The WorkbookChartGridlinesFormat to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartGridlinesFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> CreateAsync(WorkbookChartGridlinesFormat workbookChartGridlinesFormatToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartGridlinesFormat>(workbookChartGridlinesFormatToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartGridlinesFormat.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartGridlinesFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartGridlinesFormat>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartGridlinesFormat.
/// </summary>
/// <returns>The WorkbookChartGridlinesFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartGridlinesFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartGridlinesFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartGridlinesFormat>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartGridlinesFormat using PATCH.
/// </summary>
/// <param name="workbookChartGridlinesFormatToUpdate">The WorkbookChartGridlinesFormat to update.</param>
/// <returns>The updated WorkbookChartGridlinesFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> UpdateAsync(WorkbookChartGridlinesFormat workbookChartGridlinesFormatToUpdate)
{
return this.UpdateAsync(workbookChartGridlinesFormatToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartGridlinesFormat using PATCH.
/// </summary>
/// <param name="workbookChartGridlinesFormatToUpdate">The WorkbookChartGridlinesFormat to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartGridlinesFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartGridlinesFormat> UpdateAsync(WorkbookChartGridlinesFormat workbookChartGridlinesFormatToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartGridlinesFormat>(workbookChartGridlinesFormatToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartGridlinesFormatRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartGridlinesFormatRequest Expand(Expression<Func<WorkbookChartGridlinesFormat, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartGridlinesFormatRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartGridlinesFormatRequest Select(Expression<Func<WorkbookChartGridlinesFormat, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartGridlinesFormatToInitialize">The <see cref="WorkbookChartGridlinesFormat"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartGridlinesFormat workbookChartGridlinesFormatToInitialize)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security;
using Internal.Runtime.CompilerHelpers;
using Internal.Runtime.Augments;
using Debug = System.Diagnostics.Debug;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// This PInvokeMarshal class should provide full public Marshal
/// implementation for all things related to P/Invoke marshalling
/// </summary>
[CLSCompliant(false)]
public partial class PInvokeMarshal
{
[ThreadStatic]
internal static int s_lastWin32Error;
public static int GetLastWin32Error()
{
return s_lastWin32Error;
}
public static void SetLastWin32Error(int errorCode)
{
s_lastWin32Error = errorCode;
}
public static unsafe IntPtr AllocHGlobal(IntPtr cb)
{
return MemAlloc(cb);
}
public static unsafe IntPtr AllocHGlobal(int cb)
{
return AllocHGlobal((IntPtr)cb);
}
public static void FreeHGlobal(IntPtr hglobal)
{
MemFree(hglobal);
}
public static unsafe IntPtr AllocCoTaskMem(int cb)
{
IntPtr allocatedMemory = CoTaskMemAlloc(new UIntPtr(unchecked((uint)cb)));
if (allocatedMemory == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
return allocatedMemory;
}
public static void FreeCoTaskMem(IntPtr ptr)
{
CoTaskMemFree(ptr);
}
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: false);
}
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: true, unicode: true); ;
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: false);
}
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
return s.MarshalToString(globalAlloc: false, unicode: true);
}
public static unsafe void CopyToManaged(IntPtr source, Array destination, int startIndex, int length)
{
if (source == IntPtr.Zero)
throw new ArgumentNullException(nameof(source));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (!destination.IsBlittable())
throw new ArgumentException(nameof(destination), SR.Arg_CopyNonBlittableArray);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange);
if ((uint)startIndex + (uint)length > (uint)destination.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
nuint bytesToCopy = (nuint)length * destination.ElementSize;
nuint startOffset = (nuint)startIndex * destination.ElementSize;
fixed (byte* pDestination = &destination.GetRawArrayData())
{
byte* destinationData = pDestination + startOffset;
Buffer.Memmove(destinationData, (byte*)source, bytesToCopy);
}
}
public static unsafe void CopyToNative(Array source, int startIndex, IntPtr destination, int length)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (!source.IsBlittable())
throw new ArgumentException(nameof(source), SR.Arg_CopyNonBlittableArray);
if (destination == IntPtr.Zero)
throw new ArgumentNullException(nameof(destination));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.Arg_CopyOutOfRange);
if ((uint)startIndex + (uint)length > (uint)source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.Arg_CopyOutOfRange);
nuint bytesToCopy = (nuint)length * source.ElementSize;
nuint startOffset = (nuint)startIndex * source.ElementSize;
fixed (byte* pSource = &source.GetRawArrayData())
{
byte* sourceData = pSource + startOffset;
Buffer.Memmove((byte*)destination, sourceData, bytesToCopy);
}
}
public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
{
if (arr == null)
throw new ArgumentNullException(nameof(arr));
byte* p = (byte*)Unsafe.AsPointer(ref arr.GetRawArrayData()) + (nuint)index * arr.ElementSize;
return (IntPtr)p;
}
#region Delegate marshalling
private static object s_thunkPoolHeap;
/// <summary>
/// Return the stub to the pinvoke marshalling stub
/// </summary>
/// <param name="del">The delegate</param>
public static IntPtr GetStubForPInvokeDelegate(Delegate del)
{
if (del == null)
return IntPtr.Zero;
NativeFunctionPointerWrapper fpWrapper = del.Target as NativeFunctionPointerWrapper;
if (fpWrapper != null)
{
//
// Marshalling a delegate created from native function pointer back into function pointer
// This is easy - just return the 'wrapped' native function pointer
//
return fpWrapper.NativeFunctionPointer;
}
else
{
//
// Marshalling a managed delegate created from managed code into a native function pointer
//
return GetPInvokeDelegates().GetValue(del, s_AllocateThunk ?? (s_AllocateThunk = AllocateThunk)).Thunk;
}
}
/// <summary>
/// Used to lookup whether a delegate already has thunk allocated for it
/// </summary>
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> s_pInvokeDelegates;
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk>.CreateValueCallback s_AllocateThunk;
private static ConditionalWeakTable<Delegate, PInvokeDelegateThunk> GetPInvokeDelegates()
{
//
// Create the dictionary on-demand to avoid the dependency in the McgModule.ctor
// Otherwise NUTC will complain that McgModule being eager ctor depends on a deferred
// ctor type
//
if (s_pInvokeDelegates == null)
{
Interlocked.CompareExchange(
ref s_pInvokeDelegates,
new ConditionalWeakTable<Delegate, PInvokeDelegateThunk>(),
null
);
}
return s_pInvokeDelegates;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal unsafe struct ThunkContextData
{
public GCHandle Handle; // A weak GCHandle to the delegate
public IntPtr FunctionPtr; // Function pointer for open static delegates
}
internal sealed class PInvokeDelegateThunk
{
public IntPtr Thunk; // Thunk pointer
public IntPtr ContextData; // ThunkContextData pointer which will be stored in the context slot of the thunk
public PInvokeDelegateThunk(Delegate del)
{
Thunk = RuntimeAugments.AllocateThunk(s_thunkPoolHeap);
Debug.Assert(Thunk != IntPtr.Zero);
if (Thunk == IntPtr.Zero)
{
// We've either run out of memory, or failed to allocate a new thunk due to some other bug. Now we should fail fast
Environment.FailFast("Insufficient number of thunks.");
}
else
{
//
// Allocate unmanaged memory for GCHandle of delegate and function pointer of open static delegate
// We will store this pointer on the context slot of thunk data
//
ContextData = AllocHGlobal(2 * IntPtr.Size);
unsafe
{
ThunkContextData* thunkData = (ThunkContextData*)ContextData;
// allocate a weak GChandle for the delegate
thunkData->Handle = GCHandle.Alloc(del, GCHandleType.Weak);
// if it is an open static delegate get the function pointer
thunkData->FunctionPtr = del.GetRawFunctionPointerForOpenStaticDelegate();
}
}
}
~PInvokeDelegateThunk()
{
// Free the thunk
RuntimeAugments.FreeThunk(s_thunkPoolHeap, Thunk);
unsafe
{
if (ContextData != IntPtr.Zero)
{
// free the GCHandle
GCHandle handle = ((ThunkContextData*)ContextData)->Handle;
if (handle != null)
{
handle.Free();
}
// Free the allocated context data memory
FreeHGlobal(ContextData);
}
}
}
}
private static PInvokeDelegateThunk AllocateThunk(Delegate del)
{
if (s_thunkPoolHeap == null)
{
// TODO: Free s_thunkPoolHeap if the thread lose the race
Interlocked.CompareExchange(
ref s_thunkPoolHeap,
RuntimeAugments.CreateThunksHeap(RuntimeImports.GetInteropCommonStubAddress()),
null
);
Debug.Assert(s_thunkPoolHeap != null);
}
var delegateThunk = new PInvokeDelegateThunk(del);
McgPInvokeDelegateData pinvokeDelegateData;
if (!RuntimeAugments.InteropCallbacks.TryGetMarshallerDataForDelegate(del.GetTypeHandle(), out pinvokeDelegateData))
{
Environment.FailFast("Couldn't find marshalling stubs for delegate.");
}
//
// For open static delegates set target to ReverseOpenStaticDelegateStub which calls the static function pointer directly
//
IntPtr pTarget = del.GetRawFunctionPointerForOpenStaticDelegate() == IntPtr.Zero ? pinvokeDelegateData.ReverseStub : pinvokeDelegateData.ReverseOpenStaticDelegateStub;
RuntimeAugments.SetThunkData(s_thunkPoolHeap, delegateThunk.Thunk, delegateThunk.ContextData, pTarget);
return delegateThunk;
}
/// <summary>
/// Retrieve the corresponding P/invoke instance from the stub
/// </summary>
public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType)
{
if (pStub == IntPtr.Zero)
return null;
//
// First try to see if this is one of the thunks we've allocated when we marshal a managed
// delegate to native code
// s_thunkPoolHeap will be null if there isn't any managed delegate to native
//
IntPtr pContext;
IntPtr pTarget;
if (s_thunkPoolHeap != null && RuntimeAugments.TryGetThunkData(s_thunkPoolHeap, pStub, out pContext, out pTarget))
{
GCHandle handle;
unsafe
{
// Pull out Handle from context
handle = ((ThunkContextData*)pContext)->Handle;
}
Delegate target = InteropExtensions.UncheckedCast<Delegate>(handle.Target);
//
// The delegate might already been garbage collected
// User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive
// until they are done with the native function pointer
//
if (target == null)
{
Environment.FailFast(SR.Delegate_GarbageCollected);
}
return target;
}
//
// Otherwise, the stub must be a pure native function pointer
// We need to create the delegate that points to the invoke method of a
// NativeFunctionPointerWrapper derived class
//
McgPInvokeDelegateData pInvokeDelegateData;
if (!RuntimeAugments.InteropCallbacks.TryGetMarshallerDataForDelegate(delegateType, out pInvokeDelegateData))
{
return null;
}
return CalliIntrinsics.Call<Delegate>(
pInvokeDelegateData.ForwardDelegateCreationStub,
pStub
);
}
/// <summary>
/// Retrieves the function pointer for the current open static delegate that is being called
/// </summary>
public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer()
{
//
// RH keeps track of the current thunk that is being called through a secret argument / thread
// statics. No matter how that's implemented, we get the current thunk which we can use for
// look up later
//
IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext();
Debug.Assert(pContext != null);
IntPtr fnPtr;
unsafe
{
// Pull out function pointer for open static delegate
fnPtr = ((ThunkContextData*)pContext)->FunctionPtr;
}
Debug.Assert(fnPtr != null);
return fnPtr;
}
/// <summary>
/// Retrieves the current delegate that is being called
/// </summary>
public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate
{
//
// RH keeps track of the current thunk that is being called through a secret argument / thread
// statics. No matter how that's implemented, we get the current thunk which we can use for
// look up later
//
IntPtr pContext = RuntimeImports.GetCurrentInteropThunkContext();
Debug.Assert(pContext != null);
GCHandle handle;
unsafe
{
// Pull out Handle from context
handle = ((ThunkContextData*)pContext)->Handle;
}
T target = InteropExtensions.UncheckedCast<T>(handle.Target);
//
// The delegate might already been garbage collected
// User should use GC.KeepAlive or whatever ways necessary to keep the delegate alive
// until they are done with the native function pointer
//
if (target == null)
{
Environment.FailFast(SR.Delegate_GarbageCollected);
}
return target;
}
[McgIntrinsics]
private static unsafe class CalliIntrinsics
{
internal static T Call<T>(IntPtr pfn, IntPtr arg0) { throw new NotSupportedException(); }
}
#endregion
#region String marshalling
public static unsafe String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
if (len < 0)
throw new ArgumentException(nameof(len));
return new String((char*)ptr, 0, len);
}
public static unsafe String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr)
{
return null;
}
else if (IsWin32Atom(ptr))
{
return null;
}
else
{
return new String((char*)ptr);
}
}
public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination)
{
stringBuilder.UnsafeCopyTo((char*)destination);
}
public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder)
{
stringBuilder.ReplaceBuffer((char*)newBuffer);
}
public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative,
bool bestFit, bool throwOnUnmappableChar)
{
int len;
// Convert StringBuilder to UNICODE string
// Optimize for the most common case. If there is only a single char[] in the StringBuilder,
// get it and convert it to ANSI
char[] buffer = stringBuilder.GetBuffer(out len);
if (buffer != null)
{
fixed (char* pManaged = buffer)
{
StringToAnsiString(pManaged, len, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
else // Otherwise, convert StringBuilder to string and then convert to ANSI
{
string str = stringBuilder.ToString();
// Convert UNICODE string to ANSI string
fixed (char* pManaged = str)
{
StringToAnsiString(pManaged, str.Length, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
}
public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder)
{
if (newBuffer == null)
throw new ArgumentNullException(nameof(newBuffer));
int lenAnsi;
int lenUnicode;
CalculateStringLength(newBuffer, out lenAnsi, out lenUnicode);
if (lenUnicode > 0)
{
char[] buffer = new char[lenUnicode];
fixed (char* pTemp = &buffer[0])
{
ConvertMultiByteToWideChar(newBuffer,
lenAnsi,
pTemp,
lenUnicode);
}
stringBuilder.ReplaceBuffer(buffer);
}
else
{
stringBuilder.Clear();
}
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
public static unsafe string AnsiStringToString(byte* pchBuffer)
{
if (pchBuffer == null)
{
return null;
}
int lenAnsi;
int lenUnicode;
CalculateStringLength(pchBuffer, out lenAnsi, out lenUnicode);
string result = String.Empty;
if (lenUnicode > 0)
{
result = string.FastAllocateString(lenUnicode);
fixed (char* pTemp = result)
{
ConvertMultiByteToWideChar(pchBuffer,
lenAnsi,
pTemp,
lenUnicode);
}
}
return result;
}
/// <summary>
/// Convert UNICODE string to ANSI string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar)
{
if (str != null)
{
int lenUnicode = str.Length;
fixed (char* pManaged = str)
{
return StringToAnsiString(pManaged, lenUnicode, null, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
return null;
}
/// <summary>
/// Convert UNICODE wide char array to ANSI ByVal byte array.
/// </summary>
/// <remarks>
/// * This version works with array instead string, it means that there will be NO NULL to terminate the array.
/// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length.
/// </remarks>
/// <param name="managedArray">UNICODE wide char array</param>
/// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param>
public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount,
bool bestFit, bool throwOnUnmappableChar)
{
// Zero-init pNative if it is NULL
if (managedArray == null)
{
Buffer.ZeroMemory((byte*)pNative, expectedCharCount);
return;
}
int lenUnicode = managedArray.Length;
if (lenUnicode < expectedCharCount)
throw new ArgumentException(SR.WrongSizeArrayInNStruct);
fixed (char* pManaged = managedArray)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
}
}
public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
// This should never happen because it is a embedded array
Debug.Assert(pNative != null);
// This should never happen because the array is always allocated by the marshaller
Debug.Assert(managedArray != null);
// COMPAT: Use the managed array length as the maximum length of native buffer
// This obviously doesn't make sense but desktop CLR does that
int lenInBytes = managedArray.Length;
fixed (char* pManaged = managedArray)
{
ConvertMultiByteToWideChar(pNative,
lenInBytes,
pManaged,
lenInBytes);
}
}
public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar)
{
// Do nothing if array is NULL. This matches desktop CLR behavior
if (managedArray == null)
return;
// Desktop CLR crash (AV at runtime) - we can do better in .NET Native
if (pNative == null)
throw new ArgumentNullException(nameof(pNative));
int lenUnicode = managedArray.Length;
fixed (char* pManaged = managedArray)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
}
}
/// <summary>
/// Convert ANSI ByVal byte array to UNICODE wide char array, best fit
/// </summary>
/// <remarks>
/// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to
/// terminate the array.
/// * The buffer to the UNICODE wide char array must be allocated by the caller.
/// </remarks>
/// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param>
/// <param name="lenInBytes">Maximum buffer size.</param>
/// <param name="managedArray">Wide char array that has already been allocated.</param>
public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
// Do nothing if native is NULL. This matches desktop CLR behavior
if (pNative == null)
return;
// Desktop CLR crash (AV at runtime) - we can do better in .NET Native
if (managedArray == null)
throw new ArgumentNullException(nameof(managedArray));
// COMPAT: Use the managed array length as the maximum length of native buffer
// This obviously doesn't make sense but desktop CLR does that
int lenInBytes = managedArray.Length;
fixed (char* pManaged = managedArray)
{
ConvertMultiByteToWideChar(pNative,
lenInBytes,
pManaged,
lenInBytes);
}
}
/// <summary>
/// Convert a single UNICODE wide char to a single ANSI byte.
/// </summary>
/// <param name="managedArray">single UNICODE wide char value</param>
public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar)
{
// @TODO - we really shouldn't allocate one-byte arrays and then destroy it
byte* nativeArray = StringToAnsiString(&managedValue, 1, null, /*terminateWithNull=*/false, bestFit, throwOnUnmappableChar);
byte native = (*nativeArray);
CoTaskMemFree(new IntPtr(nativeArray));
return native;
}
/// <summary>
/// Convert a single ANSI byte value to a single UNICODE wide char value, best fit.
/// </summary>
/// <param name="nativeValue">Single ANSI byte value.</param>
public static unsafe char AnsiCharToWideChar(byte nativeValue)
{
char ch;
ConvertMultiByteToWideChar(&nativeValue, 1, &ch, 1);
return ch;
}
/// <summary>
/// Convert UNICODE string to ANSI ByVal string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
/// <param name="str">Unicode string.</param>
/// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param>
public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar, bool truncate = true)
{
if (pNative == null)
throw new ArgumentNullException(nameof(pNative));
if (str != null)
{
// Truncate the string if it is larger than specified by SizeConst
int lenUnicode;
if (truncate)
{
lenUnicode = str.Length;
if (lenUnicode >= charCount)
lenUnicode = charCount - 1;
}
else
{
lenUnicode = charCount;
}
fixed (char* pManaged = str)
{
StringToAnsiString(pManaged, lenUnicode, pNative, /*terminateWithNull=*/true, bestFit, throwOnUnmappableChar);
}
}
else
{
(*pNative) = (byte)'\0';
}
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount)
{
// Match desktop CLR behavior
if (charCount == 0)
throw new MarshalDirectiveException();
int lenAnsi = GetAnsiStringLen(pchBuffer);
int lenUnicode = charCount;
string result = String.Empty;
if (lenUnicode > 0)
{
char* unicodeBuf = stackalloc char[lenUnicode];
int unicodeCharWritten = ConvertMultiByteToWideChar(pchBuffer,
lenAnsi,
unicodeBuf,
lenUnicode);
// If conversion failure, return empty string to match desktop CLR behavior
if (unicodeCharWritten > 0)
result = new string(unicodeBuf, 0, unicodeCharWritten);
}
return result;
}
private static unsafe int GetAnsiStringLen(byte* pchBuffer)
{
byte* pchBufferOriginal = pchBuffer;
while (*pchBuffer != 0)
{
pchBuffer++;
}
return (int)(pchBuffer - pchBufferOriginal);
}
// c# string (UTF-16) to UTF-8 encoded byte array
private static unsafe byte* StringToAnsiString(char* pManaged, int lenUnicode, byte* pNative, bool terminateWithNull,
bool bestFit, bool throwOnUnmappableChar)
{
bool allAscii = true;
for (int i = 0; i < lenUnicode; i++)
{
if (pManaged[i] >= 128)
{
allAscii = false;
break;
}
}
int length;
if (allAscii) // If all ASCII, map one UNICODE character to one ANSI char
{
length = lenUnicode;
}
else // otherwise, let OS count number of ANSI chars
{
length = GetByteCount(pManaged, lenUnicode);
}
if (pNative == null)
{
pNative = (byte*)CoTaskMemAlloc((System.UIntPtr)(length + 1));
}
if (allAscii) // ASCII conversion
{
byte* pDst = pNative;
char* pSrc = pManaged;
while (lenUnicode > 0)
{
unchecked
{
*pDst++ = (byte)(*pSrc++);
lenUnicode--;
}
}
}
else // Let OS convert
{
ConvertWideCharToMultiByte(pManaged,
lenUnicode,
pNative,
length,
bestFit,
throwOnUnmappableChar);
}
// Zero terminate
if (terminateWithNull)
*(pNative + length) = 0;
return pNative;
}
/// <summary>
/// This is a auxiliary function that counts the length of the ansi buffer and
/// estimate the length of the buffer in Unicode. It returns true if all bytes
/// in the buffer are ANSII.
/// </summary>
private static unsafe bool CalculateStringLength(byte* pchBuffer, out int ansiBufferLen, out int unicodeBufferLen)
{
ansiBufferLen = 0;
bool allAscii = true;
{
byte* p = pchBuffer;
byte b = *p++;
while (b != 0)
{
if (b >= 128)
{
allAscii = false;
}
ansiBufferLen++;
b = *p++;
}
}
if (allAscii)
{
unicodeBufferLen = ansiBufferLen;
}
else // If non ASCII, let OS calculate number of characters
{
unicodeBufferLen = GetCharCount(pchBuffer, ansiBufferLen);
}
return allAscii;
}
#endregion
}
}
| |
/*
* The author of this software is Steven Fortune. Copyright (c) 1994 by AT&T
* Bell Laboratories.
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
using UnityEngine;
using System;
using System.Collections.Generic;
using Delaunay.Geo;
using Delaunay.Utils;
using Delaunay.LR;
namespace Delaunay
{
public sealed class Voronoi: Utils.IDisposable
{
private SiteList _sites;
private Dictionary <Vector2,Site> _sitesIndexedByLocation;
private List<Triangle> _triangles;
private List<Edge> _edges;
// TODO generalize this so it doesn't have to be a rectangle;
// then we can make the fractal voronois-within-voronois
private Rect _plotBounds;
public Rect plotBounds {
get { return _plotBounds;}
}
public void Dispose ()
{
int i, n;
if (_sites != null) {
_sites.Dispose ();
_sites = null;
}
if (_triangles != null) {
n = _triangles.Count;
for (i = 0; i < n; ++i) {
_triangles [i].Dispose ();
}
_triangles.Clear ();
_triangles = null;
}
if (_edges != null) {
n = _edges.Count;
for (i = 0; i < n; ++i) {
_edges [i].Dispose ();
}
_edges.Clear ();
_edges = null;
}
// _plotBounds = null;
_sitesIndexedByLocation = null;
}
public Voronoi (List<Vector2> points, List<uint> colors, Rect plotBounds)
{
_sites = new SiteList ();
_sitesIndexedByLocation = new Dictionary <Vector2,Site> (); // XXX: Used to be Dictionary(true) -- weak refs.
AddSites (points, colors);
_plotBounds = plotBounds;
_triangles = new List<Triangle> ();
_edges = new List<Edge> ();
FortunesAlgorithm ();
}
private void AddSites (List<Vector2> points, List<uint> colors)
{
int length = points.Count;
for (int i = 0; i < length; ++i) {
AddSite (points [i], (colors != null) ? colors [i] : 0, i);
}
}
private void AddSite (Vector2 p, uint color, int index)
{
if (_sitesIndexedByLocation.ContainsKey (p))
return; // Prevent duplicate site! (Adapted from https://github.com/nodename/as3delaunay/issues/1)
float weight = UnityEngine.Random.value * 100f;
Site site = Site.Create (p, (uint)index, weight, color);
_sites.Add (site);
_sitesIndexedByLocation [p] = site;
}
public List<Edge> Edges ()
{
return _edges;
}
public List<Vector2> Region (Vector2 p)
{
Site site = _sitesIndexedByLocation [p];
if (site == null) {
return new List<Vector2> ();
}
return site.Region (_plotBounds);
}
// TODO: bug: if you call this before you call region(), something goes wrong :(
public List<Vector2> NeighborSitesForSite (Vector2 coord)
{
List<Vector2> points = new List<Vector2> ();
Site site = _sitesIndexedByLocation [coord];
if (site == null) {
return points;
}
List<Site> sites = site.NeighborSites ();
Site neighbor;
for (int nIndex =0; nIndex<sites.Count; nIndex++) {
neighbor = sites [nIndex];
points.Add (neighbor.Coord);
}
return points;
}
public List<Circle> Circles ()
{
return _sites.Circles ();
}
public List<LineSegment> VoronoiBoundaryForSite (Vector2 coord)
{
return DelaunayHelpers.VisibleLineSegments (DelaunayHelpers.SelectEdgesForSitePoint (coord, _edges));
}
public List<LineSegment> DelaunayLinesForSite (Vector2 coord)
{
return DelaunayHelpers.DelaunayLinesForEdges (DelaunayHelpers.SelectEdgesForSitePoint (coord, _edges));
}
public List<LineSegment> VoronoiDiagram ()
{
return DelaunayHelpers.VisibleLineSegments (_edges);
}
public List<LineSegment> DelaunayTriangulation (/*BitmapData keepOutMask = null*/)
{
return DelaunayHelpers.DelaunayLinesForEdges (DelaunayHelpers.SelectNonIntersectingEdges (/*keepOutMask,*/_edges));
}
public List<LineSegment> Hull ()
{
return DelaunayHelpers.DelaunayLinesForEdges (HullEdges ());
}
private List<Edge> HullEdges ()
{
return _edges.FindAll (delegate (Edge edge) {
return (edge.IsPartOfConvexHull ());
});
}
public List<Vector2> HullPointsInOrder ()
{
List<Edge> hullEdges = HullEdges ();
List<Vector2> points = new List<Vector2> ();
if (hullEdges.Count == 0) {
return points;
}
EdgeReorderer reorderer = new EdgeReorderer (hullEdges, VertexOrSite.SITE);
hullEdges = reorderer.edges;
List<Side> orientations = reorderer.edgeOrientations;
reorderer.Dispose ();
Side orientation;
int n = hullEdges.Count;
for (int i = 0; i < n; ++i) {
Edge edge = hullEdges [i];
orientation = orientations [i];
points.Add (edge.Site (orientation).Coord);
}
return points;
}
public List<LineSegment> SpanningTree (KruskalType type = KruskalType.MINIMUM/*, BitmapData keepOutMask = null*/)
{
List<Edge> edges = DelaunayHelpers.SelectNonIntersectingEdges (/*keepOutMask,*/_edges);
List<LineSegment> segments = DelaunayHelpers.DelaunayLinesForEdges (edges);
return DelaunayHelpers.Kruskal (segments, type);
}
public List<List<Vector2>> Regions ()
{
return _sites.Regions (_plotBounds);
}
public List<uint> SiteColors (/*BitmapData referenceImage = null*/)
{
return _sites.SiteColors (/*referenceImage*/);
}
/**
*
* @param proximityMap a BitmapData whose regions are filled with the site index values; see PlanePointsCanvas::fillRegions()
* @param x
* @param y
* @return coordinates of nearest Site to (x, y)
*
*/
public Nullable<Vector2> NearestSitePoint (/*BitmapData proximityMap,*/float x, float y)
{
return _sites.NearestSitePoint (/*proximityMap,*/x, y);
}
public List<Vector2> SiteCoords ()
{
return _sites.SiteCoords ();
}
private Site fortunesAlgorithm_bottomMostSite;
private void FortunesAlgorithm ()
{
Site newSite, bottomSite, topSite, tempSite;
Vertex v, vertex;
Vector2 newintstar = Vector2.zero; //Because the compiler doesn't know that it will have a value - Julian
Side leftRight;
Halfedge lbnd, rbnd, llbnd, rrbnd, bisector;
Edge edge;
Rect dataBounds = _sites.GetSitesBounds ();
int sqrt_nsites = (int)(Mathf.Sqrt (_sites.Count + 4));
HalfedgePriorityQueue heap = new HalfedgePriorityQueue (dataBounds.y, dataBounds.height, sqrt_nsites);
EdgeList edgeList = new EdgeList (dataBounds.x, dataBounds.width, sqrt_nsites);
List<Halfedge> halfEdges = new List<Halfedge> ();
List<Vertex> vertices = new List<Vertex> ();
fortunesAlgorithm_bottomMostSite = _sites.Next ();
newSite = _sites.Next ();
for (;;) {
if (heap.Empty () == false) {
newintstar = heap.Min ();
}
if (newSite != null
&& (heap.Empty () || CompareByYThenX (newSite, newintstar) < 0)) {
/* new site is smallest */
//trace("smallest: new site " + newSite);
// Step 8:
lbnd = edgeList.EdgeListLeftNeighbor (newSite.Coord); // the Halfedge just to the left of newSite
//trace("lbnd: " + lbnd);
rbnd = lbnd.edgeListRightNeighbor; // the Halfedge just to the right
//trace("rbnd: " + rbnd);
bottomSite = FortunesAlgorithm_rightRegion (lbnd); // this is the same as leftRegion(rbnd)
// this Site determines the region containing the new site
//trace("new Site is in region of existing site: " + bottomSite);
// Step 9:
edge = Edge.CreateBisectingEdge (bottomSite, newSite);
//trace("new edge: " + edge);
_edges.Add (edge);
bisector = Halfedge.Create (edge, Side.LEFT);
halfEdges.Add (bisector);
// inserting two Halfedges into edgeList constitutes Step 10:
// insert bisector to the right of lbnd:
edgeList.Insert (lbnd, bisector);
// first half of Step 11:
if ((vertex = Vertex.Intersect (lbnd, bisector)) != null) {
vertices.Add (vertex);
heap.Remove (lbnd);
lbnd.vertex = vertex;
lbnd.ystar = vertex.y + newSite.Dist (vertex);
heap.Insert (lbnd);
}
lbnd = bisector;
bisector = Halfedge.Create (edge, Side.RIGHT);
halfEdges.Add (bisector);
// second Halfedge for Step 10:
// insert bisector to the right of lbnd:
edgeList.Insert (lbnd, bisector);
// second half of Step 11:
if ((vertex = Vertex.Intersect (bisector, rbnd)) != null) {
vertices.Add (vertex);
bisector.vertex = vertex;
bisector.ystar = vertex.y + newSite.Dist (vertex);
heap.Insert (bisector);
}
newSite = _sites.Next ();
} else if (heap.Empty () == false) {
/* intersection is smallest */
lbnd = heap.ExtractMin ();
llbnd = lbnd.edgeListLeftNeighbor;
rbnd = lbnd.edgeListRightNeighbor;
rrbnd = rbnd.edgeListRightNeighbor;
bottomSite = FortunesAlgorithm_leftRegion (lbnd);
topSite = FortunesAlgorithm_rightRegion (rbnd);
// these three sites define a Delaunay triangle
// (not actually using these for anything...)
//_triangles.push(new Triangle(bottomSite, topSite, rightRegion(lbnd)));
v = lbnd.vertex;
v.SetIndex ();
lbnd.edge.SetVertex ((Side)lbnd.leftRight, v);
rbnd.edge.SetVertex ((Side)rbnd.leftRight, v);
edgeList.Remove (lbnd);
heap.Remove (rbnd);
edgeList.Remove (rbnd);
leftRight = Side.LEFT;
if (bottomSite.y > topSite.y) {
tempSite = bottomSite;
bottomSite = topSite;
topSite = tempSite;
leftRight = Side.RIGHT;
}
edge = Edge.CreateBisectingEdge (bottomSite, topSite);
_edges.Add (edge);
bisector = Halfedge.Create (edge, leftRight);
halfEdges.Add (bisector);
edgeList.Insert (llbnd, bisector);
edge.SetVertex (SideHelper.Other (leftRight), v);
if ((vertex = Vertex.Intersect (llbnd, bisector)) != null) {
vertices.Add (vertex);
heap.Remove (llbnd);
llbnd.vertex = vertex;
llbnd.ystar = vertex.y + bottomSite.Dist (vertex);
heap.Insert (llbnd);
}
if ((vertex = Vertex.Intersect (bisector, rrbnd)) != null) {
vertices.Add (vertex);
bisector.vertex = vertex;
bisector.ystar = vertex.y + bottomSite.Dist (vertex);
heap.Insert (bisector);
}
} else {
break;
}
}
// heap should be empty now
heap.Dispose ();
edgeList.Dispose ();
for (int hIndex = 0; hIndex<halfEdges.Count; hIndex++) {
Halfedge halfEdge = halfEdges [hIndex];
halfEdge.ReallyDispose ();
}
halfEdges.Clear ();
// we need the vertices to clip the edges
for (int eIndex = 0; eIndex<_edges.Count; eIndex++) {
edge = _edges [eIndex];
edge.ClipVertices (_plotBounds);
}
// but we don't actually ever use them again!
for (int vIndex = 0; vIndex<vertices.Count; vIndex++) {
vertex = vertices [vIndex];
vertex.Dispose ();
}
vertices.Clear ();
}
private Site FortunesAlgorithm_leftRegion (Halfedge he)
{
Edge edge = he.edge;
if (edge == null) {
return fortunesAlgorithm_bottomMostSite;
}
return edge.Site ((Side)he.leftRight);
}
private Site FortunesAlgorithm_rightRegion (Halfedge he)
{
Edge edge = he.edge;
if (edge == null) {
return fortunesAlgorithm_bottomMostSite;
}
return edge.Site (SideHelper.Other ((Side)he.leftRight));
}
public static int CompareByYThenX (Site s1, Site s2)
{
if (s1.y < s2.y)
return -1;
if (s1.y > s2.y)
return 1;
if (s1.x < s2.x)
return -1;
if (s1.x > s2.x)
return 1;
return 0;
}
public static int CompareByYThenX (Site s1, Vector2 s2)
{
if (s1.y < s2.y)
return -1;
if (s1.y > s2.y)
return 1;
if (s1.x < s2.x)
return -1;
if (s1.x > s2.x)
return 1;
return 0;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.Configuration.PagesSection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.Configuration
{
sealed public partial class PagesSection : System.Configuration.ConfigurationSection
{
#region Methods and constructors
protected override void DeserializeSection(System.Xml.XmlReader reader)
{
}
public PagesSection()
{
}
#endregion
#region Properties and indexers
public TimeSpan AsyncTimeout
{
get
{
return default(TimeSpan);
}
set
{
}
}
public bool AutoEventWireup
{
get
{
return default(bool);
}
set
{
}
}
public bool Buffer
{
get
{
return default(bool);
}
set
{
}
}
public System.Web.UI.ClientIDMode ClientIDMode
{
get
{
return default(System.Web.UI.ClientIDMode);
}
set
{
}
}
public System.Web.UI.CompilationMode CompilationMode
{
get
{
return default(System.Web.UI.CompilationMode);
}
set
{
}
}
public Version ControlRenderingCompatibilityVersion
{
get
{
return default(Version);
}
set
{
}
}
public TagPrefixCollection Controls
{
get
{
return default(TagPrefixCollection);
}
}
public bool EnableEventValidation
{
get
{
return default(bool);
}
set
{
}
}
public PagesEnableSessionState EnableSessionState
{
get
{
return default(PagesEnableSessionState);
}
set
{
}
}
public bool EnableViewState
{
get
{
return default(bool);
}
set
{
}
}
public bool EnableViewStateMac
{
get
{
return default(bool);
}
set
{
}
}
public IgnoreDeviceFilterElementCollection IgnoreDeviceFilters
{
get
{
return default(IgnoreDeviceFilterElementCollection);
}
}
public bool MaintainScrollPositionOnPostBack
{
get
{
return default(bool);
}
set
{
}
}
public string MasterPageFile
{
get
{
return default(string);
}
set
{
}
}
public int MaxPageStateFieldLength
{
get
{
return default(int);
}
set
{
}
}
public NamespaceCollection Namespaces
{
get
{
return default(NamespaceCollection);
}
}
public string PageBaseType
{
get
{
return default(string);
}
set
{
}
}
public string PageParserFilterType
{
get
{
return default(string);
}
set
{
}
}
protected override System.Configuration.ConfigurationPropertyCollection Properties
{
get
{
return default(System.Configuration.ConfigurationPropertyCollection);
}
}
public bool RenderAllHiddenFieldsAtTopOfForm
{
get
{
return default(bool);
}
set
{
}
}
public bool SmartNavigation
{
get
{
return default(bool);
}
set
{
}
}
public string StyleSheetTheme
{
get
{
return default(string);
}
set
{
}
}
public TagMapCollection TagMapping
{
get
{
return default(TagMapCollection);
}
}
public string Theme
{
get
{
return default(string);
}
set
{
}
}
public string UserControlBaseType
{
get
{
return default(string);
}
set
{
}
}
public bool ValidateRequest
{
get
{
return default(bool);
}
set
{
}
}
public System.Web.UI.ViewStateEncryptionMode ViewStateEncryptionMode
{
get
{
return default(System.Web.UI.ViewStateEncryptionMode);
}
set
{
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Factotum
{
public partial class ThermoView : Form
{
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
// Form constructor
public ThermoView()
{
InitializeComponent();
// Take care of settings that are not as easily managed in the designer.
InitializeControls();
}
// Take care of the non-default DataGridView settings that are not as easily managed
// in the designer.
private void InitializeControls()
{
}
// Set the status filter to show active tools by default
// and update the tool selector combo box
private void ThermoView_Load(object sender, EventArgs e)
{
// Set the status combo first. The selector DataGridView depends on it.
cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive;
// Apply the current filters and set the selector row.
// Passing a null selects the first row if there are any rows.
UpdateSelector(null);
// Now that we have some rows and columns, we can do some customization.
CustomizeGrid();
// Need to do this because the customization clears the row selection.
SelectGridRow(null);
// Wire up the handler for the Entity changed event
EThermo.Changed += new EventHandler<EntityChangedEventArgs>(EThermo_Changed);
}
private void ThermoView_FormClosed(object sender, FormClosedEventArgs e)
{
EThermo.Changed -= new EventHandler<EntityChangedEventArgs>(EThermo_Changed);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
// If any of this type of entity object was saved or deleted, we want to update the selector
// The event args contain the ID of the entity that was added, mofified or deleted.
void EThermo_Changed(object sender, EntityChangedEventArgs e)
{
UpdateSelector(e.ID);
}
// Handle the user's decision to edit the current tool
private void EditCurrentSelection()
{
// Make sure there's a row selected
if (dgvThermometers.SelectedRows.Count != 1) return;
Guid? currentEditItem = (Guid?)(dgvThermometers.SelectedRows[0].Cells["ID"].Value);
// First check to see if an instance of the form set to the selected ID already exists
if (!Globals.CanActivateForm(this, "ThermoEdit", currentEditItem))
{
// Open the edit form with the currently selected ID.
ThermoEdit frm = new ThermoEdit(currentEditItem);
frm.MdiParent = this.MdiParent;
frm.Show();
}
}
// This handles the datagridview double-click as well as button click
void btnEdit_Click(object sender, System.EventArgs e)
{
EditCurrentSelection();
}
private void dgvThermometers_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
EditCurrentSelection();
}
// Handle the user's decision to add a new tool
private void btnAdd_Click(object sender, EventArgs e)
{
ThermoEdit frm = new ThermoEdit();
frm.MdiParent = this.MdiParent;
frm.Show();
}
// Handle the user's decision to delete the selected tool
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvThermometers.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum");
return;
}
Guid? currentEditItem = (Guid?)(dgvThermometers.SelectedRows[0].Cells["ID"].Value);
if (Globals.IsFormOpen(this, "ThermoEdit", currentEditItem))
{
MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
return;
}
EThermo Thermo = new EThermo(currentEditItem);
Thermo.Delete(true);
if (Thermo.ThermoErrMsg != null)
{
MessageBox.Show(Thermo.ThermoErrMsg, "Factotum");
Thermo.ThermoErrMsg = null;
}
}
// The user changed the status filter setting, so update the selector combo.
private void cboStatus_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilters();
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
// ----------------------------------------------------------------------
// Private utilities
// ----------------------------------------------------------------------
// Update the tool selector combo box by filling its items based on current data and filters.
// Then set the currently displayed item to that of the supplied ID.
// If the supplied ID isn't on the list because of the current filter state, just show the
// first item if there is one.
private void UpdateSelector(Guid? id)
{
// Save the sort specs if there are any, so we can re-apply them
SortOrder sortOrder = dgvThermometers.SortOrder;
int sortCol = -1;
if (sortOrder != SortOrder.None)
sortCol = dgvThermometers.SortedColumn.Index;
// Update the grid view selector
DataView dv = EThermo.GetDefaultDataView();
dgvThermometers.DataSource = dv;
ApplyFilters();
// Re-apply the sort specs
if (sortOrder == SortOrder.Ascending)
dgvThermometers.Sort(dgvThermometers.Columns[sortCol], ListSortDirection.Ascending);
else if (sortOrder == SortOrder.Descending)
dgvThermometers.Sort(dgvThermometers.Columns[sortCol], ListSortDirection.Descending);
// Select the current row
SelectGridRow(id);
}
private void CustomizeGrid()
{
// Apply a default sort
dgvThermometers.Sort(dgvThermometers.Columns["ThermoSerialNumber"], ListSortDirection.Ascending);
// Fix up the column headings
dgvThermometers.Columns["ThermoSerialNumber"].HeaderText = "Serial Number";
dgvThermometers.Columns["ThermoKitName"].HeaderText = "Kit";
dgvThermometers.Columns["ThermoIsActive"].HeaderText = "Active";
// Hide some columns
dgvThermometers.Columns["ID"].Visible = false;
dgvThermometers.Columns["ThermoIsActive"].Visible = false;
dgvThermometers.Columns["ThermoIsLclChg"].Visible = false;
dgvThermometers.Columns["ThermoUsedInOutage"].Visible = false;
dgvThermometers.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
}
// Apply the current filters to the DataView. The DataGridView will auto-refresh.
private void ApplyFilters()
{
if (dgvThermometers.DataSource == null) return;
StringBuilder sb = new StringBuilder("ThermoIsActive = ", 255);
sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'");
DataView dv = (DataView)dgvThermometers.DataSource;
dv.RowFilter = sb.ToString();
}
// Select the row with the specified ID if it is currently displayed and scroll to it.
// If the ID is not in the list,
private void SelectGridRow(Guid? id)
{
bool found = false;
int rows = dgvThermometers.Rows.Count;
if (rows == 0) return;
int r = 0;
DataGridViewCell firstCell = dgvThermometers.FirstDisplayedCell;
if (id != null)
{
// Find the row with the specified key id and select it.
for (r = 0; r < rows; r++)
{
if ((Guid?)dgvThermometers.Rows[r].Cells["ID"].Value == id)
{
dgvThermometers.CurrentCell = dgvThermometers[firstCell.ColumnIndex, r];
dgvThermometers.Rows[r].Selected = true;
found = true;
break;
}
}
}
if (found)
{
if (!dgvThermometers.Rows[r].Displayed)
{
// Scroll to the selected row if the ID was in the list.
dgvThermometers.FirstDisplayedScrollingRowIndex = r;
}
}
else
{
// Select the first item
dgvThermometers.CurrentCell = firstCell;
dgvThermometers.Rows[0].Selected = true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XmlDiff;
using System.Collections;
using System.Collections.Generic;
using XmlCoreTest.Common;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class MiscTests : XLinqTestCase
{
public partial class XmlErrata4 : XLinqTestCase
{
// Invalid charcters in names
//[Variation(Desc = "XName with InValid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XElement" })]
//[Variation(Desc = "XName with InValid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XElement" })]
//[Variation(Desc = "XName with InValid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XElement" })]
//[Variation(Desc = "XName with InValid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XElement" })]
//[Variation(Desc = "XName with InValid NCName Characters", Params = new object[] { "InValid", "NCNameChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid NCName Characters", Params = new object[] { "InValid", "NCNameChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid NCName Characters", Params = new object[] { "InValid", "NCNameChar", "XElement" })]
//[Variation(Desc = "XName with InValid NCName Start Characters", Params = new object[] { "InValid", "NCNameStartChar", "XName" })]
//[Variation(Desc = "XAttribute with InValid NCName Start Characters", Params = new object[] { "InValid", "NCNameStartChar", "XAttribute" })]
//[Variation(Desc = "XElement with InValid NCName Start Characters", Params = new object[] { "InValid", "NCNameStartChar", "XElement" })]
// Valid characters in names
//[Variation(Desc = "XName with Valid NCName Characters", Params = new object[] { "Valid", "NCNameChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid NCName Characters", Params = new object[] { "Valid", "NCNameChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid NCName Characters", Params = new object[] { "Valid", "NCNameChar", "XElement" })]
//[Variation(Desc = "XName with Valid NCName Start Characters", Params = new object[] { "Valid", "NCNameStartChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid NCName Start Characters", Params = new object[] { "Valid", "NCNameStartChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid NCName Start Characters", Params = new object[] { "Valid", "NCNameStartChar", "XElement" })]
// This variation runs through about 1000 iterations for each of the above variations
public void varation1()
{
string testType = Variation.Params[0] as string;
string charType = Variation.Params[1] as string;
string nodeType = Variation.Params[2] as string;
int iterations = 0;
foreach (char c in GetRandomCharacters(testType, charType))
{
string name = GetName(charType, c);
if (testType.Equals("Valid"))
RunValidTests(nodeType, name);
else if (testType.Equals("InValid"))
RunInValidTests(nodeType, name);
iterations++;
}
}
// Get valid(Fifth Edition) surrogate characters but since surrogates are not supported in Fourth Edition Xml we still expect an exception.
//[Variation(Desc = "XName with Valid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid Name Surrogate Low Characters", Params = new object[] { "InValid", "NameSurrogateLowChar", "XElement" })]
//[Variation(Desc = "XName with Valid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid Name Surrogate High Characters", Params = new object[] { "InValid", "NameSurrogateHighChar", "XElement" })]
//[Variation(Desc = "XName with Valid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid NameStart Surrogate Low Characters", Params = new object[] { "InValid", "NameStartSurrogateLowChar", "XElement" })]
//[Variation(Desc = "XName with Valid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XName" })]
//[Variation(Desc = "XAttribute with Valid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XAttribute" })]
//[Variation(Desc = "XElement with Valid NameStart Surrogate High Characters", Params = new object[] { "InValid", "NameStartSurrogateHighChar", "XElement" })]
public void varation2()
{
string testType = Variation.Params[0] as string;
string charType = Variation.Params[1] as string;
string nodeType = Variation.Params[2] as string;
int iterations = 0;
foreach (char c in GetRandomCharacters("Valid", charType))
{
string name = GetName(charType, c);
RunInValidTests(nodeType, name);
iterations++;
}
}
//[Variation(Desc = "Xml Version Number Change Test")]
public void varation3()
{
string xml = @"<?xml version='1.9999'?>"
+ "<!-- an implausibly-versioned document -->"
+ "<foo/>";
try
{
XDeclaration xDec = new XDeclaration("1.99999", "utf-16", "false");
XDocument xDoc = XDocument.Load(XmlReader.Create(new StringReader(xml)));
xDoc.Declaration = xDec;
xDoc.Save(new MemoryStream());
}
catch (XmlException)
{
return;
}
throw new TestFailedException("Verion number '1.99999' is invalid exception should have been thrown");
}
/// <summary>
/// Returns a set of random characters depending on the input type.
/// </summary>
/// <param name="testType">Valid or InValid</param>
/// <param name="charType">type from CharType class</param>
/// <returns>IEnumerable of characters</returns>
public IEnumerable GetRandomCharacters(string testType, string charType)
{
string chars = string.Empty;
if (testType.Equals("Valid"))
chars = GetValidCharacters(charType);
else if (testType.Equals("InValid"))
chars = GetInValidCharacters(charType);
int count = chars.Length;
int step = count < 1000 ? 1 : count / 1000;
for (int index = 0; index < count - step; index += step)
{
Random random = new Random(unchecked((int)(DateTime.Now.Ticks)));
int select = random.Next(index, index + step);
yield return chars[select];
}
}
/// <summary>
/// Returns a string of valid characters
/// </summary>
/// <param name="charType">type form CharType class</param>
/// <returns>string of characters</returns>
public string GetValidCharacters(string charType)
{
string chars = string.Empty;
switch (charType)
{
case "NCNameStartChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NCNameStartChar);
break;
case "NCNameChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NCNameChar);
break;
case "NameStartSurrogateHighChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameStartSurrogateHighChar);
break;
case "NameStartSurrogateLowChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameStartSurrogateLowChar);
break;
case "NameSurrogateHighChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameSurrogateHighChar);
break;
case "NameSurrogateLowChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameSurrogateLowChar);
break;
default:
break;
}
return chars;
}
/// <summary>
/// Returns a string of InValid characters
/// </summary>
/// <param name="charType">type form CharType class</param>
/// <returns>string of characters</returns>
public string GetInValidCharacters(string charType)
{
string chars = string.Empty;
switch (charType)
{
case "NCNameStartChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NCNameStartChar);
break;
case "NCNameChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NCNameChar);
break;
case "NameStartSurrogateHighChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameStartSurrogateHighChar);
break;
case "NameStartSurrogateLowChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameStartSurrogateLowChar);
break;
case "NameSurrogateHighChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameSurrogateHighChar);
break;
case "NameSurrogateLowChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameSurrogateLowChar);
break;
default:
break;
}
return chars;
}
/// <summary>
/// Runs test for valid cases
/// </summary>
/// <param name="nodeType">XElement/XAttribute</param>
/// <param name="name">name to be tested</param>
public void RunValidTests(string nodeType, string name)
{
XDocument xDocument = new XDocument();
XElement element = null;
try
{
switch (nodeType)
{
case "XElement":
element = new XElement(name, name);
xDocument.Add(element);
IEnumerable<XNode> nodeList = xDocument.Nodes();
TestLog.Compare(nodeList.Count(), 1, "Failed to create element { " + name + " }");
xDocument.RemoveNodes();
break;
case "XAttribute":
element = new XElement(name, name);
XAttribute attribute = new XAttribute(name, name);
element.Add(attribute);
xDocument.Add(element);
XAttribute x = element.Attribute(name);
TestLog.Compare(x.Name.LocalName, name, "Failed to get the added attribute");
xDocument.RemoveNodes();
break;
case "XName":
XName xName = XName.Get(name, name);
TestLog.Compare(xName.LocalName.Equals(name), "Invalid LocalName");
TestLog.Compare(xName.NamespaceName.Equals(name), "Invalid Namespace Name");
TestLog.Compare(xName.Namespace.NamespaceName.Equals(name), "Invalid Namespace Name");
break;
default:
break;
}
}
catch (Exception e)
{
TestLog.WriteLine(nodeType + "failed to create with a valid name { " + name + " }");
throw new TestFailedException(e.ToString());
}
}
/// <summary>
/// Runs test for InValid cases
/// </summary>
/// <param name="nodeType">XElement/XAttribute</param>
/// <param name="name">name to be tested</param>
public void RunInValidTests(string nodeType, string name)
{
XDocument xDocument = new XDocument();
XElement element = null;
try
{
switch (nodeType)
{
case "XElement":
element = new XElement(name, name);
xDocument.Add(element);
IEnumerable<XNode> nodeList = xDocument.Nodes();
break;
case "XAttribute":
element = new XElement(name, name);
XAttribute attribute = new XAttribute(name, name);
element.Add(attribute);
xDocument.Add(element);
XAttribute x = element.Attribute(name);
break;
case "XName":
XName xName = XName.Get(name, name);
break;
default:
break;
}
}
catch (XmlException)
{
return;
}
catch (ArgumentException)
{
return;
}
// If it gets here then test has failed.
throw new TestFailedException(nodeType + "was created with an Invalid name { " + name + " }");
}
/// <summary>
/// returns a name using the character provided in the appropriate postion
/// </summary>
/// <param name="charType">type from CharType class</param>
/// <param name="c">character to be used in the name</param>
/// <returns>name with the character</returns>
public string GetName(string charType, char c)
{
string name = string.Empty;
switch (charType)
{
case "NCNameStartChar":
name = new string(new char[] { c, 'l', 'e', 'm', 'e', 'n', 't' });
break;
case "NCNameChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', 'n', c });
break;
case "NameStartSurrogateHighChar":
name = new string(new char[] { c, '\udc00', 'e', 'm', 'e', 'n', 't' });
break;
case "NameStartSurrogateLowChar":
name = new string(new char[] { '\udb7f', c, 'e', 'm', 'e', 'n', 't' });
break;
case "NameSurrogateHighChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', c, '\udfff' });
break;
case "NameSurrogateLowChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', '\ud800', c });
break;
default:
break;
}
return name;
}
}
}
}
}
| |
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.EventManagerInvites;
using AllReady.Areas.Admin.Features.Notifications;
using AllReady.Areas.Admin.ViewModels.ManagerInvite;
using AllReady.Features.Events;
using AllReady.Models;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Moq;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class EventManagerInviteControllerTests
{
private const int campaignId = 100;
private const int eventId = 200;
private const int inviteId = 300;
#region Send GET Tests
[Fact]
public async Task SendEventByEventIdQueryWithCorrectEventId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
await sut.Send(eventId);
// Assert
mockMediator.Verify(mock => mock.SendAsync(It.Is<EventManagerInviteQuery>(e => e.EventId == eventId)));
}
[Fact]
public async Task SendReturnsNotFoundResult_WhenNoEventMatchesId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteQuery>())).ReturnsAsync((EventManagerInviteViewModel)null);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(eventId);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task SendReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var viewModel = new EventManagerInviteViewModel()
{
OrganizationId = 1
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteQuery>())).ReturnsAsync(viewModel);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
// Act
IActionResult result = await sut.Send(eventId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var viewModel = new EventManagerInviteViewModel
{
OrganizationId = 1
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteQuery>())).ReturnsAsync(viewModel);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
// Act
IActionResult result = await sut.Send(eventId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendReturnsSendView_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var viewModel = new EventManagerInviteViewModel
{
OrganizationId = 1
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteQuery>())).ReturnsAsync(viewModel);
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser());
var sut = new EventManagerInviteController(mockMediator.Object, userManager.Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Send(eventId);
// Assert
Assert.IsType<ViewResult>(result);
ViewResult view = result as ViewResult;
}
[Fact]
public async Task SendPassesCorrectViewModelToView()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var viewModel = new EventManagerInviteViewModel
{
EventId = eventId,
EventName = "TestEvent",
CampaignId = campaignId,
CampaignName = "TestCampaign",
OrganizationId = 1
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteQuery>())).ReturnsAsync(viewModel);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Send(eventId);
// Assert
ViewResult view = result as ViewResult;
var model = Assert.IsType<EventManagerInviteViewModel>(view.ViewData.Model);
Assert.Equal(eventId, model.EventId);
Assert.Equal(campaignId, model.CampaignId);
Assert.Equal("TestCampaign", model.CampaignName);
Assert.Equal("TestEvent", model.EventName);
}
#endregion
#region Send POST Tests
[Fact]
public async Task SendReturnsBadRequestResult_WhenViewModelIsNull()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(eventId, null);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenViewModelIsNull()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(eventId, null);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateEventManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendReturnsSendView_WhenModelStateIsNotValid()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.ModelState.AddModelError("Error", "Message");
// Act
var result = await sut.Send(eventId, new EventManagerInviteViewModel());
// Assert
var view = Assert.IsType<ViewResult>(result);
Assert.Equal("Send", view.ViewName);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenModelStateIsNotValid()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.ModelState.AddModelError("Error", "Message");
// Act
var result = await sut.Send(eventId, new EventManagerInviteViewModel());
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateEventManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendPostReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
var invite = new EventManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(eventId, invite);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
var invite = new EventManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(eventId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateEventManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendPostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
var invite = new EventManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(eventId, invite);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
var invite = new EventManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(eventId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateEventManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenAnInviteAlreadyExistsForInviteeEmailAddress()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<UserHasEventManagerInviteQuery>())).ReturnsAsync(true);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new EventManagerInviteViewModel
{
EventId = 1,
InviteeEmailAddress = "test@test.com",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(invite.EventId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Never);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsAllreadyManagerForEvent()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<UserHasEventManagerInviteQuery>())).ReturnsAsync(false);
var mockUserManger = UserManagerMockHelper.CreateUserManagerMock();
mockUserManger.Setup(mock => mock.FindByEmailAsync(It.Is<string>(e => e == "test@test.com"))).ReturnsAsync(new ApplicationUser
{
ManagedEvents = new List<EventManager> { new EventManager() { EventId = 1 } },
});
var sut = new EventManagerInviteController(mockMediator.Object, mockUserManger.Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new EventManagerInviteViewModel
{
EventId = 1,
InviteeEmailAddress = "test@test.com",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(invite.EventId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Never);
}
[Fact]
public async Task SendShouldCreateInvite_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var @event = new Event
{
Campaign = new Campaign() { ManagingOrganizationId = 1 }
};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser());
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>());
var sut = new EventManagerInviteController(mockMediator.Object, userManager.Object) { Url = urlHelper.Object };
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new EventManagerInviteViewModel
{
EventId = 1,
InviteeEmailAddress = "test@test.com",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(invite.EventId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Once);
}
#endregion
#region Details Tests
[Fact]
public async Task DetailsSendsEventManagerInviteDetailQueryWithCorrectInviteId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
await sut.Details(inviteId);
// Assert
mockMediator.Verify(mock => mock.SendAsync(It.Is<EventManagerInviteDetailQuery>(c => c.EventManagerInviteId == inviteId)));
}
[Fact]
public async Task DetailsReturnsNotFoundResult_WhenNoInviteMatchesId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task DetailsReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteDetailQuery>()))
.ReturnsAsync(new EventManagerInviteDetailsViewModel { Id = inviteId });
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task DetailsReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new EventManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task DetailsReturnsView_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new EventManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task DetailsPassesCorrectViewModelToView()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new EventManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<EventManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
ViewResult view = result as ViewResult;
var model = Assert.IsType<EventManagerInviteDetailsViewModel>(view.ViewData.Model);
Assert.Equal(inviteId, model.Id);
}
#endregion
}
}
| |
namespace Rhino.Etl.Core.Operations
{
using System;
using System.Collections.Generic;
using Commons;
using Enumerables;
/// <summary>
/// Perform a join between two sources
/// </summary>
public abstract class JoinOperation : AbstractOperation
{
private readonly PartialProcessOperation left = new PartialProcessOperation();
private readonly PartialProcessOperation right = new PartialProcessOperation();
private JoinType jointype;
private string[] leftColumns;
private string[] rightColumns;
private Dictionary<Row, object> rightRowsWereMatched = new Dictionary<Row, object>();
private Dictionary<ObjectArrayKeys, List<Row>> rightRowsByJoinKey = new Dictionary<ObjectArrayKeys, List<Row>>();
/// <summary>
/// Sets the right part of the join
/// </summary>
/// <value>The right.</value>
public JoinOperation Right(IOperation value)
{
right.Register(value);
return this;
}
/// <summary>
/// Sets the left part of the join
/// </summary>
/// <value>The left.</value>
public JoinOperation Left(IOperation value)
{
left.Register(value);
return this;
}
/// <summary>
/// Executes this operation
/// </summary>
/// <param name="ignored">Ignored rows</param>
/// <returns></returns>
public override IEnumerable<Row> Execute(IEnumerable<Row> ignored)
{
PrepareForJoin();
IEnumerable<Row> rightEnumerable = GetRightEnumerable();
IEnumerable<Row> execute = left.Execute(null);
foreach (Row leftRow in new EventRaisingEnumerator(left, execute))
{
ObjectArrayKeys key = leftRow.CreateKey(leftColumns);
List<Row> rightRows;
if (this.rightRowsByJoinKey.TryGetValue(key, out rightRows))
{
foreach (Row rightRow in rightRows)
{
rightRowsWereMatched[rightRow] = null;
yield return MergeRows(leftRow, rightRow);
}
}
else if ((jointype & JoinType.Left) != 0)
{
Row emptyRow = new Row();
yield return MergeRows(leftRow, emptyRow);
}
else
{
LeftOrphanRow(leftRow);
}
}
foreach (Row rightRow in rightEnumerable)
{
if (rightRowsWereMatched.ContainsKey(rightRow))
continue;
Row emptyRow = new Row();
if ((jointype & JoinType.Right) != 0)
yield return MergeRows(emptyRow, rightRow);
else
RightOrphanRow(rightRow);
}
}
private void PrepareForJoin()
{
Initialize();
Guard.Against(left == null, "Left branch of a join cannot be null");
Guard.Against(right == null, "Right branch of a join cannot be null");
SetupJoinConditions();
Guard.Against(leftColumns == null, "You must setup the left columns");
Guard.Against(rightColumns == null, "You must setup the right columns");
}
private IEnumerable<Row> GetRightEnumerable()
{
IEnumerable<Row> rightEnumerable = new CachingEnumerable<Row>(
new EventRaisingEnumerator(right, right.Execute(null))
);
foreach (Row row in rightEnumerable)
{
ObjectArrayKeys key = row.CreateKey(rightColumns);
List<Row> rowsForKey;
if (this.rightRowsByJoinKey.TryGetValue(key, out rowsForKey) == false)
{
this.rightRowsByJoinKey[key] = rowsForKey = new List<Row>();
}
rowsForKey.Add(row);
}
return rightEnumerable;
}
/// <summary>
/// Called when a row on the right side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
protected virtual void RightOrphanRow(Row row)
{
}
/// <summary>
/// Called when a row on the left side was filtered by
/// the join condition, allow a derived class to perform
/// logic associated to that, such as logging
/// </summary>
/// <param name="row">The row.</param>
protected virtual void LeftOrphanRow(Row row)
{
}
/// <summary>
/// Merges the two rows into a single row
/// </summary>
/// <param name="leftRow">The left row.</param>
/// <param name="rightRow">The right row.</param>
/// <returns></returns>
protected abstract Row MergeRows(Row leftRow, Row rightRow);
/// <summary>
/// Initializes this instance.
/// </summary>
protected virtual void Initialize()
{
}
/// <summary>
/// Setups the join conditions.
/// </summary>
protected abstract void SetupJoinConditions();
/// <summary>
/// Create an inner join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder InnerJoin
{
get { return new JoinBuilder(this, JoinType.Inner); }
}
/// <summary>
/// Create a left outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder LeftJoin
{
get { return new JoinBuilder(this, JoinType.Left); }
}
/// <summary>
/// Create a right outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder RightJoin
{
get { return new JoinBuilder(this, JoinType.Right); }
}
/// <summary>
/// Create a full outer join
/// </summary>
/// <value>The inner.</value>
protected JoinBuilder FullOuterJoin
{
get { return new JoinBuilder(this, JoinType.Full); }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
left.Dispose();
right.Dispose();
}
/// <summary>
/// Initializes this instance
/// </summary>
/// <param name="pipelineExecuter">The current pipeline executer.</param>
public override void PrepareForExecution(IPipelineExecuter pipelineExecuter)
{
left.PrepareForExecution(pipelineExecuter);
right.PrepareForExecution(pipelineExecuter);
}
/// <summary>
/// Gets all errors that occured when running this operation
/// </summary>
/// <returns></returns>
public override IEnumerable<Exception> GetAllErrors()
{
foreach (Exception error in left.GetAllErrors())
{
yield return error;
}
foreach (Exception error in right.GetAllErrors())
{
yield return error;
}
}
/// <summary>
/// Fluent interface to create joins
/// </summary>
public class JoinBuilder
{
private readonly JoinOperation parent;
/// <summary>
/// Initializes a new instance of the <see cref="JoinBuilder"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="joinType">Type of the join.</param>
public JoinBuilder(JoinOperation parent, JoinType joinType)
{
this.parent = parent;
parent.jointype = joinType;
}
/// <summary>
/// Setup the left side of the join
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public JoinBuilder Left(params string[] columns)
{
parent.leftColumns = columns;
return this;
}
/// <summary>
/// Setup the right side of the join
/// </summary>
/// <param name="columns">The columns.</param>
/// <returns></returns>
public JoinBuilder Right(params string[] columns)
{
parent.rightColumns = columns;
return this;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// load gui used to display various metric outputs
exec("~/art/gui/FrameOverlayGui.gui");
// Note: To implement your own metrics overlay
// just add a function with a name in the form
// XXXXMetricsCallback which can be enabled via
// metrics( XXXX )
function fpsMetricsCallback()
{
return " | FPS |" @
" " @ $fps::real @
" max: " @ $fps::realMax @
" min: " @ $fps::realMin @
" mspf: " @ 1000 / $fps::real;
}
function gfxMetricsCallback()
{
return " | GFX |" @
" PolyCount: " @ $GFXDeviceStatistics::polyCount @
" DrawCalls: " @ $GFXDeviceStatistics::drawCalls @
" RTChanges: " @ $GFXDeviceStatistics::renderTargetChanges;
}
function terrainMetricsCallback()
{
return " | Terrain |" @
" Cells: " @ $TerrainBlock::cellsRendered @
" Override Cells: " @ $TerrainBlock::overrideCells @
" DrawCalls: " @ $TerrainBlock::drawCalls;
}
function netMetricsCallback()
{
return " | Net |" @
" BitsSent: " @ $Stats::netBitsSent @
" BitsRcvd: " @ $Stats::netBitsReceived @
" GhostUpd: " @ $Stats::netGhostUpdates;
}
function groundCoverMetricsCallback()
{
return " | GroundCover |" @
" Cells: " @ $GroundCover::renderedCells @
" Billboards: " @ $GroundCover::renderedBillboards @
" Batches: " @ $GroundCover::renderedBatches @
" Shapes: " @ $GroundCover::renderedShapes;
}
function forestMetricsCallback()
{
return " | Forest |" @
" Cells: " @ $Forest::totalCells @
" Cells Meshed: " @ $Forest::cellsRendered @
" Cells Billboarded: " @ $Forest::cellsBatched @
" Meshes: " @ $Forest::cellItemsRendered @
" Billboards: " @ $Forest::cellItemsBatched;
}
function sfxMetricsCallback()
{
return " | SFX |" @
" Sounds: " @ $SFX::numSounds @
" Lists: " @ ( $SFX::numSources - $SFX::numSounds - $SFX::Device::fmodNumEventSource ) @
" Events: " @ $SFX::fmodNumEventSources @
" Playing: " @ $SFX::numPlaying @
" Culled: " @ $SFX::numCulled @
" Voices: " @ $SFX::numVoices @
" Buffers: " @ $SFX::Device::numBuffers @
" Memory: " @ ( $SFX::Device::numBufferBytes / 1024.0 / 1024.0 ) @ " MB" @
" Time/S: " @ $SFX::sourceUpdateTime @
" Time/P: " @ $SFX::parameterUpdateTime @
" Time/A: " @ $SFX::ambientUpdateTime;
}
function sfxSourcesMetricsCallback()
{
return sfxDumpSourcesToString();
}
function sfxStatesMetricsCallback()
{
return " | SFXStates |" @ sfxGetActiveStates();
}
function timeMetricsCallback()
{
return " | Time |" @
" Sim Time: " @ getSimTime() @
" Mod: " @ getSimTime() % 32;
}
function reflectMetricsCallback()
{
return " | REFLECT |" @
" Objects: " @ $Reflect::numObjects @
" Visible: " @ $Reflect::numVisible @
" Occluded: " @ $Reflect::numOccluded @
" Updated: " @ $Reflect::numUpdated @
" Elapsed: " @ $Reflect::elapsed NL
" Allocated: " @ $Reflect::renderTargetsAllocated @
" Pooled: " @ $Reflect::poolSize NL
" " @ getWord( $Reflect::textureStats, 1 ) TAB
" " @ getWord( $Reflect::textureStats, 2 ) @ "MB" TAB
" " @ getWord( $Reflect::textureStats, 0 );
}
function decalMetricsCallback()
{
return " | DECAL |" @
" Batches: " @ $Decal::Batches @
" Buffers: " @ $Decal::Buffers @
" DecalsRendered: " @ $Decal::DecalsRendered;
}
function renderMetricsCallback()
{
return " | Render |" @
" Mesh: " @ $RenderMetrics::RIT_Mesh @
" MeshDL: " @ $RenderMetrics::RIT_MeshDynamicLighting @
" Shadow: " @ $RenderMetrics::RIT_Shadow @
" Sky: " @ $RenderMetrics::RIT_Sky @
" Obj: " @ $RenderMetrics::RIT_Object @
" ObjT: " @ $RenderMetrics::RIT_ObjectTranslucent @
" Decal: " @ $RenderMetrics::RIT_Decal @
" Water: " @ $RenderMetrics::RIT_Water @
" Foliage: " @ $RenderMetrics::RIT_Foliage @
" Trans: " @ $RenderMetris::RIT_Translucent @
" Custom: " @ $RenderMetrics::RIT_Custom;
}
function shadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $ShadowStats::activeMaps @
" Updated: " @ $ShadowStats::updatedMaps @
" PolyCount: " @ $ShadowStats::polyCount @
" DrawCalls: " @ $ShadowStats::drawCalls @
" RTChanges: " @ $ShadowStats::rtChanges @
" PoolTexCount: " @ $ShadowStats::poolTexCount @
" PoolTexMB: " @ $ShadowStats::poolTexMemory @ "MB";
}
function basicShadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $BasicLightManagerStats::activePlugins @
" Updated: " @ $BasicLightManagerStats::shadowsUpdated @
" Elapsed Ms: " @ $BasicLightManagerStats::elapsedUpdateMs;
}
function lightMetricsCallback()
{
return " | Deferred Lights |" @
" Active: " @ $lightMetrics::activeLights @
" Culled: " @ $lightMetrics::culledLights;
}
function particleMetricsCallback()
{
return " | Particles |" @
" # Simulated " @ $particle::numSimulated;
}
function partMetricsCallback()
{
return particleMetricsCallback();
}
// alias
function audioMetricsCallback()
{
return sfxMetricsCallback();
}
// alias
function videoMetricsCallback()
{
return gfxMetricsCallback();
}
// Add a metrics HUD. %expr can be a vector of names where each element
// must have a corresponding '<name>MetricsCallback()' function defined
// that will be called on each update of the GUI control. The results
// of each function are stringed together.
//
// Example: metrics( "fps gfx" );
function metrics( %expr )
{
%metricsExpr = "";
if( %expr !$= "" )
{
for( %i = 0;; %i ++ )
{
%name = getWord( %expr, %i );
if( %name $= "" )
break;
else
{
%cb = %name @ "MetricsCallback";
if( !isFunction( %cb ) )
error( "metrics - undefined callback: " @ %cb );
else
{
%cb = %cb @ "()";
if( %i > 0 )
%metricsExpr = %metricsExpr @ " NL ";
%metricsExpr = %metricsExpr @ %cb;
}
}
}
if( %metricsExpr !$= "" )
%metricsExpr = %metricsExpr @ " @ \" \"";
}
if( %metricsExpr !$= "" )
{
Canvas.pushDialog( FrameOverlayGui, 1000 );
TextOverlayControl.setValue( %metricsExpr );
}
else
Canvas.popDialog(FrameOverlayGui);
}
| |
using Signum.Entities.Mailing;
using Signum.Entities.Isolation;
using Signum.Entities.Templating;
using Signum.Engine.UserAssets;
using Signum.Engine.Authorization;
namespace Signum.Engine.Mailing;
public interface IEmailModel
{
ModifiableEntity UntypedEntity { get; }
List<EmailOwnerRecipientData> GetRecipients();
List<Filter> GetFilters(QueryDescription qd);
Pagination GetPagination();
List<Order> GetOrders(QueryDescription queryDescription);
}
public class EmailOwnerRecipientData
{
public EmailOwnerRecipientData(EmailOwnerData ownerData)
{
this.OwnerData = ownerData;
}
public readonly EmailOwnerData OwnerData;
public EmailRecipientKind Kind;
}
public abstract class EmailModel<T> : IEmailModel
where T : ModifiableEntity
{
public EmailModel(T entity)
{
this.Entity = entity;
}
public T Entity { get; set; }
ModifiableEntity IEmailModel.UntypedEntity
{
get { return Entity; }
}
public virtual List<EmailOwnerRecipientData> GetRecipients()
{
return new List<EmailOwnerRecipientData>();
}
protected static List<EmailOwnerRecipientData> SendTo(EmailOwnerData ownerData)
{
return new List<EmailOwnerRecipientData> { new EmailOwnerRecipientData(ownerData) };
}
public virtual List<Filter> GetFilters(QueryDescription qd)
{
var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value;
if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T)))
return new List<Filter>
{
new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, ((Entity)(ModifiableEntity)Entity).ToLite())
};
throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}");
}
public virtual List<Order> GetOrders(QueryDescription queryDescription)
{
return new List<Order>();
}
public virtual Pagination GetPagination()
{
return new Pagination.All();
}
}
public class MultiEntityEmail : EmailModel<MultiEntityModel>
{
public MultiEntityEmail(MultiEntityModel entity) : base(entity)
{
}
public override List<Filter> GetFilters(QueryDescription qd)
{
return new List<Filter>
{
new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.IsIn, this.Entity.Entities.ToList())
};
}
}
public class QueryEmail : EmailModel<QueryModel>
{
public QueryEmail(QueryModel entity) : base(entity)
{
}
public override List<Filter> GetFilters(QueryDescription qd)
{
return this.Entity.Filters;
}
public override Pagination GetPagination()
{
return this.Entity.Pagination;
}
public override List<Order> GetOrders(QueryDescription queryDescription)
{
return this.Entity.Orders;
}
}
public static class EmailModelLogic
{
class EmailModelInfo
{
public object QueryName;
public Func<EmailTemplateEntity>? DefaultTemplateConstructor;
public EmailModelInfo(object queryName)
{
QueryName = queryName;
}
}
static ResetLazy<Dictionary<Lite<EmailModelEntity>, List<EmailTemplateEntity>>> EmailModelToTemplates = null!;
static Dictionary<Type, EmailModelInfo> registeredModels = new Dictionary<Type, EmailModelInfo>();
static ResetLazy<Dictionary<Type, EmailModelEntity>> typeToEntity = null!;
static ResetLazy<Dictionary<EmailModelEntity, Type>> entityToType = null!;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Schema.Generating += Schema_Generating;
sb.Schema.Synchronizing += Schema_Synchronizing;
sb.Include<EmailModelEntity>()
.WithQuery(() => se => new
{
Entity = se,
se.Id,
se.FullClassName,
});
UserAssetsImporter.Register<EmailTemplateEntity>("EmailTemplate", EmailTemplateOperation.Save);
new Graph<EmailTemplateEntity>.ConstructFrom<EmailModelEntity>(EmailTemplateOperation.CreateEmailTemplateFromModel)
{
Construct = (se, _) => CreateDefaultTemplateInternal(se)
}.Register();
EmailModelToTemplates = sb.GlobalLazy(() => (
from et in Database.Query<EmailTemplateEntity>()
where et.Model != null
select new { se = et.Model, et })
.GroupToDictionary(pair => pair.se!.ToLite(), pair => pair.et!), /*CSBUG*/
new InvalidateWith(typeof(EmailModelEntity), typeof(EmailTemplateEntity)));
typeToEntity = sb.GlobalLazy(() =>
{
var dbModels = Database.RetrieveAll<EmailModelEntity>();
return EnumerableExtensions.JoinRelaxed(
dbModels,
registeredModels.Keys,
entity => entity.FullClassName,
type => type.FullName!,
(entity, type) => KeyValuePair.Create(type, entity),
"caching " + nameof(EmailModelEntity))
.ToDictionary();
}, new InvalidateWith(typeof(EmailModelEntity)));
sb.Schema.Initializing += () => typeToEntity.Load();
entityToType = sb.GlobalLazy(() => typeToEntity.Value.Inverse(),
new InvalidateWith(typeof(EmailModelEntity)));
}
}
static readonly string EmailModelReplacementKey = "EmailModel";
static SqlPreCommand? Schema_Synchronizing(Replacements replacements)
{
Table table = Schema.Current.Table<EmailModelEntity>();
Dictionary<string, EmailModelEntity> should = GenerateEmailModelEntities().ToDictionary(s => s.FullClassName);
Dictionary<string, EmailModelEntity> old = Administrator.TryRetrieveAll<EmailModelEntity>(replacements).ToDictionary(c =>
c.FullClassName);
replacements.AskForReplacements(
old.Keys.ToHashSet(),
should.Keys.ToHashSet(), EmailModelReplacementKey);
Dictionary<string, EmailModelEntity> current = replacements.ApplyReplacementsToOld(old, EmailModelReplacementKey);
using (replacements.WithReplacedDatabaseName())
return Synchronizer.SynchronizeScript(Spacing.Double, should, current,
createNew: (tn, s) => table.InsertSqlSync(s),
removeOld: (tn, c) => table.DeleteSqlSync(c, se => se.FullClassName == c.FullClassName),
mergeBoth: (tn, s, c) =>
{
var oldClassName = c.FullClassName;
c.FullClassName = s.FullClassName;
return table.UpdateSqlSync(c, se => se.FullClassName == oldClassName);
});
}
public static void RegisterEmailModel<T>(Func<EmailTemplateEntity>? defaultTemplateConstructor, object? queryName = null)
where T : IEmailModel
{
RegisterEmailModel(typeof(T), defaultTemplateConstructor, queryName);
}
public static void RegisterEmailModel(Type model, Func<EmailTemplateEntity>? defaultTemplateConstructor, object? queryName = null)
{
registeredModels[model] = new EmailModelInfo(queryName ?? GetEntityType(model))
{
DefaultTemplateConstructor = defaultTemplateConstructor,
};
}
public static Type GetEntityType(Type model)
{
var baseType = model.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(EmailModel<>)));
if (baseType != null)
{
return baseType.GetGenericArguments()[0];
}
throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterEmailModel".FormatWith(model.TypeName()));
}
internal static List<EmailModelEntity> GenerateEmailModelEntities()
{
var list = (from type in registeredModels.Keys
select new EmailModelEntity
{
FullClassName = type.FullName!
}).ToList();
return list;
}
static SqlPreCommand? Schema_Generating()
{
Table table = Schema.Current.Table<EmailModelEntity>();
return (from ei in GenerateEmailModelEntities()
select table.InsertSqlSync(ei)).Combine(Spacing.Simple);
}
public static EmailModelEntity GetEmailModelEntity<T>() where T : IEmailModel
{
return ToEmailModelEntity(typeof(T));
}
public static EmailModelEntity GetEmailModelEntity(string fullClassName)
{
return typeToEntity.Value.Where(x => x.Key.FullName == fullClassName).FirstOrDefault().Value;
}
public static EmailModelEntity ToEmailModelEntity(Type emailModelType)
{
return typeToEntity.Value.GetOrThrow(emailModelType, "The EmailModel {0} was not registered");
}
public static Type ToType(this EmailModelEntity modelEntity)
{
return entityToType.Value.GetOrThrow(modelEntity, "The EmailModel {0} was not registered");
}
public static IEnumerable<EmailMessageEntity> CreateEmailMessage(this IEmailModel emailModel)
{
if (emailModel.UntypedEntity == null)
throw new InvalidOperationException("Entity property not set on EmailModel");
using (IsolationEntity.Override((emailModel.UntypedEntity as Entity)?.TryIsolation()))
{
var emailModelEntity = ToEmailModelEntity(emailModel.GetType());
var template = GetCurrentTemplate(emailModelEntity, emailModel.UntypedEntity as Entity);
return EmailTemplateLogic.CreateEmailMessage(template.ToLite(), model: emailModel);
}
}
public static EmailTemplateEntity GetCurrentTemplate<M>() where M : IEmailModel
{
var emailModelEntity = ToEmailModelEntity(typeof(M));
return GetCurrentTemplate(emailModelEntity, null);
}
private static EmailTemplateEntity GetCurrentTemplate(EmailModelEntity emailModelEntity, Entity? entity)
{
var isAllowed = Schema.Current.GetInMemoryFilter<EmailTemplateEntity>(userInterface: false);
var templates = EmailModelToTemplates.Value.TryGetC(emailModelEntity.ToLite()).EmptyIfNull();
templates = templates.Where(isAllowed);
if (templates.IsNullOrEmpty())
return CreateDefaultEmailTemplate(emailModelEntity);
return templates.Where(t => t.IsApplicable(entity)).SingleEx(() => "Active EmailTemplates for EmailModel {0}".FormatWith(emailModelEntity));
}
public static EmailTemplateEntity CreateDefaultEmailTemplate(EmailModelEntity emailModelEntity)
{
using (AuthLogic.Disable())
using (OperationLogic.AllowSave<EmailTemplateEntity>())
using (var tr = Transaction.ForceNew())
{
var template = CreateDefaultTemplateInternal(emailModelEntity);
template.Save();
return tr.Commit(template);
}
}
internal static EmailTemplateEntity CreateDefaultTemplateInternal(EmailModelEntity emailModel)
{
EmailModelInfo info = registeredModels.GetOrThrow(entityToType.Value.GetOrThrow(emailModel));
if (info.DefaultTemplateConstructor == null)
throw new InvalidOperationException($"No EmailTemplate for {emailModel} found and DefaultTemplateConstructor = null");
EmailTemplateEntity template = info.DefaultTemplateConstructor.Invoke();
if (template.MasterTemplate == null)
template.MasterTemplate = EmailMasterTemplateLogic.GetDefaultMasterTemplate();
if (template.Name == null)
template.Name = emailModel.FullClassName;
template.Model = emailModel;
template.Query = QueryLogic.GetQueryEntity(info.QueryName);
template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName));
return template;
}
public static void GenerateAllTemplates()
{
foreach (var emailModelType in registeredModels.Keys)
{
var emailModelEntity = ToEmailModelEntity(emailModelType);
var template = Database.Query<EmailTemplateEntity>().SingleOrDefaultEx(t => t.Model.Is(emailModelEntity));
if (template == null)
{
template = CreateDefaultTemplateInternal(emailModelEntity);
using (ExecutionMode.Global())
using (OperationLogic.AllowSave<EmailTemplateEntity>())
template.Save();
}
}
}
public static bool RequiresExtraParameters(EmailModelEntity emailModelEntity)
{
return GetEntityConstructor(entityToType.Value.GetOrThrow(emailModelEntity)) == null;
}
internal static bool HasDefaultTemplateConstructor(EmailModelEntity emailModelEntity)
{
EmailModelInfo info = registeredModels.GetOrThrow(emailModelEntity.ToType());
return info.DefaultTemplateConstructor != null;
}
public static IEmailModel CreateModel(EmailModelEntity model, ModifiableEntity? entity)
{
return (IEmailModel)EmailModelLogic.GetEntityConstructor(model.ToType())!.Invoke(new[] { entity });
}
public static ConstructorInfo? GetEntityConstructor(Type emailModel)
{
var entityType = GetEntityType(emailModel);
return (from ci in emailModel.GetConstructors()
let pi = ci.GetParameters().Only()
where pi != null && pi.ParameterType == entityType
select ci).SingleOrDefaultEx();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Part of ComEventHelpers APIs which allow binding
/// managed delegates to COM's connection point based events.
/// </summary>
internal class ComEventsSink : IDispatch, ICustomQueryInterface
{
private Guid _iidSourceItf;
private ComTypes.IConnectionPoint? _connectionPoint;
private int _cookie;
private ComEventsMethod? _methods;
private ComEventsSink? _next;
public ComEventsSink(object rcw, Guid iid)
{
_iidSourceItf = iid;
this.Advise(rcw);
}
public static ComEventsSink? Find(ComEventsSink? sinks, ref Guid iid)
{
ComEventsSink? sink = sinks;
while (sink != null && sink._iidSourceItf != iid)
{
sink = sink._next;
}
return sink;
}
public static ComEventsSink Add(ComEventsSink? sinks, ComEventsSink sink)
{
sink._next = sinks;
return sink;
}
public static ComEventsSink? RemoveAll(ComEventsSink? sinks)
{
while (sinks != null)
{
sinks.Unadvise();
sinks = sinks._next;
}
return null;
}
public static ComEventsSink? Remove(ComEventsSink sinks, ComEventsSink sink)
{
Debug.Assert(sinks != null, "removing event sink from empty sinks collection");
Debug.Assert(sink != null, "specify event sink is null");
ComEventsSink? toReturn = sinks;
if (sink == sinks)
{
toReturn = sinks._next;
}
else
{
ComEventsSink? current = sinks;
while (current != null && current._next != sink)
{
current = current._next;
}
if (current != null)
{
current._next = sink._next;
}
}
sink.Unadvise();
return toReturn;
}
public ComEventsMethod? RemoveMethod(ComEventsMethod method)
{
_methods = ComEventsMethod.Remove(_methods!, method);
return _methods;
}
public ComEventsMethod? FindMethod(int dispid)
{
return ComEventsMethod.Find(_methods, dispid);
}
public ComEventsMethod AddMethod(int dispid)
{
ComEventsMethod method = new ComEventsMethod(dispid);
_methods = ComEventsMethod.Add(_methods, method);
return method;
}
int IDispatch.GetTypeInfoCount()
{
return 0;
}
ComTypes.ITypeInfo IDispatch.GetTypeInfo(int iTInfo, int lcid)
{
throw new NotImplementedException();
}
void IDispatch.GetIDsOfNames(ref Guid iid, string[] names, int cNames, int lcid, int[] rgDispId)
{
throw new NotImplementedException();
}
private const VarEnum VT_BYREF_VARIANT = VarEnum.VT_BYREF | VarEnum.VT_VARIANT;
private const VarEnum VT_TYPEMASK = (VarEnum)0x0fff;
private const VarEnum VT_BYREF_TYPEMASK = VT_TYPEMASK | VarEnum.VT_BYREF;
private static unsafe ref Variant GetVariant(ref Variant pSrc)
{
if (pSrc.VariantType == VT_BYREF_VARIANT)
{
// For VB6 compatibility reasons, if the VARIANT is a VT_BYREF | VT_VARIANT that
// contains another VARIANT with VT_BYREF | VT_VARIANT, then we need to extract the
// inner VARIANT and use it instead of the outer one. Note that if the inner VARIANT
// is VT_BYREF | VT_VARIANT | VT_ARRAY, it will pass the below test too.
Span<Variant> pByRefVariant = new Span<Variant>(pSrc.AsByRefVariant.ToPointer(), 1);
if ((pByRefVariant[0].VariantType & VT_BYREF_TYPEMASK) == VT_BYREF_VARIANT)
{
return ref pByRefVariant[0];
}
}
return ref pSrc;
}
unsafe void IDispatch.Invoke(
int dispid,
ref Guid riid,
int lcid,
InvokeFlags wFlags,
ref ComTypes.DISPPARAMS pDispParams,
IntPtr pVarResult,
IntPtr pExcepInfo,
IntPtr puArgErr)
{
ComEventsMethod? method = FindMethod(dispid);
if (method == null)
{
return;
}
// notice the unsafe pointers we are using. This is to avoid unnecessary
// arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling
const int InvalidIdx = -1;
object[] args = new object[pDispParams.cArgs];
int[] byrefsMap = new int[pDispParams.cArgs];
bool[] usedArgs = new bool[pDispParams.cArgs];
int totalCount = pDispParams.cNamedArgs + pDispParams.cArgs;
var vars = new Span<Variant>(pDispParams.rgvarg.ToPointer(), totalCount);
var namedArgs = new Span<int>(pDispParams.rgdispidNamedArgs.ToPointer(), totalCount);
// copy the named args (positional) as specified
int i;
int pos;
for (i = 0; i < pDispParams.cNamedArgs; i++)
{
pos = namedArgs[i];
ref Variant pvar = ref GetVariant(ref vars[i]);
args[pos] = pvar.ToObject()!;
usedArgs[pos] = true;
int byrefIdx = InvalidIdx;
if (pvar.IsByRef)
{
byrefIdx = i;
}
byrefsMap[pos] = byrefIdx;
}
// copy the rest of the arguments in the reverse order
pos = 0;
for (; i < pDispParams.cArgs; i++)
{
// find the next unassigned argument
while (usedArgs[pos])
{
pos++;
}
ref Variant pvar = ref GetVariant(ref vars[pDispParams.cArgs - 1 - i]);
args[pos] = pvar.ToObject()!;
int byrefIdx = InvalidIdx;
if (pvar.IsByRef)
{
byrefIdx = pDispParams.cArgs - 1 - i;
}
byrefsMap[pos] = byrefIdx;
pos++;
}
// Do the actual delegate invocation
object? result = method.Invoke(args);
// convert result to VARIANT
if (pVarResult != IntPtr.Zero)
{
Marshal.GetNativeVariantForObject(result, pVarResult);
}
// Now we need to marshal all the byrefs back
for (i = 0; i < pDispParams.cArgs; i++)
{
int idxToPos = byrefsMap[i];
if (idxToPos == InvalidIdx)
{
continue;
}
ref Variant pvar = ref GetVariant(ref vars[idxToPos]);
pvar.CopyFromIndirect(args[i]);
}
}
CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv)
{
ppv = IntPtr.Zero;
if (iid == _iidSourceItf || iid == typeof(IDispatch).GUID)
{
ppv = Marshal.GetComInterfaceForObject(this, typeof(IDispatch), CustomQueryInterfaceMode.Ignore);
return CustomQueryInterfaceResult.Handled;
}
return CustomQueryInterfaceResult.NotHandled;
}
private void Advise(object rcw)
{
Debug.Assert(_connectionPoint == null, "comevent sink is already advised");
ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw;
ComTypes.IConnectionPoint cp;
cpc.FindConnectionPoint(ref _iidSourceItf, out cp!);
object sinkObject = this;
cp.Advise(sinkObject, out _cookie);
_connectionPoint = cp;
}
private void Unadvise()
{
Debug.Assert(_connectionPoint != null, "can not unadvise from empty connection point");
try
{
_connectionPoint.Unadvise(_cookie);
Marshal.ReleaseComObject(_connectionPoint);
}
catch
{
// swallow all exceptions on unadvise
// the host may not be available at this point
}
finally
{
_connectionPoint = null;
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class ParameterDeclaration : Node, INodeWithAttributes
{
protected string _name;
protected TypeReference _type;
protected ParameterModifiers _modifiers;
protected AttributeCollection _attributes;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ParameterDeclaration CloneNode()
{
return (ParameterDeclaration)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ParameterDeclaration CleanClone()
{
return (ParameterDeclaration)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.ParameterDeclaration; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnParameterDeclaration(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( ParameterDeclaration)node;
if (_name != other._name) return NoMatch("ParameterDeclaration._name");
if (!Node.Matches(_type, other._type)) return NoMatch("ParameterDeclaration._type");
if (_modifiers != other._modifiers) return NoMatch("ParameterDeclaration._modifiers");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("ParameterDeclaration._attributes");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_type == existing)
{
this.Type = (TypeReference)newNode;
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
ParameterDeclaration clone = new ParameterDeclaration();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._name = _name;
if (null != _type)
{
clone._type = _type.Clone() as TypeReference;
clone._type.InitializeParent(clone);
}
clone._modifiers = _modifiers;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _type)
{
_type.ClearTypeSystemBindings();
}
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlAttribute]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public string Name
{
get { return _name; }
set { _name = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference Type
{
get { return _type; }
set
{
if (_type != value)
{
_type = value;
if (null != _type)
{
_type.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlAttribute,
System.ComponentModel.DefaultValue(ParameterModifiers.None)]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterModifiers Modifiers
{
get { return _modifiers; }
set { _modifiers = value; }
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Attribute))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public AttributeCollection Attributes
{
get { return _attributes ?? (_attributes = new AttributeCollection(this)); }
set
{
if (_attributes != value)
{
_attributes = value;
if (null != _attributes)
{
_attributes.InitializeParent(this);
}
}
}
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Xamarin.Forms;
namespace ArcGISRuntime.Samples.StatsQueryGroupAndSort
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Statistical query group and sort",
category: "Data",
description: "Query a feature table for statistics, grouping and sorting by different fields.",
instructions: "The sample will start with some default options selected. You can immediately tap the \"Get Statistics\" button to see the results for these options. There are several ways to customize your queries:",
tags: new[] { "correlation", "data", "fields", "filter", "group", "sort", "statistics", "table" })]
public partial class StatsQueryGroupAndSort : ContentPage
{
// URI for the US states map service
private Uri _usStatesServiceUri = new Uri("https://services.arcgis.com/jIL9msH9OI208GCb/arcgis/rest/services/Counties_Obesity_Inactivity_Diabetes_2013/FeatureServer/0");
// US states feature table
private FeatureTable _usStatesTable;
// Collection of (user-defined) statistics to use in the query
private ObservableCollection<StatisticDefinition> _statDefinitions = new ObservableCollection<StatisticDefinition>();
// Selected fields for grouping results
private List<string> _groupByFields = new List<string>();
// Collection to hold fields to order results by
private ObservableCollection<OrderFieldOption> _orderByFields = new ObservableCollection<OrderFieldOption>();
public StatsQueryGroupAndSort()
{
InitializeComponent();
// Initialize the US states feature table and populate UI controls
Initialize();
}
private async void Initialize()
{
// Create the US states feature table
_usStatesTable = new ServiceFeatureTable(_usStatesServiceUri);
try
{
// Load the table
await _usStatesTable.LoadAsync();
// Fill the fields combo and "group by" list with field names from the table
List<string> fieldNames = _usStatesTable.Fields.Select(field => field.Name).ToList();
FieldsComboBox.ItemsSource = fieldNames;
GroupFieldsListBox.ItemsSource = _usStatesTable.Fields;
// Set the (initially empty) collection of fields as the "order by" fields list data source
OrderByFieldsListBox.ItemsSource = _orderByFields;
// Fill the statistics type combo with values from the StatisticType enum
StatTypeComboBox.ItemsSource = Enum.GetValues(typeof(StatisticType));
// Set the (initially empty) collection of statistic definitions as the statistics list box data source
StatFieldsListBox.ItemsSource = _statDefinitions;
}
catch (Exception e)
{
await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
}
}
// Execute a statistical query using the parameters defined by the user and display the results
private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
{
// Verify that there is at least one statistic definition
if (!_statDefinitions.Any())
{
await Application.Current.MainPage.DisplayAlert("Please define at least one statistic for the query.", "Statistical Query","OK");
return;
}
// Create the statistics query parameters, pass in the list of statistic definitions
StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(_statDefinitions);
// Specify the group fields (if any)
foreach (string groupField in _groupByFields)
{
statQueryParams.GroupByFieldNames.Add(groupField);
}
// Specify the fields to order by (if any)
foreach (OrderFieldOption orderBy in _orderByFields)
{
statQueryParams.OrderByFields.Add(orderBy.OrderInfo);
}
// Ignore counties with missing data
statQueryParams.WhereClause = "\"State\" IS NOT NULL";
try
{
// Execute the statistical query with these parameters and await the results
StatisticsQueryResult statQueryResult = await _usStatesTable.QueryStatisticsAsync(statQueryParams);
// Get results formatted as a lookup (list of group names and their associated dictionary of results)
ILookup<string,IReadOnlyDictionary<string,object>> resultsLookup = statQueryResult.ToLookup(result => string.Join(", ", result.Group.Values), result => result.Statistics);
// Loop through the formatted results and build a list of classes to display as grouped results in the list view
ObservableCollection<ResultGroup> resultsGroupCollection = new ObservableCollection<ResultGroup>();
foreach (IGrouping<string,IReadOnlyDictionary<string,object>> group in resultsLookup)
{
// Create a new group
ResultGroup resultGroup = new ResultGroup() { GroupName = group.Key };
// Loop through all the results for this group and add them to the collection
foreach (IReadOnlyDictionary<string,object> resultSet in group)
{
foreach(KeyValuePair<string,object> result in resultSet)
{
resultGroup.Add(new StatisticResult { FieldName = result.Key, StatValue = result.Value});
}
}
// Add the group of results to the collection
resultsGroupCollection.Add(resultGroup);
}
// Apply the results to the list view data source and show the results grid
StatResultsList.ItemsSource = resultsGroupCollection;
ResultsGrid.IsVisible = true;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
}
}
// Handle when the switch for a "group by" field is toggled on or off by adding or removing the field from the collection
private void GroupFieldCheckChanged(object sender, EventArgs e)
{
// Get the check box that raised the event (group field)
Switch groupFieldCheckBox = (Switch)sender;
// Get the field name
string fieldName = groupFieldCheckBox.BindingContext.ToString();
// See if the field is being added or removed from the "group by" list
bool fieldAdded = groupFieldCheckBox.IsToggled;
// See if the field already exists in the "group by" list
bool fieldIsInList = _groupByFields.Contains(fieldName);
// If the field is being added, and is NOT in the list, add it ...
if (fieldAdded && !fieldIsInList)
{
_groupByFields.Add(fieldName);
// Also add it to the "order by" list
OrderBy orderBy = new OrderBy(fieldName, SortOrder.Ascending);
OrderFieldOption orderOption = new OrderFieldOption(false, orderBy);
_orderByFields.Add(orderOption);
}
// If the field is being removed and it IS in the list, remove it ...
else if (!fieldAdded && fieldIsInList)
{
_groupByFields.Remove(fieldName);
// Also check for this field in the "order by" list and remove if necessary (only group fields can be used to order results)
OrderFieldOption orderBy = _orderByFields.FirstOrDefault(field => field.OrderInfo.FieldName == fieldName);
if (orderBy != null)
{
// Remove the field from the "order by" list
_orderByFields.Remove(orderBy);
}
}
}
// Create a statistic definition and add it to the collection based on the user selection in the combo boxes
private void AddStatisticClicked(object sender, EventArgs e)
{
// Verify that a field name and statistic type has been selected
if (FieldsComboBox.SelectedItem == null || StatTypeComboBox.SelectedItem == null) { return; }
// Get the chosen field name and statistic type from the combo boxes
string fieldName = FieldsComboBox.SelectedItem.ToString();
StatisticType statType = (StatisticType)StatTypeComboBox.SelectedItem;
// Check if this statistic definition has already be created (same field name and statistic type)
StatisticDefinition existingStatDefinition = _statDefinitions.FirstOrDefault(def => def.OnFieldName == fieldName && def.StatisticType == statType);
// If it doesn't exist, create it and add it to the collection (use the field name and statistic type to build the output alias)
if (existingStatDefinition == null)
{
StatisticDefinition statDefinition = new StatisticDefinition(fieldName, statType, fieldName + "_" + statType.ToString());
_statDefinitions.Add(statDefinition);
}
}
// Toggle the sort order (ascending/descending) for the field selected in the sort fields list
private void ChangeFieldSortOrder(object sender, EventArgs e)
{
// Verify that there is a selected sort field in the list
OrderFieldOption selectedSortField = OrderByFieldsListBox.SelectedItem as OrderFieldOption;
if (selectedSortField == null) { return; }
// Create a new order field info to define the sort for the selected field
OrderBy newOrderBy = new OrderBy(selectedSortField.OrderInfo.FieldName, selectedSortField.OrderInfo.SortOrder);
OrderFieldOption newSortDefinition = new OrderFieldOption(true, newOrderBy);
// Toggle the sort order from the current value
if (newSortDefinition.OrderInfo.SortOrder == SortOrder.Ascending)
{
newSortDefinition.OrderInfo.SortOrder = SortOrder.Descending;
}
else
{
newSortDefinition.OrderInfo.SortOrder = SortOrder.Ascending;
}
// Add the new OrderBy at the same location in the collection and remove the old one
_orderByFields.Insert(_orderByFields.IndexOf(selectedSortField), newSortDefinition);
_orderByFields.Remove(selectedSortField);
}
// Remove the selected statistic definition from the list
private void RemoveStatisticClicked(object sender, EventArgs e)
{
// Verify that there is a selected statistic definition
if (StatFieldsListBox.SelectedItem == null) { return; }
// Get the selected statistic definition and remove it from the collection
StatisticDefinition selectedStat = StatFieldsListBox.SelectedItem as StatisticDefinition;
_statDefinitions.Remove(selectedStat);
}
// Add the selected field in the "group by" list to the "order by" list
private void AddSortFieldClicked(object sender, EventArgs e)
{
// Verify that there is a selected field in the "group by" list
if (GroupFieldsListBox.SelectedItem == null) { return; }
// Get the name of the selected field and ensure that it's in the list of selected group fields (checked on in the list, e.g.)
string selectedFieldName = GroupFieldsListBox.SelectedItem.ToString();
if (!_groupByFields.Contains(selectedFieldName))
{
Application.Current.MainPage.DisplayAlert("Only fields used for grouping can be used to order results.", "Query", "OK");
return;
}
// Verify that the field isn't already in the "order by" list
OrderFieldOption existingOrderBy = _orderByFields.FirstOrDefault(field => field.OrderInfo.FieldName == selectedFieldName);
if (existingOrderBy == null)
{
// Create a new OrderBy for this field and add it to the collection (default to ascending sort order)
OrderBy newOrderBy = new OrderBy(selectedFieldName, SortOrder.Ascending);
OrderFieldOption orderField = new OrderFieldOption(false, newOrderBy);
_orderByFields.Add(orderField);
}
}
// Remove the selected field from the list of "order by" fields
private void RemoveSortFieldClicked(object sender, EventArgs e)
{
// Verify that there is a selected item in the "order by" list
if (OrderByFieldsListBox.SelectedItem == null) { return; }
// Get the selected OrderFieldOption object and remove it from the collection
OrderFieldOption selectedOrderBy = OrderByFieldsListBox.SelectedItem as OrderFieldOption;
_orderByFields.Remove(selectedOrderBy);
}
private void HideResults(object sender, EventArgs e)
{
// Dismiss the results grid and show the input controls
ResultsGrid.IsVisible = false;
}
}
// Simple class to describe an "order by" option
public class OrderFieldOption
{
// Whether or not to use this field to order results
public bool OrderWith { get; set; }
// The order by info: field name and sort order
public OrderBy OrderInfo { get; set; }
public OrderFieldOption(bool orderWith, OrderBy orderInfo)
{
OrderWith = orderWith;
OrderInfo = orderInfo;
}
}
// A simple class to hold a single statistic result
public class StatisticResult
{
public string FieldName { get; set; }
public object StatValue { get; set; }
}
// A class to represent a group of statistics results
public class ResultGroup : ObservableCollection<StatisticResult>
{
public string GroupName { get; set; }
public string ShortName { get; set; }
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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.Threading;
using System.Threading.Tasks;
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>, IUnaryResponseClientCallback, IReceivedStatusOnClientCallback, IReceivedResponseHeadersCallback
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
readonly CallInvocationDetails<TRequest, TResponse> details;
readonly INativeCall injectedNativeCall; // for testing
bool registeredWithChannel;
// Dispose of to de-register cancellation token registration
IDisposable cancellationTokenRegistration;
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Completion of a streaming response call if not null.
TaskCompletionSource<object> streamingResponseCallFinishedTcs;
// TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers).
// 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.ContextualSerializer, callDetails.ResponseMarshaller.ContextualDeserializer)
{
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.CreateSync())
{
bool callStartedOk = false;
try
{
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(cq);
halfcloseRequested = true;
readingDone = true;
}
byte[] payload = UnsafeSerialize(msg);
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
var ctx = details.Channel.Environment.BatchContextPool.Lease();
try
{
call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
callStartedOk = true;
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 occurred while invoking completion delegate.");
}
}
finally
{
ctx.Recycle();
}
}
}
finally
{
if (!callStartedOk)
{
lock (myLock)
{
OnFailedToStartCallLocked();
}
}
}
// 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)
{
bool callStartedOk = false;
try
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartUnary(UnaryResponseClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
callStartedOk = true;
}
return unaryResponseTcs.Task;
}
finally
{
if (!callStartedOk)
{
OnFailedToStartCallLocked();
}
}
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync()
{
lock (myLock)
{
bool callStartedOk = false;
try
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartClientStreaming(UnaryResponseClientCallback, metadataArray, details.Options.Flags);
callStartedOk = true;
}
return unaryResponseTcs.Task;
}
finally
{
if (!callStartedOk)
{
OnFailedToStartCallLocked();
}
}
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg)
{
lock (myLock)
{
bool callStartedOk = false;
try
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
byte[] payload = UnsafeSerialize(msg);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartServerStreaming(ReceivedStatusOnClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
callStartedOk = true;
}
call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback);
}
finally
{
if (!callStartedOk)
{
OnFailedToStartCallLocked();
}
}
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall()
{
lock (myLock)
{
bool callStartedOk = false;
try
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartDuplexStreaming(ReceivedStatusOnClientCallback, metadataArray, details.Options.Flags);
callStartedOk = true;
}
call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback);
}
finally
{
if (!callStartedOk)
{
OnFailedToStartCallLocked();
}
}
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// </summary>
public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags)
{
return SendMessageInternalAsync(msg, writeFlags);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// </summary>
public Task<TResponse> ReadMessageAsync()
{
return ReadMessageInternalAsync();
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// </summary>
public Task SendCloseFromClientAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (disposed || finished)
{
// In case the call has already been finished by the serverside,
// the halfclose has already been done implicitly, so just return
// completed task here.
halfcloseRequested = true;
return TaskUtils.CompletedTask;
}
call.StartSendCloseFromClient(SendCompletionCallback);
halfcloseRequested = true;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise.
/// </summary>
public Task StreamingResponseCallFinishedTask
{
get
{
return streamingResponseCallFinishedTcs.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 OnAfterReleaseResourcesLocked()
{
if (registeredWithChannel)
{
details.Channel.RemoveCallReference(this);
registeredWithChannel = false;
}
}
protected override void OnAfterReleaseResourcesUnlocked()
{
// If cancellation callback is in progress, this can block
// so we need to do this outside of call's lock to prevent
// deadlock.
// See https://github.com/grpc/grpc/issues/14777
// See https://github.com/dotnet/corefx/issues/14903
cancellationTokenRegistration?.Dispose();
}
protected override bool IsClient
{
get { return true; }
}
protected override Exception GetRpcExceptionClientOnly()
{
return new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers);
}
protected override Task CheckSendAllowedOrEarlyResult()
{
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (finishedStatus.HasValue)
{
// throwing RpcException if we already received status on client
// side makes the most sense.
// Note that this throws even for StatusCode.OK.
// Writing after the call has finished is not a programming error because server can close
// the call anytime, so don't throw directly, but let the write task finish with an error.
var tcs = new TaskCompletionSource<object>();
tcs.SetException(new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers));
return tcs.Task;
}
return null;
}
private Task CheckSendPreconditionsClientSide()
{
GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed.");
GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time.");
if (cancelRequested)
{
// Return a cancelled task.
var tcs = new TaskCompletionSource<object>();
tcs.SetCanceled();
return tcs.Task;
}
return null;
}
private void Initialize(CompletionQueueSafeHandle cq)
{
var call = CreateNativeCall(cq);
details.Channel.AddCallReference(this);
registeredWithChannel = true;
InitializeInternal(call);
RegisterCancellationCallback();
}
private void OnFailedToStartCallLocked()
{
ReleaseResources();
// We need to execute the hook that disposes the cancellation token
// registration, but it cannot be done from under a lock.
// To make things simple, we just schedule the unregistering
// on a threadpool.
// - Once the native call is disposed, the Cancel() calls are ignored anyway
// - We don't care about the overhead as OnFailedToStartCallLocked() only happens
// when something goes very bad when initializing a call and that should
// never happen when gRPC is used correctly.
ThreadPool.QueueUserWorkItem((state) => OnAfterReleaseResourcesUnlocked());
}
private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
{
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(
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)
{
cancellationTokenRegistration = 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)
{
// TODO(jtattermusch): handle success==false
responseHeadersTcs.SetResult(responseHeaders);
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
TResponse msg = default(TResponse);
var deserializeException = TryDeserialize(receivedMessage, out msg);
bool releasedResources;
lock (myLock)
{
finished = true;
if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
{
receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
}
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
responseHeadersTcs.SetResult(responseHeaders);
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status, receivedStatus.Trailers));
return;
}
unaryResponseTcs.SetResult(msg);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, ClientSideStatus receivedStatus)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
bool releasedResources;
lock (myLock)
{
finished = true;
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
releasedResources = ReleaseResourcesIfPossible();
}
if (releasedResources)
{
OnAfterReleaseResourcesUnlocked();
}
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
streamingResponseCallFinishedTcs.SetException(new RpcException(status, receivedStatus.Trailers));
return;
}
streamingResponseCallFinishedTcs.SetResult(null);
}
IUnaryResponseClientCallback UnaryResponseClientCallback => this;
void IUnaryResponseClientCallback.OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
HandleUnaryResponse(success, receivedStatus, receivedMessage, responseHeaders);
}
IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback => this;
void IReceivedStatusOnClientCallback.OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus)
{
HandleFinished(success, receivedStatus);
}
IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback => this;
void IReceivedResponseHeadersCallback.OnReceivedResponseHeaders(bool success, Metadata responseHeaders)
{
HandleReceivedResponseHeaders(success, responseHeaders);
}
}
}
| |
// <copyright file="Requires.NumericTypesNegativeValidation.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Runtime.CompilerServices;
namespace IX.StandardExtensions.Contracts;
/// <summary>
/// Methods for approximating the works of contract-oriented programming.
/// </summary>
public static partial class Requires
{
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="byte" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in byte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="byte" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out byte field,
in byte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="sbyte" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in sbyte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="sbyte" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in sbyte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="sbyte" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out sbyte field,
in sbyte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="sbyte" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out sbyte field,
in sbyte argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="short" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in short argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="short" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in short argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="short" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out short field,
in short argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="short" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out short field,
in short argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="ushort" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in ushort argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="ushort" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out ushort field,
in ushort argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="char" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in char argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="char" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out char field,
in char argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="int" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in int argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="int" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in int argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="int" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out int field,
in int argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="int" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out int field,
in int argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="uint" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in uint argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="uint" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out uint field,
in uint argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="long" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in long argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="long" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in long argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="long" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out long field,
in long argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="long" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out long field,
in long argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="ulong" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in ulong argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="ulong" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveIntegerException">
/// The argument is equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out ulong field,
in ulong argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument == 0)
{
throw new ArgumentNotNegativeIntegerException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="float" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in float argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="float" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in float argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="float" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out float field,
in float argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="float" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out float field,
in float argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="double" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in double argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="double" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in double argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="double" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out double field,
in double argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="double" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out double field,
in double argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="decimal" /> is
/// negative (less than zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
in decimal argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a contract requires that a numeric argument of type <see cref="decimal" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
in decimal argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="decimal" /> is
/// negative (less than zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than or equal to 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Negative(
out decimal field,
in decimal argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument <= 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
/// <summary>
/// Called when a field initialization requires that a numeric argument of type <see cref="decimal" /> is
/// non-positive (less than or equal to zero).
/// </summary>
/// <param name="field">
/// The field that the argument is initializing.
/// </param>
/// <param name="argument">
/// The numeric argument.
/// </param>
/// <param name="argumentName">
/// The argument name.
/// </param>
/// <exception cref="ArgumentNotPositiveException">
/// The argument is less than 0.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NonPositive(
out decimal field,
in decimal argument,
[CallerArgumentExpression("argument")]
string argumentName = "argument")
{
if (argument < 0)
{
throw new ArgumentNotNegativeException(argumentName);
}
field = argument;
}
}
| |
#if !SILVERLIGHT && !PORTABLE
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Zirpl.Reflection
{
/// <summary>
/// Implements the <see cref="IDynamicAccessor"/> and provides fast dynamic access to an object's fields and properties.
/// </summary>
/// <remarks>The first time you attempt to get or set a property, it will dynamically generate the get and/or set
/// methods and cache them internally. Subsequent calls uses the dynamic methods without having to query the type's
/// meta data.</remarks>
internal sealed class DynamicAccessor : IDynamicAccessor
{
#region Private Fields
private readonly Type _type;
private readonly Dictionary<string, GetHandler> _propertyGetters;
private readonly Dictionary<string, SetHandler> _propertySetters;
private readonly Dictionary<string, GetHandler> _fieldGetters;
private readonly Dictionary<string, SetHandler> _fieldSetters;
#endregion
#region Constructors
internal DynamicAccessor(Type type)
{
_type = type;
_propertyGetters = new Dictionary<string, GetHandler>();
_propertySetters = new Dictionary<string, SetHandler>();
_fieldGetters = new Dictionary<string, GetHandler>();
_fieldSetters = new Dictionary<string, SetHandler>();
}
#endregion
#region Public Accessors
/// <summary>
/// Gets or Sets the supplied property on the supplied target
/// </summary>
public object this[object target, string propertyName]
{
get
{
ValidatePropertyGetter(propertyName);
return _propertyGetters[propertyName](target);
}
set
{
ValidatePropertySetter(propertyName);
_propertySetters[propertyName](target, value);
}
}
public void SetPropertyValue(object target, string propertyName, object value)
{
ValidatePropertySetter(propertyName);
_propertySetters[propertyName](target, value);
}
public object GetPropertyValue(object target, string propertyName)
{
ValidatePropertyGetter(propertyName);
return _propertyGetters[propertyName](target);
}
public void SetFieldValue(object target, string fieldName, object value)
{
ValidateFieldSetter(fieldName);
_fieldSetters[fieldName](target, value);
}
public object GetFieldValue(object target, string fieldName)
{
ValidateFieldGetter(fieldName);
return _fieldGetters[fieldName](target);
}
#endregion
#region Private Helpers
private void ValidateFieldSetter(string fieldName)
{
if (!_fieldSetters.ContainsKey(fieldName))
{
FieldInfo fieldInfo = _type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
throw new ArgumentOutOfRangeException(fieldName, "Unable to find fieldname");
_fieldSetters.Add(fieldName, DynamicMethodCompiler.CreateSetHandler(_type, fieldInfo));
}
}
private void ValidatePropertySetter(string propertyName)
{
if (!_propertySetters.ContainsKey(propertyName))
{
_propertySetters.Add(propertyName, DynamicMethodCompiler.CreateSetHandler(_type, _type.GetProperty(propertyName)));
}
}
private void ValidatePropertyGetter(string propertyName)
{
if (!_propertyGetters.ContainsKey(propertyName))
{
_propertyGetters.Add(propertyName, DynamicMethodCompiler.CreateGetHandler(_type, _type.GetProperty(propertyName)));
}
}
private void ValidateFieldGetter(string fieldName)
{
if (!_fieldGetters.ContainsKey(fieldName))
{
FieldInfo fieldInfo = _type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
throw new ArgumentOutOfRangeException(fieldName, "Unable to find fieldname");
_fieldGetters.Add(fieldName, DynamicMethodCompiler.CreateGetHandler(_type, fieldInfo));
}
}
#endregion
#region Contained Classes
internal delegate object GetHandler(object source);
internal delegate void SetHandler(object source, object value);
internal delegate object InstantiateObjectHandler();
/// <summary>
/// provides helper functions for late binding a class
/// </summary>
/// <remarks>
/// Class found here:
/// http://www.codeproject.com/useritems/Dynamic_Code_Generation.asp
/// </remarks>
internal sealed class DynamicMethodCompiler
{
// DynamicMethodCompiler
private DynamicMethodCompiler() { }
internal static InstantiateObjectHandler CreateInstantiateObjectHandler(Type type)
{
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
if (constructorInfo == null)
{
throw new ApplicationException(string.Format("The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).", type));
}
DynamicMethod dynamicMethod = new DynamicMethod("InstantiateObject", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), null, type, true);
ILGenerator generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, PropertyInfo propertyInfo)
{
MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Call, getMethodInfo);
BoxIfNeeded(getMethodInfo.ReturnType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, FieldInfo Season)
{
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Ldfld, Season);
BoxIfNeeded(Season.FieldType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
{
MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
setGenerator.Emit(OpCodes.Call, setMethodInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, FieldInfo Season)
{
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(Season.FieldType, setGenerator);
setGenerator.Emit(OpCodes.Stfld, Season);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
}
// CreateGetDynamicMethod
private static DynamicMethod CreateGetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicGet", typeof(object), new Type[] { typeof(object) }, type, true);
}
// CreateSetDynamicMethod
private static DynamicMethod CreateSetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicSet", typeof(void), new Type[] { typeof(object), typeof(object) }, type, true);
}
// BoxIfNeeded
private static void BoxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Box, type);
}
}
// UnboxIfNeeded
private static void UnboxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Unbox_Any, type);
}
}
}
#endregion
}
}
#endif
| |
// 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.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
{
double* inArray = stackalloc double[4];
byte* outBuffer = stackalloc byte[64];
double* outArray = (double*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<double>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (BitConverter.DoubleToInt64Bits(inArray[i]) != BitConverter.DoubleToInt64Bits(outArray[i]))
{
Console.WriteLine("Avx StoreAligned failed on double:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
float* inArray = stackalloc float[8];
byte* outBuffer = stackalloc byte[64];
float* outArray = (float*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<float>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (BitConverter.SingleToInt32Bits(inArray[i]) != BitConverter.SingleToInt32Bits(outArray[i]))
{
Console.WriteLine("Avx StoreAligned failed on float:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
long* inArray = stackalloc long[4];
byte* outBuffer = stackalloc byte[64];
long* outArray = (long*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<long>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on long:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
ulong* inArray = stackalloc ulong[4];
byte* outBuffer = stackalloc byte[64];
ulong* outArray = (ulong*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<ulong>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 4; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on ulong:");
for (var n = 0; n < 4; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
int* inArray = stackalloc int[8];
byte* outBuffer = stackalloc byte[64];
int* outArray = (int*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<int>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on int:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
uint* inArray = stackalloc uint[8];
byte* outBuffer = stackalloc byte[64];
uint* outArray = (uint*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<uint>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 8; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on uint:");
for (var n = 0; n < 8; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
short* inArray = stackalloc short[16];
byte* outBuffer = stackalloc byte[64];
short* outArray = (short*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<short>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on short:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
ushort* inArray = stackalloc ushort[16];
byte* outBuffer = stackalloc byte[64];
ushort* outArray = (ushort*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<ushort>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 16; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on ushort:");
for (var n = 0; n < 16; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
byte* inArray = stackalloc byte[32];
byte* outBuffer = stackalloc byte[64];
byte* outArray = (byte*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<byte>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on byte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
{
sbyte* inArray = stackalloc sbyte[32];
byte* outBuffer = stackalloc byte[64];
sbyte* outArray = (sbyte*)Align(outBuffer, 32);
var vf = Unsafe.Read<Vector256<sbyte>>(inArray);
Avx.StoreAligned(outArray, vf);
for (var i = 0; i < 32; i++)
{
if (inArray[i] != outArray[i])
{
Console.WriteLine("Avx StoreAligned failed on byte:");
for (var n = 0; n < 32; n++)
{
Console.Write(outArray[n] + ", ");
}
Console.WriteLine();
testResult = Fail;
break;
}
}
}
}
return testResult;
}
static unsafe void* Align(byte* buffer, byte expectedAlignment)
{
// Compute how bad the misalignment is, which is at most (expectedAlignment - 1).
// Then subtract that from the expectedAlignment and add it to the original address
// to compute the aligned address.
var misalignment = expectedAlignment - ((ulong)(buffer) % expectedAlignment);
return (void*)(buffer + misalignment);
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Collections;
namespace Moscrif.IDE.Iface
{
/// <summary>
/// A socket that sends and recieves data to and from Flash.
/// </summary>
public class FlashSocket
{
private const int DEFAULT_BACKLOG = 10;
#region Member Variables
private int m_portnumber;
private int m_backlog = DEFAULT_BACKLOG;
private Socket m_socketlistener;
private Socket m_socketclient = null;
private AsyncCallback m_datareciever;
private bool m_socketalive = false;
private string m_currentmessage = "";
private System.Collections.Queue m_queuedSends;
private static System.Collections.ArrayList m_workerSocketList =
ArrayList.Synchronized(new System.Collections.ArrayList());
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of FlashSocket.
/// </summary>
public FlashSocket()
{
m_socketlistener = null;
m_queuedSends = new System.Collections.Queue();
m_datareciever = new AsyncCallback(OnDataReceived);
}
/// <summary>
/// Creates a new instance of FlashSocket and creates the socket
/// listening on portNumber.
/// </summary>
/// <param name="portNumber">
/// The port to listen on.
/// </param>
public FlashSocket(int portNumber)
: this(portNumber, DEFAULT_BACKLOG)
{ }
/// <summary>
/// Creates a new instance of FlashSocket and creates the socket
/// listening on portNumber with a maximum backlog queue length
/// or backLog.
/// </summary>
/// <param name="portNumber">
/// The port to listen on.
/// </param>
/// <param name="backLog">
/// The socket's maximum number of pending connection requests.
/// </param>
public FlashSocket(int portNumber, int backLog) : this()
{
m_portnumber = portNumber;
m_backlog = backLog;
//CreateSocket();
}
#endregion
#region Properties
/// <summary>
/// Gets / sets whether the socket is alive.
/// </summary>
public bool IsAlive
{
get
{
return m_socketalive;
}
/*set
{
if (m_socketalive == value)
return;
m_socketalive = value;
if (value)
CreateSocket();
else
KillSocket();
}*/
}
/// <summary>
/// Gets / sets the port number on which the socket exists.
/// </summary>
/// <remarks>
/// This property can only be set while IsAlive is false.
/// </remarks>
public int Port
{
get
{
return m_portnumber;
}
set
{
if (m_socketalive)
{
throw new InvalidOperationException(
"Port can only be set after setting IsAlive to false or calling KillSocket()");
}
m_portnumber = value;
}
}
/// <summary>
/// Gets the socket's maximum number of pending connection requests.
/// </summary>
public int BackLog
{
get
{
return m_backlog;
}
}
#endregion
#region Internal Event Handlers, Events (and their delegates)
public delegate void ClientConnectHandler(Socket socket);
/// <summary>
/// Occurs when the client connects.
/// </summary>
public event ClientConnectHandler ClientConnect;
/// <summary>
/// Occurs when the client disconnects.
/// </summary>
public event EventHandler ClientDisconnect;
/// <summary>
/// Fired when a connection to a Flash movie is made.
/// </summary>
/// <param name="target"></param>
protected void OnClientConnect(IAsyncResult target)
{
try
{
//
// Ends the connection acceptance.
//
m_socketclient = m_socketlistener.EndAccept(target);
//
// Mark connection as alive.
//
m_socketalive = true;
//
// Dispatch event.
//
if (ClientConnect != null)
ClientConnect(m_socketclient);
//
// Send the messages waiting in the qeueue.
//
SendQueuedMessages();
//
// Wait for the client to send data.
//
WaitForData(m_socketclient);
}
catch(ObjectDisposedException)
{
KillSocket();
if (ClientDisconnect != null)
ClientDisconnect(this, EventArgs.Empty);
}
catch(SocketException e)
{
System.Diagnostics.Debugger.Log(0, "1", "\n" + e.ToString() + "\n");
}
}
public delegate void DataRecievedHandler(string message);//(Socket socket, XmlNode data);
public event DataRecievedHandler DataRecieved;
/// <summary>
/// Fired when data is recieved from the socket.
/// </summary>
/// <param name="asyn"></param>
protected void OnDataReceived(IAsyncResult asyn)
{
try
{
//
// Get the socket packet (as set by BeginRecieve's state)
//
SocketPacket spacket = (SocketPacket)asyn.AsyncState ;
//
// Decode the text.
//
int numbytes = 0;
numbytes = spacket.Socket.EndReceive(asyn);
char[] chars = new char[numbytes];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(spacket.DataBuffer, 0, numbytes, chars, 0);
string recievedData = new String(chars);
m_currentmessage += recievedData;
//
// Dispatch event.
//
//if (recievedData == "\0" && DataRecieved != null)
if (recievedData.Contains("\n" ) && DataRecieved != null)
{
XmlNode node;
try
{
/*XmlDocument doc = new XmlDocument();
doc.LoadXml(m_currentmessage);
node = doc.FirstChild;*/
}
catch
{
m_currentmessage = "";
WaitForData(m_socketclient);
return;
}
DataRecieved(m_currentmessage);//(spacket.Socket, node);
m_currentmessage = "";
}
//
// Wait for data again.
//
WaitForData(m_socketclient);
}
catch (ObjectDisposedException )
{
KillSocket();
if (ClientDisconnect != null)
ClientDisconnect(this, EventArgs.Empty);
}
catch(SocketException e)
{
System.Diagnostics.Debugger.Log(0,"1","\n" + e.ToString() + "\n");
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates the socket.
/// </summary>
public void CreateSocket(string IPadress)
{
try
{
if (m_socketlistener == null)
{
//
// Create the socket.
//
IPAddress ipAddress = IPAddress.Parse(IPadress);
m_socketlistener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//
// Create the endpoint.
//
IPEndPoint ep = new IPEndPoint(ipAddress, m_portnumber);//IPAddress.Any, m_portnumber);
//
// Bind the socket to the server's ip / port.
//
m_socketlistener.Bind(ep);
}
//
// Tell the socket to begin listening.
//
m_socketlistener.Listen(m_backlog);
//
// Begin listening
//
m_socketlistener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (SocketException e)
{
KillSocket();
if (ClientDisconnect != null)
ClientDisconnect(this, EventArgs.Empty);
}
}
/// <summary>
/// Kills the socket connection.
/// </summary>
public void KillSocket()
{
if (m_socketlistener.Connected)
{
m_socketlistener.Shutdown(SocketShutdown.Both);
m_socketlistener.Close();
}
if (m_socketclient.Connected)
{
m_socketclient.Shutdown(SocketShutdown.Both);
m_socketclient.Close();
}
m_socketalive = false;
}
/// <summary>
/// Sends data to the Flash client.
/// </summary>
/// <param name="data"></param>
/* public void Send(SendableData data)
{
if (m_socketclient == null)
{
m_queuedSends.Enqueue(data);
return;
}
byte[] byData = System.Text.Encoding.ASCII.GetBytes(data.Xml + "\0");
try
{
m_socketclient.Send(byData);
}
catch
{
if (!m_socketclient.Connected)
{
this.KillSocket();
if (ClientDisconnect != null)
ClientDisconnect(this, EventArgs.Empty);
}
}
}*/
public void SendMsgToClient(string msg)
{
if (m_socketclient == null)
{
//m_queuedSends.Enqueue(data);
return;
}
//byte[] byData = System.Text.Encoding.ASCII.GetBytes(data.Xml + "\0");
byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg);
try
{
m_socketclient.Send(byData);
}
catch
{
if (!m_socketclient.Connected)
{
this.KillSocket();
if (ClientDisconnect != null)
ClientDisconnect(this, EventArgs.Empty);
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Waits for data to arrive from the socket connection.
/// </summary>
/// <param name="s">The socket to wait on.</param>
private void WaitForData(Socket s)
{
try
{
SocketPacket spacket = new SocketPacket();
spacket.Socket = s;
//
// Begin listening for data.
//
s.BeginReceive(spacket.DataBuffer, 0, spacket.DataBuffer.Length,
SocketFlags.None, m_datareciever, spacket);
}
catch (SocketException e)
{
}
}
private void SendQueuedMessages()
{
//SendableData data;
//while (null != (data = (SendableData) m_queuedSends.Dequeue()))
// Send(data);
}
#endregion
}
/// <summary>
/// Summary description for SocketPacket.
/// </summary>
public class SocketPacket
{
public System.Net.Sockets.Socket Socket;
public byte[] DataBuffer = new byte[1];
}
}
| |
/*
* 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.Globalization;
using System.Text;
using ZXing.Common;
using ZXing.PDF417.Internal.EC;
namespace ZXing.PDF417.Internal
{
/// <summary>
///
/// </summary>
/// <author>Guenther Grau</author>
public static class PDF417ScanningDecoder
{
private const int CODEWORD_SKEW_SIZE = 2;
private const int MAX_ERRORS = 3;
private const int MAX_EC_CODEWORDS = 512;
private static readonly ErrorCorrection errorCorrection = new ErrorCorrection();
/// <summary>
/// Decode the specified image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth
/// and maxCodewordWidth.
/// TODO: don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern
/// columns. That way width can be deducted from the pattern column.
/// This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider
/// than it should be. This can happen if the scanner used a bad blackpoint.
/// </summary>
/// <param name="image">Image.</param>
/// <param name="imageTopLeft">Image top left.</param>
/// <param name="imageBottomLeft">Image bottom left.</param>
/// <param name="imageTopRight">Image top right.</param>
/// <param name="imageBottomRight">Image bottom right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
public static DecoderResult decode(BitMatrix image,
ResultPoint imageTopLeft,
ResultPoint imageBottomLeft,
ResultPoint imageTopRight,
ResultPoint imageBottomRight,
int minCodewordWidth,
int maxCodewordWidth)
{
var boundingBox = BoundingBox.Create(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight);
if (boundingBox == null)
return null;
DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null;
DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null;
DetectionResult detectionResult;
for (bool firstPass = true; ; firstPass = false)
{
if (imageTopLeft != null)
{
leftRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth);
}
if (imageTopRight != null)
{
rightRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth);
}
detectionResult = merge(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (detectionResult == null)
{
// TODO Based on Owen's Comments in <see cref="ZXing.ReaderException"/>, this method has been modified to continue silently
// if a barcode was not decoded where it was detected instead of throwing a new exception object.
return null;
}
var resultBox = detectionResult.Box;
if (firstPass && resultBox != null &&
(resultBox.MinY < boundingBox.MinY || resultBox.MaxY > boundingBox.MaxY))
{
boundingBox = resultBox;
}
else
{
break;
}
}
detectionResult.Box = boundingBox;
int maxBarcodeColumn = detectionResult.ColumnCount + 1;
detectionResult.DetectionResultColumns[0] = leftRowIndicatorColumn;
detectionResult.DetectionResultColumns[maxBarcodeColumn] = rightRowIndicatorColumn;
bool leftToRight = leftRowIndicatorColumn != null;
for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++)
{
int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;
if (detectionResult.DetectionResultColumns[barcodeColumn] != null)
{
// This will be the case for the opposite row indicator column, which doesn't need to be decoded again.
continue;
}
DetectionResultColumn detectionResultColumn;
if (barcodeColumn == 0 || barcodeColumn == maxBarcodeColumn)
{
detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn == 0);
}
else
{
detectionResultColumn = new DetectionResultColumn(boundingBox);
}
detectionResult.DetectionResultColumns[barcodeColumn] = detectionResultColumn;
int startColumn = -1;
int previousStartColumn = startColumn;
// TODO start at a row for which we know the start position, then detect upwards and downwards from there.
for (int imageRow = boundingBox.MinY; imageRow <= boundingBox.MaxY; imageRow++)
{
startColumn = getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight);
if (startColumn < 0 || startColumn > boundingBox.MaxX)
{
if (previousStartColumn == -1)
{
continue;
}
startColumn = previousStartColumn;
}
Codeword codeword = detectCodeword(image, boundingBox.MinX, boundingBox.MaxX, leftToRight,
startColumn, imageRow, minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
detectionResultColumn.setCodeword(imageRow, codeword);
previousStartColumn = startColumn;
minCodewordWidth = Math.Min(minCodewordWidth, codeword.Width);
maxCodewordWidth = Math.Max(maxCodewordWidth, codeword.Width);
}
}
}
return createDecoderResult(detectionResult);
}
/// <summary>
/// Merge the specified leftRowIndicatorColumn and rightRowIndicatorColumn.
/// </summary>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static DetectionResult merge(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null)
{
return null;
}
BarcodeMetadata barcodeMetadata = getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (barcodeMetadata == null)
{
return null;
}
BoundingBox boundingBox = BoundingBox.merge(adjustBoundingBox(leftRowIndicatorColumn),
adjustBoundingBox(rightRowIndicatorColumn));
return new DetectionResult(barcodeMetadata, boundingBox);
}
/// <summary>
/// Adjusts the bounding box.
/// </summary>
/// <returns>The bounding box.</returns>
/// <param name="rowIndicatorColumn">Row indicator column.</param>
private static BoundingBox adjustBoundingBox(DetectionResultRowIndicatorColumn rowIndicatorColumn)
{
if (rowIndicatorColumn == null)
{
return null;
}
int[] rowHeights = rowIndicatorColumn.getRowHeights();
if (rowHeights == null)
{
return null;
}
int maxRowHeight = getMax(rowHeights);
int missingStartRows = 0;
foreach (int rowHeight in rowHeights)
{
missingStartRows += maxRowHeight - rowHeight;
if (rowHeight > 0)
{
break;
}
}
Codeword[] codewords = rowIndicatorColumn.Codewords;
for (int row = 0; missingStartRows > 0 && codewords[row] == null; row++)
{
missingStartRows--;
}
int missingEndRows = 0;
for (int row = rowHeights.Length - 1; row >= 0; row--)
{
missingEndRows += maxRowHeight - rowHeights[row];
if (rowHeights[row] > 0)
{
break;
}
}
for (int row = codewords.Length - 1; missingEndRows > 0 && codewords[row] == null; row--)
{
missingEndRows--;
}
return rowIndicatorColumn.Box.addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.IsLeft);
}
private static int getMax(int[] values)
{
int maxValue = -1;
for (var index = values.Length - 1; index >= 0; index--)
{
maxValue = Math.Max(maxValue, values[index]);
}
return maxValue;
}
/// <summary>
/// Gets the barcode metadata.
/// </summary>
/// <returns>The barcode metadata.</returns>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static BarcodeMetadata getBarcodeMetadata(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
BarcodeMetadata leftBarcodeMetadata;
if (leftRowIndicatorColumn == null ||
(leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata();
}
BarcodeMetadata rightBarcodeMetadata;
if (rightRowIndicatorColumn == null ||
(rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return leftBarcodeMetadata;
}
if (leftBarcodeMetadata.ColumnCount != rightBarcodeMetadata.ColumnCount &&
leftBarcodeMetadata.ErrorCorrectionLevel != rightBarcodeMetadata.ErrorCorrectionLevel &&
leftBarcodeMetadata.RowCount != rightBarcodeMetadata.RowCount)
{
return null;
}
return leftBarcodeMetadata;
}
/// <summary>
/// Gets the row indicator column.
/// </summary>
/// <returns>The row indicator column.</returns>
/// <param name="image">Image.</param>
/// <param name="boundingBox">Bounding box.</param>
/// <param name="startPoint">Start point.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static DetectionResultRowIndicatorColumn getRowIndicatorColumn(BitMatrix image,
BoundingBox boundingBox,
ResultPoint startPoint,
bool leftToRight,
int minCodewordWidth,
int maxCodewordWidth)
{
DetectionResultRowIndicatorColumn rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight);
for (int i = 0; i < 2; i++)
{
int increment = i == 0 ? 1 : -1;
int startColumn = (int)startPoint.X;
for (int imageRow = (int)startPoint.Y; imageRow <= boundingBox.MaxY &&
imageRow >= boundingBox.MinY; imageRow += increment)
{
Codeword codeword = detectCodeword(image, 0, image.Width, leftToRight, startColumn, imageRow,
minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
rowIndicatorColumn.setCodeword(imageRow, codeword);
if (leftToRight)
{
startColumn = codeword.StartX;
}
else
{
startColumn = codeword.EndX;
}
}
}
}
return rowIndicatorColumn;
}
/// <summary>
/// Adjusts the codeword count.
/// </summary>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeMatrix">Barcode matrix.</param>
private static bool adjustCodewordCount(DetectionResult detectionResult, BarcodeValue[][] barcodeMatrix)
{
var barcodeMatrix01 = barcodeMatrix[0][1];
int[] numberOfCodewords = barcodeMatrix01.getValue();
int calculatedNumberOfCodewords = detectionResult.ColumnCount *
detectionResult.RowCount -
getNumberOfECCodeWords(detectionResult.ErrorCorrectionLevel);
if (numberOfCodewords.Length == 0)
{
if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE)
{
return false;
}
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
}
else if (numberOfCodewords[0] != calculatedNumberOfCodewords)
{
if (calculatedNumberOfCodewords >= 1 && calculatedNumberOfCodewords <= PDF417Common.MAX_CODEWORDS_IN_BARCODE)
{
// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix01.setValue(calculatedNumberOfCodewords);
}
}
return true;
}
/// <summary>
/// Creates the decoder result.
/// </summary>
/// <returns>The decoder result.</returns>
/// <param name="detectionResult">Detection result.</param>
private static DecoderResult createDecoderResult(DetectionResult detectionResult)
{
BarcodeValue[][] barcodeMatrix = createBarcodeMatrix(detectionResult);
if (barcodeMatrix == null)
return null;
if (!adjustCodewordCount(detectionResult, barcodeMatrix))
{
return null;
}
List<int> erasures = new List<int>();
int[] codewords = new int[detectionResult.RowCount * detectionResult.ColumnCount];
List<int[]> ambiguousIndexValuesList = new List<int[]>();
List<int> ambiguousIndexesList = new List<int>();
for (int row = 0; row < detectionResult.RowCount; row++)
{
for (int column = 0; column < detectionResult.ColumnCount; column++)
{
int[] values = barcodeMatrix[row][column + 1].getValue();
int codewordIndex = row * detectionResult.ColumnCount + column;
if (values.Length == 0)
{
erasures.Add(codewordIndex);
}
else if (values.Length == 1)
{
codewords[codewordIndex] = values[0];
}
else
{
ambiguousIndexesList.Add(codewordIndex);
ambiguousIndexValuesList.Add(values);
}
}
}
int[][] ambiguousIndexValues = new int[ambiguousIndexValuesList.Count][];
for (int i = 0; i < ambiguousIndexValues.Length; i++)
{
ambiguousIndexValues[i] = ambiguousIndexValuesList[i];
}
return createDecoderResultFromAmbiguousValues(detectionResult.ErrorCorrectionLevel, codewords,
erasures.ToArray(), ambiguousIndexesList.ToArray(), ambiguousIndexValues);
}
/// <summary>
/// This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
/// current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
/// for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
/// the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
/// ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
/// so decoding the normal barcodes is not affected by this.
/// </summary>
/// <returns>The decoder result from ambiguous values.</returns>
/// <param name="ecLevel">Ec level.</param>
/// <param name="codewords">Codewords.</param>
/// <param name="erasureArray">contains the indexes of erasures.</param>
/// <param name="ambiguousIndexes">array with the indexes that have more than one most likely value.</param>
/// <param name="ambiguousIndexValues">two dimensional array that contains the ambiguous values. The first dimension must
/// be the same Length as the ambiguousIndexes array.</param>
private static DecoderResult createDecoderResultFromAmbiguousValues(int ecLevel,
int[] codewords,
int[] erasureArray,
int[] ambiguousIndexes,
int[][] ambiguousIndexValues)
{
int[] ambiguousIndexCount = new int[ambiguousIndexes.Length];
int tries = 100;
while (tries-- > 0)
{
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]];
}
try
{
var result = decodeCodewords(codewords, ecLevel, erasureArray);
if (result != null)
return result;
}
catch (ReaderException)
{
// ignored, should not happen
}
if (ambiguousIndexCount.Length == 0)
{
return null;
}
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
if (ambiguousIndexCount[i] < ambiguousIndexValues[i].Length - 1)
{
ambiguousIndexCount[i]++;
break;
}
else
{
ambiguousIndexCount[i] = 0;
if (i == ambiguousIndexCount.Length - 1)
{
return null;
}
}
}
}
return null;
}
/// <summary>
/// Creates the barcode matrix.
/// </summary>
/// <returns>The barcode matrix.</returns>
/// <param name="detectionResult">Detection result.</param>
private static BarcodeValue[][] createBarcodeMatrix(DetectionResult detectionResult)
{
// Manually setup Jagged Array in C#
var barcodeMatrix = new BarcodeValue[detectionResult.RowCount][];
for (int row = 0; row < barcodeMatrix.Length; row++)
{
barcodeMatrix[row] = new BarcodeValue[detectionResult.ColumnCount + 2];
for (int col = 0; col < barcodeMatrix[row].Length; col++)
{
barcodeMatrix[row][col] = new BarcodeValue();
}
}
int column = 0;
foreach (DetectionResultColumn detectionResultColumn in detectionResult.getDetectionResultColumns())
{
if (detectionResultColumn != null)
{
foreach (Codeword codeword in detectionResultColumn.Codewords)
{
if (codeword != null)
{
int rowNumber = codeword.RowNumber;
if (rowNumber >= 0)
{
if (rowNumber >= barcodeMatrix.Length)
{
// We have more rows than the barcode metadata allows for, ignore them.
continue;
}
barcodeMatrix[rowNumber][column].setValue(codeword.Value);
}
}
}
}
column++;
}
return barcodeMatrix;
}
/// <summary>
/// Tests to see if the Barcode Column is Valid
/// </summary>
/// <returns><c>true</c>, if barcode column is valid, <c>false</c> otherwise.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
private static bool isValidBarcodeColumn(DetectionResult detectionResult, int barcodeColumn)
{
return (barcodeColumn >= 0) && (barcodeColumn < detectionResult.DetectionResultColumns.Length);
}
/// <summary>
/// Gets the start column.
/// </summary>
/// <returns>The start column.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
private static int getStartColumn(DetectionResult detectionResult,
int barcodeColumn,
int imageRow,
bool leftToRight)
{
int offset = leftToRight ? 1 : -1;
Codeword codeword = null;
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodeword(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
codeword = detectionResult.DetectionResultColumns[barcodeColumn].getCodewordNearby(imageRow);
if (codeword != null)
{
return leftToRight ? codeword.StartX : codeword.EndX;
}
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodewordNearby(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
int skippedColumns = 0;
while (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
barcodeColumn -= offset;
foreach (Codeword previousRowCodeword in detectionResult.DetectionResultColumns[barcodeColumn].Codewords)
{
if (previousRowCodeword != null)
{
return (leftToRight ? previousRowCodeword.EndX : previousRowCodeword.StartX) +
offset *
skippedColumns *
(previousRowCodeword.EndX - previousRowCodeword.StartX);
}
}
skippedColumns++;
}
return leftToRight ? detectionResult.Box.MinX : detectionResult.Box.MaxX;
}
/// <summary>
/// Detects the codeword.
/// </summary>
/// <returns>The codeword.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static Codeword detectCodeword(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow,
int minCodewordWidth,
int maxCodewordWidth)
{
startColumn = adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
// we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length
// and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels.
// min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate
// for the current position
int[] moduleBitCount = getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
if (moduleBitCount == null)
{
return null;
}
int endColumn;
int codewordBitCount = ZXing.Common.Detector.MathUtils.sum(moduleBitCount);
if (leftToRight)
{
endColumn = startColumn + codewordBitCount;
}
else
{
for (int i = 0; i < (moduleBitCount.Length >> 1); i++)
{
int tmpCount = moduleBitCount[i];
moduleBitCount[i] = moduleBitCount[moduleBitCount.Length - 1 - i];
moduleBitCount[moduleBitCount.Length - 1 - i] = tmpCount;
}
endColumn = startColumn;
startColumn = endColumn - codewordBitCount;
}
// TODO implement check for width and correction of black and white bars
// use start (and maybe stop pattern) to determine if blackbars are wider than white bars. If so, adjust.
// should probably done only for codewords with a lot more than 17 bits.
// The following fixes 10-1.png, which has wide black bars and small white bars
// for (int i = 0; i < moduleBitCount.Length; i++) {
// if (i % 2 == 0) {
// moduleBitCount[i]--;
// } else {
// moduleBitCount[i]++;
// }
// }
// We could also use the width of surrounding codewords for more accurate results, but this seems
// sufficient for now
if (!checkCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth))
{
// We could try to use the startX and endX position of the codeword in the same column in the previous row,
// create the bit count from it and normalize it to 8. This would help with single pixel errors.
return null;
}
int decodedValue = PDF417CodewordDecoder.getDecodedValue(moduleBitCount);
int codeword = PDF417Common.getCodeword(decodedValue);
if (codeword == -1)
{
return null;
}
return new Codeword(startColumn, endColumn, getCodewordBucketNumber(decodedValue), codeword);
}
/// <summary>
/// Gets the module bit count.
/// </summary>
/// <returns>The module bit count.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
private static int[] getModuleBitCount(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow)
{
int imageColumn = startColumn;
int[] moduleBitCount = new int[8];
int moduleNumber = 0;
int increment = leftToRight ? 1 : -1;
bool previousPixelValue = leftToRight;
while ((leftToRight ? imageColumn < maxColumn : imageColumn >= minColumn) &&
moduleNumber < moduleBitCount.Length)
{
if (image[imageColumn, imageRow] == previousPixelValue)
{
moduleBitCount[moduleNumber]++;
imageColumn += increment;
}
else
{
moduleNumber++;
previousPixelValue = !previousPixelValue;
}
}
if (moduleNumber == moduleBitCount.Length ||
((imageColumn == (leftToRight ? maxColumn : minColumn)) &&
moduleNumber == moduleBitCount.Length - 1))
{
return moduleBitCount;
}
return null;
}
/// <summary>
/// Gets the number of EC code words.
/// </summary>
/// <returns>The number of EC code words.</returns>
/// <param name="barcodeECLevel">Barcode EC level.</param>
private static int getNumberOfECCodeWords(int barcodeECLevel)
{
return 2 << barcodeECLevel;
}
/// <summary>
/// Adjusts the codeword start column.
/// </summary>
/// <returns>The codeword start column.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="codewordStartColumn">Codeword start column.</param>
/// <param name="imageRow">Image row.</param>
private static int adjustCodewordStartColumn(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int codewordStartColumn,
int imageRow)
{
int correctedStartColumn = codewordStartColumn;
int increment = leftToRight ? -1 : 1;
// there should be no black pixels before the start column. If there are, then we need to start earlier.
for (int i = 0; i < 2; i++)
{
while ((leftToRight ? correctedStartColumn >= minColumn : correctedStartColumn < maxColumn) &&
leftToRight == image[correctedStartColumn, imageRow])
{
if (Math.Abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE)
{
return codewordStartColumn;
}
correctedStartColumn += increment;
}
increment = -increment;
leftToRight = !leftToRight;
}
return correctedStartColumn;
}
/// <summary>
/// Checks the codeword for any skew.
/// </summary>
/// <returns><c>true</c>, if codeword is within the skew, <c>false</c> otherwise.</returns>
/// <param name="codewordSize">Codeword size.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static bool checkCodewordSkew(int codewordSize, int minCodewordWidth, int maxCodewordWidth)
{
return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize &&
codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE;
}
/// <summary>
/// Decodes the codewords.
/// </summary>
/// <returns>The codewords.</returns>
/// <param name="codewords">Codewords.</param>
/// <param name="ecLevel">Ec level.</param>
/// <param name="erasures">Erasures.</param>
private static DecoderResult decodeCodewords(int[] codewords, int ecLevel, int[] erasures)
{
if (codewords.Length == 0)
{
return null;
}
int numECCodewords = 1 << (ecLevel + 1);
int correctedErrorsCount = correctErrors(codewords, erasures, numECCodewords);
if (correctedErrorsCount < 0)
{
return null;
}
if (!verifyCodewordCount(codewords, numECCodewords))
{
return null;
}
// Decode the codewords
DecoderResult decoderResult = DecodedBitStreamParser.decode(codewords, ecLevel.ToString());
if (decoderResult != null)
{
decoderResult.ErrorsCorrected = correctedErrorsCount;
decoderResult.Erasures = erasures.Length;
}
return decoderResult;
}
/// <summary>
/// Given data and error-correction codewords received, possibly corrupted by errors, attempts to
/// correct the errors in-place.
/// </summary>
/// <returns>The errors.</returns>
/// <param name="codewords">data and error correction codewords.</param>
/// <param name="erasures">positions of any known erasures.</param>
/// <param name="numECCodewords">number of error correction codewords that are available in codewords.</param>
private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords)
{
if (erasures != null &&
erasures.Length > numECCodewords / 2 + MAX_ERRORS ||
numECCodewords < 0 ||
numECCodewords > MAX_EC_CODEWORDS)
{
// Too many errors or EC Codewords is corrupted
return -1;
}
int errorCount;
if (!errorCorrection.decode(codewords, numECCodewords, erasures, out errorCount))
{
return -1;
}
return errorCount;
}
/// <summary>
/// Verifies that all is well with the the codeword array.
/// </summary>
/// <param name="codewords">Codewords.</param>
/// <param name="numECCodewords">Number EC codewords.</param>
private static bool verifyCodewordCount(int[] codewords, int numECCodewords)
{
if (codewords.Length < 4)
{
// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
return false;
}
// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
int numberOfCodewords = codewords[0];
if (numberOfCodewords > codewords.Length)
{
return false;
}
if (numberOfCodewords == 0)
{
// Reset to the Length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if (numECCodewords < codewords.Length)
{
codewords[0] = codewords.Length - numECCodewords;
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the bit count for codeword.
/// </summary>
/// <returns>The bit count for codeword.</returns>
/// <param name="codeword">Codeword.</param>
private static int[] getBitCountForCodeword(int codeword)
{
int[] result = new int[8];
int previousValue = 0;
int i = result.Length - 1;
while (true)
{
if ((codeword & 0x1) != previousValue)
{
previousValue = codeword & 0x1;
i--;
if (i < 0)
{
break;
}
}
result[i]++;
codeword >>= 1;
}
return result;
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="codeword">Codeword.</param>
private static int getCodewordBucketNumber(int codeword)
{
return getCodewordBucketNumber(getBitCountForCodeword(codeword));
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="moduleBitCount">Module bit count.</param>
private static int getCodewordBucketNumber(int[] moduleBitCount)
{
return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9) % 9;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.</returns>
/// <param name="barcodeMatrix">Barcode matrix as a jagged array.</param>
public static String ToString(BarcodeValue[][] barcodeMatrix)
{
StringBuilder formatter = new StringBuilder();
for (int row = 0; row < barcodeMatrix.Length; row++)
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "Row {0,2}: ", row);
for (int column = 0; column < barcodeMatrix[row].Length; column++)
{
BarcodeValue barcodeValue = barcodeMatrix[row][column];
int[] values = barcodeValue.getValue();
if (values.Length == 0)
{
formatter.Append(" ");
}
else
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "{0,4}({1,2})", values[0], barcodeValue.getConfidence(values[0]));
}
}
formatter.Append("\n");
}
return formatter.ToString();
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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 UnityEngine;
using UnityEditor;
namespace Spine.Unity.Editor {
using Event = UnityEngine.Event;
using Icons = SpineEditorUtilities.Icons;
[CustomEditor(typeof(BoundingBoxFollower))]
public class BoundingBoxFollowerInspector : UnityEditor.Editor {
SerializedProperty skeletonRenderer, slotName, isTrigger, clearStateOnDisable;
BoundingBoxFollower follower;
bool rebuildRequired = false;
bool addBoneFollower = false;
bool sceneRepaintRequired = false;
bool debugIsExpanded;
GUIContent addBoneFollowerLabel;
GUIContent AddBoneFollowerLabel {
get {
if (addBoneFollowerLabel == null) addBoneFollowerLabel = new GUIContent("Add Bone Follower", Icons.bone);
return addBoneFollowerLabel;
}
}
void OnEnable () {
skeletonRenderer = serializedObject.FindProperty("skeletonRenderer");
slotName = serializedObject.FindProperty("slotName");
isTrigger = serializedObject.FindProperty("isTrigger");
clearStateOnDisable = serializedObject.FindProperty("clearStateOnDisable");
follower = (BoundingBoxFollower)target;
}
public override void OnInspectorGUI () {
bool isInspectingPrefab = (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab);
// Try to auto-assign SkeletonRenderer field.
if (skeletonRenderer.objectReferenceValue == null) {
var foundSkeletonRenderer = follower.GetComponentInParent<SkeletonRenderer>();
if (foundSkeletonRenderer != null)
Debug.Log("BoundingBoxFollower automatically assigned: " + foundSkeletonRenderer.gameObject.name);
else if (Event.current.type == EventType.Repaint)
Debug.Log("No Spine GameObject detected. Make sure to set this GameObject as a child of the Spine GameObject; or set BoundingBoxFollower's 'Skeleton Renderer' field in the inspector.");
skeletonRenderer.objectReferenceValue = foundSkeletonRenderer;
serializedObject.ApplyModifiedProperties();
}
var sr = skeletonRenderer.objectReferenceValue as SkeletonRenderer;
if (sr != null && sr.gameObject == follower.gameObject) {
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) {
EditorGUILayout.HelpBox("It's ideal to add BoundingBoxFollower to a separate child GameObject of the Spine GameObject.", MessageType.Warning);
if (GUILayout.Button(new GUIContent("Move BoundingBoxFollower to new GameObject", Icons.boundingBox), GUILayout.Height(50f))) {
AddBoundingBoxFollowerChild(sr, follower);
DestroyImmediate(follower);
return;
}
}
EditorGUILayout.Space();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(skeletonRenderer);
EditorGUILayout.PropertyField(slotName, new GUIContent("Slot"));
if (EditorGUI.EndChangeCheck()) {
serializedObject.ApplyModifiedProperties();
if (!isInspectingPrefab)
rebuildRequired = true;
}
using (new SpineInspectorUtility.LabelWidthScope(150f)) {
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(isTrigger);
bool triggerChanged = EditorGUI.EndChangeCheck();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(clearStateOnDisable, new GUIContent(clearStateOnDisable.displayName, "Enable this if you are pooling your Spine GameObject"));
bool clearStateChanged = EditorGUI.EndChangeCheck();
if (clearStateChanged || triggerChanged) {
serializedObject.ApplyModifiedProperties();
if (triggerChanged)
foreach (var col in follower.colliderTable.Values)
col.isTrigger = isTrigger.boolValue;
}
}
if (isInspectingPrefab) {
follower.colliderTable.Clear();
follower.nameTable.Clear();
EditorGUILayout.HelpBox("BoundingBoxAttachments cannot be previewed in prefabs.", MessageType.Info);
// How do you prevent components from being saved into the prefab? No such HideFlag. DontSaveInEditor | DontSaveInBuild does not work. DestroyImmediate does not work.
var collider = follower.GetComponent<PolygonCollider2D>();
if (collider != null) Debug.LogWarning("Found BoundingBoxFollower collider components in prefab. These are disposed and regenerated at runtime.");
} else {
using (new SpineInspectorUtility.BoxScope()) {
if (debugIsExpanded = EditorGUILayout.Foldout(debugIsExpanded, "Debug Colliders")) {
EditorGUI.indentLevel++;
EditorGUILayout.LabelField(string.Format("Attachment Names ({0} PolygonCollider2D)", follower.colliderTable.Count));
EditorGUI.BeginChangeCheck();
foreach (var kp in follower.nameTable) {
string attachmentName = kp.Value;
var collider = follower.colliderTable[kp.Key];
bool isPlaceholder = attachmentName != kp.Key.Name;
collider.enabled = EditorGUILayout.ToggleLeft(new GUIContent(!isPlaceholder ? attachmentName : string.Format("{0} [{1}]", attachmentName, kp.Key.Name), isPlaceholder ? Icons.skinPlaceholder : Icons.boundingBox), collider.enabled);
}
sceneRepaintRequired |= EditorGUI.EndChangeCheck();
EditorGUI.indentLevel--;
}
}
}
bool hasBoneFollower = follower.GetComponent<BoneFollower>() != null;
if (!hasBoneFollower) {
bool buttonDisabled = follower.Slot == null;
using (new EditorGUI.DisabledGroupScope(buttonDisabled)) {
addBoneFollower |= SpineInspectorUtility.LargeCenteredButton(AddBoneFollowerLabel, true);
EditorGUILayout.Space();
}
}
if (Event.current.type == EventType.Repaint) {
if (addBoneFollower) {
var boneFollower = follower.gameObject.AddComponent<BoneFollower>();
boneFollower.SetBone(follower.Slot.Data.BoneData.Name);
addBoneFollower = false;
}
if (sceneRepaintRequired) {
SceneView.RepaintAll();
sceneRepaintRequired = false;
}
if (rebuildRequired) {
follower.Initialize();
rebuildRequired = false;
}
}
}
#region Menus
[MenuItem("CONTEXT/SkeletonRenderer/Add BoundingBoxFollower GameObject")]
static void AddBoundingBoxFollowerChild (MenuCommand command) {
var go = AddBoundingBoxFollowerChild((SkeletonRenderer)command.context);
Undo.RegisterCreatedObjectUndo(go, "Add BoundingBoxFollower");
}
#endregion
static GameObject AddBoundingBoxFollowerChild (SkeletonRenderer sr, BoundingBoxFollower original = null) {
var go = new GameObject("BoundingBoxFollower");
go.transform.SetParent(sr.transform, false);
var newFollower = go.AddComponent<BoundingBoxFollower>();
if (original != null) {
newFollower.slotName = original.slotName;
newFollower.isTrigger = original.isTrigger;
newFollower.clearStateOnDisable = original.clearStateOnDisable;
}
newFollower.skeletonRenderer = sr;
newFollower.Initialize();
Selection.activeGameObject = go;
EditorGUIUtility.PingObject(go);
return go;
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Windows.Forms;
using DeOps.Services;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Comm;
using DeOps.Implementation.Protocol.Net;
namespace DeOps.Interface.Tools
{
/// <summary>
/// Summary description for PacketsForm.
/// </summary>
public class PacketsForm : DeOps.Interface.CustomIconForm
{
DhtNetwork Network;
G2Protocol Protocol;
SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.ListView ListViewPackets;
private System.Windows.Forms.ColumnHeader columnHeaderProtocol;
private System.Windows.Forms.ColumnHeader columnHeaderType;
private System.Windows.Forms.ColumnHeader columnHeaderAddress;
private System.Windows.Forms.ColumnHeader columnHeaderSize;
private System.Windows.Forms.TreeView TreeViewPacket;
private System.Windows.Forms.ColumnHeader columnHeaderHash;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItemCommands;
private System.Windows.Forms.MenuItem menuItemPause;
private MenuItem MenuItemTcp;
private MenuItem MenuItemUdp;
private MenuItem MenuItemRudp;
private ColumnHeader columnHeaderTime;
private MenuItem ClearMenuItem;
private MenuItem MenuItemTunnel;
private MenuItem MenuItemLAN;
private IContainer components;
public static void Show(DhtNetwork network)
{
var form = new PacketsForm(network);
form.Show();
form.Activate();
}
public PacketsForm(DhtNetwork network)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
Network = network;
Protocol = new G2Protocol();
Text = "Packets (" + Network.GetLabel() + ")";
RefreshView();
Network.UpdatePacketLog += AsyncUpdateLog;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.TreeViewPacket = new System.Windows.Forms.TreeView();
this.splitter1 = new System.Windows.Forms.Splitter();
this.ListViewPackets = new System.Windows.Forms.ListView();
this.columnHeaderTime = new System.Windows.Forms.ColumnHeader();
this.columnHeaderProtocol = new System.Windows.Forms.ColumnHeader();
this.columnHeaderAddress = new System.Windows.Forms.ColumnHeader();
this.columnHeaderType = new System.Windows.Forms.ColumnHeader();
this.columnHeaderSize = new System.Windows.Forms.ColumnHeader();
this.columnHeaderHash = new System.Windows.Forms.ColumnHeader();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.menuItemCommands = new System.Windows.Forms.MenuItem();
this.ClearMenuItem = new System.Windows.Forms.MenuItem();
this.menuItemPause = new System.Windows.Forms.MenuItem();
this.MenuItemTcp = new System.Windows.Forms.MenuItem();
this.MenuItemUdp = new System.Windows.Forms.MenuItem();
this.MenuItemLAN = new System.Windows.Forms.MenuItem();
this.MenuItemRudp = new System.Windows.Forms.MenuItem();
this.MenuItemTunnel = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// TreeViewPacket
//
this.TreeViewPacket.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.TreeViewPacket.Dock = System.Windows.Forms.DockStyle.Bottom;
this.TreeViewPacket.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TreeViewPacket.Location = new System.Drawing.Point(0, 214);
this.TreeViewPacket.Name = "TreeViewPacket";
this.TreeViewPacket.Size = new System.Drawing.Size(568, 112);
this.TreeViewPacket.TabIndex = 0;
this.TreeViewPacket.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TreeViewPacket_MouseClick);
this.TreeViewPacket.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TreeViewPacket_KeyDown);
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter1.Location = new System.Drawing.Point(0, 208);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(568, 6);
this.splitter1.TabIndex = 1;
this.splitter1.TabStop = false;
//
// ListViewPackets
//
this.ListViewPackets.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.ListViewPackets.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderTime,
this.columnHeaderProtocol,
this.columnHeaderAddress,
this.columnHeaderType,
this.columnHeaderSize,
this.columnHeaderHash});
this.ListViewPackets.Dock = System.Windows.Forms.DockStyle.Fill;
this.ListViewPackets.FullRowSelect = true;
this.ListViewPackets.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.ListViewPackets.Location = new System.Drawing.Point(0, 0);
this.ListViewPackets.MultiSelect = false;
this.ListViewPackets.Name = "ListViewPackets";
this.ListViewPackets.Size = new System.Drawing.Size(568, 208);
this.ListViewPackets.TabIndex = 2;
this.ListViewPackets.UseCompatibleStateImageBehavior = false;
this.ListViewPackets.View = System.Windows.Forms.View.Details;
this.ListViewPackets.Click += new System.EventHandler(this.ListViewPackets_Click);
//
// columnHeaderTime
//
this.columnHeaderTime.Text = "Time";
//
// columnHeaderProtocol
//
this.columnHeaderProtocol.Text = "Protocol";
this.columnHeaderProtocol.Width = 92;
//
// columnHeaderAddress
//
this.columnHeaderAddress.Text = "Address";
this.columnHeaderAddress.Width = 99;
//
// columnHeaderType
//
this.columnHeaderType.Text = "Type";
this.columnHeaderType.Width = 78;
//
// columnHeaderSize
//
this.columnHeaderSize.Text = "Size";
this.columnHeaderSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.columnHeaderSize.Width = 90;
//
// columnHeaderHash
//
this.columnHeaderHash.Text = "Hash";
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemCommands});
//
// menuItemCommands
//
this.menuItemCommands.Index = 0;
this.menuItemCommands.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.ClearMenuItem,
this.menuItemPause,
this.MenuItemTcp,
this.MenuItemUdp,
this.MenuItemLAN,
this.MenuItemRudp,
this.MenuItemTunnel});
this.menuItemCommands.Text = "Commands";
//
// ClearMenuItem
//
this.ClearMenuItem.Index = 0;
this.ClearMenuItem.Text = "Clear";
this.ClearMenuItem.Click += new System.EventHandler(this.ClearMenuItem_Click);
//
// menuItemPause
//
this.menuItemPause.Index = 1;
this.menuItemPause.Text = "Pause";
this.menuItemPause.Click += new System.EventHandler(this.menuItemPause_Click);
//
// MenuItemTcp
//
this.MenuItemTcp.Checked = true;
this.MenuItemTcp.Index = 2;
this.MenuItemTcp.Text = "Tcp";
this.MenuItemTcp.Click += new System.EventHandler(this.MenuItemTcp_Click);
//
// MenuItemUdp
//
this.MenuItemUdp.Checked = true;
this.MenuItemUdp.Index = 3;
this.MenuItemUdp.Text = "Udp";
this.MenuItemUdp.Click += new System.EventHandler(this.MenuItemUdp_Click);
//
// MenuItemLAN
//
this.MenuItemLAN.Checked = true;
this.MenuItemLAN.Index = 4;
this.MenuItemLAN.Text = "LAN";
this.MenuItemLAN.Click += new System.EventHandler(this.MenuItemLAN_Click);
//
// MenuItemRudp
//
this.MenuItemRudp.Checked = true;
this.MenuItemRudp.Index = 5;
this.MenuItemRudp.Text = "Rudp";
this.MenuItemRudp.Click += new System.EventHandler(this.MenuItemRudp_Click);
//
// MenuItemTunnel
//
this.MenuItemTunnel.Checked = true;
this.MenuItemTunnel.Index = 6;
this.MenuItemTunnel.Text = "Tunnel";
this.MenuItemTunnel.Click += new System.EventHandler(this.MenuItemTunnel_Click);
//
// PacketsForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(568, 326);
this.Controls.Add(this.ListViewPackets);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.TreeViewPacket);
this.Menu = this.mainMenu1;
this.Name = "PacketsForm";
this.Text = "Packets";
this.Load += new System.EventHandler(this.PacketsForm_Load);
this.Closing += new System.ComponentModel.CancelEventHandler(this.PacketsForm_Closing);
this.ResumeLayout(false);
}
#endregion
private void PacketsForm_Load(object sender, System.EventArgs e)
{
}
private void PacketsForm_Closing(object sender, System.EventArgs e)
{
Network.UpdatePacketLog -= AsyncUpdateLog;
}
public void AsyncUpdateLog(PacketLogEntry logEntry)
{
if(menuItemPause.Checked)
return;
AddListItem(logEntry);
if (!ListViewPackets.Focused && ListViewPackets.Items.Count > 0)
ListViewPackets.EnsureVisible(ListViewPackets.Items.Count - 1);
}
private void AddListItem(PacketLogEntry logEntry)
{
if ((logEntry.Protocol == TransportProtocol.Tcp && MenuItemTcp.Checked) ||
(logEntry.Protocol == TransportProtocol.Udp && MenuItemUdp.Checked) ||
(logEntry.Protocol == TransportProtocol.LAN && MenuItemLAN.Checked) ||
(logEntry.Protocol == TransportProtocol.Rudp && MenuItemRudp.Checked) ||
(logEntry.Protocol == TransportProtocol.Tunnel && MenuItemTunnel.Checked))
ListViewPackets.Items.Add(PackettoItem(logEntry));
}
public ListViewItem PackettoItem(PacketLogEntry logEntry)
{
// hash, protocol, direction, address, type, size
string hash = Utilities.BytestoHex(sha.ComputeHash( logEntry.Data), 0, 2, false);
string protocol = logEntry.Protocol.ToString();
// Network - Search / Search Req / Store ... - Component
// Comm - Data / Ack / Syn
// Rudp - Type - Component
string name = "?";
G2Header root = new G2Header(logEntry.Data);
if (G2Protocol.ReadPacket(root))
{
if(logEntry.Protocol == TransportProtocol.Rudp)
{
name = TransportProtocol.Rudp.ToString() + " - ";
name += GetVariableName(typeof(CommPacket), root.Name);
if (root.Name == CommPacket.Data)
{
CommData data = CommData.Decode(root);
name += " - " + Network.Core.GetServiceName(data.Service);
}
}
else
{
name = GetVariableName(typeof(RootPacket), root.Name) + " - ";
if (root.Name == RootPacket.Comm)
{
RudpPacket commPacket = RudpPacket.Decode(root);
name += GetVariableName(typeof(RudpPacketType), commPacket.PacketType);
}
if (root.Name == RootPacket.Network)
{
NetworkPacket netPacket = NetworkPacket.Decode(root);
G2Header internalRoot = new G2Header(netPacket.InternalData);
if (G2Protocol.ReadPacket(internalRoot))
{
name += GetVariableName(typeof(NetworkPacket), internalRoot.Name);
uint id = 0;
G2ReceivedPacket wrap = new G2ReceivedPacket();
wrap.Root = internalRoot;
// search request / search acks / stores have component types
if (internalRoot.Name == NetworkPacket.SearchRequest)
{
SearchReq req = SearchReq.Decode(wrap);
id = req.Service;
}
if (internalRoot.Name == NetworkPacket.SearchAck)
{
SearchAck ack = SearchAck.Decode(wrap);
id = ack.Service;
}
if (internalRoot.Name == NetworkPacket.StoreRequest)
{
StoreReq store = StoreReq.Decode(wrap);
id = store.Service;
}
if(id != 0)
name += " - " + Network.Core.GetServiceName(id); // GetVariableName(typeof(ServiceID), id);
}
}
}
}
string time = logEntry.Time.ToString("HH:mm:ss:ff");
string address = (logEntry.Address == null) ? "Broadcast" : logEntry.Address.ToString();
return new PacketListViewItem(logEntry, new string[] { time, protocol, address, name, logEntry.Data.Length.ToString(), hash }, logEntry.Direction == DirectionType.In );
}
private string GetVariableName(Type packet, byte val)
{
FieldInfo[] fields = packet.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
foreach (FieldInfo info in fields)
if(info.IsLiteral && val == (byte) info.GetValue(null))
return info.Name;
return "unknown";
}
private string GetVariableName(Type packet, ushort val)
{
FieldInfo[] fields = packet.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
foreach (FieldInfo info in fields)
if (info.IsLiteral && val == (ushort)info.GetValue(null))
return info.Name;
return "unknown";
}
private void ListViewPackets_Click(object sender, System.EventArgs e)
{
if(ListViewPackets.SelectedItems.Count == 0)
return;
PacketListViewItem selected = (PacketListViewItem) ListViewPackets.SelectedItems[0];
// build tree
TreeViewPacket.Nodes.Clear();
G2Header root = new G2Header(selected.LogEntry.Data);
if (G2Protocol.ReadPacket(root))
{
if (selected.LogEntry.Protocol == TransportProtocol.Rudp)
{
string name = root.Name.ToString() + " : " + GetVariableName(typeof(CommPacket), root.Name);
TreeNode rootNode = TreeViewPacket.Nodes.Add(name);
if (G2Protocol.ReadPayload(root))
rootNode.Nodes.Add(new DataNode(root.Data, root.PayloadPos, root.PayloadSize));
G2Protocol.ResetPacket(root);
// get type
Type packetType = null;
switch (root.Name)
{
case CommPacket.SessionRequest:
packetType = typeof(SessionRequest);
break;
case CommPacket.SessionAck:
packetType = typeof(SessionAck);
break;
case CommPacket.KeyRequest:
packetType = typeof(KeyRequest);
break;
case CommPacket.KeyAck:
packetType = typeof(KeyAck);
break;
case CommPacket.Data:
packetType = typeof(CommData);
break;
case CommPacket.Close:
packetType = typeof(CommClose);
break;
}
ReadChildren(root, rootNode, packetType);
}
else
{
string name = root.Name.ToString() + " : " + GetVariableName(typeof(RootPacket), root.Name);
TreeNode rootNode = TreeViewPacket.Nodes.Add(name);
DataNode payloadNode = null;
if (G2Protocol.ReadPayload(root))
{
payloadNode = new DataNode(root.Data, root.PayloadPos, root.PayloadSize);
rootNode.Nodes.Add(payloadNode);
}
G2Protocol.ResetPacket(root);
if (root.Name == RootPacket.Comm)
{
ReadChildren(root, rootNode, typeof(RudpPacket));
}
if (root.Name == RootPacket.Tunnel)
{
ReadChildren(root, rootNode, typeof(RudpPacket));
}
if (root.Name == RootPacket.Network)
{
ReadChildren(root, rootNode, typeof(NetworkPacket));
G2Header payloadRoot = new G2Header(payloadNode.Data);
if (payloadNode.Data != null && G2Protocol.ReadPacket(payloadRoot))
{
name = payloadRoot.Name.ToString() + " : " + GetVariableName(typeof(NetworkPacket), payloadRoot.Name);
TreeNode netNode = payloadNode.Nodes.Add(name);
if (G2Protocol.ReadPayload(payloadRoot))
netNode.Nodes.Add(new DataNode(payloadRoot.Data, payloadRoot.PayloadPos, payloadRoot.PayloadSize));
G2Protocol.ResetPacket(payloadRoot);
Type packetType = null;
switch (payloadRoot.Name)
{
case NetworkPacket.SearchRequest:
packetType = typeof(SearchReq);
break;
case NetworkPacket.SearchAck:
packetType = typeof(SearchAck);
break;
case NetworkPacket.StoreRequest:
packetType = typeof(StoreReq);
break;
case NetworkPacket.Ping:
packetType = typeof(Ping);
break;
case NetworkPacket.Pong:
packetType = typeof(Pong);
break;
case NetworkPacket.Bye:
packetType = typeof(Bye);
break;
case NetworkPacket.ProxyRequest:
packetType = typeof(ProxyReq);
break;
case NetworkPacket.ProxyAck:
packetType = typeof(ProxyAck);
break;
case NetworkPacket.CrawlRequest:
packetType = typeof(CrawlRequest);
break;
case NetworkPacket.CrawlAck:
packetType = typeof(CrawlAck);
break;
}
ReadChildren(payloadRoot, netNode, packetType);
}
}
}
}
/*G2Header rootPacket = new G2Header(selected.LogEntry.Data);
int start = 0;
int size = selected.LogEntry.Data.Length;
if(G2ReadResult.PACKET_GOOD == Protocol.ReadNextPacket(rootPacket, ref start, ref size) )
{
TreeNode rootNode = TreeViewPacket.Nodes.Add( TrimName(rootPacket.Name.ToString()) );
if(G2Protocol.ReadPayload(rootPacket))
{
//rootNode.Nodes.Add( Utilities.BytestoAscii(rootPacket.Data, rootPacket.PayloadPos, rootPacket.PayloadSize));
rootNode.Nodes.Add( Utilities.BytestoHex(rootPacket.Data, rootPacket.PayloadPos, rootPacket.PayloadSize, true));
}
G2Protocol.ResetPacket(rootPacket);
ReadChildren(rootPacket, rootNode, null);
}*/
TreeViewPacket.ExpandAll();
}
public void ReadChildren(G2Header rootPacket, TreeNode rootNode, Type packetType)
{
G2Header child = new G2Header(rootPacket.Data);
while( G2Protocol.ReadNextChild(rootPacket, child) == G2ReadResult.PACKET_GOOD )
{
string name = child.Name.ToString();
if (packetType != null)
name += " : " + GetVariableName(packetType, child.Name);
TreeNode childNode = rootNode.Nodes.Add(name);
if(G2Protocol.ReadPayload(child))
{
//childNode.Nodes.Add( "Payload Ascii: " + Utilities.BytestoAscii(childPacket.Data, childPacket.PayloadPos, childPacket.PayloadSize));
childNode.Nodes.Add(new DataNode(child.Data, child.PayloadPos, child.PayloadSize));
}
G2Protocol.ResetPacket(child);
ReadChildren(child, childNode, null);
}
}
string TrimName(string name)
{
int pos = name.LastIndexOf("/");
return name.Substring(pos + 1);
}
private void TreeViewPacket_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.Control && e.KeyCode == Keys.C)
Clipboard.SetDataObject(TreeViewPacket.SelectedNode.Text, true);
}
private void menuItemPause_Click(object sender, System.EventArgs e)
{
menuItemPause.Checked = !menuItemPause.Checked;
if (!menuItemPause.Checked)
RefreshView();
}
private void MenuItemUdp_Click(object sender, EventArgs e)
{
MenuItemUdp.Checked = !MenuItemUdp.Checked;
RefreshView();
}
private void MenuItemTcp_Click(object sender, EventArgs e)
{
MenuItemTcp.Checked = !MenuItemTcp.Checked;
RefreshView();
}
private void MenuItemRudp_Click(object sender, EventArgs e)
{
MenuItemRudp.Checked = !MenuItemRudp.Checked;
RefreshView();
}
private void MenuItemTunnel_Click(object sender, EventArgs e)
{
MenuItemTunnel.Checked = !MenuItemTunnel.Checked;
RefreshView();
}
private void MenuItemLAN_Click(object sender, EventArgs e)
{
MenuItemLAN.Checked = !MenuItemLAN.Checked;
}
void RefreshView()
{
// un-pause
ListViewPackets.Items.Clear();
lock (Network.LoggedPackets)
foreach (PacketLogEntry logEntry in Network.LoggedPackets)
AddListItem(logEntry);
}
private void TreeViewPacket_MouseClick(object sender, MouseEventArgs e)
{
TreeNode item = TreeViewPacket.GetNodeAt(e.Location);
if (item == null)
return;
TreeViewPacket.SelectedNode = item;
DataNode node = item as DataNode;
if (node == null || e.Button != MouseButtons.Right)
return;
ContextMenu menu = new ContextMenu();
if(node.Data.Length == 8)
menu.MenuItems.Add("To Binary", new EventHandler(Menu_ToBinary));
if (node.Data.Length == 8 || node.Data.Length == 4 || node.Data.Length == 2 || node.Data.Length == 1)
menu.MenuItems.Add("To Decimal", new EventHandler(Menu_ToDecimal));
menu.MenuItems.Add("To Hex", new EventHandler(Menu_ToHex));
if (node.Data.Length == 4)
menu.MenuItems.Add("To IP", new EventHandler(Menu_ToIP));
menu.Show(TreeViewPacket, e.Location);
}
private void Menu_ToBinary(object sender, EventArgs e)
{
DataNode node = TreeViewPacket.SelectedNode as DataNode;
if (node == null)
return;
if (node.Data.Length == 8)
node.Text = Utilities.IDtoBin(BitConverter.ToUInt64(node.Data, 0));
}
private void Menu_ToDecimal(object sender, EventArgs e)
{
DataNode node = TreeViewPacket.SelectedNode as DataNode;
if (node == null)
return;
if (node.Data.Length == 8)
node.Text = BitConverter.ToUInt64(node.Data, 0).ToString();
if (node.Data.Length == 4)
node.Text = BitConverter.ToUInt32(node.Data, 0).ToString();
if (node.Data.Length == 2)
node.Text = BitConverter.ToUInt16(node.Data, 0).ToString();
if (node.Data.Length == 1)
node.Text = node.Data[0].ToString();
}
private void Menu_ToHex(object sender, EventArgs e)
{
DataNode node = TreeViewPacket.SelectedNode as DataNode;
if (node == null)
return;
node.Text = Utilities.BytestoHex(node.Data, 0, node.Data.Length, true);
}
private void Menu_ToIP(object sender, EventArgs e)
{
DataNode node = TreeViewPacket.SelectedNode as DataNode;
if (node == null)
return;
if (node.Data.Length == 4)
node.Text = new IPAddress(node.Data).ToString();
}
private void ClearMenuItem_Click(object sender, EventArgs e)
{
ListViewPackets.Items.Clear();
TreeViewPacket.Nodes.Clear();
}
}
public class DataNode : TreeNode
{
public byte[] Data;
public DataNode(byte[] buffer, int pos, int length)
: base(Utilities.BytestoHex(buffer, pos, length, true))
{
Data = Utilities.ExtractBytes(buffer, pos, length);
}
}
public class PacketListViewItem : ListViewItem
{
public PacketLogEntry LogEntry;
public PacketListViewItem(PacketLogEntry logEntry, string[] subItems, bool incoming) : base(subItems)
{
LogEntry = logEntry;
ForeColor = incoming ? Color.DarkBlue : Color.DarkRed;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ISpecialOfferOriginalData : ISchemaBaseOriginalData
{
string Description { get; }
string DiscountPct { get; }
string Type { get; }
string Category { get; }
System.DateTime StartDate { get; }
System.DateTime EndDate { get; }
int MinQty { get; }
string MaxQty { get; }
string rowguid { get; }
}
public partial class SpecialOffer : OGM<SpecialOffer, SpecialOffer.SpecialOfferData, System.String>, ISchemaBase, INeo4jBase, ISpecialOfferOriginalData
{
#region Initialize
static SpecialOffer()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, SpecialOffer> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.SpecialOfferAlias, IWhereQuery> query)
{
q.SpecialOfferAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.SpecialOffer.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"SpecialOffer => Description : {this.Description}, DiscountPct : {this.DiscountPct}, Type : {this.Type}, Category : {this.Category}, StartDate : {this.StartDate}, EndDate : {this.EndDate}, MinQty : {this.MinQty}, MaxQty : {this.MaxQty}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new SpecialOfferData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Description == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the Description cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.DiscountPct == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the DiscountPct cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.Type == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the Type cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.Category == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the Category cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.StartDate == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the StartDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.EndDate == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the EndDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.MinQty == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the MinQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.MaxQty == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the MaxQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save SpecialOffer with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class SpecialOfferData : Data<System.String>
{
public SpecialOfferData()
{
}
public SpecialOfferData(SpecialOfferData data)
{
Description = data.Description;
DiscountPct = data.DiscountPct;
Type = data.Type;
Category = data.Category;
StartDate = data.StartDate;
EndDate = data.EndDate;
MinQty = data.MinQty;
MaxQty = data.MaxQty;
rowguid = data.rowguid;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "SpecialOffer";
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Description", Description);
dictionary.Add("DiscountPct", DiscountPct);
dictionary.Add("Type", Type);
dictionary.Add("Category", Category);
dictionary.Add("StartDate", Conversion<System.DateTime, long>.Convert(StartDate));
dictionary.Add("EndDate", Conversion<System.DateTime, long>.Convert(EndDate));
dictionary.Add("MinQty", Conversion<int, long>.Convert(MinQty));
dictionary.Add("MaxQty", MaxQty);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("Description", out value))
Description = (string)value;
if (properties.TryGetValue("DiscountPct", out value))
DiscountPct = (string)value;
if (properties.TryGetValue("Type", out value))
Type = (string)value;
if (properties.TryGetValue("Category", out value))
Category = (string)value;
if (properties.TryGetValue("StartDate", out value))
StartDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("EndDate", out value))
EndDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("MinQty", out value))
MinQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("MaxQty", out value))
MaxQty = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ISpecialOffer
public string Description { get; set; }
public string DiscountPct { get; set; }
public string Type { get; set; }
public string Category { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public int MinQty { get; set; }
public string MaxQty { get; set; }
public string rowguid { get; set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ISpecialOffer
public string Description { get { LazyGet(); return InnerData.Description; } set { if (LazySet(Members.Description, InnerData.Description, value)) InnerData.Description = value; } }
public string DiscountPct { get { LazyGet(); return InnerData.DiscountPct; } set { if (LazySet(Members.DiscountPct, InnerData.DiscountPct, value)) InnerData.DiscountPct = value; } }
public string Type { get { LazyGet(); return InnerData.Type; } set { if (LazySet(Members.Type, InnerData.Type, value)) InnerData.Type = value; } }
public string Category { get { LazyGet(); return InnerData.Category; } set { if (LazySet(Members.Category, InnerData.Category, value)) InnerData.Category = value; } }
public System.DateTime StartDate { get { LazyGet(); return InnerData.StartDate; } set { if (LazySet(Members.StartDate, InnerData.StartDate, value)) InnerData.StartDate = value; } }
public System.DateTime EndDate { get { LazyGet(); return InnerData.EndDate; } set { if (LazySet(Members.EndDate, InnerData.EndDate, value)) InnerData.EndDate = value; } }
public int MinQty { get { LazyGet(); return InnerData.MinQty; } set { if (LazySet(Members.MinQty, InnerData.MinQty, value)) InnerData.MinQty = value; } }
public string MaxQty { get { LazyGet(); return InnerData.MaxQty; } set { if (LazySet(Members.MaxQty, InnerData.MaxQty, value)) InnerData.MaxQty = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static SpecialOfferMembers members = null;
public static SpecialOfferMembers Members
{
get
{
if (members == null)
{
lock (typeof(SpecialOffer))
{
if (members == null)
members = new SpecialOfferMembers();
}
}
return members;
}
}
public class SpecialOfferMembers
{
internal SpecialOfferMembers() { }
#region Members for interface ISpecialOffer
public Property Description { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["Description"];
public Property DiscountPct { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["DiscountPct"];
public Property Type { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["Type"];
public Property Category { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["Category"];
public Property StartDate { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["StartDate"];
public Property EndDate { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["EndDate"];
public Property MinQty { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["MinQty"];
public Property MaxQty { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["MaxQty"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["SpecialOffer"].Properties["rowguid"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static SpecialOfferFullTextMembers fullTextMembers = null;
public static SpecialOfferFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(SpecialOffer))
{
if (fullTextMembers == null)
fullTextMembers = new SpecialOfferFullTextMembers();
}
}
return fullTextMembers;
}
}
public class SpecialOfferFullTextMembers
{
internal SpecialOfferFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(SpecialOffer))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["SpecialOffer"];
}
}
return entity;
}
private static SpecialOfferEvents events = null;
public static SpecialOfferEvents Events
{
get
{
if (events == null)
{
lock (typeof(SpecialOffer))
{
if (events == null)
events = new SpecialOfferEvents();
}
}
return events;
}
}
public class SpecialOfferEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<SpecialOffer, EntityEventArgs> onNew;
public event EventHandler<SpecialOffer, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<SpecialOffer, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<SpecialOffer, EntityEventArgs> onDelete;
public event EventHandler<SpecialOffer, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<SpecialOffer, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<SpecialOffer, EntityEventArgs> onSave;
public event EventHandler<SpecialOffer, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<SpecialOffer, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnDescription
private static bool onDescriptionIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onDescription;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnDescription
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDescriptionIsRegistered)
{
Members.Description.Events.OnChange -= onDescriptionProxy;
Members.Description.Events.OnChange += onDescriptionProxy;
onDescriptionIsRegistered = true;
}
onDescription += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDescription -= value;
if (onDescription == null && onDescriptionIsRegistered)
{
Members.Description.Events.OnChange -= onDescriptionProxy;
onDescriptionIsRegistered = false;
}
}
}
}
private static void onDescriptionProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onDescription;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnDiscountPct
private static bool onDiscountPctIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onDiscountPct;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnDiscountPct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDiscountPctIsRegistered)
{
Members.DiscountPct.Events.OnChange -= onDiscountPctProxy;
Members.DiscountPct.Events.OnChange += onDiscountPctProxy;
onDiscountPctIsRegistered = true;
}
onDiscountPct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDiscountPct -= value;
if (onDiscountPct == null && onDiscountPctIsRegistered)
{
Members.DiscountPct.Events.OnChange -= onDiscountPctProxy;
onDiscountPctIsRegistered = false;
}
}
}
}
private static void onDiscountPctProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onDiscountPct;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnType
private static bool onTypeIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onType;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnType
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onTypeIsRegistered)
{
Members.Type.Events.OnChange -= onTypeProxy;
Members.Type.Events.OnChange += onTypeProxy;
onTypeIsRegistered = true;
}
onType += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onType -= value;
if (onType == null && onTypeIsRegistered)
{
Members.Type.Events.OnChange -= onTypeProxy;
onTypeIsRegistered = false;
}
}
}
}
private static void onTypeProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onType;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnCategory
private static bool onCategoryIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onCategory;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnCategory
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCategoryIsRegistered)
{
Members.Category.Events.OnChange -= onCategoryProxy;
Members.Category.Events.OnChange += onCategoryProxy;
onCategoryIsRegistered = true;
}
onCategory += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCategory -= value;
if (onCategory == null && onCategoryIsRegistered)
{
Members.Category.Events.OnChange -= onCategoryProxy;
onCategoryIsRegistered = false;
}
}
}
}
private static void onCategoryProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onCategory;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnStartDate
private static bool onStartDateIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onStartDate;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnStartDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
Members.StartDate.Events.OnChange += onStartDateProxy;
onStartDateIsRegistered = true;
}
onStartDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStartDate -= value;
if (onStartDate == null && onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
onStartDateIsRegistered = false;
}
}
}
}
private static void onStartDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onStartDate;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnEndDate
private static bool onEndDateIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onEndDate;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnEndDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
Members.EndDate.Events.OnChange += onEndDateProxy;
onEndDateIsRegistered = true;
}
onEndDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEndDate -= value;
if (onEndDate == null && onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
onEndDateIsRegistered = false;
}
}
}
}
private static void onEndDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onEndDate;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnMinQty
private static bool onMinQtyIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onMinQty;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnMinQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onMinQtyIsRegistered)
{
Members.MinQty.Events.OnChange -= onMinQtyProxy;
Members.MinQty.Events.OnChange += onMinQtyProxy;
onMinQtyIsRegistered = true;
}
onMinQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onMinQty -= value;
if (onMinQty == null && onMinQtyIsRegistered)
{
Members.MinQty.Events.OnChange -= onMinQtyProxy;
onMinQtyIsRegistered = false;
}
}
}
}
private static void onMinQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onMinQty;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnMaxQty
private static bool onMaxQtyIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onMaxQty;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnMaxQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onMaxQtyIsRegistered)
{
Members.MaxQty.Events.OnChange -= onMaxQtyProxy;
Members.MaxQty.Events.OnChange += onMaxQtyProxy;
onMaxQtyIsRegistered = true;
}
onMaxQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onMaxQty -= value;
if (onMaxQty == null && onMaxQtyIsRegistered)
{
Members.MaxQty.Events.OnChange -= onMaxQtyProxy;
onMaxQtyIsRegistered = false;
}
}
}
}
private static void onMaxQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onMaxQty;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onrowguid;
public static event EventHandler<SpecialOffer, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onModifiedDate;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<SpecialOffer, PropertyEventArgs> onUid;
public static event EventHandler<SpecialOffer, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SpecialOffer, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((SpecialOffer)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ISpecialOfferOriginalData
public ISpecialOfferOriginalData OriginalVersion { get { return this; } }
#region Members for interface ISpecialOffer
string ISpecialOfferOriginalData.Description { get { return OriginalData.Description; } }
string ISpecialOfferOriginalData.DiscountPct { get { return OriginalData.DiscountPct; } }
string ISpecialOfferOriginalData.Type { get { return OriginalData.Type; } }
string ISpecialOfferOriginalData.Category { get { return OriginalData.Category; } }
System.DateTime ISpecialOfferOriginalData.StartDate { get { return OriginalData.StartDate; } }
System.DateTime ISpecialOfferOriginalData.EndDate { get { return OriginalData.EndDate; } }
int ISpecialOfferOriginalData.MinQty { get { return OriginalData.MinQty; } }
string ISpecialOfferOriginalData.MaxQty { get { return OriginalData.MaxQty; } }
string ISpecialOfferOriginalData.rowguid { get { return OriginalData.rowguid; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace NServiceKit.FluentValidation
{
using System;
using System.Linq;
using System.Linq.Expressions;
using Internal;
using Resources;
using Validators;
/// <summary>
/// Default options that can be used to configure a validator.
/// </summary>
public static class DefaultValidatorOptions {
/// <summary>
/// Specifies the cascade mode for failures.
/// If set to 'Stop' then execution of the rule will stop once the first validator in the chain fails.
/// If set to 'Continue' then all validators in the chain will execute regardless of failures.
/// </summary>
public static IRuleBuilderInitial<T, TProperty> Cascade<T, TProperty>(this IRuleBuilderInitial<T, TProperty> ruleBuilder, CascadeMode cascadeMode) {
return ruleBuilder.Configure(cfg => {
cfg.CascadeMode = cascadeMode;
});
}
/// <summary>
/// Specifies a custom action to be invoked when the validator fails.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="rule"></param>
/// <param name="onFailure"></param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> OnAnyFailure<T, TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Action<T> onFailure) {
return rule.Configure(config => {
config.OnFailure = onFailure.CoerceToNonGeneric();
});
}
/// <summary>
/// Specifies a custom error message to use if validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="errorMessage">The error message to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage) {
return rule.WithMessage(errorMessage, null as object[]);
}
/// <summary>
/// Specifies a custom error message to use if validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="errorMessage">The error message to use</param>
/// <param name="formatArgs">Additional arguments to be specified when formatting the custom error message.</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params object[] formatArgs) {
var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
return rule.WithMessage(errorMessage, funcs);
}
/// <summary>
/// Specifies a custom error message to use if validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="errorMessage">The error message to use</param>
/// <param name="funcs">Additional property values to be included when formatting the custom error message.</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params Func<T, object>[] funcs) {
errorMessage.Guard("A message must be specified when calling WithMessage.");
return rule.Configure(config => {
config.CurrentValidator.ErrorMessageSource = new StaticStringSource(errorMessage);
funcs
.Select(func => func.CoerceToNonGeneric())
.ForEach(config.CurrentValidator.CustomMessageFormatArguments.Add);
});
}
/// <summary>
/// Specifies a custom error message resource to use when validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
/// <returns></returns>
public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector) {
// We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType.
return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder());
}
/// <summary>
/// Specifies a custom error message resource to use when validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
/// <param name="formatArgs">Custom message format args</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params object[] formatArgs) {
var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs);
return rule.WithLocalizedMessage(resourceSelector, funcs);
}
/// <summary>
/// Specifies a custom error message resource to use when validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
/// <param name="formatArgs">Custom message format args</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params Func<T, object>[] formatArgs) {
// We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType.
return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder())
.Configure(cfg => {
formatArgs
.Select(func => func.CoerceToNonGeneric())
.ForEach(cfg.CurrentValidator.CustomMessageFormatArguments.Add);
});
}
/// <summary>
/// Specifies a custom error message resource to use when validation fails.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
/// <param name="resourceAccessorBuilder">The resource accessor builder to use. </param>
/// <returns></returns>
public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder) {
resourceSelector.Guard("An expression must be specified when calling WithLocalizedMessage, eg .WithLocalizedMessage(() => Messages.MyResource)");
return rule.Configure(config => {
config.CurrentValidator.ErrorMessageSource = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder);
});
}
/// <summary>
/// Specifies a custom error code to use when validation fails
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="errorCode">The error code to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithErrorCode<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorCode)
{
return rule.Configure(config =>
{
config.CurrentValidator.ErrorCode = errorCode;
});
}
/// <summary>
/// Specifies a condition limiting when the validator should run.
/// The validator will only be executed if the result of the lambda returns true.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param>
/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> When<T,TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
predicate.Guard("A predicate must be specified when calling When.");
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
return rule.Configure(config => {
config.ApplyCondition(predicate.CoerceToNonGeneric(), applyConditionTo);
});
}
/// <summary>
/// Specifies a condition limiting when the validator should not run.
/// The validator will only be executed if the result of the lambda returns false.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param>
/// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Unless<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
predicate.Guard("A predicate must be specified when calling Unless");
return rule.When(x => !predicate(x), applyConditionTo);
}
/// <summary>
/// Specifies a custom property name to use within the error message.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="overridePropertyName">The property name to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string overridePropertyName) {
overridePropertyName.Guard("A property name must be specified when calling WithName.");
return rule.Configure(config => {
config.DisplayName = new StaticStringSource(overridePropertyName);
});
}
/// <summary>
/// Specifies a localized name for the error message.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param>
/// <param name="resourceAccessorBuilder">Resource accessor builder to use</param>
public static IRuleBuilderOptions<T, TProperty> WithLocalizedName<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder = null) {
resourceSelector.Guard("A resource selector must be specified.");
// default to the static resource accessor builder - explicit resources configured with WithLocalizedName should take precedence over ResourceProviderType.
resourceAccessorBuilder = resourceAccessorBuilder ?? new StaticResourceAccessorBuilder();
return rule.Configure(config => {
config.DisplayName = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder);
});
}
/// <summary>
/// Overrides the name of the property associated with this rule.
/// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="propertyName">The property name to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> OverridePropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) {
propertyName.Guard("A property name must be specified when calling WithNamePropertyName.");
return rule.Configure(config => config.PropertyName = propertyName);
}
/// <summary>
/// Overrides the name of the property associated with this rule.
/// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName.
/// </summary>
/// <param name="rule">The current rule</param>
/// <param name="propertyName">The property name to use</param>
/// <returns></returns>
[Obsolete("WithPropertyName has been deprecated. If you wish to set the name of the property within the error message, use 'WithName'. If you actually intended to change which property this rule was declared against, use 'OverridePropertyName' instead.")]
public static IRuleBuilderOptions<T, TProperty> WithPropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) {
return rule.OverridePropertyName(propertyName);
}
/// <summary>
/// Specifies custom state that should be stored alongside the validation message when validation fails for this rule.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="rule"></param>
/// <param name="stateProvider"></param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, object> stateProvider) {
stateProvider.Guard("A lambda expression must be passed to WithState");
return rule.Configure(config => config.CurrentValidator.CustomStateProvider = stateProvider.CoerceToNonGeneric());
}
static Func<T, object>[] ConvertArrayOfObjectsToArrayOfDelegates<T>(object[] objects) {
if(objects == null || objects.Length == 0) {
return new Func<T, object>[0];
}
return objects.Select(obj => new Func<T, object>(x => obj)).ToArray();
}
}
}
| |
/* ====================================================================
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 NPOI.HWPF;
using NPOI.HWPF.UserModel;
using NPOI.HWPF.Model;
using NUnit.Framework;
namespace TestCases.HWPF.UserModel
{
/**
* Test to see if Range.Delete() works even if the Range Contains a
* CharacterRun that uses Unicode characters.
*/
[TestFixture]
public class TestRangeDelete
{
// u201c and u201d are "smart-quotes"
private String introText =
"Introduction\r";
private String fillerText =
"${delete} This is an MS-Word 97 formatted document created using NeoOffice v. 2.2.4 Patch 0 (OpenOffice.org v. 2.2.1).\r";
private String originalText =
"It is used to confirm that text delete works even if Unicode characters (such as \u201c\u2014\u201d (U+2014), \u201c\u2e8e\u201d (U+2E8E), or \u201c\u2714\u201d (U+2714)) are present. Everybody should be thankful to the ${organization} ${delete} and all the POI contributors for their assistance in this matter.\r";
private String lastText =
"Thank you, ${organization} ${delete}!\r";
private String searchText = "${delete}";
private String expectedText1 = " This is an MS-Word 97 formatted document created using NeoOffice v. 2.2.4 Patch 0 (OpenOffice.org v. 2.2.1).\r";
private String expectedText2 =
"It is used to confirm that text delete works even if Unicode characters (such as \u201c\u2014\u201d (U+2014), \u201c\u2e8e\u201d (U+2E8E), or \u201c\u2714\u201d (U+2714)) are present. Everybody should be thankful to the ${organization} and all the POI contributors for their assistance in this matter.\r";
private String expectedText3 = "Thank you, ${organization} !\r";
private String illustrativeDocFile;
[SetUp]
public void SetUp()
{
illustrativeDocFile = "testRangeDelete.doc";
}
/**
* Test just opening the files
*/
[Test]
public void TestOpen()
{
HWPFTestDataSamples.OpenSampleFile(illustrativeDocFile);
}
/**
* Test (more "Confirm" than Test) that we have the general structure that we expect to have.
*/
[Test]
public void TestDocStructure()
{
HWPFDocument daDoc = HWPFTestDataSamples.OpenSampleFile(illustrativeDocFile);
Range range;
Section section;
Paragraph para;
PAPX paraDef;
// First, check overall
range = daDoc.GetOverallRange();
Assert.AreEqual(1, range.NumSections);
Assert.AreEqual(5, range.NumParagraphs);
// Now, onto just the doc bit
range = daDoc.GetRange();
Assert.AreEqual(1, range.NumSections);
Assert.AreEqual(1, daDoc.SectionTable.GetSections().Count);
section = range.GetSection(0);
Assert.AreEqual(5, section.NumParagraphs);
para = section.GetParagraph(0);
Assert.AreEqual(1, para.NumCharacterRuns);
Assert.AreEqual(introText, para.Text);
para = section.GetParagraph(1);
Assert.AreEqual(5, para.NumCharacterRuns);
Assert.AreEqual(fillerText, para.Text);
paraDef = (PAPX)daDoc.ParagraphTable.GetParagraphs()[2];
Assert.AreEqual(132, paraDef.Start);
Assert.AreEqual(400, paraDef.End);
para = section.GetParagraph(2);
Assert.AreEqual(5, para.NumCharacterRuns);
Assert.AreEqual(originalText, para.Text);
paraDef = (PAPX)daDoc.ParagraphTable.GetParagraphs()[3];
Assert.AreEqual(400, paraDef.Start);
Assert.AreEqual(438, paraDef.End);
para = section.GetParagraph(3);
Assert.AreEqual(1, para.NumCharacterRuns);
Assert.AreEqual(lastText, para.Text);
// Check things match on text length
Assert.AreEqual(439, range.Text.Length);
Assert.AreEqual(439, section.Text.Length);
Assert.AreEqual(439,
section.GetParagraph(0).Text.Length +
section.GetParagraph(1).Text.Length +
section.GetParagraph(2).Text.Length +
section.GetParagraph(3).Text.Length +
section.GetParagraph(4).Text.Length
);
}
/**
* Test that we can delete text (one instance) from our Range with Unicode text.
*/
[Test]
public void TestRangeDeleteOne()
{
HWPFDocument daDoc = HWPFTestDataSamples.OpenSampleFile(illustrativeDocFile);
Range range = daDoc.GetOverallRange();
Assert.AreEqual(1, range.NumSections);
Section section = range.GetSection(0);
Assert.AreEqual(5, section.NumParagraphs);
Paragraph para = section.GetParagraph(2);
String text = para.Text;
Assert.AreEqual(originalText, text);
int offset = text.IndexOf(searchText);
Assert.AreEqual(192, offset);
int absOffset = para.StartOffset + offset;
Range subRange = new Range(absOffset, (absOffset + searchText.Length), para.GetDocument());
Assert.AreEqual(searchText, subRange.Text);
subRange.Delete();
// we need to let the model re-calculate the Range before we Evaluate it
range = daDoc.GetRange();
Assert.AreEqual(1, range.NumSections);
section = range.GetSection(0);
Assert.AreEqual(5, section.NumParagraphs);
para = section.GetParagraph(2);
text = para.Text;
Assert.AreEqual(expectedText2, text);
// this can lead to a StringBuilderOutOfBoundsException, so we will add it
// even though we don't have an assertion for it
Range daRange = daDoc.GetRange();
text = daRange.Text;
}
/**
* Test that we can delete text (all instances of) from our Range with Unicode text.
*/
[Test]
public void TestRangeDeleteAll()
{
HWPFDocument daDoc = HWPFTestDataSamples.OpenSampleFile(illustrativeDocFile);
Range range = daDoc.GetRange();
Assert.AreEqual(1, range.NumSections);
Section section = range.GetSection(0);
Assert.AreEqual(5, section.NumParagraphs);
Paragraph para = section.GetParagraph(2);
String text = para.Text;
Assert.AreEqual(originalText, text);
bool keepLooking = true;
while (keepLooking)
{
// Reload the range every time
range = daDoc.GetRange();
int offset = range.Text.IndexOf(searchText);
if (offset >= 0)
{
int absOffset = range.StartOffset + offset;
Range subRange = new Range(
absOffset, (absOffset + searchText.Length), range.GetDocument());
Assert.AreEqual(searchText, subRange.Text);
subRange.Delete();
}
else
{
keepLooking = false;
}
}
// we need to let the model re-calculate the Range before we use it
range = daDoc.GetRange();
Assert.AreEqual(1, range.NumSections);
section = range.GetSection(0);
Assert.AreEqual(5, section.NumParagraphs);
para = section.GetParagraph(0);
text = para.Text;
Assert.AreEqual(introText, text);
para = section.GetParagraph(1);
text = para.Text;
Assert.AreEqual(expectedText1, text);
para = section.GetParagraph(2);
text = para.Text;
Assert.AreEqual(expectedText2, text);
para = section.GetParagraph(3);
text = para.Text;
Assert.AreEqual(expectedText3, text);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
namespace Artem.Data.Access {
/// <summary>
///
/// </summary>
public class DataScope : IDisposable {
#region Static Properties ///////////////////////////////////////////////////////
/// <summary>
/// Gets or sets the current.
/// </summary>
/// <value>The current.</value>
static public DataScope Current {
get {
return DataAccessContext.Current.CurrentScope;
}
set {
DataAccessContext.Current.CurrentScope = value;
}
}
#endregion
#region Static Methods //////////////////////////////////////////////////////////
static void ThrowIfNestedScope() {
if (DataScope.Current != null)
throw new DataAccessException(SR.ERR_500);
}
#endregion
#region Fields //////////////////////////////////////////////////////////////////
IDbConnection _connection;
IDbTransaction _transaction;
Exception _innerException;
bool _isDisposed;
bool _isComplete;
#endregion
#region Properties //////////////////////////////////////////////////////////////
/// <summary>
/// Gets the connection.
/// </summary>
/// <value>The connection.</value>
protected internal IDbConnection Connection {
get { return _connection; }
}
/// <summary>
/// Gets a value indicating whether this instance has exception.
/// </summary>
/// <value>
/// <c>true</c> if this instance has exception; otherwise, <c>false</c>.
/// </value>
public bool HasException {
get { return _innerException != null; }
}
/// <summary>
/// Gets a value indicating whether this instance has transaction.
/// </summary>
/// <value>
/// <c>true</c> if this instance has transaction; otherwise, <c>false</c>.
/// </value>
private bool HasTransaction {
get { return _transaction != null; }
}
/// <summary>
/// Gets or sets the inner exception.
/// </summary>
/// <value>The inner exception.</value>
public Exception InnerException {
get { return _innerException; }
set { _innerException = value; }
}
/// <summary>
/// Gets the transaction.
/// </summary>
/// <value>The transaction.</value>
protected internal IDbTransaction Transaction {
get { return _transaction; }
}
#endregion
#region Construct / Destruct ////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <see cref="DataScope"/> class.
/// </summary>
public DataScope() {
ThrowIfNestedScope();
_connection = DataAccess.Provider.CreateConnection();
_connection.ConnectionString =
DataAccess.ConnectionStringSettings[DataAccess.Provider.ConnectionName].ConnectionString;
_connection.Open();
_transaction = _connection.BeginTransaction();
DataScope.Current = this;
}
/// <summary>
/// Initializes a new instance of the <see cref="DataScope"/> class.
/// </summary>
/// <param name="level">The level.</param>
public DataScope(IsolationLevel level) {
ThrowIfNestedScope();
_connection = DataAccess.Provider.CreateConnection();
_connection.ConnectionString =
DataAccess.ConnectionStringSettings[DataAccess.Provider.ConnectionName].ConnectionString;
_connection.Open();
_transaction = _connection.BeginTransaction();
DataScope.Current = this;
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the specified disposing.
/// </summary>
/// <param name="disposing">if set to <c>true</c> [disposing].</param>
protected virtual void Dispose(bool disposing) {
if (!_isDisposed) {
_isDisposed = true;
if (disposing) {
try {
if (HasException) {
this.Rollback(true);
}
else {
this.Commit(true);
}
}
catch (Exception ex) {
this._innerException = ex;
}
try {
this.CloseConnection();
}
catch (Exception ex1) {
this._innerException = ex1;
}
if (HasException) {
DataAccessContext.DeliverException(this.InnerException);
}
DataScope.Current = null;
}
}
}
#endregion
#endregion
#region Methods /////////////////////////////////////////////////////////////////
/// <summary>
/// Closes the used connection.
/// </summary>
private void CloseConnection() {
if (_connection != null && _connection.State != ConnectionState.Closed) {
//try {
_connection.Close();
//}
//catch { }
}
}
/// <summary>
/// Commits this instance.
/// </summary>
public void Commit() {
this.Commit(false);
}
/// <summary>
/// Commits the specified disposing.
/// </summary>
/// <param name="disposing">if set to <c>true</c> [disposing].</param>
protected void Commit(bool disposing) {
if (this.HasTransaction) {
if (!_isComplete) {
_transaction.Commit();
_isComplete = true;
}
if (disposing) {
_transaction.Dispose();
_transaction = null;
}
}
}
/// <summary>
/// Rollbacks this instance.
/// </summary>
public void Rollback() {
this.Rollback(false);
}
/// <summary>
/// Rollbacks this instance.
/// </summary>
/// <param name="disposing">if set to <c>true</c> [disposing].</param>
public void Rollback(bool disposing) {
if (this.HasTransaction) {
if (!_isComplete) {
_transaction.Rollback();
_isComplete = true;
}
if (disposing) {
_transaction.Dispose();
_transaction = null;
}
}
}
#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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.IO
{
internal class MultiplexingWin32WinRTFileSystem : FileSystem
{
private readonly FileSystem _win32FileSystem = new Win32FileSystem();
private readonly FileSystem _winRTFileSystem = new WinRTFileSystem();
internal static IFileSystemObject GetFileSystemObject(FileSystemInfo caller, string fullPath)
{
return ShouldUseWinRT(fullPath, isCreate: false) ?
(IFileSystemObject)new WinRTFileSystem.WinRTFileSystemObject(fullPath, asDirectory: caller is DirectoryInfo) :
(IFileSystemObject)caller;
}
public override int MaxPath { get { return Interop.mincore.MAX_PATH; } }
public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } }
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
Select(sourceFullPath, destFullPath).CopyFile(sourceFullPath, destFullPath, overwrite);
}
public override void CreateDirectory(string fullPath)
{
Select(fullPath, isCreate: true).CreateDirectory(fullPath);
}
public override void DeleteFile(string fullPath)
{
Select(fullPath).DeleteFile(fullPath);
}
public override bool DirectoryExists(string fullPath)
{
return Select(fullPath).DirectoryExists(fullPath);
}
public override Collections.Generic.IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return Select(fullPath).EnumeratePaths(fullPath, searchPattern, searchOption, searchTarget);
}
public override Collections.Generic.IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return Select(fullPath).EnumerateFileSystemInfos(fullPath, searchPattern, searchOption, searchTarget);
}
public override bool FileExists(string fullPath)
{
return Select(fullPath).FileExists(fullPath);
}
public override FileAttributes GetAttributes(string fullPath)
{
return Select(fullPath).GetAttributes(fullPath);
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return Select(fullPath).GetCreationTime(fullPath);
}
public override string GetCurrentDirectory()
{
// WinRT honors the Win32 current directory, but does not expose it,
// so we use the Win32 implementation always.
return _win32FileSystem.GetCurrentDirectory();
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return Select(fullPath).GetFileSystemInfo(fullPath, asDirectory);
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return Select(fullPath).GetLastAccessTime(fullPath);
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return Select(fullPath).GetLastWriteTime(fullPath);
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
Select(sourceFullPath, destFullPath).MoveDirectory(sourceFullPath, destFullPath);
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
Select(sourceFullPath, destFullPath).MoveFile(sourceFullPath, destFullPath);
}
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
bool isCreate = mode != FileMode.Open && mode != FileMode.Truncate;
return Select(fullPath, isCreate).Open(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
Select(fullPath).RemoveDirectory(fullPath, recursive);
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
Select(fullPath).SetAttributes(fullPath, attributes);
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
Select(fullPath).SetCreationTime(fullPath, time, asDirectory);
}
public override void SetCurrentDirectory(string fullPath)
{
// WinRT honors the Win32 current directory, but does not expose it,
// so we use the Win32 implementation always.
// This will throw UnauthorizedAccess on brokered paths.
_win32FileSystem.SetCurrentDirectory(fullPath);
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
Select(fullPath).SetLastAccessTime(fullPath, time, asDirectory);
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
Select(fullPath).SetLastWriteTime(fullPath, time, asDirectory);
}
private FileSystem Select(string fullPath, bool isCreate = false)
{
return ShouldUseWinRT(fullPath, isCreate) ? _winRTFileSystem : _win32FileSystem;
}
private FileSystem Select(string sourceFullPath, string destFullPath)
{
return (ShouldUseWinRT(sourceFullPath, isCreate: false) || ShouldUseWinRT(destFullPath, isCreate: true)) ? _winRTFileSystem : _win32FileSystem;
}
private static bool ShouldUseWinRT(string fullPath, bool isCreate)
{
// The purpose of this method is to determine if we can access a path
// via Win32 or if we need to fallback to WinRT.
// We prefer Win32 since it is faster, WinRT's APIs eventually just
// call into Win32 after all, but it doesn't provide access to,
// brokered paths (like Pictures or Documents) nor does it handle
// placeholder files. So we'd like to fall back to WinRT whenever
// we can't access a path, or if it known to be a placeholder file.
bool useWinRt = false;
do
{
// first use GetFileAttributesEx as it is faster than FindFirstFile and requires minimum permissions
Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA();
if (Interop.mincore.GetFileAttributesEx(fullPath, Interop.mincore.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data))
{
// got the attributes
if ((data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0 ||
(data.fileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT) == 0)
{
// we have a directory or a file that is not a reparse point
// useWinRt = false;
break;
}
else
{
// we need to get the find data to determine if it is a placeholder file
Interop.mincore.WIN32_FIND_DATA findData = new Interop.mincore.WIN32_FIND_DATA();
using (SafeFindHandle handle = Interop.mincore.FindFirstFile(fullPath, ref findData))
{
if (!handle.IsInvalid)
{
// got the find data, use WinRT for placeholder files
Debug.Assert((findData.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0);
Debug.Assert((findData.dwFileAttributes & Interop.mincore.FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT) != 0);
useWinRt = findData.dwReserved0 == Interop.mincore.IOReparseOptions.IO_REPARSE_TAG_FILE_PLACEHOLDER;
break;
}
}
}
}
int error = Marshal.GetLastWin32Error();
Debug.Assert(error != Interop.mincore.Errors.ERROR_SUCCESS);
if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
// The path was not accessible with Win32, so try WinRT
useWinRt = true;
break;
}
else if (error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND && error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
// We hit some error other than ACCESS_DENIED or NOT_FOUND,
// Default to Win32 to provide most accurate error behavior
break;
}
// error was ERROR_PATH_NOT_FOUND or ERROR_FILE_NOT_FOUND
// if we are creating a file/directory we cannot assume that Win32 will have access to
// the parent directory, so we walk up the path.
fullPath = PathHelpers.GetDirectoryNameInternal(fullPath);
// only walk up the path if we are creating a file/directory and not at the root
} while (isCreate && !String.IsNullOrEmpty(fullPath));
return useWinRt;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using Xunit;
namespace MR.AttributeDI
{
[AddToServices]
public class Service1 { }
public interface IService2 { }
[AddToServices]
[AddToServices(As = typeof(IService2))]
public class Service2 : IService2 { }
[AddToServices(Tags = "foo")]
public class Service3 { }
[AddToServices(Tags = "foo, bar")]
public class Service4 { }
public interface IServiceAsImplementedInterface1 { }
public interface IServiceAsImplementedInterface2 { }
public interface IServiceAsImplementedInterfaceSub { }
[AddToServices(AsImplementedInterface = true)]
public class ServiceAsImplementedInterfaceOne : IServiceAsImplementedInterface1 { }
[AddToServices(AsImplementedInterface = true)]
public class ServiceAsImplementedInterfaceNone { }
[AddToServices(AsImplementedInterface = true)]
public class ServiceAsImplementedInterfaceMultiple : IServiceAsImplementedInterface1, IServiceAsImplementedInterface2 { }
public class FakeApplier : IApplier
{
public void Apply(ApplierContext context)
{
Contexts.Add(context);
}
public List<ApplierContext> Contexts { get; set; } = new List<ApplierContext>();
}
public class CollectorTest
{
[Fact]
public void Ctor_ArgumentNullCheck()
{
Assert.Throws<ArgumentNullException>(() =>
{
new Collector(default(Assembly[]));
});
}
[Fact]
public void Ctor_ArgumentCheck()
{
Assert.Throws<ArgumentException>(() =>
{
new Collector(new Assembly[0]);
});
}
[Fact]
public void Collect_ArgumentNullCheck()
{
Assert.Throws<ArgumentNullException>(() =>
{
Create(typeof(Service1)).Collect(null);
});
}
[Fact]
public void Collect()
{
// Assert
var applier = new FakeApplier();
var collector = Create(typeof(Service1));
// Act
collector.Collect(applier);
// Assert
applier.Contexts.Should().Contain(c => c.Implementation == typeof(Service1));
}
[Fact]
public void Collect_Multiple()
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(Service2));
// Act
collector.Collect(applier);
// Assert
applier.Contexts.Should().Contain(c =>
c.Implementation == typeof(Service2) && c.Service == typeof(Service2)).And.Contain((c) =>
c.Implementation == typeof(Service2) && c.Service == typeof(IService2));
}
[Fact]
public void Collect_MultipleTags()
{
// Arrange
var applier1 = new FakeApplier();
var applier2 = new FakeApplier();
var collector1 = Create(typeof(Service4));
var collector2 = Create(typeof(Service4));
// Act
collector1.Collect(applier1, "foo");
collector2.Collect(applier2, "bar");
// Assert
applier1.Contexts.Should().Contain(c => c.Implementation == typeof(Service4));
applier2.Contexts.Should().Contain(c => c.Implementation == typeof(Service4));
}
[Theory]
[InlineData(default(string))]
[InlineData("bar")]
public void Collect_DoesNotCollectDifferentTags(string tag)
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(Service3));
// Act
collector.Collect(applier, tag);
// Assert
applier.Contexts.Should().NotContain(c => c.Implementation == typeof(Service3));
}
[Theory]
[InlineData("foo")]
[InlineData("FoO")]
public void Collect_CollectsTags(string tag)
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(Service3));
// Act
collector.Collect(applier, tag);
// Assert
applier.Contexts.Should().Contain(c => c.Implementation == typeof(Service3));
}
[Fact]
public void Collect_AsImplementedInterface_One()
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(ServiceAsImplementedInterfaceOne));
// Act
collector.Collect(applier);
// Assert
var c = applier.Contexts.First();
c.Service.Should().Be(typeof(IServiceAsImplementedInterface1));
}
[Fact]
public void Collect_AsImplementedInterface_None()
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(ServiceAsImplementedInterfaceNone));
// Act + Assert
Assert.Throws<InvalidOperationException>(() => collector.Collect(applier));
}
[Fact]
public void Collect_AsImplementedInterface_Multiple()
{
// Arrange
var applier = new FakeApplier();
var collector = Create(typeof(ServiceAsImplementedInterfaceMultiple));
// Act + Assert
Assert.Throws<InvalidOperationException>(() => collector.Collect(applier));
}
private Collector Create(Type type) => new Collector(new OneTypeProvider(type));
}
public class OneTypeProvider : IAddToServicesAttributeListProvider
{
private Type _type;
public OneTypeProvider(Type type)
{
_type = type;
}
public List<(Type Implementation, IEnumerable<AddToServicesAttribute> Attributes)> GetAttributes()
{
return new List<(Type Implementation, IEnumerable<AddToServicesAttribute> Attributes)>
{
(_type, _type.GetCustomAttributes<AddToServicesAttribute>())
};
}
}
}
| |
//
// Copyright (C) 2010 The Sanity Engine Development Team
//
// This source code is licensed under the terms of the
// MIT License.
//
// For more information, see the file LICENSE
using System;
using System.Collections.Generic;
namespace SanityEngine.Utility.Containers
{
/// <summary>
/// A simple heap based priority queue. Specially tailored for use
/// in best first search.
/// </summary>
/// <typeparam name="T">The type contained in the queue.</typeparam>
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> data = new List<T>();
/// <summary>
/// Add an item into the queue.
/// </summary>
/// <param name="item">The item to enqueue.</param>
public void Enqueue(T item)
{
int index = data.Count;
data.Add(item);
Promote(index);
}
/// <summary>
/// Remove the highest priority item from the queue.
/// </summary>
/// <returns>The highest priority item.</returns>
public T Dequeue()
{
if (Empty)
{
throw new IndexOutOfRangeException();
}
T item = data[0];
int last = data.Count - 1;
data[0] = data[last];
data.RemoveAt(last);
Demote(0);
return item;
}
/// <summary>
/// Get the first element without removing.
/// </summary>
/// <returns>The first element.</returns>
public T Peek()
{
if (Empty)
{
throw new IndexOutOfRangeException();
}
return data[0];
}
/// <summary>
/// Set to <code>true</code> if this queue is empty.
/// </summary>
public bool Empty
{
get { return data.Count <= 0; }
}
/// <summary>
/// Clear the queue's contents.
/// </summary>
public void Clear()
{
data.Clear();
}
/// <summary>
/// Checks to see if the queue contains the given item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns><code>true</code> if the item is in the queue.</returns>
public bool Contains(T item)
{
return data.Contains(item);
}
/// <summary>
/// The number of items in the queue.
/// </summary>
public int Count
{
get { return data.Count; }
}
/// <summary>
/// Corrects the item's position in the queue if the value has changed.
/// </summary>
/// <param name="item">The item to fix.</param>
public void Fix(T item)
{
int index = data.IndexOf(item);
if (index < 0)
{
return;
}
FixAt(index);
}
/// <summary>
/// Remove the item from the priority queue.
/// </summary>
/// <param name="item">The item to remove.</param>
public void Remove(T item)
{
int index = data.IndexOf(item);
if (index < 0)
{
return;
}
int last = data.Count - 1;
if (index == last)
{
data.RemoveAt(last);
}
else
{
Swap(index, last);
data.RemoveAt(last);
FixAt(index);
}
}
private void FixAt(int index)
{
int parent = Parent(index);
if (data[parent].CompareTo(data[index]) > 0)
{
Promote(index);
}
else
{
Demote(index);
}
}
private void Promote(int index)
{
int parent = Parent(index);
if (data[parent].CompareTo(data[index]) > 0)
{
Swap(parent, index);
Promote(parent);
}
}
private void Demote(int index)
{
int left = Left(index);
int right = Right(index);
if (left >= data.Count)
{
// We've reached the end
return;
}
if (right >= data.Count)
{
// Check the left side only
if (left < data.Count && data[index].CompareTo(data[left]) > 0)
{
Swap(index, left);
Demote(left);
}
return;
}
// Otherwise, compare to the smallest
if (data[left].CompareTo(data[right]) < 0)
{
if (data[index].CompareTo(data[left]) > 0)
{
Swap(index, left);
Demote(left);
}
}
else
{
if (data[index].CompareTo(data[right]) > 0)
{
Swap(index, right);
Demote(right);
}
}
}
private void Swap(int i1, int i2)
{
T tmp = data[i1];
data[i1] = data[i2];
data[i2] = tmp;
}
private static int Parent(int index)
{
return (index - 1) / 2;
}
private static int Left(int index)
{
return (index * 2) + 1;
}
private static int Right(int index)
{
return (index * 2) + 2;
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security;
using Quartz.Util;
namespace Quartz.Impl.Calendar
{
/// <summary>
/// This implementation of the Calendar excludes a set of days of the year. You
/// may use it to exclude bank holidays which are on the same date every year.
/// </summary>
/// <seealso cref="ICalendar" />
/// <seealso cref="BaseCalendar" />
/// <author>Juergen Donnerstag</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class AnnualCalendar : BaseCalendar
{
private List<DateTimeOffset> excludeDays = new List<DateTimeOffset>();
// true, if excludeDays is sorted
private bool dataSorted;
// year to use as fixed year
private const int FixedYear = 2000;
/// <summary>
/// Constructor
/// </summary>
public AnnualCalendar()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="baseCalendar">The base calendar.</param>
public AnnualCalendar(ICalendar baseCalendar) : base(baseCalendar)
{
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected AnnualCalendar(SerializationInfo info, StreamingContext context) : base(info, context)
{
int version;
try
{
version = info.GetInt32("version");
}
catch
{
version = 0;
}
switch (version)
{
case 0:
// 1.x
object o = info.GetValue("excludeDays", typeof (object));
ArrayList oldFormat = o as ArrayList;
if (oldFormat != null)
{
foreach (DateTime dateTime in oldFormat)
{
excludeDays.Add(dateTime);
}
}
else
{
// must be new..
excludeDays = (List<DateTimeOffset>) o;
}
break;
case 1:
excludeDays = (List<DateTimeOffset>) info.GetValue("excludeDays", typeof (List<DateTimeOffset>));
break;
default:
throw new NotSupportedException("Unknown serialization version");
}
}
[SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("version", 1);
info.AddValue("excludeDays", excludeDays);
}
/// <summary>
/// Get or the array which defines the exclude-value of each day of month.
/// Setting will redefine the array of days excluded. The array must of size greater or
/// equal 31.
/// </summary>
public virtual IList<DateTimeOffset> DaysExcluded
{
get { return excludeDays; }
set
{
if (value == null)
{
excludeDays = new List<DateTimeOffset>();
}
else
{
excludeDays = new List<DateTimeOffset>(value);
}
dataSorted = false;
}
}
/// <summary>
/// Return true, if day is defined to be excluded.
/// </summary>
public virtual bool IsDayExcluded(DateTimeOffset day)
{
return IsDateTimeExcluded(day, true);
}
private bool IsDateTimeExcluded(DateTimeOffset day, bool checkBaseCalendar)
{
// Check baseCalendar first
if (checkBaseCalendar && !base.IsTimeIncluded(day))
{
return true;
}
int dmonth = day.Month;
int dday = day.Day;
if (!dataSorted)
{
excludeDays.Sort();
dataSorted = true;
}
foreach (DateTimeOffset cl in excludeDays)
{
// remember, the list is sorted
if (dmonth < cl.Month)
{
return false;
}
if (dday != cl.Day)
{
continue;
}
if (dmonth != cl.Month)
{
continue;
}
return true;
}
// not found
return false;
}
/// <summary>
/// Redefine a certain day to be excluded (true) or included (false).
/// </summary>
public virtual void SetDayExcluded(DateTimeOffset day, bool exclude)
{
DateTimeOffset d = new DateTimeOffset(FixedYear, day.Month, day.Day, 0, 0, 0, TimeSpan.Zero);
if (exclude)
{
if (!IsDateTimeExcluded(day, false))
{
excludeDays.Add(d);
}
}
else
{
// include
if (IsDateTimeExcluded(day, false))
{
excludeDays.Remove(d);
}
}
dataSorted = false;
}
/// <summary>
/// Determine whether the given UTC time (in milliseconds) is 'included' by the
/// Calendar.
/// <para>
/// Note that this Calendar is only has full-day precision.
/// </para>
/// </summary>
public override bool IsTimeIncluded(DateTimeOffset dateUtc)
{
// Test the base calendar first. Only if the base calendar not already
// excludes the time/date, continue evaluating this calendar instance.
if (!base.IsTimeIncluded(dateUtc))
{
return false;
}
//apply the timezone
dateUtc = TimeZoneUtil.ConvertTime(dateUtc, TimeZone);
return !(IsDayExcluded(dateUtc));
}
/// <summary>
/// Determine the next UTC time (in milliseconds) that is 'included' by the
/// Calendar after the given time. Return the original value if timeStampUtc is
/// included. Return 0 if all days are excluded.
/// <para>
/// Note that this Calendar is only has full-day precision.
/// </para>
/// </summary>
public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeStampUtc)
{
// Call base calendar implementation first
DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeStampUtc);
if ((baseTime != DateTimeOffset.MinValue) && (baseTime > timeStampUtc))
{
timeStampUtc = baseTime;
}
//apply the timezone
timeStampUtc = TimeZoneUtil.ConvertTime(timeStampUtc, TimeZone);
// Get timestamp for 00:00:00, in the correct timezone offset
DateTimeOffset day = new DateTimeOffset(timeStampUtc.Date, timeStampUtc.Offset);
if (!IsDayExcluded(day))
{
// return the original value
return timeStampUtc;
}
while (IsDayExcluded(day))
{
day = day.AddDays(1);
}
return day;
}
public override int GetHashCode()
{
int baseHash = 13;
if (GetBaseCalendar() != null)
{
baseHash = GetBaseCalendar().GetHashCode();
}
return excludeDays.GetHashCode() + 5*baseHash;
}
public bool Equals(AnnualCalendar obj)
{
if (obj == null)
{
return false;
}
bool toReturn = GetBaseCalendar() == null || GetBaseCalendar().Equals(obj.GetBaseCalendar());
toReturn = toReturn && (DaysExcluded.Count == obj.DaysExcluded.Count);
if (toReturn)
{
foreach (DateTimeOffset date in DaysExcluded)
{
toReturn = toReturn && obj.DaysExcluded.Contains(date);
}
}
return toReturn;
}
public override bool Equals(object obj)
{
if ((obj == null) || !(obj is AnnualCalendar))
{
return false;
}
return Equals((AnnualCalendar) obj);
}
public override object Clone()
{
AnnualCalendar copy = (AnnualCalendar) base.Clone();
copy.excludeDays = new List<DateTimeOffset>(excludeDays);
return copy;
}
}
}
| |
// 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.Text;
using System.Drawing;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdprfx;
using Microsoft.Protocols.TestSuites.Rdpbcgr;
namespace Microsoft.Protocols.TestSuites.Rdprfx
{
public partial class RdprfxTestSuite
{
[TestMethod]
[Priority(0)]
[TestCategory("BVT")]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Sending client an encoded bitmap data which encoded with RLGR1 algorithm.")]
public void Rdprfx_VideoMode_PositiveTest_RLGR1()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send multiple frames of Encode Data Messages (encoded with RLGR1) to SUT.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol, true);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0; //The index of the sending frame.
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
ushort destLeft = 64; //the left bound of the frame.
ushort destTop = 64; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "the input pair of Operational Mode ({0}) / Entropy Algorithm ({1}) is not supported by client, so stop running this test case.", opMode, enAlgorithm);
return;
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending encoded bitmap data to client. Operational Mode = {0}, Entropy Algorithm = {1}, destLeft = {2}, destTop = {3}.",
opMode, enAlgorithm, destLeft, destTop);
rdprfxAdapter.SendImageToClient(imageForVideoMode, opMode, enAlgorithm, destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
Rectangle compareRect = new Rectangle(destLeft, destTop, imageForVideoMode.Width, imageForVideoMode.Height);
this.VerifySUTDisplay(true, compareRect);
#endregion
}
[TestMethod]
[Priority(0)]
[TestCategory("BVT")]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Sending client an encoded bitmap data which encoded with RLGR3 algorithm.")]
public void Rdprfx_VideoMode_PositiveTest_RLGR3()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send multiple frames of Encode Data Messages (encoded with RLGR3) to SUT.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol, true);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0; //The index of the sending frame.
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 64; //the left bound of the frame.
ushort destTop = 64; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "the input pair of Operational Mode ({0}) / Entropy Algorithm ({1}) is not supported by client, so stop running this test case.", opMode, enAlgorithm);
return;
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending encoded bitmap data to client. Operational Mode = {0}, Entropy Algorithm = {1}, destLeft = {2}, destTop = {3}.",
opMode, enAlgorithm, destLeft, destTop);
rdprfxAdapter.SendImageToClient(imageForVideoMode, opMode, enAlgorithm, destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
Rectangle compareRect = new Rectangle(destLeft, destTop, imageForVideoMode.Width, imageForVideoMode.Height);
this.VerifySUTDisplay(true, compareRect);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Send a TS_RFX_SYNC message among frames of the video mode stream.")]
public void Rdprfx_VideoMode_PositiveTest_SendTsRfxSyncInStream()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] set operation mode to video mode, send one pair of Encode Header Messages to client.
Step 4: [RDPRFX] send one frame of Encode Data Messages to client.
Step 5: [RDPRFX] send a TS_RFX_SYNC message to client.
Step 6: [RDPRFX] send another frame of Encode Data Messages to client.
Step 7: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 8: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0;
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client does not support Video Mode, so stop to run this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending the encode header messages to client.");
rdprfxAdapter.SendTsRfxSync();
rdprfxAdapter.SendTsRfxCodecVersions();
rdprfxAdapter.SendTsRfxChannels();
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending one frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 0.");
rdprfxAdapter.SendTsRfxFrameBegin(0);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending a TS_RFX_SYNC message to client.");
rdprfxAdapter.SendTsRfxSync();
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending another frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 2.");
rdprfxAdapter.SendTsRfxFrameBegin(1);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
checked
{
rdprfxAdapter.FlushEncodedData((ushort)(destLeft + 0x40), (ushort)(destTop + 0x40));
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Send a TS_RFX_CODEC_VERSIONS message among frames of the video mode stream.")]
public void Rdprfx_VideoMode_PositiveTest_SendTsRfxCodecVersioinsInStream()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] set operation mode to video mode, send one pair of Encode Header Messages to client.
Step 4: [RDPRFX] send one frame of Encode Data Messages to client.
Step 5: [RDPRFX] send a TS_RFX_CODEC_VERSIONS message to client.
Step 6: [RDPRFX] send another frame of Encode Data Messages to client.
Step 7: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 8: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0;
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client does not support Video Mode, so stop running this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending the encode header messages to client.");
rdprfxAdapter.SendTsRfxSync();
rdprfxAdapter.SendTsRfxCodecVersions();
rdprfxAdapter.SendTsRfxChannels();
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending one frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 0.");
rdprfxAdapter.SendTsRfxFrameBegin(0);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending a TS_RFX_CODEC_VERSIONS message to client.");
rdprfxAdapter.SendTsRfxCodecVersions();
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending another frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 2.");
rdprfxAdapter.SendTsRfxFrameBegin(1);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
checked
{
rdprfxAdapter.FlushEncodedData((ushort)(destLeft + 0x40), (ushort)(destTop + 0x40));
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Send a TS_RFX_CHANNELS message among frames of the video mode stream.")]
public void Rdprfx_VideoMode_PositiveTest_SendTsRfxChannelsInStream()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] set operation mode to video mode, send one pair of Encode Header Messages to client.
Step 4: [RDPRFX] send one frame of Encode Data Messages to client.
Step 5: [RDPRFX] send a TS_RFX_CHANNELS message to client.
Step 6: [RDPRFX] send another frame of Encode Data Messages to client.
Step 7: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 8: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0;
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client does not support Video Mode, so stop running this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending the encode header messages to client.");
rdprfxAdapter.SendTsRfxSync();
rdprfxAdapter.SendTsRfxCodecVersions();
rdprfxAdapter.SendTsRfxChannels();
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending one frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 0.");
rdprfxAdapter.SendTsRfxFrameBegin(0);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending a TS_RFX_CHANNELS message to client.");
rdprfxAdapter.SendTsRfxChannels();
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending another frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 2.");
rdprfxAdapter.SendTsRfxFrameBegin(1);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
checked
{
rdprfxAdapter.FlushEncodedData((ushort)(destLeft + 0x40), (ushort)(destTop + 0x40));
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Send a TS_RFX_CONTEXT message among frames of the video mode stream.")]
public void Rdprfx_VideoMode_PositiveTest_SendTsRfxContextInStream()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] set operation mode to video mode, send one pair of Encode Header Messages to client.
Step 4: [RDPRFX] send one frame of Encode Data Messages to client.
Step 5: [RDPRFX] send a TS_RFX_CONTEXT message to client.
Step 6: [RDPRFX] send another frame of Encode Data Messages to client.
Step 7: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 8: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0;
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client does not support Video Mode, so stop running this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending the encode header messages to client.");
rdprfxAdapter.SendTsRfxSync();
rdprfxAdapter.SendTsRfxCodecVersions();
rdprfxAdapter.SendTsRfxChannels();
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending one frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 0.");
rdprfxAdapter.SendTsRfxFrameBegin(0);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending a TS_RFX_CONTEXT message to client.");
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending another frame of encode data messages to client, and set the frameId of TS_RFX_FRAME_BEGIN to 2.");
rdprfxAdapter.SendTsRfxFrameBegin(1);
rdprfxAdapter.SendTsRfxRegion();
rdprfxAdapter.SendTsRfxTileSet(opMode, enAlgorithm, image_64X64);
rdprfxAdapter.SendTsRfxFrameEnd();
checked
{
rdprfxAdapter.FlushEncodedData((ushort)(destLeft + 0x40), (ushort)(destTop + 0x40));
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"When Video Mode is in effect, ensure the client terminates the RDP connection when the server uses an unsupported entropy algorithm to encode data.")]
public void Rdprfx_VideoMode_NegativeTest_UnsupportedEntropyAlgorithm()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPRFX] send one frame of Encode Header and Data Messages to client, the bitmap is encoded with an entropy algorithem that client not supported.
Step 3: [RDPRFX] expect the client terminates the RDP connection.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0; //The index of the sending frame.
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client supports both RLGR1 and RLGR3 while operation mode is video mode, so stop running this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending one frame of encoded bitmap data to client. Operational Mode = {0}, Entropy Algorithm = {1}, destLeft = {2}, destTop = {3}.",
opMode, enAlgorithm, destLeft, destTop);
rdprfxAdapter.SendImageToClient(image_64X64, opMode, enAlgorithm, destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the client terminates the RDP connection.");
bool bDisconnected = rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "Client is expected to drop the connection if the received data is encoded with unsupported entropy algorithm.");
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Ensure the client terminates the RDP connection when received a TS_RFX_FRAME_BEGIN with the blockLen field set to an invalid value.")]
public void Rdprfx_VideoMode_NegativeTest_TsRfxFrameBegin_InvalidBlockLen()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPRFX] send one frame of Encode Header and Data Messages to client, set the blockLen field of TS_RFX_FRAME_BEGIN to an invalid value (less than the actual).
Step 3: [RDPRFX] expect the client terminates the RDP connection.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0;
OperationalMode opMode = OperationalMode.VideoMode;
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR3;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "Client does not support Video Mode, so stop running this test case.");
return;
}
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Set the test type to {0}.", RdprfxNegativeType.TsRfxFrameBegin_InvalidBlockLen);
rdprfxAdapter.SetTestType(RdprfxNegativeType.TsRfxFrameBegin_InvalidBlockLen);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Encode Header/Data Messages to client.");
rdprfxAdapter.SendImageToClient(image_64X64, opMode, enAlgorithm, destLeft, destTop);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the client terminates the RDP connection.");
bool bDisconnected = rdpbcgrAdapter.WaitForDisconnection(waitTime);
this.TestSite.Assert.IsTrue(bDisconnected, "Client is expected to drop the connection if received encode data in Video Mode when Image Mode is in effect.");
#endregion
}
[TestMethod]
[Priority(0)]
[TestCategory("BVT")]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Test video mode differencing scenario.")]
public void Rdprfx_VideoMode_PositiveTest_Differencing()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send multiple frames of Encode Data Messages (encoded with RLGR1) to SUT.
Step 4: [RDPRFX] Send multiple frames with one frame no changes (encoded with RLGR1) to SUT.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
#region Test Sequence
//Start RDP listening.
this.TestSite.Log.Add(LogEntryKind.Comment, "Starting RDP listening.");
this.rdpbcgrAdapter.StartRDPListening(transportProtocol);
#region Trigger client to connect
//Trigger client to connect.
this.TestSite.Log.Add(LogEntryKind.Comment, "Triggering SUT to initiate a RDP connection to server.");
triggerClientRDPConnect(transportProtocol, true);
#endregion
#region RDPBCGR Connection
//Waiting for the transport level connection request.
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting the transport layer connection request.");
this.rdpbcgrAdapter.ExpectTransportConnection(RDPSessionType.Normal);
//Set Server Capability with RomoteFX codec supported.
this.TestSite.Log.Add(LogEntryKind.Comment, "Setting Server Capability.");
setServerCapabilitiesWithRemoteFxSupported();
//Waiting for the RDP connection sequence.
this.TestSite.Log.Add(LogEntryKind.Comment, "Establishing RDP connection.");
this.rdpbcgrAdapter.EstablishRDPConnection(selectedProtocol, enMethod, enLevel, true, false, rdpServerVersion);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Server Save Session Info PDU to SUT to notify user has logged on.");
this.rdpbcgrAdapter.ServerSaveSessionInfo(LogonNotificationType.UserLoggedOn, ErrorNotificationType_Values.LOGON_FAILED_OTHER);
#endregion
//Initial the RDPRFX adapter context.
rdprfxAdapter.Accept(this.rdpbcgrAdapter.ServerStack, this.rdpbcgrAdapter.SessionContext);
receiveAndLogClientRfxCapabilites();
uint frameId = 0; //The index of the sending frame.
OperationalMode opMode = OperationalMode.VideoMode;
// OperationalMode opMode = OperationalMode.ImageMode; // This also works. Strange. Because in TD it mentions that When operating in image mode, the Encode Headers messages (section 2.2.2.2) MUST always precede an encoded frame. When operating in video mode, the header messages MUST be present at the beginning of the stream and MAY be present elsewhere.
EntropyAlgorithm enAlgorithm = EntropyAlgorithm.CLW_ENTROPY_RLGR1;
ushort destLeft = 0; //the left bound of the frame.
ushort destTop = 0; //the top bound of the frame.
//Check if the above setting is supported by client.
if (!this.rdprfxAdapter.CheckIfClientSupports(opMode, enAlgorithm))
{
this.TestSite.Log.Add(LogEntryKind.Comment, "the input pair of Operational Mode ({0}) / Entropy Algorithm ({1}) is not supported by client, so stop running this test case.", opMode, enAlgorithm);
return;
}
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (Begin) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_BEGIN, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Create a rectangle whose width and height is TileSize * 2.");
Rectangle clipRect = new Rectangle(destLeft, destTop, RgbTile.TileSize * 2, RgbTile.TileSize * 2);
Rectangle[] rects = new Rectangle[] { clipRect };
uint surfFrameId = 0;
rdprfxAdapter.SendTsRfxSync();
rdprfxAdapter.SendTsRfxCodecVersions();
rdprfxAdapter.SendTsRfxChannels(RgbTile.TileSize * 2, RgbTile.TileSize * 2);
rdprfxAdapter.SendTsRfxContext(opMode, enAlgorithm);
rdprfxAdapter.SendTsRfxFrameBegin(surfFrameId++);
rdprfxAdapter.SendTsRfxRegion(rects);
TILE_POSITION[] positions = new TILE_POSITION[4]{
new TILE_POSITION{ xIdx = 0, yIdx = 0 },
new TILE_POSITION{ xIdx = 0, yIdx = 1 },
new TILE_POSITION{ xIdx = 1, yIdx = 0 },
new TILE_POSITION{ xIdx = 1, yIdx = 1 }
};
var bitmapBlue = new Bitmap(RgbTile.TileSize, RgbTile.TileSize);
Graphics graphics = Graphics.FromImage(bitmapBlue);
graphics.FillRectangle(Brushes.Blue, new Rectangle(0, 0, RgbTile.TileSize, RgbTile.TileSize));
var bitmapRed = new Bitmap(RgbTile.TileSize, RgbTile.TileSize);
graphics = Graphics.FromImage(bitmapRed);
graphics.FillRectangle(Brushes.Red, new Rectangle(0, 0, RgbTile.TileSize, RgbTile.TileSize));
rdprfxAdapter.SendTsRfxTileSet(
opMode,
enAlgorithm,
new Image[] { bitmapBlue, bitmapBlue, bitmapBlue, bitmapBlue },
positions);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop, RgbTile.TileSize * 2, RgbTile.TileSize * 2);
System.Threading.Thread.Sleep(1000);
rdprfxAdapter.SendTsRfxFrameBegin(surfFrameId++);
rdprfxAdapter.SendTsRfxRegion(rects);
positions = new TILE_POSITION[3]{
new TILE_POSITION{ xIdx = 0, yIdx = 1 },
new TILE_POSITION{ xIdx = 1, yIdx = 0 },
new TILE_POSITION{ xIdx = 1, yIdx = 1 }
};
rdprfxAdapter.SendTsRfxTileSet(
opMode,
enAlgorithm,
new Image[] { bitmapRed, bitmapRed, bitmapRed },
positions);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop, RgbTile.TileSize * 2, RgbTile.TileSize * 2);
System.Threading.Thread.Sleep(1000);
rdprfxAdapter.SendTsRfxFrameBegin(surfFrameId++);
rdprfxAdapter.SendTsRfxRegion(rects);
positions = new TILE_POSITION[1]{
new TILE_POSITION{ xIdx = 0, yIdx = 0 }
};
rdprfxAdapter.SendTsRfxTileSet(
opMode,
enAlgorithm,
new Image[] { bitmapRed },
positions);
rdprfxAdapter.SendTsRfxFrameEnd();
rdprfxAdapter.FlushEncodedData(destLeft, destTop, RgbTile.TileSize * 2, RgbTile.TileSize * 2);
this.TestSite.Log.Add(LogEntryKind.Comment, "Sending Frame Marker Command (End) with frameID: {0}.", frameId);
rdpbcgrAdapter.SendFrameMarkerCommand(frameAction_Values.SURFACECMD_FRAMEACTION_END, frameId);
this.TestSite.Log.Add(LogEntryKind.Comment, "Expecting TS_FRAME_ACKNOWLEDGE_PDU.");
rdprfxAdapter.ExpectTsFrameAcknowledgePdu(frameId, waitTime);
this.TestSite.Log.Add(LogEntryKind.Comment, "Verify output on SUT Display if the verifySUTDisplay entry in PTF config is true.");
Rectangle compareRect = new Rectangle(destLeft, destTop, RgbTile.TileSize * 2, RgbTile.TileSize * 2);
this.VerifySUTDisplay(true, compareRect);
#endregion
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when one rectangular is composed by four tiles in the corner in TS_RFX_REGION and the rectangle has no common boundaries with each tile.")]
public void Rdprfx_VideoMode_PositiveTest_FourTilesComposeOneRectWithoutCommonBoundary()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains rectangular which is composed by four tiles and the rectangle has no common boundaries with each tile.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
FourTilesComposeOneRectWithoutCommonBoundary(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when one rectangular is composed by four tiles in the corner in TS_RFX_REGION and the rectangle has common boundaries with each tile.")]
public void Rdprfx_VideoMode_PositiveTest_FourTilesComposeOneRectWithCommonBoundary()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains rectangular which is composed by four tiles and the rectangle has common boundaries with each tile.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
FourTilesComposeOneRectWithCommonBoundary(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when send a list of rectangle.")]
public void Rdprfx_VideoMode_PositiveTest_ListOfRects()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains a list of rectangles.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
SendListOfRects(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when send a list of rectangles with overlapping.")]
public void Rdprfx_VideoMode_PositiveTest_ListOfRectsOverlap()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains a list of rectangular which overlap with each other.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
SendListOfRectsOverlap(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when send a list of rectangles with overlapping and duplicated tile.")]
public void Rdprfx_VideoMode_PositiveTest_ListOfRectsOverlapWithDuplicateTiles()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains a list of rectangular which overlap with each other and contains a duplicated tile.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
SendListOfRectsOverlapWithDuplicateTiles(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can handle a duplicated tile correctly.")]
public void Rdprfx_VideoMode_NegtiveTest_DuplicatedTile()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains rectangular which contains a duplicated tile.
Step 5: [RDPRFX] Expect the client terminates the RDP connection.
*/
#endregion
NegtiveTest_DuplicatedTile(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when the numRects field of TS_RFX_REGION is set to zero.")]
public void Rdprfx_VideoMode_PositiveTest_numRectsSetToZero()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, the TS_RFX_REGION structure contains numRects field of TS_RFX_REGION which is set to zero.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
SendNumRectsSetToZero(OperationalMode.VideoMode);
}
[TestMethod]
[Priority(1)]
[TestCategory("RDP7.1")]
[TestCategory("RDPRFX")]
[Description(@"Verify the client can decode a RemoteFX encoded bitmap and render correctly when some tiles are out of the rectangle in TS_RFX_REGION.")]
public void Rdprfx_VideoMode_PositiveTest_OutOfRects()
{
#region Test Description
/*
Step 1: [RDPBCGR] establishing the connection.
Step 2: [RDPBCGR] send Frame Maker Command (Begin) to SUT.
Step 3: [RDPRFX] Send Encode Header Messages to SUT.
Step 4: [RDPRFX] Send one frame of Encode Data Messages (encoded with RLGR1) to SUT, when some tiles are out of the rectangle in TS_RFX_REGION.
Step 5: [RDPBCGR] send Frame Maker Command (End) to SUT.
Step 6: [RDPRFX] Expect SUT sends a TS_FRAME_ACKNOWLEDGE_PDU.
*/
#endregion
SendOutOfRects(OperationalMode.VideoMode);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ZipCodeFinal.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
// Managed mirror of NativeFormatWriter.h/.cpp
namespace Internal.NativeFormat
{
#if NATIVEFORMAT_PUBLICWRITER
public
#else
internal
#endif
abstract class Vertex
{
internal int _offset = NotPlaced;
internal int _iteration = -1; // Iteration that the offset is valid for
internal const int NotPlaced = -1;
internal const int Placed = -2;
internal const int Unified = -3;
public Vertex()
{
}
internal abstract void Save(NativeWriter writer);
public int VertexOffset
{
get
{
Debug.Assert(_offset >= 0);
return _offset;
}
}
}
#if NATIVEFORMAT_PUBLICWRITER
public
#else
internal
#endif
class Section
{
internal List<Vertex> _items = new List<Vertex>();
internal Dictionary<Vertex, Vertex> _placedMap = new Dictionary<Vertex, Vertex>();
public Section()
{
}
public Vertex Place(Vertex vertex)
{
if (vertex._offset == Vertex.Unified)
{
Vertex placedVertex;
if (_placedMap.TryGetValue(vertex, out placedVertex))
return placedVertex;
placedVertex = new PlacedVertex(vertex);
_placedMap.Add(vertex, placedVertex);
vertex = placedVertex;
}
Debug.Assert(vertex._offset == Vertex.NotPlaced);
vertex._offset = Vertex.Placed;
_items.Add(vertex);
return vertex;
}
}
#if NATIVEFORMAT_PUBLICWRITER
public
#else
internal
#endif
class NativeWriter
{
List<Section> _sections = new List<Section>();
enum SavePhase
{
Initial,
Shrinking,
Growing
}
int _iteration = 0;
SavePhase _phase; // Current save phase
int _offsetAdjustment; // Cumulative offset adjustment compared to previous iteration
int _paddingSize; // How much padding was used
Dictionary<Vertex, Vertex> _unifier = new Dictionary<Vertex, Vertex>();
NativePrimitiveEncoder _encoder = new NativePrimitiveEncoder();
#if NATIVEFORMAT_COMPRESSION
struct Tentative
{
internal Vertex Vertex;
internal int PreviousOffset;
}
// State used by compression
List<Tentative> _tentativelyWritten = new List<Tentative>(); // Tentatively written Vertices.
int _compressionDepth = 0;
#endif
public NativeWriter()
{
_encoder.Init();
}
public Section NewSection()
{
Section section = new Section();
_sections.Add(section);
return section;
}
public void WriteByte(byte b) { _encoder.WriteByte(b); }
public void WriteUInt8(byte value) { _encoder.WriteUInt8(value); }
public void WriteUInt16(ushort value) { _encoder.WriteUInt16(value); }
public void WriteUInt32(uint value) { _encoder.WriteUInt32(value); }
public void WriteUInt64(ulong value) { _encoder.WriteUInt64(value); }
public void WriteUnsigned(uint d) { _encoder.WriteUnsigned(d); }
public void WriteSigned(int i) { _encoder.WriteSigned(i); }
public void WriteUnsignedLong(ulong i) { _encoder.WriteUnsignedLong(i); }
public void WriteSignedLong(long i) { _encoder.WriteSignedLong(i); }
public void WriteFloat(float value) { _encoder.WriteFloat(value); }
public void WriteDouble(double value) { _encoder.WriteDouble(value); }
public void WritePad(int size)
{
while (size > 0)
{
_encoder.WriteByte(0);
size--;
}
}
public bool IsGrowing()
{
return _phase == SavePhase.Growing;
}
public void UpdateOffsetAdjustment(int offsetDelta)
{
switch (_phase)
{
case SavePhase.Shrinking:
_offsetAdjustment = Math.Min(_offsetAdjustment, offsetDelta);
break;
case SavePhase.Growing:
_offsetAdjustment = Math.Max(_offsetAdjustment, offsetDelta);
break;
default:
break;
}
}
public void RollbackTo(int offset)
{
_encoder.RollbackTo(offset);
}
public void RollbackTo(int offset, int offsetAdjustment)
{
_offsetAdjustment = offsetAdjustment;
RollbackTo(offset);
}
public void PatchByteAt(int offset, byte value)
{
_encoder.PatchByteAt(offset, value);
}
// Swallow exceptions if invalid encoding is detected.
// This is the price we have to pay for using UTF8. Thing like High Surrogate Start Char - '\ud800'
// can be expressed in UTF-16 (which is the format used to store ECMA metadata), but don't have
// a representation in UTF-8.
private static Encoding _stringEncoding = new UTF8Encoding(false, false);
public void WriteString(string s)
{
// The actual bytes are only necessary for the final version during the growing plase
if (IsGrowing())
{
byte[] bytes = _stringEncoding.GetBytes(s);
_encoder.WriteUnsigned((uint)bytes.Length);
for (int i = 0; i < bytes.Length; i++)
_encoder.WriteByte(bytes[i]);
}
else
{
int byteCount = _stringEncoding.GetByteCount(s);
_encoder.WriteUnsigned((uint)byteCount);
WritePad(byteCount);
}
}
public void WriteRelativeOffset(Vertex val)
{
if (val._iteration == -1)
{
// If the offsets are not determined yet, use the maximum possible encoding
_encoder.WriteSigned(0x7FFFFFFF);
return;
}
int offset = val._offset;
// If the offset was not update in this iteration yet, adjust it by delta we have accumulated in this iteration so far.
// This adjustment allows the offsets to converge faster.
if (val._iteration < _iteration)
offset += _offsetAdjustment;
_encoder.WriteSigned(offset - GetCurrentOffset());
}
public int GetCurrentOffset()
{
return _encoder.Size;
}
public int GetNumberOfIterations()
{
return _iteration;
}
public int GetPaddingSize()
{
return _paddingSize;
}
public void Save(Stream stream)
{
_encoder.Clear();
_phase = SavePhase.Initial;
foreach (var section in _sections) foreach (var vertex in section._items)
{
vertex._offset = GetCurrentOffset();
vertex._iteration = _iteration;
vertex.Save(this);
#if NATIVEFORMAT_COMPRESSION
// Ensure that the compressor state is fully flushed
Debug.Assert(_TentativelyWritten.Count == 0);
Debug.Assert(_compressionDepth == 0);
#endif
}
// Aggresive phase that only allows offsets to shrink.
_phase = SavePhase.Shrinking;
for (; ; )
{
_iteration++;
_encoder.Clear();
_offsetAdjustment = 0;
foreach (var section in _sections) foreach (var vertex in section._items)
{
int currentOffset = GetCurrentOffset();
// Only allow the offsets to shrink.
_offsetAdjustment = Math.Min(_offsetAdjustment, currentOffset - vertex._offset);
vertex._offset += _offsetAdjustment;
if (vertex._offset < currentOffset)
{
// It is possible for the encoding of relative offsets to grow during some iterations.
// Ignore this growth because of it should disappear during next iteration.
RollbackTo(vertex._offset);
}
Debug.Assert(vertex._offset == GetCurrentOffset());
vertex._iteration = _iteration;
vertex.Save(this);
#if NATIVEFORMAT_COMPRESSION
// Ensure that the compressor state is fully flushed
Debug.Assert(_tentativelyWritten.Count == 0);
Debug.Assert(_compressionDepth == 0);
#endif
}
// We are not able to shrink anymore. We cannot just return here. It is possible that we have rolledback
// above because of we shrinked too much.
if (_offsetAdjustment == 0)
break;
// Limit number of shrinking interations. This limit is meant to be hit in corner cases only.
if (_iteration > 10)
break;
}
// Conservative phase that only allows the offsets to grow. It is guaranteed to converge.
_phase = SavePhase.Growing;
for (; ; )
{
_iteration++;
_encoder.Clear();
_offsetAdjustment = 0;
_paddingSize = 0;
foreach (var section in _sections) foreach (var vertex in section._items)
{
int currentOffset = GetCurrentOffset();
// Only allow the offsets to grow.
_offsetAdjustment = Math.Max(_offsetAdjustment, currentOffset - vertex._offset);
vertex._offset += _offsetAdjustment;
if (vertex._offset > currentOffset)
{
// Padding
int padding = vertex._offset - currentOffset;
_paddingSize += padding;
WritePad(padding);
}
Debug.Assert(vertex._offset == GetCurrentOffset());
vertex._iteration = _iteration;
vertex.Save(this);
#if NATIVEFORMAT_COMPRESSION
// Ensure that the compressor state is fully flushed
Debug.Assert(_tentativelyWritten.Count == 0);
Debug.Assert(_compressionDepth == 0);
#endif
}
if (_offsetAdjustment == 0)
{
_encoder.Save(stream);
return;
}
}
}
#if NATIVEFORMAT_COMPRESSION
// TODO:
#else
struct TypeSignatureCompressor
{
TypeSignatureCompressor(NativeWriter pWriter) { }
void Pack(Vertex vertex) { }
}
#endif
T Unify<T>(T vertex) where T : Vertex
{
Vertex existing;
if (_unifier.TryGetValue(vertex, out existing))
return (T)existing;
Debug.Assert(vertex._offset == Vertex.NotPlaced);
vertex._offset = Vertex.Unified;
_unifier.Add(vertex, vertex);
return vertex;
}
public Vertex GetUnsignedConstant(uint value)
{
UnsignedConstant vertex = new UnsignedConstant(value);
return Unify(vertex);
}
public Vertex GetTuple(Vertex item1, Vertex item2)
{
Tuple vertex = new Tuple(item1, item2);
return Unify(vertex);
}
public Vertex GetTuple(Vertex item1, Vertex item2, Vertex item3)
{
Tuple vertex = new Tuple(item1, item2, item3);
return Unify(vertex);
}
}
class PlacedVertex : Vertex
{
Vertex _unified;
public PlacedVertex(Vertex unified)
{
_unified = unified;
}
internal override void Save(NativeWriter writer)
{
_unified.Save(writer);
}
}
class UnsignedConstant : Vertex
{
uint _value;
public UnsignedConstant(uint value)
{
_value = value;
}
internal override void Save(NativeWriter writer)
{
writer.WriteUnsigned(_value);
}
public override int GetHashCode()
{
return 6659 + ((int)_value) * 19;
}
public override bool Equals(object other)
{
if (!(other is UnsignedConstant))
return false;
UnsignedConstant p = (UnsignedConstant)other;
if (_value != p._value) return false;
return true;
}
}
class Tuple : Vertex
{
private Vertex _item1;
private Vertex _item2;
private Vertex _item3;
public Tuple(Vertex item1, Vertex item2, Vertex item3 = null)
{
_item1 = item1;
_item2 = item2;
_item3 = item3;
}
internal override void Save(NativeWriter writer)
{
_item1.Save(writer);
_item2.Save(writer);
if (_item3 != null)
_item3.Save(writer);
}
public override int GetHashCode()
{
int hash = _item1.GetHashCode() * 93481 + _item2.GetHashCode() + 3492;
if (_item3 != null)
hash += (hash << 7) + _item3.GetHashCode() * 34987 + 213;
return hash;
}
public override bool Equals(object obj)
{
Tuple other = obj as Tuple;
if (other == null)
return false;
return Object.Equals(_item1, other._item1) &&
Object.Equals(_item2, other._item2) &&
Object.Equals(_item3, other._item3);
}
}
#if NATIVEFORMAT_PUBLICWRITER
public
#else
internal
#endif
class VertexHashtable : Vertex
{
struct Entry
{
public Entry(uint hashcode, Vertex vertex)
{
Offset = 0;
Hashcode = hashcode;
Vertex = vertex;
}
public int Offset;
public uint Hashcode;
public Vertex Vertex;
public static int Comparison(Entry a, Entry b)
{
return (int)(a.Hashcode /*& mask*/) - (int)(b.Hashcode /*& mask*/);
}
}
List<Entry> _Entries;
// How many entries to target per bucket. Higher fill factor means smaller size, but worse runtime perf.
int _nFillFactor;
// Number of buckets choosen for the table. Must be power of two. 0 means that the table is still open for mutation.
uint _nBuckets;
// Current size of index entry
int _entryIndexSize; // 0 - uint8, 1 - uint16, 2 - uint32
public const int DefaultFillFactor = 13;
public VertexHashtable(int fillFactor = DefaultFillFactor)
{
_Entries = new List<Entry>();
_nFillFactor = fillFactor;
_nBuckets = 0;
_entryIndexSize = 0;
}
public void Append(uint hashcode, Vertex element)
{
// The table needs to be open for mutation
Debug.Assert(_nBuckets == 0);
_Entries.Add(new Entry(hashcode, element));
}
// Returns 1 + log2(x) rounded up, 0 iff x == 0
static int HighestBit(uint x)
{
int ret = 0;
while (x != 0)
{
x >>= 1;
ret++;
}
return ret;
}
// Helper method to back patch entry index in the bucket table
static void PatchEntryIndex(NativeWriter writer, int patchOffset, int entryIndexSize, int entryIndex)
{
if (entryIndexSize == 0)
{
writer.PatchByteAt(patchOffset, (byte)entryIndex);
}
else if (entryIndexSize == 1)
{
writer.PatchByteAt(patchOffset, (byte)entryIndex);
writer.PatchByteAt(patchOffset + 1, (byte)(entryIndex >> 8));
}
else
{
writer.PatchByteAt(patchOffset, (byte)entryIndex);
writer.PatchByteAt(patchOffset + 1, (byte)(entryIndex >> 8));
writer.PatchByteAt(patchOffset + 2, (byte)(entryIndex >> 16));
writer.PatchByteAt(patchOffset + 3, (byte)(entryIndex >> 24));
}
}
void ComputeLayout()
{
uint bucketsEstimate = (uint)(_Entries.Count / _nFillFactor);
// Round number of buckets up to the power of two
_nBuckets = (uint)(1 << HighestBit(bucketsEstimate));
// Lowest byte of the hashcode is used for lookup within the bucket. Keep it sorted too so that
// we can use the ordering to terminate the lookup prematurely.
uint mask = ((_nBuckets - 1) << 8) | 0xFF;
// sort it by hashcode
_Entries.Sort(
(a, b) =>
{
return (int)(a.Hashcode & mask) - (int)(b.Hashcode & mask);
}
);
// Start with maximum size entries
_entryIndexSize = 2;
}
internal override void Save(NativeWriter writer)
{
// Compute the layout of the table if we have not done it yet
if (_nBuckets == 0)
ComputeLayout();
int nEntries = _Entries.Count;
int startOffset = writer.GetCurrentOffset();
uint bucketMask = (_nBuckets - 1);
// Lowest two bits are entry index size, the rest is log2 number of buckets
int numberOfBucketsShift = HighestBit(_nBuckets) - 1;
writer.WriteByte((byte)((numberOfBucketsShift << 2) | _entryIndexSize));
int bucketsOffset = writer.GetCurrentOffset();
writer.WritePad((int)((_nBuckets + 1) << _entryIndexSize));
// For faster lookup at runtime, we store the first entry index even though it is redundant (the
// value can be inferred from number of buckets)
PatchEntryIndex(writer, bucketsOffset, _entryIndexSize, writer.GetCurrentOffset() - bucketsOffset);
int iEntry = 0;
for (int iBucket = 0; iBucket < _nBuckets; iBucket++)
{
while (iEntry < nEntries)
{
if (((_Entries[iEntry].Hashcode >> 8) & bucketMask) != iBucket)
break;
Entry curEntry = _Entries[iEntry];
int currentOffset = writer.GetCurrentOffset();
writer.UpdateOffsetAdjustment(currentOffset - curEntry.Offset);
curEntry.Offset = currentOffset;
_Entries[iEntry] = curEntry;
writer.WriteByte((byte)curEntry.Hashcode);
writer.WriteRelativeOffset(curEntry.Vertex);
iEntry++;
}
int patchOffset = bucketsOffset + ((iBucket + 1) << _entryIndexSize);
PatchEntryIndex(writer, patchOffset, _entryIndexSize, writer.GetCurrentOffset() - bucketsOffset);
}
Debug.Assert(iEntry == nEntries);
int maxIndexEntry = (writer.GetCurrentOffset() - bucketsOffset);
int newEntryIndexSize = 0;
if (maxIndexEntry > 0xFF)
{
newEntryIndexSize++;
if (maxIndexEntry > 0xFFFF)
newEntryIndexSize++;
}
if (writer.IsGrowing())
{
if (newEntryIndexSize > _entryIndexSize)
{
// Ensure that the table will be redone with new entry index size
writer.UpdateOffsetAdjustment(1);
_entryIndexSize = newEntryIndexSize;
}
}
else
{
if (newEntryIndexSize < _entryIndexSize)
{
// Ensure that the table will be redone with new entry index size
writer.UpdateOffsetAdjustment(-1);
_entryIndexSize = newEntryIndexSize;
}
}
}
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. 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
using System;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at a given moment in time, and optionally repeated at a specified interval.
/// </summary>
/// <seealso cref="ITrigger" />
/// <seealso cref="ICronTrigger" />
/// <author>James House</author>
/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
{
/// <summary>
/// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
/// other words, the trigger should repeat continually until the trigger's
/// ending timestamp.
/// </summary>
public const int RepeatIndefinitely = -1;
private const int YearToGiveupSchedulingAt = 2299;
private DateTimeOffset? nextFireTimeUtc; // Making a public property which called GetNextFireTime/SetNextFireTime would make the json attribute unnecessary
private DateTimeOffset? previousFireTimeUtc; // Making a public property which called GetPreviousFireTime/SetPreviousFireTime would make the json attribute unnecessary
private int repeatCount;
private TimeSpan repeatInterval = TimeSpan.Zero;
private int timesTriggered;
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> with no settings.
/// </summary>
public SimpleTriggerImpl()
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name) : this(name, SchedulerConstants.DefaultGroup)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group)
: this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
: this(name, null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, string? group, int repeatCount, TimeSpan repeatInterval)
: this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
: this(name, null, startTimeUtc)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string? group, DateTimeOffset startTimeUtc)
: this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(
string name,
string? group,
DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount,
TimeSpan repeatInterval)
: base(name, group)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// fire the identified <see cref="IJob" /> and repeat at the given
/// interval the given number of times, or until the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="jobName">Name of the job.</param>
/// <param name="jobGroup">The job group.</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to fire.</param>
/// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use RepeatIndefinitely for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount, TimeSpan repeatInterval)
: base(name, group, jobName, jobGroup)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Get or set the number of times the <see cref="SimpleTriggerImpl" /> should
/// repeat, after which it will be automatically deleted.
/// </summary>
/// <seealso cref="RepeatIndefinitely" />
public int RepeatCount
{
get => repeatCount;
set
{
if (value < 0 && value != RepeatIndefinitely)
{
throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
}
repeatCount = value;
}
}
/// <summary>
/// Get or set the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
/// </summary>
public TimeSpan RepeatInterval
{
get => repeatInterval;
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException("Repeat interval must be >= 0");
}
repeatInterval = value;
}
}
/// <summary>
/// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
/// fired.
/// </summary>
public virtual int TimesTriggered
{
get => timesTriggered;
set => timesTriggered = value;
}
public override IScheduleBuilder GetScheduleBuilder()
{
SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
.WithInterval(RepeatInterval)
.WithRepeatCount(RepeatCount);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.SimpleTrigger.FireNow:
sb.WithMisfireHandlingInstructionFireNow();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount:
sb.WithMisfireHandlingInstructionNextWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount:
sb.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount:
sb.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount:
sb.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
case Quartz.MisfireInstruction.IgnoreMisfirePolicy:
sb.WithMisfireHandlingInstructionIgnoreMisfires();
break;
}
return sb;
}
/// <summary>
/// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, if repeatCount is RepeatIndefinitely, null will be returned.
/// <para>
/// Note that the return time may be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
if (repeatCount == 0)
{
return StartTimeUtc;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
if (repeatCount == RepeatIndefinitely)
{
return GetFireTimeBefore(EndTimeUtc);
}
DateTimeOffset lastTrigger = StartTimeUtc.AddTicks(repeatCount * repeatInterval.Ticks);
if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
{
return lastTrigger;
}
return GetFireTimeBefore(EndTimeUtc);
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision => true;
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
return false;
}
return true;
}
/// <summary>
/// Updates the <see cref="ISimpleTrigger" />'s state based on the
/// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
/// was created.
/// </summary>
/// <remarks>
/// If MisfireSmartPolicyEnabled is set to true,
/// then the following scheme will be used: <br />
/// <ul>
/// <li>If the Repeat Count is 0, then the instruction will
/// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.</li>
/// <li>If the Repeat Count is <see cref="RepeatIndefinitely" />, then
/// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount" />.
/// <b>WARNING:</b> using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
/// with a trigger that has a non-null end-time may cause the trigger to
/// never fire again if the end-time arrived during the misfire time span.
/// </li>
/// <li>If the Repeat Count is > 0, then the instruction
/// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
/// </li>
/// </ul>
/// </remarks>
public override void UpdateAfterMisfire(ICalendar? cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
if (RepeatCount == 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
}
else if (RepeatCount == RepeatIndefinitely)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;
}
else
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
}
if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
{
nextFireTimeUtc = SystemTime.UtcNow();
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
if (newFireTime.HasValue)
{
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc!.Value, newFireTime!.Value);
TimesTriggered = TimesTriggered + timesMissed;
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
RepeatCount = RepeatCount - TimesTriggered;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc!.Value, newFireTime);
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
if (remainingCount <= 0)
{
remainingCount = 0;
}
RepeatCount = remainingCount;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar? cal)
{
timesTriggered++;
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
}
}
/// <summary>
/// Updates the instance with new calendar.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (nextFireTimeUtc == null || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <returns>
/// The first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar? cal)
{
nextFireTimeUtc = StartTimeUtc;
while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
return null;
}
}
return nextFireTimeUtc;
}
/// <summary>
/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
/// fire. If the trigger will not fire again, <see langword="null" /> will be
/// returned. The value returned is not guaranteed to be valid until after
/// the <see cref="ITrigger" /> has been added to the scheduler.
/// </summary>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
{
nextFireTimeUtc = nextFireTime;
}
public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
{
previousFireTimeUtc = previousFireTime;
}
/// <summary>
/// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be
/// returned.
/// </summary>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, after the given UTC time. If the trigger will not fire after the given
/// time, <see langword="null" /> will be returned.
/// </summary>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if (timesTriggered > repeatCount && repeatCount != RepeatIndefinitely)
{
return null;
}
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
{
return null;
}
DateTimeOffset startMillis = StartTimeUtc;
DateTimeOffset afterMillis = afterTimeUtc.Value;
DateTimeOffset endMillis = EndTimeUtc ?? DateTimeOffset.MaxValue;
if (endMillis <= afterMillis)
{
return null;
}
if (afterMillis < startMillis)
{
return startMillis;
}
long numberOfTimesExecuted = ((afterMillis - startMillis).Ticks / repeatInterval.Ticks) + 1;
if (numberOfTimesExecuted > repeatCount &&
repeatCount != RepeatIndefinitely)
{
return null;
}
DateTimeOffset time = startMillis.AddTicks(numberOfTimesExecuted * repeatInterval.Ticks);
if (endMillis <= time)
{
return null;
}
return time;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, before the given time. If the trigger will not fire before the
/// given time, <see langword="null" /> will be returned.
/// </summary>
public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
{
if (endUtc != null && endUtc.Value < StartTimeUtc)
{
return null;
}
int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc!.Value);
return StartTimeUtc.AddTicks(numFires * repeatInterval.Ticks);
}
/// <summary>
/// Computes the number of times fired between the two UTC date times.
/// </summary>
/// <param name="startTimeUtc">The UTC start date and time.</param>
/// <param name="endTimeUtc">The UTC end date and time.</param>
/// <returns></returns>
public virtual int ComputeNumTimesFiredBetween(DateTimeOffset startTimeUtc, DateTimeOffset endTimeUtc)
{
long time = (endTimeUtc - startTimeUtc).Ticks;
return (int) (time / repeatInterval.Ticks);
}
/// <summary>
/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
/// again.
/// </summary>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public override void Validate()
{
base.Validate();
if (repeatCount != 0 && repeatInterval.Ticks < 1)
{
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans.Providers.Streams.Generator
{
/// <summary>
/// Stream generator commands
/// </summary>
public enum StreamGeneratorCommand
{
/// <summary>
/// Command to configure the generator
/// </summary>
Configure = PersistentStreamProviderCommand.AdapterFactoryCommandStartRange
}
/// <summary>
/// Adapter factory for stream generator stream provider.
/// This factory acts as the adapter and the adapter factory. It creates receivers that use configurable generator
/// to generate event streams, rather than reading them from storage.
/// </summary>
public class GeneratorAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache, IControllable
{
/// <summary>
/// Configuration property name for generator configuration type
/// </summary>
private readonly HashRingStreamQueueMapperOptions queueMapperOptions;
private readonly StreamStatisticOptions statisticOptions;
private readonly IServiceProvider serviceProvider;
private readonly Serialization.Serializer serializer;
private readonly ITelemetryProducer telemetryProducer;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger<GeneratorAdapterFactory> logger;
private IStreamGeneratorConfig generatorConfig;
private IStreamQueueMapper streamQueueMapper;
private IStreamFailureHandler streamFailureHandler;
private ConcurrentDictionary<QueueId, Receiver> receivers;
private IObjectPool<FixedSizeBuffer> bufferPool;
private BlockPoolMonitorDimensions blockPoolMonitorDimensions;
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction => StreamProviderDirection.ReadOnly;
/// <summary>
/// Name of the adapter. From IQueueAdapter.
/// </summary>
public string Name { get; }
/// <summary>
/// Create a cache monitor to report cache related metrics
/// Return a ICacheMonitor
/// </summary>
protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory;
/// <summary>
/// Create a block pool monitor to monitor block pool related metrics
/// Return a IBlockPoolMonitor
/// </summary>
protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory;
/// <summary>
/// Create a monitor to monitor QueueAdapterReceiver related metrics
/// Return a IQueueAdapterReceiverMonitor
/// </summary>
protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory;
public GeneratorAdapterFactory(string providerName, HashRingStreamQueueMapperOptions queueMapperOptions, StreamStatisticOptions statisticOptions, IServiceProvider serviceProvider, Serialization.Serializer serializer, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory)
{
this.Name = providerName;
this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions));
this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
this.logger = loggerFactory.CreateLogger<GeneratorAdapterFactory>();
}
/// <summary>
/// Initialize the factory
/// </summary>
public void Init()
{
this.receivers = new ConcurrentDictionary<QueueId, Receiver>();
if (CacheMonitorFactory == null)
this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer);
if (this.BlockPoolMonitorFactory == null)
this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer);
if (this.ReceiverMonitorFactory == null)
this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer);
generatorConfig = this.serviceProvider.GetServiceByName<IStreamGeneratorConfig>(this.Name);
if(generatorConfig == null)
{
this.logger.LogInformation("No generator configuration found for stream provider {StreamProvider}. Inactive until provided with configuration by command.", this.Name);
}
}
private void CreateBufferPoolIfNotCreatedYet()
{
if (this.bufferPool == null)
{
// 1 meg block size pool
this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}");
var oneMb = 1 << 20;
var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb);
this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval);
}
}
/// <summary>
/// Create an adapter
/// </summary>
/// <returns></returns>
public Task<IQueueAdapter> CreateAdapter()
{
return Task.FromResult<IQueueAdapter>(this);
}
/// <summary>
/// Get the cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Get the stream queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
return streamQueueMapper ?? (streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name));
}
/// <summary>
/// Get the delivery failure handler
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler()));
}
/// <summary>
/// Stores a batch of messages
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token,
Dictionary<string, object> requestContext)
{
return Task.CompletedTask;
}
/// <summary>
/// Creates a queue receiver for the specified queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
var dimensions = new ReceiverMonitorDimensions(queueId.ToString());
var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer);
var receiver = receivers.GetOrAdd(queueId, new Receiver(receiverMonitor));
SetGeneratorOnReceiver(receiver);
return receiver;
}
/// <summary>
/// A function to execute a control command.
/// </summary>
/// <param name="command">A serial number of the command.</param>
/// <param name="arg">An opaque command argument</param>
public Task<object> ExecuteCommand(int command, object arg)
{
if (arg == null)
{
throw new ArgumentNullException("arg");
}
generatorConfig = arg as IStreamGeneratorConfig;
if (generatorConfig == null)
{
throw new ArgumentOutOfRangeException("arg", "Arg must by of type IStreamGeneratorConfig");
}
// update generator on receivers
foreach (var receiver in receivers)
{
SetGeneratorOnReceiver(receiver.Value);
}
return Task.FromResult<object>(true);
}
private class Receiver : IQueueAdapterReceiver
{
const int MaxDelayMs = 20;
private readonly IQueueAdapterReceiverMonitor receiverMonitor;
public IStreamGenerator QueueGenerator { private get; set; }
public Receiver(IQueueAdapterReceiverMonitor receiverMonitor)
{
this.receiverMonitor = receiverMonitor;
}
public Task Initialize(TimeSpan timeout)
{
this.receiverMonitor?.TrackInitialization(true, TimeSpan.MinValue, null);
return Task.CompletedTask;
}
public async Task<IList<IBatchContainer>> GetQueueMessagesAsync(int maxCount)
{
var watch = Stopwatch.StartNew();
await Task.Delay(ThreadSafeRandom.Next(1,MaxDelayMs));
List<IBatchContainer> batches;
if (QueueGenerator == null || !QueueGenerator.TryReadEvents(DateTime.UtcNow, maxCount, out batches))
{
return new List<IBatchContainer>();
}
watch.Stop();
this.receiverMonitor?.TrackRead(true, watch.Elapsed, null);
if (batches.Count > 0)
{
var oldestMessage = batches[0] as GeneratedBatchContainer;
var newestMessage = batches[batches.Count - 1] as GeneratedBatchContainer;
this.receiverMonitor?.TrackMessagesReceived(batches.Count, oldestMessage?.EnqueueTimeUtc, newestMessage?.EnqueueTimeUtc);
}
return batches;
}
public Task MessagesDeliveredAsync(IList<IBatchContainer> messages)
{
return Task.CompletedTask;
}
public Task Shutdown(TimeSpan timeout)
{
this.receiverMonitor?.TrackShutdown(true, TimeSpan.MinValue, null);
return Task.CompletedTask;
}
}
private void SetGeneratorOnReceiver(Receiver receiver)
{
// if we don't have generator configuration, don't set generator
if (generatorConfig == null)
{
return;
}
var generator = (IStreamGenerator)(serviceProvider?.GetService(generatorConfig.StreamGeneratorType) ?? Activator.CreateInstance(generatorConfig.StreamGeneratorType));
if (generator == null)
{
throw new OrleansException($"StreamGenerator type not supported: {generatorConfig.StreamGeneratorType}");
}
generator.Configure(serviceProvider, generatorConfig);
receiver.QueueGenerator = generator;
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
//move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side.
CreateBufferPoolIfNotCreatedYet();
var dimensions = new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId);
var cacheMonitor = this.CacheMonitorFactory(dimensions, this.telemetryProducer);
return new GeneratorPooledCache(
bufferPool,
this.loggerFactory.CreateLogger($"{typeof(GeneratorPooledCache).FullName}.{this.Name}.{queueId}"),
serializer,
cacheMonitor,
this.statisticOptions.StatisticMonitorWriteInterval);
}
public static GeneratorAdapterFactory Create(IServiceProvider services, string name)
{
var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name);
var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name);
var factory = ActivatorUtilities.CreateInstance<GeneratorAdapterFactory>(services, name, queueMapperOptions, statisticOptions);
factory.Init();
return factory;
}
}
}
| |
/*
Copyright (C) 2009 Volker Berlin (vberlin@inetsoftware.de)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ikvm.debugger
{
/// <summary>
/// A JDWP Packet descriped at
/// http://java.sun.com/javase/6/docs/technotes/guides/jpda/jdwp-spec.html
/// </summary>
class Packet
{
private static int packetCounter;
private const byte NoFlags = 0x0;
private const byte Reply = 0x80;
private byte[] data;
private int offset;
private int id;
private byte cmdSet;
private byte cmd;
private short errorCode;
private bool isEvent;
private Stream output = new MemoryStream();
/// <summary>
/// Private constructor, use the factory methods
/// </summary>
private Packet() { }
/// <summary>
/// Create a packet from the stream.
/// </summary>
/// <param name="header">The first 11 bytes of the data.</param>
/// <param name="stream">The stream with the data</param>
/// <returns>a new Packet</returns>
/// <exception cref="IOException">If the data in the stream are invalid.</exception>
internal static Packet Read(byte[] header, Stream stream)
{
Packet packet = new Packet();
packet.data = header;
int len = packet.ReadInt();
if (len < 11)
{
throw new IOException("protocol error - invalid length");
}
packet.id = packet.ReadInt();
int flags = packet.ReadByte();
if ((flags & Reply) == 0)
{
packet.cmdSet = packet.ReadByte();
packet.cmd = packet.ReadByte();
}
else
{
packet.errorCode = packet.ReadShort();
}
packet.data = new byte[len - 11];
DebuggerUtils.ReadFully(stream, packet.data);
packet.offset = 0;
return packet;
}
/// <summary>
/// Create a empty packet to send an Event from the target VM (debuggee) to the debugger.
/// </summary>
/// <returns>a new packet</returns>
internal static Packet CreateEventPacket()
{
Packet packet = new Packet();
packet.id = ++packetCounter;
packet.cmdSet = ikvm.debugger.CommandSet.Event;
packet.cmd = 100;
packet.isEvent = true;
return packet;
}
/// <summary>
/// Is used from JdwpConnection. You should use jdwpConnection.Send(Packet).
/// </summary>
/// <param name="stream"></param>
internal void Send(Stream stream)
{
MemoryStream ms = (MemoryStream)output;
try
{
output = stream;
WriteInt((int)ms.Length + 11);
WriteInt(id);
if (!isEvent)
{
WriteByte(Reply);
WriteShort(errorCode);
}
else
{
WriteByte(NoFlags);
WriteByte(cmdSet);
WriteByte(cmd);
}
ms.WriteTo(stream);
}
finally
{
output = ms; //remove the external stream
}
}
internal int ReadInt()
{
return (data[offset++] << 24) |
(data[offset++] << 16) |
(data[offset++] << 8) |
(data[offset++]);
}
internal short ReadShort()
{
return (short)((data[offset++] << 8) | (data[offset++]));
}
internal byte ReadByte()
{
return data[offset++];
}
internal bool ReadBool()
{
return data[offset++] != 0;
}
internal String ReadString()
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
int length = ReadInt();
char[] chars = encoding.GetChars(data, offset, length);
offset += length;
return new String(chars);
}
internal int ReadObjectID()
{
return ReadInt();
}
internal Location ReadLocation()
{
Location loc = new Location();
loc.tagType = ReadByte();
loc.classID = ReadObjectID();
loc.methodID = ReadObjectID();
loc.index = new byte[8];
Array.Copy(data, offset, loc.index, 0, 8);
offset += 8;
return loc;
}
internal int Id
{
get { return id; }
}
internal int CommandSet
{
get { return cmdSet; }
}
internal int Command
{
get { return cmd; }
}
internal short Error
{
get { return errorCode; }
set { errorCode = value; }
}
internal void WriteInt(int value)
{
output.WriteByte((byte)(value >> 24));
output.WriteByte((byte)(value >> 16));
output.WriteByte((byte)(value >> 8));
output.WriteByte((byte)(value));
}
internal void WriteShort(int value)
{
output.WriteByte((byte)(value >> 8));
output.WriteByte((byte)(value));
}
internal void WriteByte(int value)
{
output.WriteByte((byte)(value));
}
internal void WriteBool(bool value)
{
output.WriteByte(value ? (byte)1 : (byte)0);
}
internal void WriteString(String value)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(value);
WriteInt(bytes.Length);
output.Write(bytes, 0, bytes.Length);
}
internal void WriteObjectID(int value)
{
WriteInt(value);
}
}
struct Location
{
internal byte tagType;
internal int classID;
internal int methodID;
internal byte[] index;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
abstract class DiagnosticTraceBase
{
//Diagnostics trace
protected const string DefaultTraceListenerName = "Default";
protected const string TraceRecordVersion = "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord";
protected static string AppDomainFriendlyName = AppDomain.CurrentDomain.FriendlyName;
const ushort TracingEventLogCategory = 4;
object thisLock;
bool tracingEnabled = true;
bool calledShutdown;
bool haveListeners;
SourceLevels level;
protected string TraceSourceName;
TraceSource traceSource;
[Fx.Tag.SecurityNote(Critical = "This determines the event source name.")]
[SecurityCritical]
string eventSourceName;
public DiagnosticTraceBase(string traceSourceName)
{
this.thisLock = new object();
this.TraceSourceName = traceSourceName;
this.LastFailure = DateTime.MinValue;
}
protected DateTime LastFailure { get; set; }
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecurityCritical method. Does not expose critical resources returned by methods with Link Demands")]
[Fx.Tag.SecurityNote(Critical = "Critical because we are invoking TraceSource.Listeners which has a Link Demand for UnmanagedCode permission.",
Miscellaneous = "Asserting Unmanaged Code causes traceSource.Listeners to be successfully initiated and cached. But the Listeners property has a LinkDemand for UnmanagedCode, so it can't be read by partially trusted assemblies in heterogeneous appdomains")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
static void UnsafeRemoveDefaultTraceListener(TraceSource traceSource)
{
traceSource.Listeners.Remove(DiagnosticTraceBase.DefaultTraceListenerName);
}
public TraceSource TraceSource
{
get
{
return this.traceSource;
}
set
{
SetTraceSource(value);
}
}
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "Does not expose critical resources returned by methods with Link Demands")]
[Fx.Tag.SecurityNote(Critical = "Critical because we are invoking TraceSource.Listeners which has a Link Demand for UnmanagedCode permission.",
Safe = "Safe because are only retrieving the count of listeners and removing the default trace listener - we aren't leaking any critical resources.")]
[SecuritySafeCritical]
protected void SetTraceSource(TraceSource traceSource)
{
if (traceSource != null)
{
UnsafeRemoveDefaultTraceListener(traceSource);
this.traceSource = traceSource;
this.haveListeners = this.traceSource.Listeners.Count > 0;
}
}
public bool HaveListeners
{
get
{
return this.haveListeners;
}
}
SourceLevels FixLevel(SourceLevels level)
{
//the bit fixing below is meant to keep the trace level legal even if somebody uses numbers in config
if (((level & ~SourceLevels.Information) & SourceLevels.Verbose) != 0)
{
level |= SourceLevels.Verbose;
}
else if (((level & ~SourceLevels.Warning) & SourceLevels.Information) != 0)
{
level |= SourceLevels.Information;
}
else if (((level & ~SourceLevels.Error) & SourceLevels.Warning) != 0)
{
level |= SourceLevels.Warning;
}
if (((level & ~SourceLevels.Critical) & SourceLevels.Error) != 0)
{
level |= SourceLevels.Error;
}
if ((level & SourceLevels.Critical) != 0)
{
level |= SourceLevels.Critical;
}
// If only the ActivityTracing flag is set, then
// we really have Off. Do not do ActivityTracing then.
if (level == SourceLevels.ActivityTracing)
{
level = SourceLevels.Off;
}
return level;
}
protected virtual void OnSetLevel(SourceLevels level)
{
}
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "Does not expose critical resources returned by methods with Link Demands")]
[Fx.Tag.SecurityNote(Critical = "Critical because we are invoking TraceSource.Listeners and SourceSwitch.Level which have Link Demands for UnmanagedCode permission.")]
[SecurityCritical]
void SetLevel(SourceLevels level)
{
SourceLevels fixedLevel = FixLevel(level);
this.level = fixedLevel;
if (this.TraceSource != null)
{
// Need this for setup from places like TransactionBridge.
this.haveListeners = this.TraceSource.Listeners.Count > 0;
OnSetLevel(level);
#pragma warning disable 618
this.tracingEnabled = this.HaveListeners && (level != SourceLevels.Off);
#pragma warning restore 618
this.TraceSource.Switch.Level = level;
}
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are invoking SetLevel.")]
[SecurityCritical]
void SetLevelThreadSafe(SourceLevels level)
{
lock (this.thisLock)
{
SetLevel(level);
}
}
public SourceLevels Level
{
get
{
if (this.TraceSource != null && (this.TraceSource.Switch.Level != this.level))
{
this.level = this.TraceSource.Switch.Level;
}
return this.level;
}
[Fx.Tag.SecurityNote(Critical = "Critical because we are invoking SetLevelTheadSafe.")]
[SecurityCritical]
set
{
SetLevelThreadSafe(value);
}
}
protected string EventSourceName
{
[Fx.Tag.SecurityNote(Critical = "Access critical eventSourceName field",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
get
{
return this.eventSourceName;
}
[Fx.Tag.SecurityNote(Critical = "This determines the event source name.")]
[SecurityCritical]
set
{
this.eventSourceName = value;
}
}
public bool TracingEnabled
{
get
{
return this.tracingEnabled && this.traceSource != null;
}
}
protected static string ProcessName
{
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource and has been reviewed")]
[SecuritySafeCritical]
get
{
string retval = null;
using (Process process = Process.GetCurrentProcess())
{
retval = process.ProcessName;
}
return retval;
}
}
protected static int ProcessId
{
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource and has been reviewed")]
[SecuritySafeCritical]
get
{
int retval = -1;
using (Process process = Process.GetCurrentProcess())
{
retval = process.Id;
}
return retval;
}
}
public virtual bool ShouldTrace(TraceEventLevel level)
{
return ShouldTraceToTraceSource(level);
}
public bool ShouldTrace(TraceEventType type)
{
return this.TracingEnabled && this.HaveListeners &&
(this.TraceSource != null) &&
0 != ((int)type & (int)this.Level);
}
public bool ShouldTraceToTraceSource(TraceEventLevel level)
{
return ShouldTrace(TraceLevelHelper.GetTraceEventType(level));
}
//only used for exceptions, perf is not important
public static string XmlEncode(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
int len = text.Length;
StringBuilder encodedText = new StringBuilder(len + 8); //perf optimization, expecting no more than 2 > characters
for (int i = 0; i < len; ++i)
{
char ch = text[i];
switch (ch)
{
case '<':
encodedText.Append("<");
break;
case '>':
encodedText.Append(">");
break;
case '&':
encodedText.Append("&");
break;
default:
encodedText.Append(ch);
break;
}
}
return encodedText.ToString();
}
[Fx.Tag.SecurityNote(Critical = "Sets global event handlers for the AppDomain",
Safe = "Doesn't leak resources\\Information")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCritical method, Does not expose critical resources returned by methods with Link Demands")]
protected void AddDomainEventHandlersForCleanup()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
if (this.TraceSource != null)
{
this.haveListeners = this.TraceSource.Listeners.Count > 0;
}
this.tracingEnabled = this.haveListeners;
if (this.TracingEnabled)
{
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
this.SetLevel(this.TraceSource.Switch.Level);
currentDomain.DomainUnload += new EventHandler(ExitOrUnloadEventHandler);
currentDomain.ProcessExit += new EventHandler(ExitOrUnloadEventHandler);
}
}
void ExitOrUnloadEventHandler(object sender, EventArgs e)
{
ShutdownTracing();
}
protected abstract void OnUnhandledException(Exception exception);
protected void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
OnUnhandledException(e);
ShutdownTracing();
}
protected static string CreateSourceString(object source)
{
var traceSourceStringProvider = source as ITraceSourceStringProvider;
if (traceSourceStringProvider != null)
{
return traceSourceStringProvider.GetSourceString();
}
return CreateDefaultSourceString(source);
}
internal static string CreateDefaultSourceString(object source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return String.Format(CultureInfo.CurrentCulture, "{0}/{1}", source.GetType().ToString(), source.GetHashCode());
}
protected static void AddExceptionToTraceString(XmlWriter xml, Exception exception)
{
xml.WriteElementString(DiagnosticStrings.ExceptionTypeTag, XmlEncode(exception.GetType().AssemblyQualifiedName));
xml.WriteElementString(DiagnosticStrings.MessageTag, XmlEncode(exception.Message));
xml.WriteElementString(DiagnosticStrings.StackTraceTag, XmlEncode(StackTraceString(exception)));
xml.WriteElementString(DiagnosticStrings.ExceptionStringTag, XmlEncode(exception.ToString()));
Win32Exception win32Exception = exception as Win32Exception;
if (win32Exception != null)
{
xml.WriteElementString(DiagnosticStrings.NativeErrorCodeTag, win32Exception.NativeErrorCode.ToString("X", CultureInfo.InvariantCulture));
}
if (exception.Data != null && exception.Data.Count > 0)
{
xml.WriteStartElement(DiagnosticStrings.DataItemsTag);
foreach (object dataItem in exception.Data.Keys)
{
xml.WriteStartElement(DiagnosticStrings.DataTag);
xml.WriteElementString(DiagnosticStrings.KeyTag, XmlEncode(dataItem.ToString()));
xml.WriteElementString(DiagnosticStrings.ValueTag, XmlEncode(exception.Data[dataItem].ToString()));
xml.WriteEndElement();
}
xml.WriteEndElement();
}
if (exception.InnerException != null)
{
xml.WriteStartElement(DiagnosticStrings.InnerExceptionTag);
AddExceptionToTraceString(xml, exception.InnerException);
xml.WriteEndElement();
}
}
protected static string StackTraceString(Exception exception)
{
string retval = exception.StackTrace;
if (string.IsNullOrEmpty(retval))
{
// This means that the exception hasn't been thrown yet. We need to manufacture the stack then.
StackTrace stackTrace = new StackTrace(false);
// Figure out how many frames should be throw away
System.Diagnostics.StackFrame[] stackFrames = stackTrace.GetFrames();
int frameCount = 0;
bool breakLoop = false;
foreach (StackFrame frame in stackFrames)
{
string methodName = frame.GetMethod().Name;
switch (methodName)
{
case "StackTraceString":
case "AddExceptionToTraceString":
case "BuildTrace":
case "TraceEvent":
case "TraceException":
case "GetAdditionalPayload":
++frameCount;
break;
default:
if (methodName.StartsWith("ThrowHelper", StringComparison.Ordinal))
{
++frameCount;
}
else
{
breakLoop = true;
}
break;
}
if (breakLoop)
{
break;
}
}
stackTrace = new StackTrace(frameCount, false);
retval = stackTrace.ToString();
}
return retval;
}
//CSDMain:109153, Duplicate code from System.ServiceModel.Diagnostics
[Fx.Tag.SecurityNote(Critical = "Calls unsafe methods, UnsafeCreateEventLogger and UnsafeLogEvent.",
Safe = "Event identities cannot be spoofed as they are constants determined inside the method, Demands the same permission that is asserted by the unsafe method.")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts,
Justification = "Should not demand permission that is asserted by the EtwProvider ctor.")]
protected void LogTraceFailure(string traceString, Exception exception)
{
const int FailureBlackoutDuration = 10;
TimeSpan FailureBlackout = TimeSpan.FromMinutes(FailureBlackoutDuration);
try
{
lock (this.thisLock)
{
if (DateTime.UtcNow.Subtract(this.LastFailure) >= FailureBlackout)
{
this.LastFailure = DateTime.UtcNow;
#pragma warning disable 618
EventLogger logger = EventLogger.UnsafeCreateEventLogger(this.eventSourceName, this);
#pragma warning restore 618
if (exception == null)
{
logger.UnsafeLogEvent(TraceEventType.Error, TracingEventLogCategory, (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToTraceEvent, false,
traceString);
}
else
{
logger.UnsafeLogEvent(TraceEventType.Error, TracingEventLogCategory, (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToTraceEventWithException, false,
traceString, exception.ToString());
}
}
}
}
catch (Exception eventLoggerException)
{
if (Fx.IsFatal(eventLoggerException))
{
throw;
}
}
}
protected abstract void OnShutdownTracing();
void ShutdownTracing()
{
if (!this.calledShutdown)
{
this.calledShutdown = true;
try
{
OnShutdownTracing();
}
#pragma warning suppress 56500 //[....]; Taken care of by FxCop
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//log failure
LogTraceFailure(null, exception);
}
}
}
protected bool CalledShutdown
{
get
{
return this.calledShutdown;
}
}
public static Guid ActivityId
{
[Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode",
Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCriticial method")]
get
{
object id = Trace.CorrelationManager.ActivityId;
return id == null ? Guid.Empty : (Guid)id;
}
[Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode",
Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")]
[SecuritySafeCritical]
set
{
Trace.CorrelationManager.ActivityId = value;
}
}
#pragma warning restore 56500
protected static string LookupSeverity(TraceEventType type)
{
string s;
switch (type)
{
case TraceEventType.Critical:
s = "Critical";
break;
case TraceEventType.Error:
s = "Error";
break;
case TraceEventType.Warning:
s = "Warning";
break;
case TraceEventType.Information:
s = "Information";
break;
case TraceEventType.Verbose:
s = "Verbose";
break;
case TraceEventType.Start:
s = "Start";
break;
case TraceEventType.Stop:
s = "Stop";
break;
case TraceEventType.Suspend:
s = "Suspend";
break;
case TraceEventType.Transfer:
s = "Transfer";
break;
default:
s = type.ToString();
break;
}
#pragma warning disable 618
Fx.Assert(s == type.ToString(), "Return value should equal the name of the enum");
#pragma warning restore 618
return s;
}
public abstract bool IsEnabled();
public abstract void TraceEventLogEvent(TraceEventType type, TraceRecord traceRecord);
}
}
| |
//
// MenuButton.cs
//
// Author:
// Scott Peterson <lunchtimemama@gmail.com>
//
// Copyright (c) 2008 Scott Peterson
//
// 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 Gtk;
using Gdk;
namespace Hyena.Widgets
{
public class MenuButton : Container
{
private ToggleButton toggle_button = new ToggleButton ();
private HBox box = new HBox ();
private Alignment alignment;
private Arrow arrow;
private Widget button_widget;
private Menu menu;
private Widget size_widget;
private IconSize icon_size = IconSize.LargeToolbar;
protected MenuButton (IntPtr ptr) : base (ptr) {}
public MenuButton ()
{
}
public MenuButton (Widget buttonWidget, Menu menu, bool showArrow)
{
Construct (buttonWidget, menu, showArrow);
}
public IconSize IconSize
{
get { return icon_size; }
set
{
icon_size = value;
_RecursiveSetImageSize (this, value);
}
}
void _RecursiveSetImageSize (Widget widget, IconSize size)
{
if (widget is Container)
{
foreach (var child in ((Container) widget).Children)
{
_RecursiveSetImageSize (child, size);
}
}
if (widget is Image)
{
((Image) widget).IconSize = (int) size;
}
}
protected void Construct (Widget buttonWidget, Menu menu, bool showArrow)
{
HasWindow = false;
button_widget = buttonWidget;
Menu = menu;
toggle_button.Parent = this;
toggle_button.FocusOnClick = false;
toggle_button.Relief = ReliefStyle.None;
toggle_button.Pressed += delegate { ShowMenu (); toggle_button.Active = true; };
toggle_button.Activated += delegate { ShowMenu (); };
box.Parent = this;
if (showArrow) {
box.PackStart (button_widget, true, true, 0);
alignment = new Alignment (0f, 0.5f, 0f, 0f) {
MarginRight = 10
};
arrow = new Arrow (ArrowType.Down, ShadowType.None);
alignment.Add (arrow);
box.PackStart (alignment, false, false, 0);
size_widget = box;
FocusChain = new Widget[] {toggle_button, box};
alignment.ShowAll ();
alignment.NoShowAll = true;
} else {
toggle_button.Add (button_widget);
size_widget = toggle_button;
}
ShowAll ();
}
public Widget ButtonWidget {
get { return button_widget; }
}
public Menu Menu {
get { return menu; }
set {
if (menu == value)
return;
if (menu != null)
menu.Deactivated -= OnMenuDeactivated;
menu = value;
menu.Deactivated += OnMenuDeactivated;
}
}
private void OnMenuDeactivated (object o, EventArgs args)
{
toggle_button.Active = false;
}
public ToggleButton ToggleButton {
get { return toggle_button; }
}
public Arrow Arrow {
get { return arrow; }
}
public bool ArrowVisible {
get { return alignment.Visible; }
set { alignment.Visible = value; }
}
protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height)
{
base.OnGetPreferredHeight (out minimum_height, out natural_height);
box.GetPreferredHeight (out minimum_height, out natural_height);
toggle_button.GetPreferredHeight (out minimum_height, out natural_height);
size_widget.GetPreferredHeight (out minimum_height, out natural_height);
}
protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width)
{
base.OnGetPreferredWidth (out minimum_width, out natural_width);
toggle_button.GetPreferredWidth (out minimum_width, out natural_width);
box.GetPreferredWidth (out minimum_width, out natural_width);
size_widget.GetPreferredWidth (out minimum_width, out natural_width);
}
protected override void OnSizeAllocated (Rectangle allocation)
{
box.SizeAllocate (allocation);
toggle_button.SizeAllocate (allocation);
base.OnSizeAllocated (allocation);
}
protected override void ForAll (bool include_internals, Callback callback)
{
callback (toggle_button);
callback (box);
}
protected override void OnAdded (Widget widget)
{
}
protected override void OnRemoved (Widget widget)
{
}
protected void ShowMenu ()
{
menu.Popup (null, null, PositionMenu, 1, Gtk.Global.CurrentEventTime);
}
private void PositionMenu (Menu menu, out int x, out int y, out bool push_in)
{
Gtk.Requisition menu_req, nat_req;
menu.GetPreferredSize (out menu_req, out nat_req);
int monitor_num = Screen.GetMonitorAtWindow (Window);
Gdk.Rectangle monitor = Screen.GetMonitorGeometry (monitor_num < 0 ? 0 : monitor_num);
Window.GetOrigin (out x, out y);
y += Allocation.Y;
x += Allocation.X + (Direction == TextDirection.Ltr
? Math.Max (Allocation.Width - menu_req.Width, 0)
: - (menu_req.Width - Allocation.Width));
if (y + Allocation.Height + menu_req.Height <= monitor.Y + monitor.Height) {
y += Allocation.Height;
} else if (y - menu_req.Height >= monitor.Y) {
y -= menu_req.Height;
} else if (monitor.Y + monitor.Height - (y + Allocation.Height) > y) {
y += Allocation.Height;
} else {
y -= menu_req.Height;
}
push_in = false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.