context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework;
using osu.Framework.Caching;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Graphics.Shapes;
namespace osu.Game.Screens.Play
{
public class SquareGraph : BufferedContainer
{
private Column[] columns = { };
public int ColumnCount => columns.Length;
public override bool HandleInput => false;
private int progress;
public int Progress
{
get { return progress; }
set
{
if (value == progress) return;
progress = value;
redrawProgress();
}
}
private float[] calculatedValues = { }; // values but adjusted to fit the amount of columns
private int[] values;
public int[] Values
{
get { return values; }
set
{
if (value == values) return;
values = value;
layout.Invalidate();
}
}
private Color4 fillColour;
public Color4 FillColour
{
get { return fillColour; }
set
{
if (value == fillColour) return;
fillColour = value;
redrawFilled();
}
}
public SquareGraph()
{
CacheDrawnFrameBuffer = true;
}
private Cached layout = new Cached();
public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true)
{
if ((invalidation & Invalidation.DrawSize) > 0)
layout.Invalidate();
return base.Invalidate(invalidation, source, shallPropagate);
}
protected override void Update()
{
base.Update();
if (!layout.IsValid)
{
recreateGraph();
layout.Validate();
}
}
/// <summary>
/// Redraws all the columns to match their lit/dimmed state.
/// </summary>
private void redrawProgress()
{
for (int i = 0; i < columns.Length; i++)
columns[i].State = i <= progress ? ColumnState.Lit : ColumnState.Dimmed;
ForceRedraw();
}
/// <summary>
/// Redraws the filled amount of all the columns.
/// </summary>
private void redrawFilled()
{
for (int i = 0; i < ColumnCount; i++)
columns[i].Filled = calculatedValues.ElementAtOrDefault(i);
ForceRedraw();
}
/// <summary>
/// Takes <see cref="Values"/> and adjusts it to fit the amount of columns.
/// </summary>
private void recalculateValues()
{
var newValues = new List<float>();
if (values == null)
{
for (float i = 0; i < ColumnCount; i++)
newValues.Add(0);
return;
}
var max = values.Max();
float step = values.Length / (float)ColumnCount;
for (float i = 0; i < values.Length; i += step)
{
newValues.Add((float)values[(int)i] / max);
}
calculatedValues = newValues.ToArray();
}
/// <summary>
/// Recreates the entire graph.
/// </summary>
private void recreateGraph()
{
var newColumns = new List<Column>();
for (float x = 0; x < DrawWidth; x += Column.WIDTH)
{
newColumns.Add(new Column
{
LitColour = fillColour,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Height = DrawHeight,
Position = new Vector2(x, 0),
State = ColumnState.Dimmed,
});
}
columns = newColumns.ToArray();
Children = columns;
recalculateValues();
redrawFilled();
redrawProgress();
}
public class Column : Container, IStateful<ColumnState>
{
protected readonly Color4 EmptyColour = Color4.White.Opacity(20);
public Color4 LitColour = Color4.LightBlue;
protected readonly Color4 DimmedColour = Color4.White.Opacity(140);
private float cubeCount => DrawHeight / WIDTH;
private const float cube_size = 4;
private const float padding = 2;
public const float WIDTH = cube_size + padding;
public event Action<ColumnState> StateChanged;
private readonly List<Box> drawableRows = new List<Box>();
private float filled;
public float Filled
{
get { return filled; }
set
{
if (value == filled) return;
filled = value;
fillActive();
}
}
private ColumnState state;
public ColumnState State
{
get { return state; }
set
{
if (value == state) return;
state = value;
if (IsLoaded)
fillActive();
StateChanged?.Invoke(State);
}
}
public Column()
{
Width = WIDTH;
}
protected override void LoadComplete()
{
for (int r = 0; r < cubeCount; r++)
{
drawableRows.Add(new Box
{
Size = new Vector2(cube_size),
Position = new Vector2(0, r * WIDTH + padding),
});
}
Children = drawableRows;
// Reverse drawableRows so when iterating through them they start at the bottom
drawableRows.Reverse();
fillActive();
}
private void fillActive()
{
Color4 colour = State == ColumnState.Lit ? LitColour : DimmedColour;
int countFilled = (int)MathHelper.Clamp(filled * drawableRows.Count, 0, drawableRows.Count);
for (int i = 0; i < drawableRows.Count; i++)
drawableRows[i].Colour = i < countFilled ? colour : EmptyColour;
}
}
public enum ColumnState
{
Lit,
Dimmed
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using Lucene.Net.Index;
using Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using Directory = Lucene.Net.Store.Directory;
using ReaderUtil = Lucene.Net.Util.ReaderUtil;
namespace Lucene.Net.Search
{
/// <summary>Implements search over a single IndexReader.
///
/// <p/>Applications usually need only call the inherited <see cref="Searcher.Search(Query,int)" />
/// or <see cref="Searcher.Search(Query,Filter,int)" /> methods. For performance reasons it is
/// recommended to open only one IndexSearcher and use it for all of your searches.
///
/// <a name="thread-safety"></a><p/><b>NOTE</b>:
/// <see cref="IndexSearcher" /> instances are completely
/// thread safe, meaning multiple threads can call any of its
/// methods, concurrently. If your application requires
/// external synchronization, you should <b>not</b>
/// synchronize on the <c>IndexSearcher</c> instance;
/// use your own (non-Lucene) objects instead.<p/>
/// </summary>
[Serializable]
public class IndexSearcher : Searcher
{
internal IndexReader reader;
private bool closeReader;
private bool isDisposed;
// NOTE: these members might change in incompatible ways
// in the next release
private IndexReader[] subReaders;
private int[] docStarts;
/// <summary>Creates a searcher searching the index in the named
/// directory, with readOnly=true</summary>
/// <throws>CorruptIndexException if the index is corrupt</throws>
/// <throws>IOException if there is a low-level IO error</throws>
public IndexSearcher(Directory path)
: this(IndexReader.Open(path, true), true)
{
}
/// <summary>Creates a searcher searching the index in the named
/// directory. You should pass readOnly=true, since it
/// gives much better concurrent performance, unless you
/// intend to do write operations (delete documents or
/// change norms) with the underlying IndexReader.
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
/// <param name="path">directory where IndexReader will be opened
/// </param>
/// <param name="readOnly">if true, the underlying IndexReader
/// will be opened readOnly
/// </param>
public IndexSearcher(Directory path, bool readOnly):this(IndexReader.Open(path, readOnly), true)
{
}
/// <summary>Creates a searcher searching the provided index
/// <para>
/// Note that the underlying IndexReader is not closed, if
/// IndexSearcher was constructed with IndexSearcher(IndexReader r).
/// If the IndexReader was supplied implicitly by specifying a directory, then
/// the IndexReader gets closed.
/// </para>
/// </summary>
public IndexSearcher(IndexReader r):this(r, false)
{
}
/// <summary>
/// Expert: directly specify the reader, subReaders and their
/// DocID starts
/// <p/>
/// <b>NOTE:</b> This API is experimental and
/// might change in incompatible ways in the next
/// release<p/>
/// </summary>
public IndexSearcher(IndexReader reader, IndexReader[] subReaders, int[] docStarts)
{
this.reader = reader;
this.subReaders = subReaders;
this.docStarts = docStarts;
this.closeReader = false;
}
private IndexSearcher(IndexReader r, bool closeReader)
{
reader = r;
this.closeReader = closeReader;
System.Collections.Generic.IList<IndexReader> subReadersList = new System.Collections.Generic.List<IndexReader>();
GatherSubReaders(subReadersList, reader);
subReaders = subReadersList.ToArray();
docStarts = new int[subReaders.Length];
int maxDoc = 0;
for (int i = 0; i < subReaders.Length; i++)
{
docStarts[i] = maxDoc;
maxDoc += subReaders[i].MaxDoc;
}
}
protected internal virtual void GatherSubReaders(System.Collections.Generic.IList<IndexReader> allSubReaders, IndexReader r)
{
ReaderUtil.GatherSubReaders(allSubReaders, r);
}
/// <summary>Return the <see cref="Index.IndexReader" /> this searches. </summary>
public virtual IndexReader IndexReader
{
get { return reader; }
}
protected override void Dispose(bool disposing)
{
if (isDisposed) return;
if (disposing)
{
if (closeReader)
reader.Close();
}
isDisposed = true;
}
// inherit javadoc
public override int DocFreq(Term term)
{
return reader.DocFreq(term);
}
// inherit javadoc
public override Document Doc(int i)
{
return reader.Document(i);
}
// inherit javadoc
public override Document Doc(int i, FieldSelector fieldSelector)
{
return reader.Document(i, fieldSelector);
}
// inherit javadoc
public override int MaxDoc
{
get { return reader.MaxDoc; }
}
// inherit javadoc
public override TopDocs Search(Weight weight, Filter filter, int nDocs)
{
if (nDocs <= 0)
{
throw new System.ArgumentException("nDocs must be > 0");
}
nDocs = Math.Min(nDocs, reader.MaxDoc);
TopScoreDocCollector collector = TopScoreDocCollector.Create(nDocs, !weight.GetScoresDocsOutOfOrder());
Search(weight, filter, collector);
return collector.TopDocs();
}
public override TopFieldDocs Search(Weight weight, Filter filter, int nDocs, Sort sort)
{
return Search(weight, filter, nDocs, sort, true);
}
/// <summary> Just like <see cref="Search(Weight, Filter, int, Sort)" />, but you choose
/// whether or not the fields in the returned <see cref="FieldDoc" /> instances
/// should be set by specifying fillFields.
/// <p/>
/// NOTE: this does not compute scores by default. If you need scores, create
/// a <see cref="TopFieldCollector" /> instance by calling
/// <see cref="TopFieldCollector.Create" /> and then pass that to
/// <see cref="Search(Weight, Filter, Collector)" />.
/// <p/>
/// </summary>
public virtual TopFieldDocs Search(Weight weight, Filter filter, int nDocs, Sort sort, bool fillFields)
{
nDocs = Math.Min(nDocs, reader.MaxDoc);
TopFieldCollector collector2 = TopFieldCollector.Create(sort, nDocs, fillFields, fieldSortDoTrackScores, fieldSortDoMaxScore, !weight.GetScoresDocsOutOfOrder());
Search(weight, filter, collector2);
return (TopFieldDocs) collector2.TopDocs();
}
public override void Search(Weight weight, Filter filter, Collector collector)
{
if (filter == null)
{
for (int i = 0; i < subReaders.Length; i++)
{
// search each subreader
collector.SetNextReader(subReaders[i], docStarts[i]);
Scorer scorer = weight.Scorer(subReaders[i], !collector.AcceptsDocsOutOfOrder, true);
if (scorer != null)
{
scorer.Score(collector);
}
}
}
else
{
for (int i = 0; i < subReaders.Length; i++)
{
// search each subreader
collector.SetNextReader(subReaders[i], docStarts[i]);
SearchWithFilter(subReaders[i], weight, filter, collector);
}
}
}
private void SearchWithFilter(IndexReader reader, Weight weight, Filter filter, Collector collector)
{
System.Diagnostics.Debug.Assert(filter != null);
Scorer scorer = weight.Scorer(reader, true, false);
if (scorer == null)
{
return ;
}
int docID = scorer.DocID();
System.Diagnostics.Debug.Assert(docID == - 1 || docID == DocIdSetIterator.NO_MORE_DOCS);
// CHECKME: use ConjunctionScorer here?
DocIdSet filterDocIdSet = filter.GetDocIdSet(reader);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return ;
}
DocIdSetIterator filterIter = filterDocIdSet.Iterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return ;
}
int filterDoc = filterIter.NextDoc();
int scorerDoc = scorer.Advance(filterDoc);
collector.SetScorer(scorer);
while (true)
{
if (scorerDoc == filterDoc)
{
// Check if scorer has exhausted, only before collecting.
if (scorerDoc == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
collector.Collect(scorerDoc);
filterDoc = filterIter.NextDoc();
scorerDoc = scorer.Advance(filterDoc);
}
else if (scorerDoc > filterDoc)
{
filterDoc = filterIter.Advance(scorerDoc);
}
else
{
scorerDoc = scorer.Advance(filterDoc);
}
}
}
public override Query Rewrite(Query original)
{
Query query = original;
for (Query rewrittenQuery = query.Rewrite(reader); rewrittenQuery != query; rewrittenQuery = query.Rewrite(reader))
{
query = rewrittenQuery;
}
return query;
}
public override Explanation Explain(Weight weight, int doc)
{
int n = ReaderUtil.SubIndex(doc, docStarts);
int deBasedDoc = doc - docStarts[n];
return weight.Explain(subReaders[n], deBasedDoc);
}
private bool fieldSortDoTrackScores;
private bool fieldSortDoMaxScore;
/// <summary> By default, no scores are computed when sorting by field (using
/// <see cref="Searcher.Search(Query,Filter,int,Sort)" />). You can change that, per
/// IndexSearcher instance, by calling this method. Note that this will incur
/// a CPU cost.
///
/// </summary>
/// <param name="doTrackScores">If true, then scores are returned for every matching document
/// in <see cref="TopFieldDocs" />.
///
/// </param>
/// <param name="doMaxScore">If true, then the max score for all matching docs is computed.
/// </param>
public virtual void SetDefaultFieldSortScoring(bool doTrackScores, bool doMaxScore)
{
fieldSortDoTrackScores = doTrackScores;
fieldSortDoMaxScore = doMaxScore;
}
public IndexReader reader_ForNUnit
{
get { return reader; }
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// HashAlgorithm.cs
//
namespace System.Security.Cryptography {
using System.IO;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class HashAlgorithm : IDisposable, ICryptoTransform {
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State = 0;
private bool m_bDisposed = false;
protected HashAlgorithm() {}
//
// public properties
//
public virtual int HashSize {
get { return HashSizeValue; }
}
public virtual byte[] Hash {
get {
if (m_bDisposed)
throw new ObjectDisposedException(null);
if (State != 0)
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_HashNotYetFinalized"));
return (byte[]) HashValue.Clone();
}
}
//
// public methods
//
static public HashAlgorithm Create() {
#if FULL_AOT_RUNTIME
return new System.Security.Cryptography.SHA1CryptoServiceProvider ();
#else
return Create("System.Security.Cryptography.HashAlgorithm");
#endif
}
static public HashAlgorithm Create(String hashName) {
return (HashAlgorithm) CryptoConfig.CreateFromName(hashName);
}
public byte[] ComputeHash(Stream inputStream) {
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Default the buffer size to 4K.
byte[] buffer = new byte[4096];
int bytesRead;
do {
bytesRead = inputStream.Read(buffer, 0, 4096);
if (bytesRead > 0) {
HashCore(buffer, 0, bytesRead);
}
} while (bytesRead > 0);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
public byte[] ComputeHash(byte[] buffer) {
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Do some validation
if (buffer == null) throw new ArgumentNullException("buffer");
HashCore(buffer, 0, buffer.Length);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
public byte[] ComputeHash(byte[] buffer, int offset, int count) {
// Do some validation
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0 || (count > buffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((buffer.Length - count) < offset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
HashCore(buffer, offset, count);
HashValue = HashFinal();
byte[] Tmp = (byte[]) HashValue.Clone();
Initialize();
return(Tmp);
}
// ICryptoTransform methods
// we assume any HashAlgorithm can take input a byte at a time
public virtual int InputBlockSize {
get { return(1); }
}
public virtual int OutputBlockSize {
get { return(1); }
}
public virtual bool CanTransformMultipleBlocks {
get { return(true); }
}
public virtual bool CanReuseTransform {
get { return(true); }
}
// We implement TransformBlock and TransformFinalBlock here
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
// Do some validation, we let BlockCopy do the destination array validation
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
// Change the State value
State = 1;
HashCore(inputBuffer, inputOffset, inputCount);
if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)))
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
return inputCount;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
// Do some validation
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (m_bDisposed)
throw new ObjectDisposedException(null);
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = HashFinal();
byte[] outputBytes;
if (inputCount != 0)
{
outputBytes = new byte[inputCount];
Buffer.InternalBlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount);
}
else
{
outputBytes = EmptyArray<Byte>.Value;
}
// reset the State value
State = 0;
return outputBytes;
}
// IDisposable methods
// To keep mscorlib compatibility with Orcas, CoreCLR's HashAlgorithm has an explicit IDisposable
// implementation. Post-Orcas the desktop has an implicit IDispoable implementation.
#if FEATURE_CORECLR
void IDisposable.Dispose()
#else
public void Dispose()
#endif // FEATURE_CORECLR
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (HashValue != null)
Array.Clear(HashValue, 0, HashValue.Length);
HashValue = null;
m_bDisposed = true;
}
}
//
// abstract public methods
//
public abstract void Initialize();
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected abstract byte[] HashFinal();
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NETSTANDARD
#define DISABLE_FILE_INTERNAL_LOGGING
namespace NLog.UnitTests.Targets
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
using Xunit.Extensions;
public class ConcurrentFileTargetTests : NLogTestBase
{
private ILogger logger = LogManager.GetLogger("NLog.UnitTests.Targets.ConcurrentFileTargetTests");
private void ConfigureSharedFile(string mode, string fileName)
{
var modes = mode.Split('|');
FileTarget ft = new FileTarget();
ft.FileName = fileName;
ft.Layout = "${message}";
ft.KeepFileOpen = true;
ft.OpenFileCacheTimeout = 10;
ft.OpenFileCacheSize = 1;
ft.LineEnding = LineEndingMode.LF;
ft.KeepFileOpen = Array.IndexOf(modes, "retry") >= 0 ? false : true;
ft.ForceMutexConcurrentWrites = Array.IndexOf(modes, "mutex") >= 0 ? true : false;
ft.ArchiveAboveSize = Array.IndexOf(modes, "archive") >= 0 ? 50 : -1;
if (ft.ArchiveAboveSize > 0)
{
string archivePath = Path.Combine(Path.GetDirectoryName(fileName), "Archive");
ft.ArchiveFileName = Path.Combine(archivePath, "{####}_" + Path.GetFileName(fileName));
ft.MaxArchiveFiles = 10000;
}
var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper";
switch (modes[0])
{
case "async":
SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow) { Name = name, TimeToSleepBetweenBatches = 10 }, LogLevel.Debug);
break;
case "buffered":
SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100) { Name = name }, LogLevel.Debug);
break;
case "buffered_timed_flush":
SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10) { Name = name }, LogLevel.Debug);
break;
default:
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
break;
}
}
#pragma warning disable xUnit1013 // Needed for test
public void Process(string processIndex, string fileName, string numLogsString, string mode)
#pragma warning restore xUnit1013
{
Thread.CurrentThread.Name = processIndex;
int numLogs = Convert.ToInt32(numLogsString);
int idxProcess = Convert.ToInt32(processIndex);
ConfigureSharedFile(mode, fileName);
string format = processIndex + " {0}";
// Having the internal logger enabled would just slow things down, reducing the
// likelyhood for uncovering racing conditions. Uncomment #define DISABLE_FILE_INTERNAL_LOGGING
#if !DISABLE_FILE_INTERNAL_LOGGING
var logWriter = new StringWriter { NewLine = Environment.NewLine };
NLog.Common.InternalLogger.LogLevel = LogLevel.Trace;
NLog.Common.InternalLogger.LogFile = Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex));
NLog.Common.InternalLogger.LogWriter = logWriter;
NLog.Common.InternalLogger.LogToConsole = true;
try
#endif
{
Thread.Sleep(Math.Max((10 - idxProcess), 1) * 5); // Delay to wait for the other processes
for (int i = 0; i < numLogs; ++i)
{
logger.Debug(format, i);
}
LogManager.Configuration = null; // Flush + Close
}
#if !DISABLE_FILE_INTERNAL_LOGGING
catch (Exception ex)
{
using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex))))
{
textWriter.WriteLine(ex.ToString());
textWriter.WriteLine(logWriter.GetStringBuilder().ToString());
}
throw;
}
using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex))))
{
textWriter.WriteLine(logWriter.GetStringBuilder().ToString());
}
#endif
}
private string MakeFileName(int numProcesses, int numLogs, string mode)
{
// Having separate filenames for the various tests makes debugging easier.
return $"test_{numProcesses}_{numLogs}_{mode.Replace('|', '_')}.txt";
}
private void DoConcurrentTest(int numProcesses, int numLogs, string mode)
{
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string archivePath = Path.Combine(tempPath, "Archive");
try
{
Directory.CreateDirectory(tempPath);
Directory.CreateDirectory(archivePath);
string logFile = Path.Combine(tempPath, MakeFileName(numProcesses, numLogs, mode));
if (File.Exists(logFile))
File.Delete(logFile);
Process[] processes = new Process[numProcesses];
for (int i = 0; i < numProcesses; ++i)
{
processes[i] = ProcessRunner.SpawnMethod(
this.GetType(),
"Process",
i.ToString(),
logFile,
numLogs.ToString(),
mode);
}
// In case we'd like to capture stdout, we would need to drain it continuously.
// StandardOutput.ReadToEnd() wont work, since the other processes console only has limited buffer.
for (int i = 0; i < numProcesses; ++i)
{
processes[i].WaitForExit();
Assert.Equal(0, processes[i].ExitCode);
processes[i].Dispose();
processes[i] = null;
}
var files = new System.Collections.Generic.List<string>(Directory.GetFiles(archivePath));
files.Add(logFile);
bool verifyFileSize = files.Count > 1;
int[] maxNumber = new int[numProcesses];
//Console.WriteLine("Verifying output file {0}", logFile);
foreach (var file in files)
{
using (StreamReader sr = File.OpenText(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] tokens = line.Split(' ');
Assert.Equal(2, tokens.Length);
try
{
int thread = Convert.ToInt32(tokens[0]);
int number = Convert.ToInt32(tokens[1]);
Assert.True(thread >= 0);
Assert.True(thread < numProcesses);
Assert.Equal(maxNumber[thread], number);
maxNumber[thread]++;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Error when parsing line '{line}' in file {file}", ex);
}
}
if (verifyFileSize)
{
if (sr.BaseStream.Length > 100)
throw new InvalidOperationException(
$"Error when reading file {file}, size {sr.BaseStream.Length} is too large");
else if (sr.BaseStream.Length < 35 && files[files.Count - 1] != file)
throw new InvalidOperationException(
$"Error when reading file {file}, size {sr.BaseStream.Length} is too small");
}
}
}
}
finally
{
try
{
if (Directory.Exists(archivePath))
Directory.Delete(archivePath, true);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
catch
{
}
}
}
[Theory]
#if !MONO
// MONO Doesn't work well with global mutex, and it is needed for succesful concurrent archive operations
[InlineData(2, 500, "none|archive")]
[InlineData(2, 500, "none|mutex|archive")]
#endif
[InlineData(2, 10000, "none")]
[InlineData(5, 4000, "none")]
[InlineData(10, 2000, "none")]
[InlineData(2, 10000, "none|mutex")]
[InlineData(5, 4000, "none|mutex")]
[InlineData(10, 2000, "none|mutex")]
public void SimpleConcurrentTest(int numProcesses, int numLogs, string mode)
{
DoConcurrentTest(numProcesses, numLogs, mode);
}
[Theory]
[InlineData("async")]
[InlineData("async|mutex")]
public void AsyncConcurrentTest(string mode)
{
// Before 2 processes are running into concurrent writes,
// the first process typically already has written couple thousend events.
// Thus to have a meaningful test, at least 10K events are required.
// Due to the buffering it makes no big difference in runtime, whether we
// have 2 process writing 10K events each or couple more processes with even more events.
// Runtime is mostly defined by Runner.exe compilation and JITing the first.
DoConcurrentTest(5, 1000, mode);
}
[Theory]
[InlineData("buffered")]
[InlineData("buffered|mutex")]
public void BufferedConcurrentTest(string mode)
{
DoConcurrentTest(5, 1000, mode);
}
[Theory]
[InlineData("buffered_timed_flush")]
[InlineData("buffered_timed_flush|mutex")]
public void BufferedTimedFlushConcurrentTest(string mode)
{
DoConcurrentTest(5, 1000, mode);
}
}
}
#endif
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace Alchemi.AppStart
{
//**************************************************************
// AppStart Class
// This is the main class for appstart.exe
//**************************************************************
public class AppStart
{
public AppStart() {}
static string AppExePath;
static Process AppProcess;
static string[] CommandLineArgs;
static string[] RestartCommandLineArgs;
static string CommandLineString;
static string RestartCommandLineString;
//**************************************************************
// Main()
//**************************************************************
[STAThread]
static void Main(string[] args)
{
//Retrive cmdline to pass to new process
CommandLineString = "";
for (int i = 0; i < args.Length; i++)
{
CommandLineString = string.Format ("{0} {1}", CommandLineString, args[i]);
}
CommandLineString += " /appstartversion " + Assembly.GetExecutingAssembly().GetName().Version.ToString();
RestartCommandLineString = CommandLineString + " /restart ";
CommandLineArgs = new String[args.Length+2];
CommandLineArgs[CommandLineArgs.Length-2] = "/appstartversion";
CommandLineArgs[CommandLineArgs.Length-1] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
RestartCommandLineArgs = new String[CommandLineArgs.Length+1];
RestartCommandLineArgs[RestartCommandLineArgs.Length-1] = "/restart";
AppStartConfig Config = LoadConfig();
if (Config.AppLaunchMode == AppStartConfig.LaunchModes.Process)
StartAndWait_Process();
else
StartAndWait_Domain();
}
/*********************************************************************
* StartAndWait_Domain()
**********************************************************************/
private static void StartAndWait_Domain()
{
bool restartApp = true;
int returnCode = 0;
while (restartApp)
{
try
{
returnCode = StartApp_Domain(false);
Debug.WriteLine(returnCode.ToString());
}
catch (Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Process.WaitForExit() failed, it's possible the process is not running");
HandleTerminalError(e);
}
if (returnCode == 2)
{
restartApp = true;
}
else
restartApp = false;
}
}
/*********************************************************************
* StartAndWait_Process()
**********************************************************************/
private static void StartAndWait_Process()
{
bool restartApp = true;
StartApp_Process(false);
while (restartApp)
{
try
{
AppProcess.WaitForExit();
}
catch (Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Process.WaitForExit() failed, it's possible the process is not running");
Debug.WriteLine("APPLICATION STARTER: " + e.ToString());
return;
}
if (AppProcess.ExitCode == 2)
{
restartApp = true;
AppProcess = null;
StartApp_Process(true);
}
else
restartApp = false;
}
}
/*********************************************************************
* StartApp_Domain()
**********************************************************************/
public static int StartApp_Domain(bool restartApp)
{
Debug.WriteLine("APPLICATION STARTER: Starting the app in a seperate domain");
//Load the config file
AppStartConfig Config;
Config = LoadConfig();
AppExePath = Config.AppExePath;
//Load the app
int retValue=0;
try
{
//Create the new app domain
AppDomain NewDomain = AppDomain.CreateDomain (
"New App Domain",
AppDomain.CurrentDomain.Evidence,
Path.GetDirectoryName(AppExePath)+@"\",
"",
false);
//Execute the app in the new appdomain
string[] cmdLineArgs;
if(restartApp)
cmdLineArgs = RestartCommandLineArgs;
else
cmdLineArgs = CommandLineArgs;
retValue = NewDomain.ExecuteAssembly(AppExePath,AppDomain.CurrentDomain.Evidence,cmdLineArgs);
//Unload the app domain
AppDomain.Unload(NewDomain);
}
catch (Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Failed to start app at: " + AppExePath);
HandleTerminalError(e);
}
return (retValue);
}
/*********************************************************************
* StartApp_Process()
**********************************************************************/
public static void StartApp_Process(bool restartApp)
{
Debug.WriteLine("APPLICATION STARTER: Starting the app in a seperate process");
//Load the config file
AppStartConfig Config;
Config = LoadConfig();
AppExePath = Config.AppExePath;
//If the app has been started by this process before
if (AppProcess != null)
{
//& the app is still running, no need to start the app
if (!AppProcess.HasExited)
return;
}
//Start the app
try
{
ProcessStartInfo p = new ProcessStartInfo (AppExePath);
p.WorkingDirectory = Path.GetDirectoryName(AppExePath);
// Notify the app if we are restarting in case there's something they want to do differently
if(restartApp)
p.Arguments = RestartCommandLineString;
else
p.Arguments = CommandLineString;
AppProcess = Process.Start (p);
Debug.WriteLine("APPLICATION STARTER: Started app: " + AppExePath);
}
catch (Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Failed to start process at: " + AppExePath);
HandleTerminalError(e);
}
}
/*********************************************************************
* LoadConfig()
**********************************************************************/
private static AppStartConfig LoadConfig()
{
AppStartConfig Config;
//Load the config file which knows where the app lives
try
{
//Try app specific config file name
Config = AppStartConfig.Load(CalcConfigFileLocation());
return Config;
}
catch (Exception e)
{
try
{
//Try default config file name
Debug.WriteLine("APPLICATION STARTER: Falling back to try to read appstart.config.");
Config = AppStartConfig.Load(AppDomain.CurrentDomain.BaseDirectory + @"AppStart.Config");
return Config;
}
catch
{
HandleTerminalError(e);
}
}
return null;
}
/*********************************************************************
* GetAppExePath()
**********************************************************************/
private static string CalcConfigFileLocation()
{
//The config file name should be appstart.config if the exe name is appstart.exe
string ConfigFileName;
try
{
ConfigFileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ConfigFileName = Path.Combine(ConfigFileName,Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location));
ConfigFileName += @".config";
return ConfigFileName;
}
catch (Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Failed to properly calculate config file name");
HandleTerminalError(e);
return null;
}
}
/*********************************************************************
* HandleTerminalError()
* Prints out the terminal exception & shuts down the app
**********************************************************************/
private static void HandleTerminalError(Exception e)
{
Debug.WriteLine("APPLICATION STARTER: Terminal error encountered.");
Debug.WriteLine("APPLICATION STARTER: The following exception was encoutered:");
Debug.WriteLine(e.ToString());
Debug.WriteLine("APPLICATION STARTER: Shutting down");
MessageBox.Show("The auto-update feature of this application has encountered a configuration error.\r\n"
+"Please uninstall and reinstall the application."); Environment.Exit(0);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class AttachSegmentsRequestEncoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 56;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private AttachSegmentsRequestEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public AttachSegmentsRequestEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public AttachSegmentsRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public AttachSegmentsRequestEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public AttachSegmentsRequestEncoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public AttachSegmentsRequestEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public AttachSegmentsRequestEncoder RecordingId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
AttachSegmentsRequestDecoder writer = new AttachSegmentsRequestDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
using WeifenLuo.WinFormsUI.ThemeVS2012Light;
internal class VS2012LightDockPaneCaption : DockPaneCaptionBase
{
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image, m_imageAutoHide;
public InertButton(VS2012LightDockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide)
: base()
{
m_dockPaneCaption = dockPaneCaption;
m_image = image;
m_imageAutoHide = imageAutoHide;
RefreshChanges();
}
private VS2012LightDockPaneCaption m_dockPaneCaption;
private VS2012LightDockPaneCaption DockPaneCaption
{
get { return m_dockPaneCaption; }
}
public bool IsAutoHide
{
get { return DockPaneCaption.DockPane.IsAutoHide; }
}
public override Bitmap Image
{
get { return IsAutoHide ? m_imageAutoHide : m_image; }
}
protected override void OnRefreshChanges()
{
if (DockPaneCaption.DockPane.DockPanel != null)
{
if (DockPaneCaption.TextColor != ForeColor)
{
ForeColor = DockPaneCaption.TextColor;
Invalidate();
}
}
}
}
#region consts
private const int _TextGapTop = 3;
private const int _TextGapBottom = 2;
private const int _TextGapLeft = 2;
private const int _TextGapRight = 3;
private const int _ButtonGapTop = 2;
private const int _ButtonGapBottom = 1;
private const int _ButtonGapBetween = 1;
private const int _ButtonGapLeft = 1;
private const int _ButtonGapRight = 2;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonAutoHide;
private static Bitmap ImageButtonAutoHide
{
get
{
if (_imageButtonAutoHide == null)
_imageButtonAutoHide = Resources.DockPane_AutoHide;
return _imageButtonAutoHide;
}
}
private static Bitmap _imageButtonDock;
private static Bitmap ImageButtonDock
{
get
{
if (_imageButtonDock == null)
_imageButtonDock = Resources.DockPane_Dock;
return _imageButtonDock;
}
}
private InertButton m_buttonAutoHide;
private InertButton ButtonAutoHide
{
get
{
if (m_buttonAutoHide == null)
{
m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide);
m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide);
m_buttonAutoHide.Click += new EventHandler(AutoHide_Click);
Controls.Add(m_buttonAutoHide);
}
return m_buttonAutoHide;
}
}
private static Bitmap _imageButtonOptions;
private static Bitmap ImageButtonOptions
{
get
{
if (_imageButtonOptions == null)
_imageButtonOptions = Resources.DockPane_Option;
return _imageButtonOptions;
}
}
private InertButton m_buttonOptions;
private InertButton ButtonOptions
{
get
{
if (m_buttonOptions == null)
{
m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions);
m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions);
m_buttonOptions.Click += new EventHandler(Options_Click);
Controls.Add(m_buttonOptions);
}
return m_buttonOptions;
}
}
private IContainer m_components;
private IContainer Components
{
get { return m_components; }
}
private ToolTip m_toolTip;
public VS2012LightDockPaneCaption(DockPane pane) : base(pane)
{
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
Components.Dispose();
base.Dispose(disposing);
}
private static int TextGapTop
{
get { return _TextGapTop; }
}
public Font TextFont
{
get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; }
}
private static int TextGapBottom
{
get { return _TextGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int ButtonGapTop
{
get { return _ButtonGapTop; }
}
private static int ButtonGapBottom
{
get { return _ButtonGapBottom; }
}
private static int ButtonGapLeft
{
get { return _ButtonGapLeft; }
}
private static int ButtonGapRight
{
get { return _ButtonGapRight; }
}
private static int ButtonGapBetween
{
get { return _ButtonGapBetween; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneCaption_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipOptions;
private static string ToolTipOptions
{
get
{
if (_toolTipOptions == null)
_toolTipOptions = Strings.DockPaneCaption_ToolTipOptions;
return _toolTipOptions;
}
}
private static string _toolTipAutoHide;
private static string ToolTipAutoHide
{
get
{
if (_toolTipAutoHide == null)
_toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide;
return _toolTipAutoHide;
}
}
private static Blend _activeBackColorGradientBlend;
private static Blend ActiveBackColorGradientBlend
{
get
{
if (_activeBackColorGradientBlend == null)
{
Blend blend = new Blend(2);
blend.Factors = new float[]{0.5F, 1.0F};
blend.Positions = new float[]{0.0F, 1.0F};
_activeBackColorGradientBlend = blend;
}
return _activeBackColorGradientBlend;
}
}
private Color TextColor
{
get
{
if (DockPane.IsActivated)
return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor;
else
return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor;
}
}
private static TextFormatFlags _textFormat =
TextFormatFlags.SingleLine |
TextFormatFlags.EndEllipsis |
TextFormatFlags.VerticalCenter;
private TextFormatFlags TextFormat
{
get
{
if (RightToLeft == RightToLeft.No)
return _textFormat;
else
return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
}
}
protected override int MeasureHeight()
{
int height = TextFont.Height + TextGapTop + TextGapBottom;
if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom)
height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
DrawCaption(e.Graphics);
}
private void DrawCaption(Graphics g)
{
if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0)
return;
Rectangle rect = ClientRectangle;
Color captionColor;
var theme = (VS2012LightTheme)DockPane.DockPanel.Theme;
if (DockPane.IsActivated || theme.ForceActiveCaptionColor)
captionColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor;
else
captionColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor;
SolidBrush captionBrush = new SolidBrush(captionColor);
g.FillRectangle(captionBrush, rect);
Rectangle rectCaption = rect;
Rectangle rectCaptionText = rectCaption;
rectCaptionText.X += TextGapLeft;
rectCaptionText.Width -= TextGapLeft + TextGapRight;
//CHANGED: Make the dots extend properly when the close button is not showing.
//rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight;
rectCaptionText.Width -= ButtonGapLeft + ButtonGapRight;
if (CloseButtonVisible)
rectCaptionText.Width -= ButtonClose.Width;
if (ShouldShowAutoHideButton)
rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween;
if (HasTabPageContextMenu)
rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween;
rectCaptionText.Y += TextGapTop;
rectCaptionText.Height -= TextGapTop + TextGapBottom;
Color colorText;
if (DockPane.IsActivated || theme.ForceActiveCaptionColor)
colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor;
else
colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor;
TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat);
Rectangle rectDotsStrip = rectCaptionText;
int textLength = (int)g.MeasureString(DockPane.CaptionText, TextFont).Width + TextGapLeft;
rectDotsStrip.X += textLength;
rectDotsStrip.Width -= textLength;
rectDotsStrip.Height = ClientRectangle.Height;
Color dotsColor;
if (DockPane.IsActivated || theme.ForceActiveCaptionColor)
dotsColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor;
else
dotsColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor;
DrawDotsStrip(g, rectDotsStrip, dotsColor);
}
protected void DrawDotsStrip(Graphics g, Rectangle rectStrip, Color colorDots)
{
if (rectStrip.Width <= 0 || rectStrip.Height <= 0)
return;
var penDots = new Pen(colorDots, 1);
penDots.DashStyle = DashStyle.Custom;
penDots.DashPattern = new float[] { 1, 3 };
int positionY = rectStrip.Height / 2;
g.DrawLine(penDots, rectStrip.X + 2, positionY, rectStrip.X + rectStrip.Width - 2, positionY);
g.DrawLine(penDots, rectStrip.X, positionY - 2, rectStrip.X + rectStrip.Width, positionY - 2);
g.DrawLine(penDots, rectStrip.X, positionY + 2, rectStrip.X + rectStrip.Width, positionY + 2);
}
protected override void OnLayout(LayoutEventArgs levent)
{
SetButtonsPosition();
base.OnLayout (levent);
}
protected override void OnRefreshChanges()
{
SetButtons();
Invalidate();
}
private bool CloseButtonEnabled
{
get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; }
}
/// <summary>
/// Determines whether the close button is visible on the content
/// </summary>
private bool CloseButtonVisible
{
get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; }
}
private bool ShouldShowAutoHideButton
{
get
{
var theme = (VS2012LightTheme)DockPane.DockPanel.Theme;
return !DockPane.IsFloat && theme.ShowAutoHideButton;
}
}
private void SetButtons()
{
ButtonClose.Enabled = CloseButtonEnabled;
ButtonClose.Visible = CloseButtonVisible;
ButtonAutoHide.Visible = ShouldShowAutoHideButton;
ButtonOptions.Visible = HasTabPageContextMenu;
ButtonClose.RefreshChanges();
ButtonAutoHide.RefreshChanges();
ButtonOptions.RefreshChanges();
SetButtonsPosition();
}
private void SetButtonsPosition()
{
// set the size and location for close and auto-hide buttons
Rectangle rectCaption = ClientRectangle;
int buttonWidth = (int)(ButtonClose.Image.Width * ((double)DeviceDpi / 96));
int buttonHeight = (int)(ButtonClose.Image.Height * ((double)DeviceDpi / 96));
int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width;
int y = rectCaption.Y + ButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the auto hide button overtop.
// Otherwise it is drawn to the left of the close button.
if (CloseButtonVisible)
point.Offset(-(buttonWidth + ButtonGapBetween), 0);
ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
if (ShouldShowAutoHideButton)
point.Offset(-(buttonWidth + ButtonGapBetween), 0);
ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
private void AutoHide_Click(object sender, EventArgs e)
{
DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState);
if (DockHelper.IsDockStateAutoHide(DockPane.DockState))
{
DockPane.DockPanel.ActiveAutoHideContent = null;
DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane);
}
}
private void Options_Click(object sender, EventArgs e)
{
ShowTabPageContextMenu(PointToClient(Control.MousePosition));
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
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 System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.Models
{
/// <summary>
/// A HETS application-managed Role that has a selected list of permissions and can be assigned to Users. A role coresponds to the authorization level provided a user based on the work for which they are responsible.
/// </summary>
[MetaDataExtension (Description = "A HETS application-managed Role that has a selected list of permissions and can be assigned to Users. A role coresponds to the authorization level provided a user based on the work for which they are responsible.")]
public partial class Role : AuditableEntity, IEquatable<Role>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public Role()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Role" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a Role (required).</param>
/// <param name="Name">The name of the Role, as established by the user creating the role. (required).</param>
/// <param name="Description">A description of the role as set by the user creating&#x2F;updating the role. (required).</param>
/// <param name="RolePermissions">RolePermissions.</param>
/// <param name="UserRoles">UserRoles.</param>
public Role(int Id, string Name, string Description, List<RolePermission> RolePermissions = null, List<UserRole> UserRoles = null)
{
this.Id = Id;
this.Name = Name;
this.Description = Description;
this.RolePermissions = RolePermissions;
this.UserRoles = UserRoles;
}
/// <summary>
/// A system-generated unique identifier for a Role
/// </summary>
/// <value>A system-generated unique identifier for a Role</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a Role")]
public int Id { get; set; }
/// <summary>
/// The name of the Role, as established by the user creating the role.
/// </summary>
/// <value>The name of the Role, as established by the user creating the role.</value>
[MetaDataExtension (Description = "The name of the Role, as established by the user creating the role.")]
[MaxLength(255)]
public string Name { get; set; }
/// <summary>
/// A description of the role as set by the user creating/updating the role.
/// </summary>
/// <value>A description of the role as set by the user creating/updating the role.</value>
[MetaDataExtension (Description = "A description of the role as set by the user creating/updating the role.")]
[MaxLength(2048)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets RolePermissions
/// </summary>
public List<RolePermission> RolePermissions { get; set; }
/// <summary>
/// Gets or Sets UserRoles
/// </summary>
public List<UserRole> UserRoles { 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 Role {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" RolePermissions: ").Append(RolePermissions).Append("\n");
sb.Append(" UserRoles: ").Append(UserRoles).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)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((Role)obj);
}
/// <summary>
/// Returns true if Role instances are equal
/// </summary>
/// <param name="other">Instance of Role to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Role other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.RolePermissions == other.RolePermissions ||
this.RolePermissions != null &&
this.RolePermissions.SequenceEqual(other.RolePermissions)
) &&
(
this.UserRoles == other.UserRoles ||
this.UserRoles != null &&
this.UserRoles.SequenceEqual(other.UserRoles)
);
}
/// <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
hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
if (this.Description != null)
{
hash = hash * 59 + this.Description.GetHashCode();
}
if (this.RolePermissions != null)
{
hash = hash * 59 + this.RolePermissions.GetHashCode();
}
if (this.UserRoles != null)
{
hash = hash * 59 + this.UserRoles.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Role left, Role right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Role left, Role right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Sce.Atf.Dom;
using Sce.Atf.Controls.PropertyEditing;
using misz.Gui;
using Sce.Atf;
using pico.Controls.PropertyEditing;
namespace SettingsEditor
{
public class DynamicSchema : IDynamicSchema
{
public DynamicSchema( SettingsCompiler compiler )
{
m_compiler = compiler;
}
public void AddDynamicAttributesRecurse( SettingGroup structure, Schema schema )
{
DomNodeType dnt = new DomNodeType(
structure.DomNodeTypeFullName,
schema.structType.Type,
EmptyArray<AttributeInfo>.Instance,
EmptyArray<ChildInfo>.Instance,
EmptyArray<ExtensionInfo>.Instance );
dnt.SetTag<SettingGroup>( structure );
PropertyDescriptorCollection propertyDescriptorCollection = dnt.GetTag<PropertyDescriptorCollection>();
if (propertyDescriptorCollection == null)
{
propertyDescriptorCollection = new PropertyDescriptorCollection( null );
dnt.SetTag<PropertyDescriptorCollection>( propertyDescriptorCollection );
}
Loader.AddNodeType( dnt.Name, dnt );
foreach (Setting sett in structure.Settings)
{
if (sett is BoolSetting)
{
BoolSetting bsett = (BoolSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, AttributeType.BooleanType );
ai.DefaultValue = bsett.Value;
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is IntSetting)
{
IntSetting isett = (IntSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, AttributeType.IntType );
ai.DefaultValue = isett.Value;
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is FloatSetting)
{
FloatSetting fsett = (FloatSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, Schema.FlexibleFloatType );
ai.DefaultValue = new float[5] {
fsett.Value,
fsett.SoftMinValue,
fsett.SoftMaxValue,
fsett.StepSize,
fsett.ValueBool ? 1 : 0
};
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is EnumSetting)
{
EnumSetting esett = (EnumSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, AttributeType.IntType );
//ai.DefaultValue = esett.EnumType.GetEnumName( esett.Value );
ai.DefaultValue = (int) esett.Value;
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is StringSetting)
{
StringSetting ssett = (StringSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, AttributeType.StringType );
ai.DefaultValue = ssett.Value ?? "";
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is Float4Setting)
{
Float4Setting fsett = (Float4Setting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, Schema.Float4Type );
ai.DefaultValue = new float[4] { fsett.Value.X, fsett.Value.Y, fsett.Value.Z, fsett.Value.W };
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else if (sett is ColorSetting)
{
ColorSetting csett = (ColorSetting) sett;
AttributeInfo ai = new AttributeInfo( sett.Name, AttributeType.IntType );
ai.DefaultValue = csett.asInt();
dnt.Define( ai );
ai.SetTag<Setting>( sett );
}
else
{
throw new Exception( "Unsupported setting type!" );
}
}
foreach ( SettingGroup nestedStructure in structure.NestedStructures )
{
AddDynamicAttributesRecurse( nestedStructure, schema );
}
}
public void AddDynamicAttributes( Schema schema )
{
foreach ( SettingGroup structure in m_compiler.RootStructure.NestedStructures )
{
AddDynamicAttributesRecurse( structure, schema );
}
}
static List<Tuple<DomNodeType, AttributeInfo, bool>> GetDependsOnListValidated( List<Tuple<string, bool>> dependsOn, DomNodeType dnt, SchemaLoader loader )
{
List<Tuple<DomNodeType, AttributeInfo, bool>> validatedList = new List<Tuple<DomNodeType, AttributeInfo, bool>>();
foreach( var tup in dependsOn )
{
bool err = true;
string s = tup.Item1;
if ( s.Contains( ".") )
{
int lastDotIndex = s.LastIndexOf( '.' );
if ( lastDotIndex != -1 )
{
string fullTypeName = "SettingsEditor:" + s.Substring( 0, lastDotIndex );
DomNodeType otherDnt = loader.GetNodeType( fullTypeName );
if ( otherDnt != null )
{
string attributeName = s.Substring( lastDotIndex + 1 );
AttributeInfo ai = otherDnt.GetAttributeInfo( attributeName );
if ( ai != null )
{
if ( ai.Type == AttributeType.BooleanType )
{
err = false;
validatedList.Add( new Tuple<DomNodeType, AttributeInfo, bool>( otherDnt, ai, tup.Item2 ) );
}
}
}
}
}
else
{
AttributeInfo ai = dnt.GetAttributeInfo( s );
if ( ai != null )
{
if ( ai.Type == AttributeType.BooleanType )
{
err = false;
validatedList.Add( new Tuple<DomNodeType, AttributeInfo, bool>( dnt, ai, tup.Item2 ) );
}
}
}
if ( err )
{
Outputs.WriteLine( OutputMessageType.Error, s + " is not boolean attribute. DependsOn must refer to boolean attribute" );
}
}
return validatedList;
}
static private AttributePropertyDescriptor CreateAttributePropertyDescriptor(
Setting sett, AttributeInfo ai, object editor, TypeConverter typeConverter, List<Tuple<DomNodeType, AttributeInfo, bool>> dependsOn
)
{
AttributePropertyDescriptor apd;
if ( dependsOn.Count > 0 )
{
DependsOnNodes don = new DependsOnNodes( dependsOn );
apd = new CustomEnableAttributePropertyDescriptor(
sett.DisplayName,
ai,
sett.Category,
sett.HelpText,
false,
editor,
typeConverter,
don
);
}
else
{
apd = new AttributePropertyDescriptor(
sett.DisplayName,
ai,
sett.Category,
sett.HelpText,
false,
editor,
typeConverter
);
}
return apd;
}
public void InitGuiRecurse( SettingGroup structure, Schema schema )
{
DomNodeType dnt = Loader.GetNodeType( structure.DomNodeTypeFullName );
foreach (Setting sett in structure.Settings)
{
PropertyDescriptorCollection propertyDescriptorCollection = dnt.GetTag<PropertyDescriptorCollection>();
List<Tuple<DomNodeType, AttributeInfo, bool>> dependsOn = GetDependsOnListValidated( sett.DependsOn, dnt, Loader );
if ( structure.DependsOn != null )
{
List<Tuple<DomNodeType, AttributeInfo, bool>> structureDependsOn = GetDependsOnListValidated( structure.DependsOn, dnt, Loader );
dependsOn.AddRange( structureDependsOn );
}
dependsOn = dependsOn.Distinct().ToList();
if ( sett is BoolSetting)
{
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, new BoolEditor(), null, dependsOn )
);
}
else if (sett is IntSetting)
{
IntSetting isett = (IntSetting) sett;
object editor = null;
TypeConverter converter = null;
//if (isett.MinValue.HasValue && isett.MaxValue.HasValue)
editor = new BoundedIntEditor( isett.MinValue, isett.MaxValue );
//else if (isett.MinValue.HasValue || isett.MaxValue.HasValue)
//{
// converter = new BoundedIntConverter( isett.MinValue, isett.MaxValue );
//}
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, editor, converter, dependsOn )
);
}
else if (sett is FloatSetting)
{
FloatSetting fsett = (FloatSetting) sett;
object editor;
editor = new FlexibleFloatEditor(
fsett.MinValue,
fsett.MaxValue,
fsett.SoftMinValue,
fsett.SoftMaxValue,
fsett.StepSize,
fsett.HasCheckBox
);
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, editor, null, dependsOn )
);
}
else if (sett is EnumSetting)
{
EnumSetting esett = (EnumSetting) sett;
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
Type enumType = esett.EnumType;
string[] enumNames = enumType.GetEnumNames();
for (int i = 0; i < enumNames.Length; ++i)
{
FieldInfo enumField = enumType.GetField( enumNames[i] );
EnumLabelAttribute attr = enumField.GetCustomAttribute<EnumLabelAttribute>();
enumNames[i] = attr != null ? attr.Label : enumNames[i];
}
Array values = enumType.GetEnumValues();
int[] enumValues = new int[enumNames.Length];
for (int i = 0; i < enumNames.Length; ++i)
enumValues[i] = (int) values.GetValue( i );
//FieldInfo enumField = enumType.GetField( enumNames[i] );
//EnumLabelAttribute attr = enumField.GetCustomAttribute<EnumLabelAttribute>();
//string enumLabel = attr != null ? attr.Label : enumNames[i];
//var formatNames = Enum.GetValues( esett.EnumType );
//var formatEditor = new LongEnumEditor( esett.EnumType );
//var formatEditor = new EnumUITypeEditor( enumNames, enumValues );
var formatEditor = new LongEnumEditor();
formatEditor.DefineEnum( enumNames );
formatEditor.MaxDropDownItems = 10;
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, formatEditor, new IntEnumTypeConverter( enumNames, enumValues ), dependsOn )
);
}
else if (sett is Float4Setting)
{
Float4Setting fsett = (Float4Setting) sett;
var editor = new NumericTupleEditor( typeof( float ), new string[] { "X", "Y", "Z", "W" } );
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, editor, null, dependsOn )
);
}
else if (sett is ColorSetting)
{
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, new ColorPickerEditor(), new IntColorConverter(), dependsOn )
);
}
else if (sett is StringSetting)
{
AttributeInfo ai = dnt.GetAttributeInfo( sett.Name );
propertyDescriptorCollection.Add(
CreateAttributePropertyDescriptor( sett, ai, null, null, dependsOn )
);
}
else
{
throw new Exception( "Unsupported setting type!" );
}
}
foreach (SettingGroup nestedStructure in structure.NestedStructures)
{
InitGuiRecurse( nestedStructure, schema );
}
}
public void InitGui( Schema schema )
{
foreach (SettingGroup structure in m_compiler.RootStructure.NestedStructures)
{
InitGuiRecurse( structure, schema );
}
}
public void CreateNodesRecurse( DomNode parent, SettingGroup parentStructure )
{
// shallow copy children
//
List<DomNode> children = new List<DomNode>();
foreach (DomNode domNode in parent.Children)
{
children.Add( domNode );
}
// clear children list
//
if ( parent.Type == Schema.settingsFileType.Type )
parent.GetChildList( Schema.settingsFileType.structChild ).Clear();
else
parent.GetChildList( Schema.structType.structChild ).Clear();
// add groups in correct order, creating missing groups along the way
//
foreach (SettingGroup structure in parentStructure.NestedStructures)
{
DomNodeType groupType = Loader.GetNodeType( structure.DomNodeTypeFullName );
DomNode group = children.Find( n => n.Type == groupType );
if (group == null)
{
group = new DomNode( groupType );
//// create preset
////
//DomNodeType presetType = Loader.GetNodeType( "SettingsEditor:" + structure.Name );
//DomNode preset = new DomNode( presetType );
//// IdAttribute's default value is empty
//// must set it to anything non-empty so UniqueIdValidator can rename it correctly
//// otherwise, exception would be thrown
////
//if (presetType.IdAttribute != null)
// preset.SetAttribute( presetType.IdAttribute, structure.Name );
//group.GetChildList( Schema.groupType.presetsChild ).Add( preset );
}
if (parent.Type == Schema.settingsFileType.Type)
parent.GetChildList( Schema.settingsFileType.structChild ).Add( group );
else
parent.GetChildList( Schema.structType.structChild ).Add( group );
CreateNodesRecurse( group, groupType.GetTag<SettingGroup>() );
}
}
public void CreateNodes( DomNode rootNode )
{
CreateNodesRecurse( rootNode, m_compiler.RootStructure );
}
public SchemaLoader Loader { set; get; }
public Schema Schema { set; get; }
private int[] GetEnumIntValues( Type type )
{
System.Array valuesArray = Enum.GetValues( type );
int[] intArray = new int[valuesArray.Length];
for (int i = 0; i < valuesArray.Length; ++i)
{
intArray[i] = (int) valuesArray.GetValue( i );
}
return intArray;
}
SettingsCompiler m_compiler;
}
public class DependsOnNodes : ICustomEnableAttributePropertyDescriptorCallback
{
public DependsOnNodes()
{
m_dependsOnList = new List<Tuple<DomNodeType, AttributeInfo, bool>>();
}
public DependsOnNodes( List<Tuple<DomNodeType, AttributeInfo, bool>> dependsOn )
{
m_dependsOnList = dependsOn;
}
public void Add( DomNodeType dnt, AttributeInfo attrInfo, bool condition )
{
m_dependsOnList.Add( new Tuple<DomNodeType, AttributeInfo, bool>( dnt, attrInfo, condition ) );
}
public bool IsReadOnly( DomNode domNode, CustomEnableAttributePropertyDescriptor descriptor )
{
DomNode root = domNode.GetRoot();
foreach( Tuple<DomNodeType, AttributeInfo, bool> p in m_dependsOnList )
{
foreach( DomNode dn in root.Subtree )
{
if ( dn.Type == p.Item1 )
{
bool bval = (bool)dn.GetAttribute( p.Item2 );
if ( bval != p.Item3 )
return true;
}
}
}
return false;
}
List<Tuple<DomNodeType, AttributeInfo, bool>> m_dependsOnList;
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Mono.Security.Interface;
namespace Mono.Security.Protocol.Tls
{
#if INSIDE_SYSTEM
internal
#else
public
#endif
abstract class SslStreamBase: Stream, IDisposable
{
private delegate void AsyncHandshakeDelegate(InternalAsyncResult asyncResult, bool fromWrite);
#region Fields
static ManualResetEvent record_processing = new ManualResetEvent (true);
internal Stream innerStream;
internal MemoryStream inputBuffer;
internal Context context;
internal RecordProtocol protocol;
internal bool ownsStream;
private volatile bool disposed;
private bool checkCertRevocationStatus;
private object negotiate;
private object read;
private object write;
private ManualResetEvent negotiationComplete;
#endregion
#region Constructors
protected SslStreamBase(
Stream stream,
bool ownsStream)
{
if (stream == null)
{
throw new ArgumentNullException("stream is null.");
}
if (!stream.CanRead || !stream.CanWrite)
{
throw new ArgumentNullException("stream is not both readable and writable.");
}
this.inputBuffer = new MemoryStream();
this.innerStream = stream;
this.ownsStream = ownsStream;
this.negotiate = new object();
this.read = new object();
this.write = new object();
this.negotiationComplete = new ManualResetEvent(false);
}
#endregion
#region Handshakes
private void AsyncHandshakeCallback(IAsyncResult asyncResult)
{
InternalAsyncResult internalResult = asyncResult.AsyncState as InternalAsyncResult;
try
{
try
{
this.EndNegotiateHandshake(asyncResult);
}
catch (Exception ex)
{
this.protocol.SendAlert(ref ex);
throw new IOException("The authentication or decryption has failed.", ex);
}
if (internalResult.ProceedAfterHandshake)
{
//kick off the read or write process (whichever called us) after the handshake is complete
if (internalResult.FromWrite)
{
InternalBeginWrite(internalResult);
}
else
{
InternalBeginRead(internalResult);
}
negotiationComplete.Set();
}
else
{
negotiationComplete.Set();
internalResult.SetComplete();
}
}
catch (Exception ex)
{
negotiationComplete.Set();
internalResult.SetComplete(ex);
}
}
internal bool MightNeedHandshake
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return false;
}
else
{
lock (this.negotiate)
{
return (this.context.HandshakeState != HandshakeState.Finished);
}
}
}
}
internal void NegotiateHandshake()
{
if (this.MightNeedHandshake)
{
InternalAsyncResult ar = new InternalAsyncResult(null, null, null, 0, 0, false, false);
//if something already started negotiation, wait for it.
//otherwise end it ourselves.
if (!BeginNegotiateHandshake(ar))
{
this.negotiationComplete.WaitOne();
}
else
{
this.EndNegotiateHandshake(ar);
}
}
}
#endregion
#region Abstracts/Virtuals
internal abstract IAsyncResult BeginNegotiateHandshake (AsyncCallback callback, object state);
internal abstract void EndNegotiateHandshake (IAsyncResult result);
internal abstract X509CertificateMono OnLocalCertificateSelection(X509CertificateCollectionMono clientCertificates,
X509CertificateMono serverCertificate,
string targetHost,
X509CertificateCollectionMono serverRequestedCertificates);
internal abstract bool OnRemoteCertificateValidation(X509CertificateMono certificate, int[] errors);
internal abstract ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection);
internal abstract bool HaveRemoteValidation2Callback { get; }
internal abstract AsymmetricAlgorithm OnLocalPrivateKeySelection(X509CertificateMono certificate, string targetHost);
#endregion
#region Event Methods
internal X509CertificateMono RaiseLocalCertificateSelection(X509CertificateCollectionMono certificates,
X509CertificateMono remoteCertificate,
string targetHost,
X509CertificateCollectionMono requestedCertificates)
{
return OnLocalCertificateSelection(certificates, remoteCertificate, targetHost, requestedCertificates);
}
internal bool RaiseRemoteCertificateValidation(X509CertificateMono certificate, int[] errors)
{
return OnRemoteCertificateValidation(certificate, errors);
}
internal ValidationResult RaiseRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection)
{
return OnRemoteCertificateValidation2 (collection);
}
internal AsymmetricAlgorithm RaiseLocalPrivateKeySelection(
X509CertificateMono certificate,
string targetHost)
{
return OnLocalPrivateKeySelection(certificate, targetHost);
}
#endregion
#region Security Properties
public bool CheckCertRevocationStatus
{
get { return this.checkCertRevocationStatus; }
set { this.checkCertRevocationStatus = value; }
}
public CipherAlgorithmType CipherAlgorithm
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.Current.Cipher.CipherAlgorithmType;
}
return CipherAlgorithmType.None;
}
}
public int CipherStrength
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.Current.Cipher.EffectiveKeyBits;
}
return 0;
}
}
public HashAlgorithmType HashAlgorithm
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.Current.Cipher.HashAlgorithmType;
}
return HashAlgorithmType.None;
}
}
public int HashStrength
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.Current.Cipher.HashSize * 8;
}
return 0;
}
}
public int KeyExchangeStrength
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.ServerSettings.Certificates[0].RSA.KeySize;
}
return 0;
}
}
public ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.Current.Cipher.ExchangeAlgorithmType;
}
return ExchangeAlgorithmType.None;
}
}
public SecurityProtocolType SecurityProtocol
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
return this.context.SecurityProtocol;
}
return 0;
}
}
public X509Certificate ServerCertificate
{
get
{
if (this.context.HandshakeState == HandshakeState.Finished)
{
if (this.context.ServerSettings.Certificates != null &&
this.context.ServerSettings.Certificates.Count > 0)
{
return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData);
}
}
return null;
}
}
// this is used by Mono's certmgr tool to download certificates
internal Mono.Security.X509.X509CertificateCollection ServerCertificates
{
get { return context.ServerSettings.Certificates; }
}
#endregion
#region Internal Async Result/State Class
private class InternalAsyncResult : IAsyncResult
{
private object locker = new object ();
private AsyncCallback _userCallback;
private object _userState;
private Exception _asyncException;
private ManualResetEvent handle;
private bool completed;
private int _bytesRead;
private bool _fromWrite;
private bool _proceedAfterHandshake;
private byte[] _buffer;
private int _offset;
private int _count;
public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake)
{
_userCallback = userCallback;
_userState = userState;
_buffer = buffer;
_offset = offset;
_count = count;
_fromWrite = fromWrite;
_proceedAfterHandshake = proceedAfterHandshake;
}
public bool ProceedAfterHandshake
{
get { return _proceedAfterHandshake; }
}
public bool FromWrite
{
get { return _fromWrite; }
}
public byte[] Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
public int BytesRead
{
get { return _bytesRead; }
}
public object AsyncState
{
get { return _userState; }
}
public Exception AsyncException
{
get { return _asyncException; }
}
public bool CompletedWithError
{
get {
if (IsCompleted == false)
return false;
return null != _asyncException;
}
}
public WaitHandle AsyncWaitHandle
{
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (completed);
}
return handle;
}
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get {
lock (locker)
return completed;
}
}
private void SetComplete(Exception ex, int bytesRead)
{
lock (locker) {
if (completed)
return;
completed = true;
_asyncException = ex;
_bytesRead = bytesRead;
if (handle != null)
handle.Set ();
}
if (_userCallback != null)
_userCallback.BeginInvoke (this, null, null);
}
public void SetComplete(Exception ex)
{
SetComplete(ex, 0);
}
public void SetComplete(int bytesRead)
{
SetComplete(null, bytesRead);
}
public void SetComplete()
{
SetComplete(null, 0);
}
}
#endregion
#region Stream Overrides and Async Stream Operations
private bool BeginNegotiateHandshake(InternalAsyncResult asyncResult)
{
try
{
lock (this.negotiate)
{
if (this.context.HandshakeState == HandshakeState.None)
{
this.BeginNegotiateHandshake(new AsyncCallback(AsyncHandshakeCallback), asyncResult);
return true;
}
else
{
return false;
}
}
}
catch (Exception ex)
{
this.negotiationComplete.Set();
this.protocol.SendAlert(ref ex);
throw new IOException("The authentication or decryption has failed.", ex);
}
}
private void EndNegotiateHandshake(InternalAsyncResult asyncResult)
{
if (asyncResult.IsCompleted == false)
asyncResult.AsyncWaitHandle.WaitOne();
if (asyncResult.CompletedWithError)
{
throw asyncResult.AsyncException;
}
}
public override IAsyncResult BeginRead(
byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
this.checkDisposed();
if (buffer == null)
{
throw new ArgumentNullException("buffer is a null reference.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset is less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count is less than 0.");
}
if (count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
}
InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, false, true);
if (this.MightNeedHandshake)
{
if (! BeginNegotiateHandshake(asyncResult))
{
//we made it down here so the handshake was not started.
//another thread must have started it in the mean time.
//wait for it to complete and then perform our original operation
this.negotiationComplete.WaitOne();
InternalBeginRead(asyncResult);
}
}
else
{
InternalBeginRead(asyncResult);
}
return asyncResult;
}
// bigger than max record length for SSL/TLS
private byte[] recbuf = new byte[16384];
private void InternalBeginRead(InternalAsyncResult asyncResult)
{
try
{
int preReadSize = 0;
lock (this.read)
{
// If actual buffer is fully read, reset it
bool shouldReset = this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0;
// If the buffer isn't fully read, but does have data, we need to immediately
// read the info from the buffer and let the user know that they have more data.
bool shouldReadImmediately = (this.inputBuffer.Length > 0) && (asyncResult.Count > 0);
if (shouldReset)
{
this.resetBuffer();
}
else if (shouldReadImmediately)
{
preReadSize = this.inputBuffer.Read(asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
}
}
// This is explicitly done outside the synclock to avoid
// any potential deadlocks in the delegate call.
if (0 < preReadSize)
{
asyncResult.SetComplete(preReadSize);
}
else if (recordStream.Position < recordStream.Length) {
InternalReadCallback_inner (asyncResult, recbuf, new object[] { recbuf, asyncResult }, false, 0);
}
else if (!this.context.ReceivedConnectionEnd)
{
// this will read data from the network until we have (at least) one
// record to send back to the caller
this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
new AsyncCallback(InternalReadCallback), new object[] { recbuf, asyncResult });
}
else
{
// We're done with the connection so we need to let the caller know with 0 bytes read
asyncResult.SetComplete(0);
}
}
catch (Exception ex)
{
this.protocol.SendAlert(ref ex);
throw new IOException("The authentication or decryption has failed.", ex);
}
}
private MemoryStream recordStream = new MemoryStream();
// read encrypted data until we have enough to decrypt (at least) one
// record and return are the records (may be more than one) we have
private void InternalReadCallback(IAsyncResult result)
{
object[] state = (object[])result.AsyncState;
byte[] recbuf = (byte[])state[0];
InternalAsyncResult internalResult = (InternalAsyncResult)state[1];
try
{
this.checkDisposed();
int n = innerStream.EndRead(result);
if (n > 0)
{
// Add the just received data to the waiting data
recordStream.Write(recbuf, 0, n);
}
else
{
// 0 length data means this read operation is done (lost connection in the case of a network stream).
internalResult.SetComplete(0);
return;
}
InternalReadCallback_inner(internalResult, recbuf, state, true, n);
}
catch (Exception ex)
{
internalResult.SetComplete(ex);
}
}
// read encrypted data until we have enough to decrypt (at least) one
// record and return are the records (may be more than one) we have
private void InternalReadCallback_inner(InternalAsyncResult internalResult, byte[] recbuf, object[] state, bool didRead, int n)
{
if (this.disposed)
return;
try
{
bool dataToReturn = false;
long pos = recordStream.Position;
recordStream.Position = 0;
byte[] record = null;
// don't try to decode record unless we have at least 5 bytes
// i.e. type (1), protocol (2) and length (2)
if (recordStream.Length >= 5)
{
record = this.protocol.ReceiveRecord(recordStream);
}
// a record of 0 length is valid (and there may be more record after it)
while (record != null)
{
// we probably received more stuff after the record, and we must keep it!
long remainder = recordStream.Length - recordStream.Position;
byte[] outofrecord = null;
if (remainder > 0)
{
outofrecord = new byte[remainder];
recordStream.Read(outofrecord, 0, outofrecord.Length);
}
lock (this.read)
{
long position = this.inputBuffer.Position;
if (record.Length > 0)
{
// Write new data to the inputBuffer
this.inputBuffer.Seek(0, SeekOrigin.End);
this.inputBuffer.Write(record, 0, record.Length);
// Restore buffer position
this.inputBuffer.Seek(position, SeekOrigin.Begin);
dataToReturn = true;
}
}
recordStream.SetLength(0);
record = null;
if (remainder > 0)
{
recordStream.Write(outofrecord, 0, outofrecord.Length);
// type (1), protocol (2) and length (2)
if (recordStream.Length >= 5)
{
// try to see if another record is available
recordStream.Position = 0;
record = this.protocol.ReceiveRecord(recordStream);
if (record == null)
pos = recordStream.Length;
}
else
pos = remainder;
}
else
pos = 0;
}
if (!dataToReturn && (!didRead || (n > 0)))
{
if (context.ReceivedConnectionEnd) {
internalResult.SetComplete (0);
} else {
// there is no record to return to caller and (possibly) more data waiting
// so continue reading from network (and appending to stream)
recordStream.Position = recordStream.Length;
this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
new AsyncCallback(InternalReadCallback), state);
}
}
else
{
// we have record(s) to return -or- no more available to read from network
// reset position for further reading
recordStream.Position = pos;
int bytesRead = 0;
lock (this.read)
{
bytesRead = this.inputBuffer.Read(internalResult.Buffer, internalResult.Offset, internalResult.Count);
}
internalResult.SetComplete(bytesRead);
}
}
catch (Exception ex)
{
internalResult.SetComplete(ex);
}
}
private void InternalBeginWrite(InternalAsyncResult asyncResult)
{
try
{
// Send the buffer as a TLS record
lock (this.write)
{
byte[] record = this.protocol.EncodeRecord(
ContentType.ApplicationData, asyncResult.Buffer, asyncResult.Offset, asyncResult.Count);
this.innerStream.BeginWrite(
record, 0, record.Length, new AsyncCallback(InternalWriteCallback), asyncResult);
}
}
catch (Exception ex)
{
this.protocol.SendAlert (ref ex);
this.Close();
throw new IOException("The authentication or decryption has failed.", ex);
}
}
private void InternalWriteCallback(IAsyncResult ar)
{
InternalAsyncResult internalResult = (InternalAsyncResult)ar.AsyncState;
try
{
this.checkDisposed();
this.innerStream.EndWrite(ar);
internalResult.SetComplete();
}
catch (Exception ex)
{
internalResult.SetComplete(ex);
}
}
public override IAsyncResult BeginWrite(
byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
this.checkDisposed();
if (buffer == null)
{
throw new ArgumentNullException("buffer is a null reference.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset is less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count is less than 0.");
}
if (count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
}
InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true);
if (this.MightNeedHandshake)
{
if (! BeginNegotiateHandshake(asyncResult))
{
//we made it down here so the handshake was not started.
//another thread must have started it in the mean time.
//wait for it to complete and then perform our original operation
this.negotiationComplete.WaitOne();
InternalBeginWrite(asyncResult);
}
}
else
{
InternalBeginWrite(asyncResult);
}
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult)
{
this.checkDisposed();
InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
if (internalResult == null)
{
throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
}
// Always wait until the read is complete
if (!asyncResult.IsCompleted)
{
if (!asyncResult.AsyncWaitHandle.WaitOne ())
throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndRead");
}
if (internalResult.CompletedWithError)
{
throw internalResult.AsyncException;
}
return internalResult.BytesRead;
}
public override void EndWrite(IAsyncResult asyncResult)
{
this.checkDisposed();
InternalAsyncResult internalResult = asyncResult as InternalAsyncResult;
if (internalResult == null)
{
throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite.");
}
if (!asyncResult.IsCompleted)
{
if (!internalResult.AsyncWaitHandle.WaitOne ())
throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndWrite");
}
if (internalResult.CompletedWithError)
{
throw internalResult.AsyncException;
}
}
public override void Close()
{
base.Close ();
}
public override void Flush()
{
this.checkDisposed();
this.innerStream.Flush();
}
public int Read(byte[] buffer)
{
return this.Read(buffer, 0, buffer.Length);
}
public override int Read(byte[] buffer, int offset, int count)
{
this.checkDisposed ();
if (buffer == null)
{
throw new ArgumentNullException ("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset is less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count is less than 0.");
}
if (count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
}
if (this.context.HandshakeState != HandshakeState.Finished)
{
this.NegotiateHandshake (); // Handshake negotiation
}
lock (this.read) {
try {
record_processing.Reset ();
// do we already have some decrypted data ?
if (this.inputBuffer.Position > 0) {
// or maybe we used all the buffer before ?
if (this.inputBuffer.Position == this.inputBuffer.Length) {
this.inputBuffer.SetLength (0);
} else {
int n = this.inputBuffer.Read (buffer, offset, count);
if (n > 0) {
record_processing.Set ();
return n;
}
}
}
bool needMoreData = false;
while (true) {
// we first try to process the read with the data we already have
if ((recordStream.Position == 0) || needMoreData) {
needMoreData = false;
// if we loop, then it either means we need more data
byte[] recbuf = new byte[16384];
int n = 0;
if (count == 1) {
int value = innerStream.ReadByte ();
if (value >= 0) {
recbuf[0] = (byte) value;
n = 1;
}
} else {
n = innerStream.Read (recbuf, 0, recbuf.Length);
}
if (n > 0) {
// Add the new received data to the waiting data
if ((recordStream.Length > 0) && (recordStream.Position != recordStream.Length))
recordStream.Seek (0, SeekOrigin.End);
recordStream.Write (recbuf, 0, n);
} else {
// or that the read operation is done (lost connection in the case of a network stream).
record_processing.Set ();
return 0;
}
}
bool dataToReturn = false;
recordStream.Position = 0;
byte[] record = null;
// don't try to decode record unless we have at least 5 bytes
// i.e. type (1), protocol (2) and length (2)
if (recordStream.Length >= 5) {
record = this.protocol.ReceiveRecord (recordStream);
needMoreData = (record == null);
}
// a record of 0 length is valid (and there may be more record after it)
while (record != null) {
// we probably received more stuff after the record, and we must keep it!
long remainder = recordStream.Length - recordStream.Position;
byte[] outofrecord = null;
if (remainder > 0) {
outofrecord = new byte[remainder];
recordStream.Read (outofrecord, 0, outofrecord.Length);
}
long position = this.inputBuffer.Position;
if (record.Length > 0) {
// Write new data to the inputBuffer
this.inputBuffer.Seek (0, SeekOrigin.End);
this.inputBuffer.Write (record, 0, record.Length);
// Restore buffer position
this.inputBuffer.Seek (position, SeekOrigin.Begin);
dataToReturn = true;
}
recordStream.SetLength (0);
record = null;
if (remainder > 0) {
recordStream.Write (outofrecord, 0, outofrecord.Length);
recordStream.Position = 0;
}
if (dataToReturn) {
// we have record(s) to return -or- no more available to read from network
// reset position for further reading
int i = inputBuffer.Read (buffer, offset, count);
record_processing.Set ();
return i;
}
}
}
}
catch (TlsException ex)
{
throw new IOException("The authentication or decryption has failed.", ex);
}
catch (Exception ex)
{
throw new IOException("IO exception during read.", ex);
}
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public void Write(byte[] buffer)
{
this.Write(buffer, 0, buffer.Length);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.checkDisposed ();
if (buffer == null)
{
throw new ArgumentNullException ("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset is less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count is less than 0.");
}
if (count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
}
if (this.context.HandshakeState != HandshakeState.Finished)
{
this.NegotiateHandshake ();
}
lock (this.write)
{
try
{
// Send the buffer as a TLS record
byte[] record = this.protocol.EncodeRecord (ContentType.ApplicationData, buffer, offset, count);
this.innerStream.Write (record, 0, record.Length);
}
catch (Exception ex)
{
this.protocol.SendAlert(ref ex);
this.Close();
throw new IOException("The authentication or decryption has failed.", ex);
}
}
}
public override bool CanRead
{
get { return this.innerStream.CanRead; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return this.innerStream.CanWrite; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
#endregion
#region IDisposable Members and Finalizer
~SslStreamBase()
{
this.Dispose(false);
}
protected override void Dispose (bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (this.innerStream != null)
{
if (this.context.HandshakeState == HandshakeState.Finished &&
!this.context.SentConnectionEnd)
{
// Write close notify
try {
this.protocol.SendAlert(AlertDescription.CloseNotify);
} catch {
}
}
if (this.ownsStream)
{
// Close inner stream
this.innerStream.Close();
}
}
this.ownsStream = false;
this.innerStream = null;
}
this.disposed = true;
base.Dispose (disposing);
}
}
#endregion
#region Misc Methods
private void resetBuffer()
{
this.inputBuffer.SetLength(0);
this.inputBuffer.Position = 0;
}
internal void checkDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException("The Stream is closed.");
}
}
#endregion
}
}
| |
/*
* Copyright 2009 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 Binarizer = com.google.zxing.Binarizer;
using LuminanceSource = com.google.zxing.LuminanceSource;
using ReaderException = com.google.zxing.ReaderException;
namespace com.google.zxing.common
{
/// <summary> This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
/// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
/// algorithm. However, because it picks a global black point, it cannot handle difficult shadows
/// and gradients.
///
/// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
///
/// </summary>
/// <author> [email protected] (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public class GlobalHistogramBinarizer:Binarizer
{
override public BitMatrix BlackMatrix
{
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
get
{
LuminanceSource source = LuminanceSource;
// Redivivus.in Java to c# Porting update
// 30/01/2010
// Added
// START
sbyte[] localLuminances;
//END
int width = source.Width;
int height = source.Height;
BitMatrix matrix = new BitMatrix(width, height);
// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
initArrays(width);
int[] localBuckets = buckets;
for (int y = 1; y < 5; y++)
{
int row = height * y / 5;
// Redivivus.in Java to c# Porting update
// 30/01/2010
// Commented & Added
// START
//sbyte[] localLuminances = source.getRow(row, luminances);
localLuminances = source.getRow(row, luminances);
// END
int right = (width << 2) / 5;
for (int x = width / 5; x < right; x++)
{
int pixel = localLuminances[x] & 0xff;
localBuckets[pixel >> LUMINANCE_SHIFT]++;
}
}
int blackPoint = estimateBlackPoint(localBuckets);
// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
localLuminances = source.Matrix; // Govinda : Removed sbyte []
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
int pixel = localLuminances[offset + x] & 0xff;
if (pixel < blackPoint)
{
matrix.set_Renamed(x, y);
}
}
}
return matrix;
}
}
private const int LUMINANCE_BITS = 5;
//UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_SHIFT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
//UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_BUCKETS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private static readonly int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
private sbyte[] luminances = null;
private int[] buckets = null;
public GlobalHistogramBinarizer(LuminanceSource source):base(source)
{
}
// Applies simple sharpening to the row data to improve performance of the 1D Readers.
public override BitArray getBlackRow(int y, BitArray row)
{
LuminanceSource source = LuminanceSource;
int width = source.Width;
if (row == null || row.Size < width)
{
row = new BitArray(width);
}
else
{
row.clear();
}
initArrays(width);
sbyte[] localLuminances = source.getRow(y, luminances);
int[] localBuckets = buckets;
for (int x = 0; x < width; x++)
{
int pixel = localLuminances[x] & 0xff;
localBuckets[pixel >> LUMINANCE_SHIFT]++;
}
int blackPoint = estimateBlackPoint(localBuckets);
int left = localLuminances[0] & 0xff;
int center = localLuminances[1] & 0xff;
for (int x = 1; x < width - 1; x++)
{
int right = localLuminances[x + 1] & 0xff;
// A simple -1 4 -1 box filter with a weight of 2.
int luminance = ((center << 2) - left - right) >> 1;
if (luminance < blackPoint)
{
row.set_Renamed(x);
}
left = center;
center = right;
}
return row;
}
public override Binarizer createBinarizer(LuminanceSource source)
{
return new GlobalHistogramBinarizer(source);
}
private void initArrays(int luminanceSize)
{
if (luminances == null || luminances.Length < luminanceSize)
{
luminances = new sbyte[luminanceSize];
}
if (buckets == null)
{
buckets = new int[LUMINANCE_BUCKETS];
}
else
{
for (int x = 0; x < LUMINANCE_BUCKETS; x++)
{
buckets[x] = 0;
}
}
}
private static int estimateBlackPoint(int[] buckets)
{
// Find the tallest peak in the histogram.
int numBuckets = buckets.Length;
int maxBucketCount = 0;
int firstPeak = 0;
int firstPeakSize = 0;
for (int x = 0; x < numBuckets; x++)
{
if (buckets[x] > firstPeakSize)
{
firstPeak = x;
firstPeakSize = buckets[x];
}
if (buckets[x] > maxBucketCount)
{
maxBucketCount = buckets[x];
}
}
// Find the second-tallest peak which is somewhat far from the tallest peak.
int secondPeak = 0;
int secondPeakScore = 0;
for (int x = 0; x < numBuckets; x++)
{
int distanceToBiggest = x - firstPeak;
// Encourage more distant second peaks by multiplying by square of distance.
int score = buckets[x] * distanceToBiggest * distanceToBiggest;
if (score > secondPeakScore)
{
secondPeak = x;
secondPeakScore = score;
}
}
// Make sure firstPeak corresponds to the black peak.
if (firstPeak > secondPeak)
{
int temp = firstPeak;
firstPeak = secondPeak;
secondPeak = temp;
}
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
// TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the
// two peaks, to determine the contrast.
if (secondPeak - firstPeak <= numBuckets >> 4)
{
throw ReaderException.Instance;
}
// Find a valley between them that is low and closer to the white peak.
int bestValley = secondPeak - 1;
int bestValleyScore = - 1;
for (int x = secondPeak - 1; x > firstPeak; x--)
{
int fromFirst = x - firstPeak;
int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
if (score > bestValleyScore)
{
bestValley = x;
bestValleyScore = score;
}
}
return bestValley << LUMINANCE_SHIFT;
}
}
}
| |
//
// AudioCdService.cs
//
// Author:
// Aaron Bockover <[email protected]>
// Alex Launi <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Preferences;
using Banshee.Hardware;
using Banshee.Gui;
namespace Banshee.Discs.AudioCd
{
public class AudioCdService : DiscService, IService
{
private SourcePage pref_page;
private Section pref_section;
private uint global_interface_id;
public AudioCdService ()
{
}
public override void Initialize ()
{
lock (this) {
InstallPreferences ();
base.Initialize ();
SetupActions ();
}
}
public override void Dispose ()
{
lock (this) {
UninstallPreferences ();
base.Dispose ();
DisposeActions ();
}
}
#region DeviceCommand Handling
protected override bool DeviceCommandMatchesSource (DiscSource source, DeviceCommand command)
{
AudioCdSource cdSource = source as AudioCdSource;
if (cdSource != null && command.DeviceId.StartsWith ("cdda:")) {
try {
Uri uri = new Uri (command.DeviceId);
string match_device_node = String.Format ("{0}{1}", uri.Host,
uri.AbsolutePath).TrimEnd ('/', '\\');
string device_node = source.DiscModel.Volume.DeviceNode;
return device_node.EndsWith (match_device_node);
} catch {
}
}
return false;
}
#endregion
#region Preferences
private void InstallPreferences ()
{
PreferenceService service = ServiceManager.Get<PreferenceService> ();
if (service == null) {
return;
}
service.InstallWidgetAdapters += OnPreferencesServiceInstallWidgetAdapters;
pref_page = new Banshee.Preferences.SourcePage ("audio-cd", Catalog.GetString ("Audio CDs"), "media-cdrom", 400);
pref_section = pref_page.Add (new Section ("audio-cd", Catalog.GetString ("Audio CD Importing"), 20));
pref_section.ShowLabel = false;
pref_section.Add (new VoidPreference ("import-profile", Catalog.GetString ("_Import format")));
pref_section.Add (new VoidPreference ("import-profile-desc"));
pref_section.Add (new SchemaPreference<bool> (AutoRip,
Catalog.GetString ("_Automatically import audio CDs when inserted"),
Catalog.GetString ("When an audio CD is inserted, automatically begin importing it " +
"if metadata can be found and it is not already in the library.")));
pref_section.Add (new SchemaPreference<bool> (EjectAfterRipped,
Catalog.GetString ("_Eject when done importing"),
Catalog.GetString ("When an audio CD has been imported, automatically eject it.")));
pref_section.Add (new SchemaPreference<bool> (ErrorCorrection,
Catalog.GetString ("Use error correction when importing"),
Catalog.GetString ("Error correction tries to work around problem areas on a disc, such " +
"as surface scratches, but will slow down importing substantially.")));
}
private void UninstallPreferences ()
{
PreferenceService service = ServiceManager.Get<PreferenceService> ();
if (service == null || pref_page == null) {
return;
}
service.InstallWidgetAdapters -= OnPreferencesServiceInstallWidgetAdapters;
pref_page.Dispose ();
pref_page = null;
pref_section = null;
}
private void OnPreferencesServiceInstallWidgetAdapters (object o, EventArgs args)
{
if (pref_section == null) {
return;
}
Gtk.HBox description_box = new Gtk.HBox ();
Banshee.MediaProfiles.Gui.ProfileComboBoxConfigurable chooser
= new Banshee.MediaProfiles.Gui.ProfileComboBoxConfigurable (ServiceManager.MediaProfileManager,
"cd-importing", description_box);
pref_section["import-profile"].DisplayWidget = chooser;
pref_section["import-profile"].MnemonicWidget = chooser.Combo;
pref_section["import-profile-desc"].DisplayWidget = description_box;
}
public static readonly SchemaEntry<bool> ErrorCorrection = new SchemaEntry<bool> (
"import", "audio_cd_error_correction",
false,
"Enable error correction",
"When importing an audio CD, enable error correction (paranoia mode)"
);
public static readonly SchemaEntry<bool> AutoRip = new SchemaEntry<bool> (
"import", "auto_rip_cds",
false,
"Enable audio CD auto ripping",
"When an audio CD is inserted, automatically begin ripping it."
);
public static readonly SchemaEntry<bool> EjectAfterRipped = new SchemaEntry<bool> (
"import", "eject_after_ripped",
false,
"Eject audio CD after ripped",
"After an audio CD has been ripped, automatically eject it."
);
#endregion
#region UI Actions
private void SetupActions ()
{
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
uia_service.GlobalActions.AddImportant (new Gtk.ActionEntry [] {
new Gtk.ActionEntry ("RipDiscAction", null,
Catalog.GetString ("Import CD"), null,
Catalog.GetString ("Import this audio CD to the library"),
OnImportDisc)
});
uia_service.GlobalActions.AddImportant (
new Gtk.ActionEntry ("DuplicateDiscAction", null,
Catalog.GetString ("Duplicate CD"), null,
Catalog.GetString ("Duplicate this audio CD"),
OnDuplicateDisc)
);
global_interface_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml");
}
private void DisposeActions ()
{
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
uia_service.GlobalActions.Remove ("RipDiscAction");
uia_service.GlobalActions.Remove ("DuplicateDiscAction");
uia_service.UIManager.RemoveUi (global_interface_id);
}
private void OnImportDisc (object o, EventArgs args)
{
ImportOrDuplicateDisc (true);
}
private void OnDuplicateDisc (object o, EventArgs args)
{
ImportOrDuplicateDisc (false);
}
private void ImportOrDuplicateDisc (bool import)
{
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
AudioCdSource source = uia_service.SourceActions.ActionSource as AudioCdSource;
if (source != null) {
if (import) {
source.ImportDisc ();
} else {
source.DuplicateDisc ();
}
}
}
#endregion
string IService.ServiceName {
get { return "AudioCdService"; }
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitAuthorizationsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkClient>, IExpressRouteCircuitAuthorizationsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitAuthorizationsOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitAuthorization> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an authorization in the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='authorizationName'>
/// The name of the authorization.
/// </param>
/// <param name='authorizationParameters'>
/// Parameters supplied to the create or update express route circuit
/// authorization operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (authorizationName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName");
}
if (authorizationParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("authorizationName", authorizationName);
tracingParameters.Add("authorizationParameters", authorizationParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(authorizationParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(authorizationParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all authorizations in an express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Threading;
using FakeItEasy;
using Nancy.Json;
using Nancy.ModelBinding;
using Nancy.ModelBinding.DefaultBodyDeserializers;
using Xunit;
using Xunit.Extensions;
public class JsonBodyDeserializerFixture
{
private readonly JavaScriptSerializer serializer;
private readonly JsonBodyDeserializer deserialize;
private readonly TestModel testModel;
private readonly string testModelJson;
public JsonBodyDeserializerFixture()
{
this.deserialize = new JsonBodyDeserializer();
this.testModel = new TestModel()
{
IntProperty = 12,
StringProperty = "More cowbell",
DateProperty = DateTime.Parse("2011/12/25"),
ArrayProperty = new[] { "Ping", "Pong" }
};
this.serializer = new JavaScriptSerializer();
this.serializer.RegisterConverters(JsonSettings.Converters);
this.testModelJson = this.serializer.Serialize(this.testModel);
}
[Fact]
public void Should_report_false_for_can_deserialize_for_non_json_format()
{
// Given
const string contentType = "application/xml";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_application_json()
{
// Given
const string contentType = "application/json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_text_json()
{
// Given
const string contentType = "text/json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_report_true_for_can_deserialize_for_custom_json_format()
{
// Given
const string contentType = "application/vnd.org.nancyfx.mything+json";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_be_case_insensitive_in_can_deserialize()
{
// Given
const string contentType = "appLicaTion/jsOn";
// When
var result = this.deserialize.CanDeserialize(contentType, A<BindingContext>._);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_deserialize_timespan()
{
// Given
var json = this.serializer.Serialize(TimeSpan.FromDays(14));
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var context = new BindingContext()
{
DestinationType = typeof(TimeSpan),
ValidModelBindingMembers = BindingMemberInfo.Collect<TimeSpan>().ToList(),
};
// When
var result = (TimeSpan)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.Days.ShouldEqual(14);
}
[Fact]
public void Should_deserialize_enum()
{
// Given
var json = this.serializer.Serialize(TestEnum.One);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var context = new BindingContext()
{
DestinationType = typeof (TestEnum),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestEnum>().ToList(),
};
// When
var result = (TestEnum)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ShouldEqual(TestEnum.One);
}
[Theory]
[InlineData(TestEnum.Hundred)]
[InlineData(null)]
public void Should_deserialize_nullable_enum(TestEnum? propertyValue)
{
var context = new BindingContext()
{
DestinationType = typeof(TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model = new TestModel { NullableEnumProperty = propertyValue };
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.NullableEnumProperty.ShouldEqual(propertyValue);
}
[Fact]
public void Should_deserialize_list_of_primitives()
{
// Given
var context = new BindingContext()
{
DestinationType = typeof (TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model =
new TestModel
{
ListOfPrimitivesProperty = new List<int> { 1, 3, 5 },
ListOfPrimitivesField = new List<int> { 2, 4, 6 },
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ListOfPrimitivesProperty.ShouldHaveCount(3);
result.ListOfPrimitivesProperty[0].ShouldEqual(1);
result.ListOfPrimitivesProperty[1].ShouldEqual(3);
result.ListOfPrimitivesProperty[2].ShouldEqual(5);
result.ListOfPrimitivesField.ShouldHaveCount(3);
result.ListOfPrimitivesField[0].ShouldEqual(2);
result.ListOfPrimitivesField[1].ShouldEqual(4);
result.ListOfPrimitivesField[2].ShouldEqual(6);
}
[Fact]
public void Should_deserialize_list_of_complex_objects()
{
// Given
var context = new BindingContext()
{
DestinationType = typeof(TestModel),
ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),
};
var model =
new TestModel
{
ListOfComplexObjectsProperty = new List<ModelWithStringValues>
{
new ModelWithStringValues() { Value1 = "one", Value2 = "two"},
new ModelWithStringValues() { Value1 = "three", Value2 = "four"}
},
ListOfComplexObjectsField = new List<ModelWithStringValues>
{
new ModelWithStringValues() { Value1 = "five", Value2 = "six"},
new ModelWithStringValues() { Value1 = "seven", Value2 = "eight"}
}
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(model);
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
// When
var result = (TestModel)this.deserialize.Deserialize(
"application/json",
bodyStream,
context);
// Then
result.ListOfComplexObjectsProperty.ShouldHaveCount(2);
result.ListOfComplexObjectsProperty[0].Value1.ShouldEqual("one");
result.ListOfComplexObjectsProperty[0].Value2.ShouldEqual("two");
result.ListOfComplexObjectsProperty[1].Value1.ShouldEqual("three");
result.ListOfComplexObjectsProperty[1].Value2.ShouldEqual("four");
result.ListOfComplexObjectsField.ShouldHaveCount(2);
result.ListOfComplexObjectsField[0].Value1.ShouldEqual("five");
result.ListOfComplexObjectsField[0].Value2.ShouldEqual("six");
result.ListOfComplexObjectsField[1].Value1.ShouldEqual("seven");
result.ListOfComplexObjectsField[1].Value2.ShouldEqual("eight");
}
[Fact]
public void Should_Deserialize_Signed_And_Unsigned_Nullable_Numeric_Types()
{
//Given
const string json = "{P1: 1, P2: 2, P3: 3, F1: 4, F2: 5, F3: 6}";
//When
var model = this.serializer.Deserialize<ModelWithNullables> (json);
//Should
Assert.Equal (1, model.P1);
Assert.Equal ((uint)2, model.P2);
Assert.Equal ((uint)3, model.P3);
Assert.Equal (4, model.F1);
Assert.Equal ((uint)5, model.F2);
Assert.Equal ((uint)6, model.F3);
}
#if !__MonoCS__
[Fact]
public void Should_Serialize_Doubles_In_Different_Cultures()
{
// TODO - fixup on mono, seems to throw inside double.parse
// Given
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
var modelWithDoubleValues =
new ModelWithDoubleValues
{
Latitude = 50.933984,
Longitude = 7.330627
};
var s = new JavaScriptSerializer();
var serialized = s.Serialize(modelWithDoubleValues);
// When
var deserializedModelWithDoubleValues = s.Deserialize<ModelWithDoubleValues>(serialized);
// Then
Assert.Equal(modelWithDoubleValues.Latitude, deserializedModelWithDoubleValues.Latitude);
Assert.Equal(modelWithDoubleValues.Longitude, deserializedModelWithDoubleValues.Longitude);
}
#endif
[Theory]
[InlineData("\n")]
[InlineData("\n\r")]
[InlineData("\r\n")]
[InlineData("\r")]
public void Should_Serialize_Last_Prop_is_Bool_And_Trailing_NewLine(string lineEndings)
{
// Given
var json = string.Concat("{\"Property\": true", lineEndings, "}");
// When
var s = new JavaScriptSerializer();
var deserialized = (dynamic)s.DeserializeObject(json);
// Then
Assert.True(deserialized["Property"]);
}
[Fact]
public void Should_Serialize_Last_Prop_is_Bool()
{
// Given
var json = "{\"Property\": true}";
// When
var s = new JavaScriptSerializer();
var deserialized = (dynamic)s.DeserializeObject(json);
// Then
Assert.True(deserialized["Property"]);
}
public class TestModel : IEquatable<TestModel>
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public DateTime DateProperty { get; set; }
public string[] ArrayProperty { get; set; }
public TestEnum? NullableEnumProperty { get; set; }
public List<int> ListOfPrimitivesProperty { get; set; }
public List<int> ListOfPrimitivesField;
public List<ModelWithStringValues> ListOfComplexObjectsProperty { get; set; }
public List<ModelWithStringValues> ListOfComplexObjectsField { get; set; }
public bool Equals(TestModel other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return other.StringProperty == this.StringProperty &&
other.IntProperty == this.IntProperty &&
!other.ArrayProperty.Except(this.ArrayProperty).Any() &&
other.DateProperty.ToShortDateString() == this.DateProperty.ToShortDateString();
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(TestModel))
{
return false;
}
return Equals((TestModel)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (this.StringProperty != null ? this.StringProperty.GetHashCode() : 0);
result = (result * 397) ^ this.IntProperty;
result = (result * 397) ^ this.DateProperty.GetHashCode();
result = (result * 397) ^ (this.ArrayProperty != null ? this.ArrayProperty.GetHashCode() : 0);
return result;
}
}
public static bool operator ==(TestModel left, TestModel right)
{
return Equals(left, right);
}
public static bool operator !=(TestModel left, TestModel right)
{
return !Equals(left, right);
}
}
public enum TestEnum
{
One = 1,
Hundred = 100
}
}
public class ModelWithStringValues
{
public string Value1 { get; set; }
public string Value2;
}
public class ModelWithDoubleValues
{
public double Latitude { get; set; }
public double Longitude;
}
public class ModelWithNullables
{
public int? P1 { get; set; }
public uint P2 { get; set; }
public uint? P3 { get; set; }
public int? F1;
public uint F2;
public uint? F3;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region old xml format
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
EntityBase[] entityList = scene.GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
#endregion
#region XML2 serialization
// Called by archives (save oar)
public static string SaveGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
//return SceneObjectSerializer.ToXml2Format(grp);
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
SceneObjectSerializer.SOGToXml2(writer, grp, options);
writer.Flush();
using (StreamReader reader = new StreamReader(mem))
{
mem.Seek(0, SeekOrigin.Begin);
return reader.ReadToEnd();
}
}
}
}
// Called by scene serializer (save xml2)
public static void SavePrimsToXml2(Scene scene, string fileName)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, fileName);
}
// Called by scene serializer (save xml2)
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
EntityBase[] entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList.ToArray(), fileName);
}
// Called by REST Application plugin
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, stream, min, max);
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
XmlTextWriter writer = new XmlTextWriter(stream);
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.GetWorldPosition();
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
//stream.WriteLine(SceneObjectSerializer.ToXml2Format(g));
SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent, new Dictionary<string,object>());
stream.WriteLine();
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
#endregion
#region XML2 deserialization
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneObjectSerializer.FromXml2Format(xmlString);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = DeserializeGroupFromXml2(aPrimNode.OuterXml);
if (startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
#endregion
}
}
| |
/************************************************************************
* Copyright (c) 2006-2008, Jason Whitehorn ([email protected])
* All rights reserved.
*
* Source code and binaries distributed under the terms of the included
* license, see license.txt for details.
************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using aspNETserve.Core;
using aspNETserve.Configuration;
using aspNETserve.Core.Logging;
namespace aspNETserve {
/// <summary>
/// Handles incoming HTTP communications, and passes them into the AppDomain
/// for processing by the Host.
/// </summary>
public class Server : IServer {
private string _appId;
private int _port;
private IPAddress _endPoint;
private string _virtualDir;
private string _physicalDir;
private Socket _sock;
private DomainHook _domainHook;
private ApplicationManager _appManager;
private IDictionary<string, string> _serverVariables;
private ServerStatus _status = ServerStatus.Stopped;
private int _openConnections;
private int _maxConnections = 200;
private int _initialRequestTimeout = 30000;
private int _keepAliveRequestTimeout = 30000;
protected Server() { }
public Server(IPAddress endPoint, string virtualDir, string physicalDir, int port) {
_endPoint = endPoint;
_virtualDir = virtualDir;
_physicalDir = physicalDir;
if (!_physicalDir.EndsWith("\\"))
_physicalDir += "\\";
_port = port;
_appId = Guid.NewGuid().ToString(); //generate a new application id
_appManager = ApplicationManager.GetApplicationManager();
PrepareServerVariables();
ConfigureResponses();
}
public Server(IApplication application) : this( application.EndPoints[0].Ip,
application.Domains[0].VirtualPath,
application.PhysicalPath,
application.EndPoints[0].Port) {
/*
* This constructort takes simple-minded approach to reading configuration elements
* from an IApplication. While not robust, it is functional. A more complete
* implementation "will come soon" :-).
*/
}
public virtual void Start() {
/*
* Create a new AppDomain containing the Host, and begin handling incoming requests.
*/
if (_sock != null)
return;
_openConnections = 0;
SetStatus(ServerStatus.Starting);
try {
_domainHook = _appManager.CreateObject(_appId, typeof(DomainHook), _virtualDir, _physicalDir, false) as DomainHook;
_domainHook.Configure(_virtualDir, _physicalDir, _serverVariables);
_domainHook.RegisterILogger(Logger.Instance);
_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_sock.Bind(new IPEndPoint(_endPoint, _port));
_sock.Listen(100);
_sock.BeginAccept(new AsyncCallback(ProcessRequest), _sock);
} catch {
SetStatus(ServerStatus.Stopped);
throw;
}
SetStatus(ServerStatus.Running);
}
public virtual void Stop() {
if (_sock != null) {
SetStatus(ServerStatus.ShuttingDown);
_sock.Close(); //stop accepting connections
_domainHook.DeRegisterILogger(Logger.Instance);
_domainHook.Dispose(); //this will call InitiateShutdown from within the app domain
}
_sock = null;
SetStatus(ServerStatus.Stopped);
}
public virtual ServerStatus Status {
get { return _status; }
}
public static string Version() {
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
public virtual void Dispose() {
if (_status == ServerStatus.Running)
Stop();
}
/// <summary>
/// Gets or Sets the timeout period in ms for initial requests.
/// </summary>
public virtual int InitialRequestTimeout {
get { return _initialRequestTimeout; }
set {
if(value <= 0)
throw new ArgumentOutOfRangeException("InitialRequestTimeout must be greater than zero.");
_initialRequestTimeout = value;
}
}
/// <summary>
/// Gets or Sets the timeout period in ms for keep alive requests.
/// This is the maximum time the server will wait to between receiving chuncks
/// of data in a single request following a clients initial request.
/// </summary>
public virtual int KeepAliveRequestTimeout {
get { return _keepAliveRequestTimeout; }
set {
if(value <= 0)
throw new ArgumentOutOfRangeException("KeepAliveRequestTimeout must be greater than zero.");
_keepAliveRequestTimeout = value;
}
}
/// <summary>
/// The maximum number of simultaneous connections allowed.
/// Incoming requests will be declined once the maximum amount
/// has been reached.
/// </summary>
public virtual int MaxConnections {
get { return _maxConnections; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("MaxConnections must be greater than zero.");
_maxConnections = value;
}
}
protected virtual void PrepareServerVariables() {
_serverVariables = new Dictionary<string, string>();
_serverVariables.Add("SERVER_SOFTWARE", "aspNETserve/" + Version());
}
protected virtual void ConfigureResponses() {
// Response error403Forbidden = new Response();
// error403Forbidden.StatusDescription = "Forbidden";
// error403Forbidden.StatusCode = (int)HttpResponseCode.NotFound;
// error403Forbidden.RawData = Encoding.UTF8.GetBytes(@"
// <html>
// <head><title>403 - Forbidden</title></head>
// <body>
// <h1>403 - Forbidden</h1><br/>
// The server is actively refusing access to the specified resource.<br/>
// <hr/>
// aspNETserve/" + Version() + @"
// </body>
// </html>
// ");
// Response.Error403Forbidden = error403Forbidden;
}
/// <summary>
/// This method processes the socket request. This is the first entry point for requested entering the aspNETserve
/// server.
/// </summary>
/// <param name="async">The IAsyncResult used to aquire to Socket.</param>
protected virtual void ProcessRequest(IAsyncResult async) {
Logger.Instance.LogMemberEntry();
Socket com = null;
Interlocked.Increment(ref _openConnections);
try {
com = _sock.EndAccept(async);
_sock.BeginAccept(new AsyncCallback(ProcessRequest), _sock);
if (_openConnections < _maxConnections) { //if the number of open connections is "safe", then continue...
HttpRequestResponse transaction = null;
do {
int timeout = transaction == null ? _initialRequestTimeout : _keepAliveRequestTimeout; //the initial request and subsequent requests may have different timeouts
transaction = new HttpRequestResponse(new NetworkStream(com, false), (IPEndPoint)com.LocalEndPoint, (IPEndPoint)com.RemoteEndPoint, timeout);
_domainHook.ProcessTransaction(transaction);
transaction.Response.Flush();
} while (transaction.Request.IsKeepAlive); //loop while the client wants to "keep alive".
} //otherwise we want to fall through and close this socket, and decrement the connection count.
com.Close();
} catch(Exception ex) {
Logger.Instance.LogException(LogLevel.Error, "Error processing request", ex);
if (com != null) {
try {
com.Close();
} catch { }
}
} finally {
Interlocked.Decrement(ref _openConnections);
Logger.Instance.LogMemberExit();
}
}
protected virtual void SetStatus(ServerStatus status) {
_status = status;
}
protected string AppId {
get { return _appId; }
set { _appId = value; }
}
protected int Port {
get { return _port; }
set { _port = value; }
}
protected IPAddress EndPoint {
get { return _endPoint; }
set { _endPoint = value; }
}
protected string VirtualDir {
get { return _virtualDir; }
set { _virtualDir = value; }
}
protected string PhysicalDir {
get { return _physicalDir; }
set { _physicalDir = value; }
}
protected Socket Sock {
get { return _sock; }
set { _sock = value; }
}
protected DomainHook DomainHook {
get { return _domainHook; }
set { _domainHook = value; }
}
protected ApplicationManager AppManager {
get { return _appManager; }
set { _appManager = value; }
}
protected IDictionary<string, string> ServerVariables {
get { return _serverVariables; }
set { _serverVariables = value; }
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Cookie.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Cookie
{
/// <summary>
/// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieAttributeHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)]
public partial interface ICookieAttributeHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)]
void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Peforms cookie validation for the given attribute value.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ISMConstants
/* scope: __dot42__ */
{
/// <java-name>
/// COOKIE
/// </java-name>
[Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE = "Cookie";
/// <java-name>
/// COOKIE2
/// </java-name>
[Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE2 = "Cookie2";
/// <java-name>
/// SET_COOKIE
/// </java-name>
[Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE = "Set-Cookie";
/// <java-name>
/// SET_COOKIE2
/// </java-name>
[Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE2 = "Set-Cookie2";
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)]
public partial interface ISM
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie2
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)]
public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// setCommentURL
/// </java-name>
[Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// setPorts
/// </java-name>
[Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)]
void SetPorts(int[] ports) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para>
/// </summary>
/// <java-name>
/// setDiscard
/// </java-name>
[Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)]
void SetDiscard(bool discard) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieOrigin
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)]
public sealed partial class CookieOrigin
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)]
public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getHost
/// </java-name>
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetHost() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetPath() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPort
/// </java-name>
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
public int GetPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getHost
/// </java-name>
public string Host
{
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetHost(); }
}
/// <java-name>
/// getPath
/// </java-name>
public string Path
{
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPath(); }
}
/// <java-name>
/// getPort
/// </java-name>
public int Port
{
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
get{ return GetPort(); }
}
}
/// <summary>
/// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)]
public sealed partial class CookieSpecRegistry
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieSpecRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para>
/// </summary>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)]
public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para>
/// </summary>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)]
public void Unregister(string id) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the cookie specification with the given ID.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" +
"okieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Gets the cookie specification with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
public global::Java.Util.IList<string> SpecNames
{
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSpecNames(); }
}
}
/// <summary>
/// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/Cookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)]
public partial interface ICookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the name.</para><para></para>
/// </summary>
/// <returns>
/// <para>String name The name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the value.</para><para></para>
/// </summary>
/// <returns>
/// <para>String value The current value. </para>
/// </returns>
/// <java-name>
/// getValue
/// </java-name>
[Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetValue() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para>
/// </summary>
/// <returns>
/// <para>comment </para>
/// </returns>
/// <java-name>
/// getComment
/// </java-name>
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetComment() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// getCommentURL
/// </java-name>
[Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetCommentURL() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para>
/// </summary>
/// <returns>
/// <para>Expiration Date, or <code>null</code>. </para>
/// </returns>
/// <java-name>
/// getExpiryDate
/// </java-name>
[Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)]
global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para>
/// </returns>
/// <java-name>
/// isPersistent
/// </java-name>
[Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)]
bool IsPersistent() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns domain attribute of the cookie.</para><para></para>
/// </summary>
/// <returns>
/// <para>the value of the domain attribute </para>
/// </returns>
/// <java-name>
/// getDomain
/// </java-name>
[Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetDomain() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the path attribute of the cookie</para><para></para>
/// </summary>
/// <returns>
/// <para>The value of the path attribute. </para>
/// </returns>
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetPath() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// getPorts
/// </java-name>
[Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)]
int[] GetPorts() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this cookie requires a secure connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version of the cookie. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this cookie has expired. </para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie has expired. </para>
/// </returns>
/// <java-name>
/// isExpired
/// </java-name>
[Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/MalformedCookieException
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)]
public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public MalformedCookieException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public MalformedCookieException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)]
public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// setValue
/// </java-name>
[Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetValue(string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para>
/// </summary>
/// <java-name>
/// setComment
/// </java-name>
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetComment(string comment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para>
/// </summary>
/// <java-name>
/// setExpiryDate
/// </java-name>
[Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)]
void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para>
/// </summary>
/// <java-name>
/// setDomain
/// </java-name>
[Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetDomain(string domain) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para>
/// </summary>
/// <java-name>
/// setPath
/// </java-name>
[Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetPath(string path) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para>
/// </summary>
/// <java-name>
/// setSecure
/// </java-name>
[Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)]
void SetSecure(bool secure) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)]
void SetVersion(int version) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieIdentityComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieIdentityComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpec
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)]
public partial interface ICookieSpec
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns version of the state management this cookie specification conforms to.</para><para></para>
/// </summary>
/// <returns>
/// <para>version of the state management specification </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para>
/// </summary>
/// <returns>
/// <para>an array of <code>Cookie</code>s parsed from the header </para>
/// </returns>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" +
"rg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines if a Cookie matches the target location.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para>
/// </summary>
/// <returns>
/// <para>a Header for the given Cookies. </para>
/// </returns>
/// <java-name>
/// formatCookies
/// </java-name>
[Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" +
"tp/Header;>;")]
global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para>
/// </summary>
/// <java-name>
/// getVersionHeader
/// </java-name>
[Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)]
global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookiePathComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookiePathComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientCookieConstants
/* scope: __dot42__ */
{
/// <java-name>
/// VERSION_ATTR
/// </java-name>
[Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_ATTR = "version";
/// <java-name>
/// PATH_ATTR
/// </java-name>
[Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PATH_ATTR = "path";
/// <java-name>
/// DOMAIN_ATTR
/// </java-name>
[Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DOMAIN_ATTR = "domain";
/// <java-name>
/// MAX_AGE_ATTR
/// </java-name>
[Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_AGE_ATTR = "max-age";
/// <java-name>
/// SECURE_ATTR
/// </java-name>
[Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string SECURE_ATTR = "secure";
/// <java-name>
/// COMMENT_ATTR
/// </java-name>
[Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENT_ATTR = "comment";
/// <java-name>
/// EXPIRES_ATTR
/// </java-name>
[Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string EXPIRES_ATTR = "expires";
/// <java-name>
/// PORT_ATTR
/// </java-name>
[Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PORT_ATTR = "port";
/// <java-name>
/// COMMENTURL_ATTR
/// </java-name>
[Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENTURL_ATTR = "commenturl";
/// <java-name>
/// DISCARD_ATTR
/// </java-name>
[Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DISCARD_ATTR = "discard";
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)]
public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// getAttribute
/// </java-name>
[Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GetAttribute(string name) /* MethodBuilder.Create */ ;
/// <java-name>
/// containsAttribute
/// </java-name>
[Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool ContainsAttribute(string name) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)]
public partial interface ICookieSpecFactory
/* scope: __dot42__ */
{
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)]
global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
// using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Framework.Capabilities
{
/// <summary>
/// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
/// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
/// to just pass the whole Scene into CAPS.
/// </summary>
public delegate IClientAPI GetClientDelegate(UUID agentID);
public class Caps
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_httpListenerHostName;
private uint m_httpListenPort;
/// <summary>
/// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester.
/// </summary>
private string m_capsObjectPath;
public string CapsObjectPath { get { return m_capsObjectPath; } }
private CapsHandlers m_capsHandlers;
private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers
= new Dictionary<string, PollServiceEventArgs>();
private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>();
private IHttpServer m_httpListener;
private UUID m_agentID;
private string m_regionName;
private ManualResetEvent m_capsActive = new ManualResetEvent(false);
public UUID AgentID
{
get { return m_agentID; }
}
public string RegionName
{
get { return m_regionName; }
}
public string HostName
{
get { return m_httpListenerHostName; }
}
public uint Port
{
get { return m_httpListenPort; }
}
public IHttpServer HttpListener
{
get { return m_httpListener; }
}
public bool SSLCaps
{
get { return m_httpListener.UseSSL; }
}
public string SSLCommonName
{
get { return m_httpListener.SSLCommonName; }
}
public CapsHandlers CapsHandlers
{
get { return m_capsHandlers; }
}
public Dictionary<string, string> ExternalCapsHandlers
{
get { return m_externalCapsHandlers; }
}
public Caps(IHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
UUID agent, string regionName)
{
m_capsObjectPath = capsPath;
m_httpListener = httpServer;
m_httpListenerHostName = httpListen;
m_httpListenPort = httpPort;
if (httpServer != null && httpServer.UseSSL)
{
m_httpListenPort = httpServer.SSLPort;
httpListen = httpServer.SSLCommonName;
httpPort = httpServer.SSLPort;
}
m_agentID = agent;
m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, (httpServer == null) ? false : httpServer.UseSSL);
m_regionName = regionName;
m_capsActive.Reset();
}
/// <summary>
/// Register a handler. This allows modules to register handlers.
/// </summary>
/// <param name="capName"></param>
/// <param name="handler"></param>
public void RegisterHandler(string capName, IRequestHandler handler)
{
//m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
m_capsHandlers[capName] = handler;
}
public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler)
{
// m_log.DebugFormat(
// "[CAPS]: Registering handler with name {0}, url {1} for {2}",
// capName, pollServiceHandler.Url, m_agentID, m_regionName);
m_pollServiceHandlers.Add(capName, pollServiceHandler);
m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler);
// uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
// string protocol = "http";
// string hostName = m_httpListenerHostName;
//
// if (MainServer.Instance.UseSSL)
// {
// hostName = MainServer.Instance.SSLCommonName;
// port = MainServer.Instance.SSLPort;
// protocol = "https";
// }
// RegisterHandler(
// capName, String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, pollServiceHandler.Url));
}
/// <summary>
/// Register an external handler. The service for this capability is somewhere else
/// given by the URL.
/// </summary>
/// <param name="capsName"></param>
/// <param name="url"></param>
public void RegisterHandler(string capsName, string url)
{
m_externalCapsHandlers.Add(capsName, url);
}
/// <summary>
/// Remove all CAPS service handlers.
/// </summary>
public void DeregisterHandlers()
{
foreach (string capsName in m_capsHandlers.Caps)
{
m_capsHandlers.Remove(capsName);
}
foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values)
{
m_httpListener.RemovePollServiceHTTPHandler("", handler.Url);
}
}
public bool TryGetPollHandler(string name, out PollServiceEventArgs pollHandler)
{
return m_pollServiceHandlers.TryGetValue(name, out pollHandler);
}
public Dictionary<string, PollServiceEventArgs> GetPollHandlers()
{
return new Dictionary<string, PollServiceEventArgs>(m_pollServiceHandlers);
}
/// <summary>
/// Return an LLSD-serializable Hashtable describing the
/// capabilities and their handler details.
/// </summary>
/// <param name="excludeSeed">If true, then exclude the seed cap.</param>
public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps)
{
Hashtable caps = CapsHandlers.GetCapsDetails(excludeSeed, requestedCaps);
lock (m_pollServiceHandlers)
{
foreach (KeyValuePair <string, PollServiceEventArgs> kvp in m_pollServiceHandlers)
{
if (!requestedCaps.Contains(kvp.Key))
continue;
string hostName = m_httpListenerHostName;
uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
string protocol = "http";
if (MainServer.Instance.UseSSL)
{
hostName = MainServer.Instance.SSLCommonName;
port = MainServer.Instance.SSLPort;
protocol = "https";
}
//
// caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url);
}
}
// Add the external too
foreach (KeyValuePair<string, string> kvp in ExternalCapsHandlers)
{
if (!requestedCaps.Contains(kvp.Key))
continue;
caps[kvp.Key] = kvp.Value;
}
return caps;
}
public void Activate()
{
m_capsActive.Set();
}
public bool WaitForActivation()
{
// Wait for 30s. If that elapses, return false and run without caps
return m_capsActive.WaitOne(120000);
}
}
}
| |
// Classes used to create objects to display.
using System.Collections.Generic;
namespace MenuDemo
{
public class DemoClass1
{
public int Class1IntField = 1111;
public MyLittleObject Class1ObjectField = new MyLittleObject(11111, "Object field string");
public int Class1IntProperty
{
get { return 1; }
}
public string Class1StringProperty1
{
get { return "First string property"; }
}
public string Class1StringProperty2
{
get { return null; }
}
public DemoClass2 Class1ObjectProperty1
{
get
{
return new DemoClass2(11, "First Instance String Property 1",
new MyLittleObject(21, "MySubObject1"),
new int[] { 11, 12, 13 }, new string[] { "First Instance String Array Element 1",
"First Instance String Array Element 2" },
new List<MyLittleObject>(new MyLittleObject[]
{ new MyLittleObject(1, "ListObject1"),
new MyLittleObject(2, "ListObject2") }),
new List<string>(new string[] { "String list item 1", "String list item 2" }),
new List<int>(new int[] { 10, 20 })
);
}
}
public DemoClass2[] Class1ObjectArrayProperty1
{
get
{
DemoClass2[] objectArray = {
new DemoClass2(111, "First Element String Property 1",
new MyLittleObject(121, "MySubObject11"),
new int[] { 111, 112, 113 },
new string[] { "First Element String Array Element 1",
"First Element String Array Element 2" },
new List<MyLittleObject>( new MyLittleObject[]
{ new MyLittleObject(101, "Element 1 ListObject1"),
new MyLittleObject(102, "Element 1 ListObject2") } ),
new List<string>( new string[]
{ "Element 1 String list item 1",
"Element 1 String list item 2" } ),
new List<int>( new int[] { 110, 120 })),
new DemoClass2(211, "Second Element String Property 1",
new MyLittleObject(221, "MySubObject21"),
new int[] { 211, 212, 213 },
new string[] { "Second Element String Array Element 1",
"Second Element String Array Element 2" },
new List<MyLittleObject>( new MyLittleObject[]
{ new MyLittleObject(201, "Element 2 ListObject1"),
new MyLittleObject(202, "Element 2 ListObject2") } ),
new List<string>( new string[]
{ "Element 2 String list item 1",
"Element 2 String list item 2" } ),
new List<int>( new int[] { 210, 220 }))
};
return objectArray;
}
}
public DemoClass2[] Class1ObjectArrayProperty2
{
get { return null; }
}
public DemoClass2[] Class1ObjectArrayProperty3
{
get
{
return new DemoClass2[0];
}
}
}
public class DemoClass2
{
public DemoClass2(int intProperty, string stringProperty1,
MyLittleObject objectProperty,
int[] intArrayProperty, string[] stringArrayProperty,
List<MyLittleObject> objectListProperty, List<string> stringListProperty,
List<int> intListProperty)
{
_int = intProperty;
_string1 = stringProperty1;
_string2 = null;
_parameter = objectProperty;
_parameter2 = null;
_intArray = intArrayProperty;
_intArray2 = null;
_intArray3 = new int[0];
_stringArray = stringArrayProperty;
_stringArray2 = null;
_stringArray3 = new string[0];
_objectList1 = objectListProperty;
_objectList2 = null;
_objectList3 = new List<MyLittleObject>();
_stringList1 = stringListProperty;
_stringList2 = null;
_stringList3 = new List<string>();
_intList1 = intListProperty;
_intList2 = null;
_intList3 = new List<int>();
}
private int _int;
public int IntProperty
{
get { return _int; }
}
private string _string1;
public string StringProperty1
{
get { return _string1; }
}
private string _string2;
public string StringProperty2
{
get { return _string2; }
}
private MyLittleObject _parameter;
public MyLittleObject ObjectProperty
{
get { return _parameter; }
}
private MyLittleObject _parameter2;
public MyLittleObject ObjectProperty2
{
get { return _parameter2; }
}
private int[] _intArray;
public int[] IntArrayProperty
{
get { return _intArray; }
}
private int[] _intArray2;
public int[] IntArrayProperty2
{
get { return _intArray2; }
}
private int[] _intArray3;
public int[] IntArrayProperty3
{
get { return _intArray3; }
}
private string[] _stringArray;
public string[] StringArrayProperty
{
get { return _stringArray; }
}
private string[] _stringArray2;
public string[] StringArrayProperty2
{
get { return _stringArray2; }
}
private string[] _stringArray3;
public string[] StringArrayProperty3
{
get { return _stringArray3; }
}
private List<MyLittleObject> _objectList1;
public List<MyLittleObject> ObjectList1
{
get { return _objectList1; }
}
private List<MyLittleObject> _objectList2;
public List<MyLittleObject> ObjectList2
{
get { return _objectList2; }
}
private List<MyLittleObject> _objectList3;
public List<MyLittleObject> ObjectList3
{
get { return _objectList3; }
}
private List<string> _stringList1;
public List<string> StringList1
{
get { return _stringList1; }
}
private List<string> _stringList2;
public List<string> StringList2
{
get { return _stringList2; }
}
private List<string> _stringList3;
public List<string> StringList3
{
get { return _stringList3; }
}
private List<int> _intList1;
public List<int> IntList1
{
get { return _intList1; }
}
private List<int> _intList2;
public List<int> IntList2
{
get { return _intList2; }
}
private List<int> _intList3;
public List<int> IntList3
{
get { return _intList3; }
}
}
public class MyLittleObject
{
private int _myInt;
public int MyProperty
{
get { return _myInt; }
}
private string _myString;
public string MyStringProperty
{
get { return _myString; }
}
public MyLittleObject(int myInt, string myString)
{
_myInt = myInt;
_myString = myString;
}
}
public class RecursiveObject
{
public RecursiveObject(int integerProperty)
{
_integerProperty = integerProperty;
}
private int _integerProperty;
public int IntegerProperty
{
get { return _integerProperty; }
}
public RecursiveObject RecursiveProperty
{
get { return new RecursiveObject(_integerProperty + 1); }
}
public RecursiveObject2 ObjectProperty
{
get { return new RecursiveObject2(_integerProperty); }
}
}
public class RecursiveObject2
{
public RecursiveObject2(int integerProperty2)
{
_integerProperty2 = integerProperty2;
}
private int _integerProperty2;
public int IntegerProperty2
{
get { return _integerProperty2; }
}
public RecursiveObject RecursiveProperty2
{
get { return new RecursiveObject(_integerProperty2 + 1); }
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.Data.Edm.Internal;
using Microsoft.Data.Edm.Values;
namespace Microsoft.Data.Edm.EdmToClrConversion
{
/// <summary>
/// <see cref="IEdmValue"/> to CLR value converter.
/// </summary>
public class EdmToClrConverter
{
private static readonly Type TypeICollectionOfT = typeof(ICollection<>);
private static readonly Type TypeIListOfT = typeof(IList<>);
private static readonly Type TypeListOfT = typeof(List<>);
private static readonly Type TypeIEnumerableOfT = typeof(IEnumerable<>);
private static readonly Type TypeNullableOfT = typeof(Nullable<>);
private static readonly MethodInfo CastToClrTypeMethodInfo = typeof(CastHelper).GetMethod("CastToClrType");
private static readonly MethodInfo EnumerableToListOfTMethodInfo = typeof(CastHelper).GetMethod("EnumerableToListOfT");
private readonly TryCreateObjectInstance tryCreateObjectInstanceDelegate;
private readonly Dictionary<IEdmStructuredValue, object> convertedObjects = new Dictionary<IEdmStructuredValue, object>();
private readonly Dictionary<Type, MethodInfo> enumTypeConverters = new Dictionary<Type, MethodInfo>();
private readonly Dictionary<Type, MethodInfo> enumerableConverters = new Dictionary<Type, MethodInfo>();
/// <summary>
/// Initializes a new instance of the <see cref="EdmToClrConverter"/> class.
/// </summary>
public EdmToClrConverter()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EdmToClrConverter"/> class.
/// </summary>
/// <param name="tryCreateObjectInstanceDelegate">The delegate customizing conversion of structured values.</param>
public EdmToClrConverter(TryCreateObjectInstance tryCreateObjectInstanceDelegate)
{
EdmUtil.CheckArgumentNull(tryCreateObjectInstanceDelegate, "tryCreateObjectInstanceDelegate");
this.tryCreateObjectInstanceDelegate = tryCreateObjectInstanceDelegate;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a CLR value of the specified type.
/// Supported values for <typeparamref name="T"/> are:
/// CLR primitive types such as <see cref="System.String"/> and <see cref="System.Int32"/>,
/// CLR enum types,
/// <see cref="IEnumerable<T>"/>,
/// <see cref="ICollection<T>"/>,
/// <see cref="IList<T>"/>,
/// CLR classes with default constructors and public properties with setters and collection properties of the following shapes:
/// <see cref="IEnumerable<T>"/> EnumerableProperty { get; set; },
/// <see cref="ICollection<T>"/> CollectionProperty { get; set; },
/// <see cref="IList<T>"/> ListProperty { get; set; },
/// <see cref="ICollection<T>"/> CollectionProperty { get { return this.nonNullCollection; } },
/// <see cref="IList<T>"/> ListProperty { get { return this.nonNullList; } }.
/// </summary>
/// <typeparam name="T">The CLR type.</typeparam>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>A CLR value converted from <paramref name="edmValue"/>.</returns>
/// <remarks>This method performs boxing and unboxing for value types. Use value-type specific methods such as <see cref="AsClrString"/> to avoid boxing and unboxing.</remarks>
public T AsClrValue<T>(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
// convertEnumValues: false -- no need to produce an object of the enum type because
// the produced underlying value will get converted to the enum type by (T)this.AsClrValue.
bool convertEnumValues = false;
return (T)this.AsClrValue(edmValue, typeof(T), convertEnumValues);
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a CLR value of the specified type.
/// Supported values for <paramref name="clrType"/> are:
/// CLR primitive types such as <see cref="System.String"/> and <see cref="System.Int32"/>,
/// CLR enum types,
/// <see cref="IEnumerable<T>"/>,
/// <see cref="ICollection<T>"/>,
/// <see cref="IList<T>"/>,
/// CLR classes with default constructors and public properties with setters and collection properties of the following shapes:
/// <see cref="IEnumerable<T>"/> EnumerableProperty { get; set; },
/// <see cref="ICollection<T>"/> CollectionProperty { get; set; },
/// <see cref="IList<T>"/> ListProperty { get; set; },
/// <see cref="ICollection<T>"/> CollectionProperty { get { return this.nonNullCollection; } },
/// <see cref="IList<T>"/> ListProperty { get { return this.nonNullList; } }.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <param name="clrType">The CLR type.</param>
/// <returns>A CLR value converted from <paramref name="edmValue"/>.</returns>
/// <remarks>This method performs boxing and unboxing for value types. Use value-type specific methods such as <see cref="AsClrString"/> to avoid boxing and unboxing.</remarks>
public object AsClrValue(IEdmValue edmValue, Type clrType)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
EdmUtil.CheckArgumentNull(clrType, "clrType");
// convertEnumValues: true -- must produce an object of the requested enum type because there is nothing else
// down the line that can convert an underlying value to an enum type.
bool convertEnumValues = true;
return this.AsClrValue(edmValue, clrType, convertEnumValues);
}
/// <summary>
/// Registers the <paramref name="clrObject"/> corresponding to the <paramref name="edmValue"/>.
/// All subsequent conversions from this <paramref name="edmValue"/> performed by this instance of <see cref="EdmToClrConverter"/> will return the specified
/// <paramref name="clrObject"/>. Registration is required to support graph consistency and loops during conversion process.
/// This method should be called inside the <see cref="TryCreateObjectInstance"/> delegate if the delegate is calling back into <see cref="EdmToClrConverter"/>
/// in order to populate properties of the <paramref name="clrObject"/>.
/// </summary>
/// <param name="edmValue">The EDM value.</param>
/// <param name="clrObject">The CLR object.</param>
public void RegisterConvertedObject(IEdmStructuredValue edmValue, object clrObject)
{
this.convertedObjects.Add(edmValue, clrObject);
}
#region Static converters
/// <summary>
/// Converts <paramref name="edmValue"/> to a CLR byte array value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted byte array.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmBinaryValue"/>.</exception>
internal static byte[] AsClrByteArray(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
if (edmValue is IEdmNullValue)
{
return null;
}
return ((IEdmBinaryValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.String"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted string.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmStringValue"/>.</exception>
internal static string AsClrString(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
if (edmValue is IEdmNullValue)
{
return null;
}
return ((IEdmStringValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Boolean"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted boolean.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmBooleanValue"/>.</exception>
internal static Boolean AsClrBoolean(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmBooleanValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Int64"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted integer.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmIntegerValue"/>.</exception>
internal static Int64 AsClrInt64(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmIntegerValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Char"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted char.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmIntegerValue"/>.</exception>
/// <exception cref="OverflowException">Exception is thrown if <paramref name="edmValue"/> cannot be converted to <see cref="System.Char"/>.</exception>
internal static Char AsClrChar(IEdmValue edmValue)
{
checked
{
return (Char)AsClrInt64(edmValue);
}
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Byte"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted byte.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmIntegerValue"/>.</exception>
/// <exception cref="OverflowException">Exception is thrown if <paramref name="edmValue"/> cannot be converted to <see cref="System.Byte"/>.</exception>
internal static Byte AsClrByte(IEdmValue edmValue)
{
checked
{
return (Byte)AsClrInt64(edmValue);
}
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Int16"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted integer.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmIntegerValue"/>.</exception>
/// <exception cref="OverflowException">Exception is thrown if <paramref name="edmValue"/> cannot be converted to <see cref="System.Int16"/>.</exception>
internal static Int16 AsClrInt16(IEdmValue edmValue)
{
checked
{
return (Int16)AsClrInt64(edmValue);
}
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Int32"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted integer.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmIntegerValue"/>.</exception>
/// <exception cref="OverflowException">Exception is thrown if <paramref name="edmValue"/> cannot be converted to <see cref="System.Int32"/>.</exception>
internal static Int32 AsClrInt32(IEdmValue edmValue)
{
checked
{
return (Int32)AsClrInt64(edmValue);
}
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Double"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted double.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmFloatingValue"/>.</exception>
internal static Double AsClrDouble(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmFloatingValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Single"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted single.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmFloatingValue"/>.</exception>
internal static Single AsClrSingle(IEdmValue edmValue)
{
return (Single)AsClrDouble(edmValue);
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.Decimal"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted decimal.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmDecimalValue"/>.</exception>
internal static decimal AsClrDecimal(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmDecimalValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.DateTime"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted DateTime.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmDateTimeValue"/>.</exception>
internal static DateTime AsClrDateTime(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmDateTimeValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.TimeSpan"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted Time.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmTimeValue"/>.</exception>
internal static TimeSpan AsClrTime(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmTimeValue)edmValue).Value;
}
/// <summary>
/// Converts <paramref name="edmValue"/> to a <see cref="System.DateTimeOffset"/> value.
/// </summary>
/// <param name="edmValue">The EDM value to be converted.</param>
/// <returns>Converted DateTimeOffset.</returns>
/// <exception cref="InvalidCastException">Exception is thrown if <paramref name="edmValue"/> is not <see cref="IEdmDateTimeOffsetValue"/>.</exception>
internal static DateTimeOffset AsClrDateTimeOffset(IEdmValue edmValue)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
return ((IEdmDateTimeOffsetValue)edmValue).Value;
}
#endregion
#region Private implementation
private static bool TryConvertAsPrimitiveType(TypeCode typeCode, IEdmValue edmValue, out object clrValue)
{
switch (typeCode)
{
case TypeCode.Boolean:
clrValue = AsClrBoolean(edmValue);
return true;
case TypeCode.Char:
clrValue = AsClrChar(edmValue);
return true;
case TypeCode.SByte:
checked
{
clrValue = (SByte)AsClrInt64(edmValue);
return true;
}
case TypeCode.Byte:
clrValue = AsClrByte(edmValue);
return true;
case TypeCode.Int16:
clrValue = AsClrInt16(edmValue);
return true;
case TypeCode.UInt16:
checked
{
clrValue = (UInt16)AsClrInt64(edmValue);
return true;
}
case TypeCode.Int32:
clrValue = AsClrInt32(edmValue);
return true;
case TypeCode.UInt32:
checked
{
clrValue = (UInt32)AsClrInt64(edmValue);
return true;
}
case TypeCode.Int64:
clrValue = AsClrInt64(edmValue);
return true;
case TypeCode.UInt64:
checked
{
clrValue = (UInt64)AsClrInt64(edmValue);
return true;
}
case TypeCode.Single:
clrValue = AsClrSingle(edmValue);
return true;
case TypeCode.Double:
clrValue = AsClrDouble(edmValue);
return true;
case TypeCode.Decimal:
clrValue = AsClrDecimal(edmValue);
return true;
case TypeCode.DateTime:
clrValue = AsClrDateTime(edmValue);
return true;
case TypeCode.String:
clrValue = AsClrString(edmValue);
return true;
default:
clrValue = null;
return false;
}
}
private static MethodInfo FindICollectionOfElementTypeAddMethod(Type collectionType, Type elementType)
{
Type collectionOfElementType = typeof(ICollection<>).MakeGenericType(elementType);
return collectionOfElementType.GetMethod("Add");
}
/// <summary>
/// Searches the <paramref name="clrObjectType"/> for a property with the <paramref name="propertyName"/>.
/// Handles the case of multiple properties with the same name (declared via C# "new") by choosing the one on the deepest derived type.
/// </summary>
/// <param name="clrObjectType">The clr object type.</param>
/// <param name="propertyName">The property name.</param>
/// <returns>The property or null.</returns>
private static PropertyInfo FindProperty(Type clrObjectType, string propertyName)
{
List<PropertyInfo> properties = clrObjectType.GetProperties().Where(p => p.Name == propertyName).ToList();
switch (properties.Count)
{
case 0:
return null;
case 1:
return properties[0];
default:
PropertyInfo property = properties[0];
for (int i = 1; i < properties.Count; ++i)
{
PropertyInfo candidate = properties[i];
if (property.DeclaringType.IsAssignableFrom(candidate.DeclaringType))
{
property = candidate;
}
}
return property;
}
}
/// <summary>
/// Used for error messages only.
/// </summary>
/// <param name="edmValue">The EDM value.</param>
/// <returns>The EDM value interface name.</returns>
private static string GetEdmValueInterfaceName(IEdmValue edmValue)
{
Debug.Assert(edmValue != null, "edmValue != null");
// We want search to be stable regardless of the order of elements coming from GetInterfaces() method,
// so we sort first, then find the deepest derived interface descending from IEdmValue.
Type interfaceType = typeof(IEdmValue);
foreach (Type candidate in edmValue.GetType().GetInterfaces().OrderBy(i => i.FullName))
{
if (interfaceType.IsAssignableFrom(candidate) && interfaceType != candidate)
{
interfaceType = candidate;
}
}
return interfaceType.Name;
}
private object AsClrValue(IEdmValue edmValue, Type clrType, bool convertEnumValues)
{
TypeCode typeCode = PlatformHelper.GetTypeCode(clrType);
if (typeCode == TypeCode.Object)
{
// First look for nullable primitives, then DateTime, DateTimeOffset and byte[] which don't have dedicated TypeCode, so they are processed here.
if (clrType.IsGenericType() && clrType.GetGenericTypeDefinition() == TypeNullableOfT)
{
if (edmValue is IEdmNullValue)
{
return null;
}
return this.AsClrValue(edmValue, clrType.GetGenericArguments().Single());
}
else if (clrType == typeof(DateTime))
{
return AsClrDateTime(edmValue);
}
else if (clrType == typeof(DateTimeOffset))
{
return AsClrDateTimeOffset(edmValue);
}
else if (clrType == typeof(TimeSpan))
{
return AsClrTime(edmValue);
}
else if (clrType == typeof(byte[]))
{
return AsClrByteArray(edmValue);
}
else if (clrType.IsGenericType() && clrType.IsInterface() &&
(clrType.GetGenericTypeDefinition() == TypeICollectionOfT ||
clrType.GetGenericTypeDefinition() == TypeIListOfT ||
clrType.GetGenericTypeDefinition() == TypeIEnumerableOfT))
{
// We are asked to produce an IEnumerable<T>, perform an equivalent of this.AsIEnumerable(edmValue, typeof(T)).Cast<T>().ToList()
return this.AsListOfT(edmValue, clrType);
}
else
{
return this.AsClrObject(edmValue, clrType);
}
}
else
{
// A CLR enum type will report some primitive type code, so we get here.
// If this is the case and the value is of an edm enumeration type, we want to unbox the primitive type value,
// otherwise assume the edm value is primitive and let it fail inside the converter if it's not.
bool isEnum = clrType.IsEnum();
if (isEnum)
{
IEdmEnumValue edmEnumValue = edmValue as IEdmEnumValue;
if (edmEnumValue != null)
{
edmValue = edmEnumValue.Value;
}
}
object clrValue;
if (!TryConvertAsPrimitiveType(PlatformHelper.GetTypeCode(clrType), edmValue, out clrValue))
{
throw new InvalidCastException(Strings.EdmToClr_UnsupportedTypeCode(typeCode));
}
// In case of enums, because the converter returns a primitive type value we want to convert it to the CLR enum type.
return (isEnum && convertEnumValues) ? this.GetEnumValue(clrValue, clrType) : clrValue;
}
}
private object AsListOfT(IEdmValue edmValue, Type clrType)
{
Debug.Assert(clrType.IsGenericType(), "clrType.IsGenericType");
Type elementType = clrType.GetGenericArguments().Single();
MethodInfo enumerableConverter;
if (!this.enumerableConverters.TryGetValue(elementType, out enumerableConverter))
{
enumerableConverter = EnumerableToListOfTMethodInfo.MakeGenericMethod(elementType);
this.enumerableConverters.Add(elementType, enumerableConverter);
}
try
{
return enumerableConverter.Invoke(null, new object[] { this.AsIEnumerable(edmValue, elementType) });
}
catch (TargetInvocationException targetInvokationException)
{
// Unwrap the target invokation exception that masks an interesting invalid cast exception.
if (targetInvokationException.InnerException != null && targetInvokationException.InnerException is InvalidCastException)
{
throw targetInvokationException.InnerException;
}
else
{
throw;
}
}
}
private object GetEnumValue(object clrValue, Type clrType)
{
Debug.Assert(clrType.IsEnum(), "clrType.IsEnum");
MethodInfo enumTypeConverter;
if (!this.enumTypeConverters.TryGetValue(clrType, out enumTypeConverter))
{
enumTypeConverter = CastToClrTypeMethodInfo.MakeGenericMethod(clrType);
this.enumTypeConverters.Add(clrType, enumTypeConverter);
}
try
{
return enumTypeConverter.Invoke(null, new object[] { clrValue });
}
catch (TargetInvocationException targetInvokationException)
{
// Unwrap the target invokation exception that masks an interesting invalid cast exception.
if (targetInvokationException.InnerException != null && targetInvokationException.InnerException is InvalidCastException)
{
throw targetInvokationException.InnerException;
}
else
{
throw;
}
}
}
private object AsClrObject(IEdmValue edmValue, Type clrObjectType)
{
EdmUtil.CheckArgumentNull(edmValue, "edmValue");
EdmUtil.CheckArgumentNull(clrObjectType, "clrObjectType");
if (edmValue is IEdmNullValue)
{
return null;
}
IEdmStructuredValue edmStructuredValue = edmValue as IEdmStructuredValue;
if (edmStructuredValue == null)
{
if (edmValue is IEdmCollectionValue)
{
throw new InvalidCastException(Strings.EdmToClr_CannotConvertEdmCollectionValueToClrType(clrObjectType.FullName));
}
else
{
throw new InvalidCastException(Strings.EdmToClr_CannotConvertEdmValueToClrType(GetEdmValueInterfaceName(edmValue), clrObjectType.FullName));
}
}
object clrObject;
if (this.convertedObjects.TryGetValue(edmStructuredValue, out clrObject))
{
return clrObject;
}
// By convention we only support mapping structured values to a CLR class.
if (!clrObjectType.IsClass())
{
throw new InvalidCastException(Strings.EdmToClr_StructuredValueMappedToNonClass);
}
// Try user-defined logic before the default logic.
bool clrObjectInitialized;
if (this.tryCreateObjectInstanceDelegate != null && this.tryCreateObjectInstanceDelegate(edmStructuredValue, clrObjectType, this, out clrObject, out clrObjectInitialized))
{
// The user-defined logic might have produced null, which is Ok, but we need to null the type in to keep them in sync.
if (clrObject != null)
{
Type newClrObjectType = clrObject.GetType();
if (!clrObjectType.IsAssignableFrom(newClrObjectType))
{
throw new InvalidCastException(Strings.EdmToClr_TryCreateObjectInstanceReturnedWrongObject(newClrObjectType.FullName, clrObjectType.FullName));
}
clrObjectType = newClrObjectType;
}
}
else
{
// Default instance creation logic: use Activator to create the new CLR object from the type.
clrObject = Activator.CreateInstance(clrObjectType);
clrObjectInitialized = false;
}
// Cache the object before populating its properties as their values might refer to the object.
this.convertedObjects[edmStructuredValue] = clrObject;
if (!clrObjectInitialized && clrObject != null)
{
this.PopulateObjectProperties(edmStructuredValue, clrObject, clrObjectType);
}
return clrObject;
}
private void PopulateObjectProperties(IEdmStructuredValue edmValue, object clrObject, Type clrObjectType)
{
// Populate properties of the CLR object.
// All CLR object properties that have no edm counterparts will remain intact.
// By convention we only support converting from a structured value.
HashSetInternal<string> populatedProperties = new HashSetInternal<string>();
foreach (IEdmPropertyValue propertyValue in edmValue.PropertyValues)
{
PropertyInfo clrProperty = FindProperty(clrObjectType, propertyValue.Name);
// By convention we ignore an ems property if it has no counterpart on the CLR side.
if (clrProperty != null)
{
if (populatedProperties.Contains(propertyValue.Name))
{
throw new InvalidCastException(Strings.EdmToClr_StructuredPropertyDuplicateValue(propertyValue.Name));
}
if (!this.TrySetCollectionProperty(clrProperty, clrObject, propertyValue))
{
object convertedClrPropertyValue = this.AsClrValue(propertyValue.Value, clrProperty.PropertyType);
clrProperty.SetValue(clrObject, convertedClrPropertyValue, null);
}
populatedProperties.Add(propertyValue.Name);
}
}
}
private bool TrySetCollectionProperty(PropertyInfo clrProperty, object clrObject, IEdmPropertyValue propertyValue)
{
Type clrPropertyType = clrProperty.PropertyType;
// Process the following cases:
// class C1
// {
// IEnumerable<ElementType> EnumerableProperty { get; set; }
//
// ICollection<ElementType> CollectionProperty { get; set; }
//
// IList<ElementType> ListProperty { get; set; }
//
// ICollection<ElementType> CollectionProperty { get { return this.nonNullCollection; } }
//
// IList<ElementType> ListProperty { get { return this.nonNullList; } }
// }
if (clrPropertyType.IsGenericType() && clrPropertyType.IsInterface())
{
Type genericTypeDefinition = clrPropertyType.GetGenericTypeDefinition();
bool genericTypeDefinitionIsIEnumerableOfT = genericTypeDefinition == TypeIEnumerableOfT;
if (genericTypeDefinitionIsIEnumerableOfT || genericTypeDefinition == TypeICollectionOfT || genericTypeDefinition == TypeIListOfT)
{
object clrPropertyValue = clrProperty.GetValue(clrObject, null);
// If property already has a value, we are trying to reuse it and add elements into it (except the case of IEnumerable<T>),
// otherwise we create List<elementType>, add elements to it and then assign it to the property.
Type elementType = clrPropertyType.GetGenericArguments().Single();
Type clrPropertyValueType;
if (clrPropertyValue == null)
{
// If collection property has no value, create an instance of List<elementType> and
// assign it to the property.
clrPropertyValueType = TypeListOfT.MakeGenericType(elementType);
clrPropertyValue = Activator.CreateInstance(clrPropertyValueType);
clrProperty.SetValue(clrObject, clrPropertyValue, null);
}
else
{
if (genericTypeDefinitionIsIEnumerableOfT)
{
// Cannot add elements to an existing value of type IEnumerable<T>.
throw new InvalidCastException(Strings.EdmToClr_IEnumerableOfTPropertyAlreadyHasValue(clrProperty.Name, clrProperty.DeclaringType.FullName));
}
clrPropertyValueType = clrPropertyValue.GetType();
}
// Find the ICollection<elementType>.Add(elementType) method. Note that IList<T> implements
MethodInfo clrPropertyValueTypeAddMethod = FindICollectionOfElementTypeAddMethod(clrPropertyValueType, elementType);
// Convert the collection elements and add them to the CLR collection.
foreach (object convertedElementValue in this.AsIEnumerable(propertyValue.Value, elementType))
{
try
{
clrPropertyValueTypeAddMethod.Invoke(clrPropertyValue, new object[] { convertedElementValue });
}
catch (TargetInvocationException targetInvokationException)
{
// Unwrap the target invokation exception that masks an interesting invalid cast exception.
if (targetInvokationException.InnerException != null && targetInvokationException.InnerException is InvalidCastException)
{
throw targetInvokationException.InnerException;
}
else
{
throw;
}
}
}
return true;
}
}
return false;
}
private IEnumerable AsIEnumerable(IEdmValue edmValue, Type elementType)
{
// By convention we only support converting from a collection value.
foreach (IEdmDelayedValue element in ((IEdmCollectionValue)edmValue).Elements)
{
yield return this.AsClrValue(element.Value, elementType);
}
}
/// <summary>
/// The class contains method that are called thru reflection to produce values of correct CLR types.
/// For example if one has an int value and a clr type represnting an enum : int, there is no other way to convert the int
/// to the enum type object.
/// </summary>
private static class CastHelper
{
public static T CastToClrType<T>(object obj)
{
return (T)obj;
}
public static List<T> EnumerableToListOfT<T>(IEnumerable enumerable)
{
return enumerable.Cast<T>().ToList();
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// <OWNER>[....]</OWNER>
// <OWNER>[....]</OWNER>
// <OWNER>[....]</OWNER>
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
internal class CLRIPropertyValueImpl : IPropertyValue
{
private PropertyType _type;
private Object _data;
// Numeric scalar types which participate in coersion
private static volatile Tuple<Type, PropertyType>[] s_numericScalarTypes;
internal CLRIPropertyValueImpl(PropertyType type, Object data)
{
_type = type;
_data = data;
}
private static Tuple<Type, PropertyType>[] NumericScalarTypes {
get {
if (s_numericScalarTypes == null) {
Tuple<Type, PropertyType>[] numericScalarTypes = new Tuple<Type, PropertyType>[] {
new Tuple<Type, PropertyType>(typeof(Byte), PropertyType.UInt8),
new Tuple<Type, PropertyType>(typeof(Int16), PropertyType.Int16),
new Tuple<Type, PropertyType>(typeof(UInt16), PropertyType.UInt16),
new Tuple<Type, PropertyType>(typeof(Int32), PropertyType.Int32),
new Tuple<Type, PropertyType>(typeof(UInt32), PropertyType.UInt32),
new Tuple<Type, PropertyType>(typeof(Int64), PropertyType.Int64),
new Tuple<Type, PropertyType>(typeof(UInt64), PropertyType.UInt64),
new Tuple<Type, PropertyType>(typeof(Single), PropertyType.Single),
new Tuple<Type, PropertyType>(typeof(Double), PropertyType.Double)
};
s_numericScalarTypes = numericScalarTypes;
}
return s_numericScalarTypes;
}
}
public PropertyType Type {
[Pure]
get { return _type; }
}
public bool IsNumericScalar {
[Pure]
get {
return IsNumericScalarImpl(_type, _data);
}
}
public override string ToString()
{
if (_data != null)
{
return _data.ToString();
}
else
{
return base.ToString();
}
}
[Pure]
public Byte GetUInt8()
{
return CoerceScalarValue<Byte>(PropertyType.UInt8);
}
[Pure]
public Int16 GetInt16()
{
return CoerceScalarValue<Int16>(PropertyType.Int16);
}
public UInt16 GetUInt16()
{
return CoerceScalarValue<UInt16>(PropertyType.UInt16);
}
[Pure]
public Int32 GetInt32()
{
return CoerceScalarValue<Int32>(PropertyType.Int32);
}
[Pure]
public UInt32 GetUInt32()
{
return CoerceScalarValue<UInt32>(PropertyType.UInt32);
}
[Pure]
public Int64 GetInt64()
{
return CoerceScalarValue<Int64>(PropertyType.Int64);
}
[Pure]
public UInt64 GetUInt64()
{
return CoerceScalarValue<UInt64>(PropertyType.UInt64);
}
[Pure]
public Single GetSingle()
{
return CoerceScalarValue<Single>(PropertyType.Single);
}
[Pure]
public Double GetDouble()
{
return CoerceScalarValue<Double>(PropertyType.Double);
}
[Pure]
public char GetChar16()
{
if (this.Type != PropertyType.Char16)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char)_data;
}
[Pure]
public Boolean GetBoolean()
{
if (this.Type != PropertyType.Boolean)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool)_data;
}
[Pure]
public String GetString()
{
return CoerceScalarValue<String>(PropertyType.String);
}
[Pure]
public Object GetInspectable()
{
if (this.Type != PropertyType.Inspectable)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return _data;
}
[Pure]
public Guid GetGuid()
{
return CoerceScalarValue<Guid>(PropertyType.Guid);
}
[Pure]
public DateTimeOffset GetDateTime()
{
if (this.Type != PropertyType.DateTime)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset)_data;
}
[Pure]
public TimeSpan GetTimeSpan()
{
if (this.Type != PropertyType.TimeSpan)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan)_data;
}
[Pure]
[SecuritySafeCritical]
public Point GetPoint()
{
if (this.Type != PropertyType.Point)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Point>(IReferenceFactory.s_pointType);
}
[Pure]
[SecuritySafeCritical]
public Size GetSize()
{
if (this.Type != PropertyType.Size)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Size>(IReferenceFactory.s_sizeType);
}
[Pure]
[SecuritySafeCritical]
public Rect GetRect()
{
if (this.Type != PropertyType.Rect)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Rect>(IReferenceFactory.s_rectType);
}
[Pure]
public Byte[] GetUInt8Array()
{
return CoerceArrayValue<Byte>(PropertyType.UInt8Array);
}
[Pure]
public Int16[] GetInt16Array()
{
return CoerceArrayValue<Int16>(PropertyType.Int16Array);
}
[Pure]
public UInt16[] GetUInt16Array()
{
return CoerceArrayValue<UInt16>(PropertyType.UInt16Array);
}
[Pure]
public Int32[] GetInt32Array()
{
return CoerceArrayValue<Int32>(PropertyType.Int32Array);
}
[Pure]
public UInt32[] GetUInt32Array()
{
return CoerceArrayValue<UInt32>(PropertyType.UInt32Array);
}
[Pure]
public Int64[] GetInt64Array()
{
return CoerceArrayValue<Int64>(PropertyType.Int64Array);
}
[Pure]
public UInt64[] GetUInt64Array()
{
return CoerceArrayValue<UInt64>(PropertyType.UInt64Array);
}
[Pure]
public Single[] GetSingleArray()
{
return CoerceArrayValue<Single>(PropertyType.SingleArray);
}
[Pure]
public Double[] GetDoubleArray()
{
return CoerceArrayValue<Double>(PropertyType.DoubleArray);
}
[Pure]
public char[] GetChar16Array()
{
if (this.Type != PropertyType.Char16Array)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char[])_data;
}
[Pure]
public Boolean[] GetBooleanArray()
{
if (this.Type != PropertyType.BooleanArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool[])_data;
}
[Pure]
public String[] GetStringArray()
{
return CoerceArrayValue<String>(PropertyType.StringArray);
}
[Pure]
public Object[] GetInspectableArray()
{
if (this.Type != PropertyType.InspectableArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (Object[])_data;
}
[Pure]
public Guid[] GetGuidArray()
{
return CoerceArrayValue<Guid>(PropertyType.GuidArray);
}
[Pure]
public DateTimeOffset[] GetDateTimeArray()
{
if (this.Type != PropertyType.DateTimeArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset[])_data;
}
[Pure]
public TimeSpan[] GetTimeSpanArray()
{
if (this.Type != PropertyType.TimeSpanArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan[])_data;
}
[Pure]
[SecuritySafeCritical]
public Point[] GetPointArray()
{
if (this.Type != PropertyType.PointArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Point>(IReferenceFactory.s_pointType);
}
[Pure]
[SecuritySafeCritical]
public Size[] GetSizeArray()
{
if (this.Type != PropertyType.SizeArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Size>(IReferenceFactory.s_sizeType);
}
[Pure]
[SecuritySafeCritical]
public Rect[] GetRectArray()
{
if (this.Type != PropertyType.RectArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Rect>(IReferenceFactory.s_rectType);
}
private T[] CoerceArrayValue<T>(PropertyType unboxType) {
// If we contain the type being looked for directly, then take the fast-path
if (Type == unboxType) {
return (T[])_data;
}
// Make sure we have an array to begin with
Array dataArray = _data as Array;
if (dataArray == null) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
// Array types are 1024 larger than their equivilent scalar counterpart
BCLDebug.Assert((int)Type > 1024, "Unexpected array PropertyType value");
PropertyType scalarType = Type - 1024;
// If we do not have the correct array type, then we need to convert the array element-by-element
// to a new array of the requested type
T[] coercedArray = new T[dataArray.Length];
for (int i = 0; i < dataArray.Length; ++i) {
try {
coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i));
} catch (InvalidCastException elementCastException) {
Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
e.SetErrorCode(elementCastException._HResult);
throw e;
}
}
return coercedArray;
}
private T CoerceScalarValue<T>(PropertyType unboxType)
{
// If we are just a boxed version of the requested type, then take the fast path out
if (Type == unboxType) {
return (T)_data;
}
return CoerceScalarValue<T>(Type, _data);
}
private static T CoerceScalarValue<T>(PropertyType type, object value) {
// If the property type is neither one of the coercable numeric types nor IInspectable, we
// should not attempt coersion, even if the underlying value is technically convertable
if (!IsCoercable(type, value) && type != PropertyType.Inspectable) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
try {
// Try to coerce:
// * String <--> Guid
// * Numeric scalars
if (type == PropertyType.String && typeof(T) == typeof(Guid)) {
return (T)(object)Guid.Parse((string)value);
}
else if (type == PropertyType.Guid && typeof(T) == typeof(String)) {
return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture);
}
else {
// Iterate over the numeric scalars, to see if we have a match for one of the known conversions
foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
if (numericScalar.Item1 == typeof(T)) {
return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
}
}
catch (FormatException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
catch (InvalidCastException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
catch (OverflowException) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW);
}
// If the property type is IInspectable, and we have a nested IPropertyValue, then we need
// to pass along the request to coerce the value.
IPropertyValue ipv = value as IPropertyValue;
if (type == PropertyType.Inspectable && ipv != null) {
if (typeof(T) == typeof(Byte)) {
return (T)(object)ipv.GetUInt8();
}
else if (typeof(T) == typeof(Int16)) {
return (T)(object)ipv.GetInt16();
}
else if (typeof(T) == typeof(UInt16)) {
return (T)(object)ipv.GetUInt16();
}
else if (typeof(T) == typeof(Int32)) {
return (T)(object)ipv.GetUInt32();
}
else if (typeof(T) == typeof(UInt32)) {
return (T)(object)ipv.GetUInt32();
}
else if (typeof(T) == typeof(Int64)) {
return (T)(object)ipv.GetInt64();
}
else if (typeof(T) == typeof(UInt64)) {
return (T)(object)ipv.GetUInt64();
}
else if (typeof(T) == typeof(Single)) {
return (T)(object)ipv.GetSingle();
}
else if (typeof(T) == typeof(Double)) {
return (T)(object)ipv.GetDouble();
}
else {
BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in [....]");
}
}
// Otherwise, this is an invalid coersion
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
private static bool IsCoercable(PropertyType type, object data) {
// String <--> Guid is allowed
if (type == PropertyType.Guid || type == PropertyType.String) {
return true;
}
// All numeric scalars can also be coerced
return IsNumericScalarImpl(type, data);
}
private static bool IsNumericScalarImpl(PropertyType type, object data) {
if (data.GetType().IsEnum) {
return true;
}
foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
if (numericScalar.Item2 == type) {
return true;
}
}
return false;
}
// Unbox the data stored in the property value to a structurally equivilent type
[Pure]
[SecurityCritical]
private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
Contract.Requires(expectedBoxedType != null);
Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));
if (_data.GetType() != expectedBoxedType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T unboxed = new T();
fixed (byte *pData = &JitHelpers.GetPinningHelper(_data).m_data) {
byte* pUnboxed = (byte*)JitHelpers.UnsafeCastToStackPointer(ref unboxed);
Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed));
}
return unboxed;
}
// Convert the array stored in the property value to a structurally equivilent array type
[Pure]
[SecurityCritical]
private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
Contract.Requires(expectedArrayElementType != null);
Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));
Array dataArray = _data as Array;
if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T[] converted = new T[dataArray.Length];
if (converted.Length > 0) {
fixed (byte * dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) {
fixed (byte * convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) {
byte *pData = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0);
byte *pConverted = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0);
Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length));
}
}
}
return converted;
}
}
}
| |
// --------------------------------------------------------------------------------------------
// <copyright from='2011' to='2011' company='SIL International'>
// Copyright (c) 2011, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
using System.Runtime.InteropServices;
#if __MonoCS__
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using IBusDotNet;
using Palaso.UI.WindowsForms.Keyboarding;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces;
using Palaso.UI.WindowsForms.Keyboarding.Types;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// Class for handling ibus keyboards on Linux. Currently just a wrapper for KeyboardSwitcher.
/// </summary>
[CLSCompliant(false)]
public class IbusKeyboardAdaptor: IKeyboardAdaptor
{
private IIbusCommunicator IBusCommunicator;
private bool m_needIMELocation;
/// <summary>
/// Initializes a new instance of the
/// <see cref="Palaso.UI.WindowsForms.Keyboard.Linux.IbusKeyboardAdaptor"/> class.
/// </summary>
public IbusKeyboardAdaptor(): this(new IbusCommunicator())
{
}
/// <summary>
/// Used in unit tests
/// </summary>
public IbusKeyboardAdaptor(IIbusCommunicator ibusCommunicator)
{
IBusCommunicator = ibusCommunicator;
if (!IBusCommunicator.Connected)
return;
if (KeyboardController.EventProvider != null)
{
KeyboardController.EventProvider.ControlAdded += OnControlRegistered;
KeyboardController.EventProvider.ControlRemoving += OnControlRemoving;
}
}
protected virtual void InitKeyboards()
{
foreach (var ibusKeyboard in GetIBusKeyboards())
{
var keyboard = new IbusKeyboardDescription(this, ibusKeyboard);
KeyboardController.Manager.RegisterKeyboard(keyboard);
}
}
private IBusEngineDesc[] GetIBusKeyboards()
{
if (!IBusCommunicator.Connected)
return new IBusEngineDesc[0];
var ibusWrapper = new InputBus(IBusCommunicator.Connection);
return ibusWrapper.ListActiveEngines();
}
internal IBusEngineDesc[] GetAllIBusKeyboards()
{
if (!IBusCommunicator.Connected)
return new IBusEngineDesc[0];
var ibusWrapper = new InputBus(IBusCommunicator.Connection);
return ibusWrapper.ListEngines();
}
internal bool CanSetIbusKeyboard()
{
if (!IBusCommunicator.Connected)
return false;
IBusCommunicator.FocusIn();
if (GlobalCachedInputContext.InputContext == null)
return false;
return true;
}
internal bool IBusKeyboardAlreadySet(IbusKeyboardDescription keyboard)
{
// check our cached value
if (GlobalCachedInputContext.Keyboard == keyboard)
return true;
if (keyboard == null || keyboard.IBusKeyboardEngine == null)
{
var context = GlobalCachedInputContext.InputContext;
context.Reset();
GlobalCachedInputContext.Keyboard = null;
context.Disable();
return true;
}
return false;
}
private bool SetIMEKeyboard(IbusKeyboardDescription keyboard)
{
try
{
if (!CanSetIbusKeyboard())
return false;
if (IBusKeyboardAlreadySet(keyboard))
return true;
// Set the associated XKB keyboard
var parentLayout = keyboard.ParentLayout;
if (parentLayout == "en")
parentLayout = "us";
var xkbKeyboard = Keyboard.Controller.AllAvailableKeyboards.FirstOrDefault(kbd => kbd.Layout == parentLayout);
if (xkbKeyboard != null)
xkbKeyboard.Activate();
// Then set the IBus keyboard
var context = GlobalCachedInputContext.InputContext;
context.SetEngine(keyboard.IBusKeyboardEngine.LongName);
GlobalCachedInputContext.Keyboard = keyboard;
return true;
}
catch (Exception e)
{
Debug.WriteLine(string.Format("Changing keyboard failed, is kfml/ibus running? {0}", e));
return false;
}
}
private void SetImePreeditWindowLocationAndSize(Control control)
{
var eventHandler = GetEventHandlerForControl(control);
if (eventHandler != null)
{
var location = eventHandler.SelectionLocationAndHeight;
IBusCommunicator.NotifySelectionLocationAndHeight(location.Left, location.Top,
location.Height);
}
}
/// <summary>
/// Synchronize on a commit.
/// </summary>
/// <returns><c>true</c> if an open composition got cancelled, otherwise <c>false</c>.
/// </returns>
private bool ResetAndWaitForCommit(Control control)
{
IBusCommunicator.Reset();
// This should allow any generated commits to be handled by the message pump.
// TODO: find a better way to synchronize
Application.DoEvents();
var eventHandler = GetEventHandlerForControl(control);
if (eventHandler != null)
return eventHandler.CommitOrReset();
return false;
}
private static IIbusEventHandler GetEventHandlerForControl(Control control)
{
if (control == null)
return null;
object handler;
if (!KeyboardController.EventProvider.EventHandlers.TryGetValue(control, out handler))
return null;
return handler as IIbusEventHandler;
}
#region KeyboardController events
private void OnControlRegistered(object sender, RegisterEventArgs e)
{
if (e.Control != null)
{
var eventHandler = e.EventHandler as IIbusEventHandler;
if (eventHandler == null)
{
Debug.Assert(e.Control is TextBox, "Currently only TextBox controls are compatible with the default IBus event handler.");
eventHandler = new IbusDefaultEventHandler((TextBox)e.Control);
}
KeyboardController.EventProvider.EventHandlers[e.Control] = eventHandler;
IBusCommunicator.CommitText += eventHandler.OnCommitText;
IBusCommunicator.UpdatePreeditText += eventHandler.OnUpdatePreeditText;
IBusCommunicator.HidePreeditText += eventHandler.OnHidePreeditText;
IBusCommunicator.KeyEvent += eventHandler.OnIbusKeyPress;
IBusCommunicator.DeleteSurroundingText += eventHandler.OnDeleteSurroundingText;
e.Control.GotFocus += HandleGotFocus;
e.Control.LostFocus += HandleLostFocus;
e.Control.MouseDown += HandleMouseDown;
e.Control.PreviewKeyDown += HandlePreviewKeyDown;
e.Control.KeyPress += HandleKeyPress;
e.Control.KeyDown += HandleKeyDown;
var scrollableControl = e.Control as ScrollableControl;
if (scrollableControl != null)
scrollableControl.Scroll += HandleScroll;
}
}
private void OnControlRemoving(object sender, ControlEventArgs e)
{
if (e.Control != null)
{
e.Control.GotFocus -= HandleGotFocus;
e.Control.LostFocus -= HandleLostFocus;
e.Control.MouseDown -= HandleMouseDown;
e.Control.PreviewKeyDown -= HandlePreviewKeyDown;
e.Control.KeyPress -= HandleKeyPress;
e.Control.KeyDown -= HandleKeyDown;
var scrollableControl = e.Control as ScrollableControl;
if (scrollableControl != null)
scrollableControl.Scroll -= HandleScroll;
var eventHandler = GetEventHandlerForControl(e.Control);
if (eventHandler != null)
{
IBusCommunicator.CommitText -= eventHandler.OnCommitText;
IBusCommunicator.UpdatePreeditText -= eventHandler.OnUpdatePreeditText;
IBusCommunicator.HidePreeditText -= eventHandler.OnHidePreeditText;
IBusCommunicator.KeyEvent -= eventHandler.OnIbusKeyPress;
IBusCommunicator.DeleteSurroundingText -= eventHandler.OnDeleteSurroundingText;
KeyboardController.EventProvider.EventHandlers.Remove(e.Control);
}
}
}
#endregion
private bool PassKeyEventToIbus(Control control, Keys keyChar, Keys modifierKeys)
{
var keySym = X11KeyConverter.GetKeySym(keyChar);
return PassKeyEventToIbus(control, keySym, modifierKeys);
}
private bool PassKeyEventToIbus(Control control, char keyChar, Keys modifierKeys)
{
if (keyChar == 0x7f) // we get this for Ctrl-Backspace
keyChar = '\b';
return PassKeyEventToIbus(control, (int)keyChar, modifierKeys);
}
private bool PassKeyEventToIbus(Control control, int keySym, Keys modifierKeys)
{
if (!IBusCommunicator.Connected)
return false;
int scancode = X11KeyConverter.GetScanCode(keySym);
if (scancode > -1)
{
if (IBusCommunicator.ProcessKeyEvent(keySym, scancode, modifierKeys))
{
return true;
}
}
// If ProcessKeyEvent doesn't consume the key, we need to kill any preedits and
// sync before continuing processing the keypress. We return false so that the
// control can process the character.
ResetAndWaitForCommit(control);
return false;
}
#region Event Handler for control
private void HandleGotFocus(object sender, EventArgs e)
{
if (!IBusCommunicator.Connected)
return;
IBusCommunicator.FocusIn();
m_needIMELocation = true;
}
private void HandleLostFocus(object sender, EventArgs e)
{
if (!IBusCommunicator.Connected)
return;
IBusCommunicator.FocusOut();
var eventHandler = GetEventHandlerForControl(sender as Control);
if (eventHandler == null)
return;
eventHandler.CommitOrReset();
}
/// <summary>
/// Inform input bus of Keydown events
/// This is useful to get warning of key that should stop the preedit
/// </summary>
private void HandlePreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (!IBusCommunicator.Connected)
return;
var eventHandler = GetEventHandlerForControl(sender as Control);
if (eventHandler == null)
return;
if (m_needIMELocation)
{
SetImePreeditWindowLocationAndSize(sender as Control);
m_needIMELocation = false;
}
var key = e.KeyCode;
switch (key)
{
case Keys.Escape:
// These should end a preedit, so wait until that has happened
// before allowing the key to be processed.
ResetAndWaitForCommit(sender as Control);
return;
case Keys.Up:
case Keys.Down:
case Keys.Left:
case Keys.Right:
case Keys.Delete:
case Keys.PageUp:
case Keys.PageDown:
case Keys.Home:
case Keys.End:
PassKeyEventToIbus(sender as Control, key, e.Modifiers);
return;
}
// pass function keys onto ibus since they don't appear (on mono at least) as WM_SYSCHAR
if (key >= Keys.F1 && key <= Keys.F24)
PassKeyEventToIbus(sender as Control, key, e.Modifiers);
}
/// <summary>
/// Handles a key down. While a preedit is active we don't want the control to handle
/// any of the keys that IBus deals with.
/// </summary>
private void HandleKeyDown (object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
case Keys.Down:
case Keys.Left:
case Keys.Right:
case Keys.Delete:
case Keys.PageUp:
case Keys.PageDown:
case Keys.Home:
case Keys.End:
var eventHandler = GetEventHandlerForControl(sender as Control);
if (eventHandler != null)
e.Handled = eventHandler.IsPreeditActive;
break;
}
}
/// <summary>
/// Handles a key press.
/// </summary>
/// <remarks>When the user types a character the control receives the KeyPress event and
/// this method gets called. We forward the key press to IBus. If IBus swallowed the key
/// it will return true, so no further handling is done by the control, otherwise the
/// control will process the key and update the selection.
/// If IBus swallows the key event, it will either raise the UpdatePreeditText event,
/// allowing the event handler to insert the composition as preedit (and update the
/// selection), or it will raise the CommitText event so that the event handler can
/// remove the preedit, replace it with the final composition string and update the
/// selection. Some IBus keyboards might raise a ForwardKeyEvent (handled by
/// <see cref="IIbusEventHandler.OnIbusKeyPress"/>) prior to calling CommitText to
/// simulate a key press (e.g. backspace) so that the event handler can modify the
/// existing text of the control.
/// IBus might also open a pop-up window at the location we told it
/// (<see cref="IIbusEventHandler.SelectionLocationAndHeight"/>) to display possible
/// compositions. However, it will still call UpdatePreeditText.</remarks>
private void HandleKeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = PassKeyEventToIbus(sender as Control, e.KeyChar, Control.ModifierKeys);
}
private void HandleMouseDown(object sender, MouseEventArgs e)
{
if (!IBusCommunicator.Connected)
return;
ResetAndWaitForCommit(sender as Control);
m_needIMELocation = true;
}
private void HandleScroll(object sender, ScrollEventArgs e)
{
if (!IBusCommunicator.Connected)
return;
SetImePreeditWindowLocationAndSize(sender as Control);
}
#endregion
#region IKeyboardAdaptor implementation
/// <summary>
/// Initialize the installed keyboards
/// </summary>
public void Initialize()
{
InitKeyboards();
// Don't turn on any Ibus IME keyboard until requested explicitly.
// If we do nothing, the first Ibus IME keyboard is automatically activated.
IBusCommunicator.FocusIn();
if (GlobalCachedInputContext.InputContext != null)
{
var context = GlobalCachedInputContext.InputContext;
context.Reset();
GlobalCachedInputContext.Keyboard = null;
context.SetEngine("");
context.Disable();
}
IBusCommunicator.FocusOut();
}
public void UpdateAvailableKeyboards()
{
InitKeyboards();
}
/// <summary/>
public void Close()
{
if (!IBusCommunicator.IsDisposed)
{
IBusCommunicator.Dispose();
}
}
public bool ActivateKeyboard(IKeyboardDefinition keyboard)
{
var ibusKeyboard = keyboard as IbusKeyboardDescription;
return SetIMEKeyboard(ibusKeyboard);
}
/// <summary>
/// Deactivates the specified keyboard.
/// </summary>
public void DeactivateKeyboard(IKeyboardDefinition keyboard)
{
SetIMEKeyboard(null);
}
/// <summary>
/// List of keyboard layouts that either gave an exception or other error trying to
/// get more information. We don't have enough information for these keyboard layouts
/// to include them in the list of installed keyboards.
/// </summary>
public List<IKeyboardErrorDescription> ErrorKeyboards
{
get
{
return new List<IKeyboardErrorDescription>();
}
}
// Currently we expect this to only be useful on Windows.
public IKeyboardDefinition GetKeyboardForInputLanguage(IInputLanguage inputLanguage)
{
throw new NotImplementedException();
}
/// <summary>
/// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...)
/// </summary>
public KeyboardType Type
{
get { return KeyboardType.OtherIm; }
}
/// <summary>
/// Implemenation is not required because this is not the primary (Type System) adapter.
/// </summary>
public IKeyboardDefinition DefaultKeyboard
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Only the primary (Type=System) adapter is required to implement this method. This one makes keyboards
/// during Initialize, but is not used to make an unavailable keyboard to match an LDML file.
/// </summary>
public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale)
{
throw new NotImplementedException();
}
#endregion
}
}
#endif
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* 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;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tests.FileTests
{
[TestFixture]
public class GetTests
{
[Test]
public void GetFiles()
{
// GET:files
// http://developer.mindtouch.com/Deki/API_Reference/GET%3afiles
Plug p = Utils.BuildPlugForAdmin();
DreamMessage msg = p.At("files").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void GetFileInfo()
{
// GET:pages/{pageid}/files/{filename}/info
// http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2ffiles%2f%2f%7bfilename%7d%2f%2finfo
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id);
string fileid = null;
string filename = null;
msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename);
msg = p.At("pages", id, "files", "=" + filename, "info").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["@id"].AsText == fileid);
Assert.IsTrue(msg.ToDocument()["page.parent/@id"].AsText == id);
// GET:files/{fileid}/info
// http://developer.mindtouch.com/Deki/API_Reference/GET%3afiles%2f%2f%7bfileid%7d%2f%2finfo
msg = p.At("files", fileid, "info").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["@id"].AsText == fileid);
Assert.IsTrue(msg.ToDocument()["page.parent/@id"].AsText == id);
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetFileContent()
{
// GET:files/{fileid}
// http://developer.mindtouch.com/Deki/API_Reference/GET%3afiles%2f%2f%7bfileid%7d
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
byte[] content = FileUtils.GenerateRandomContent();
string fileid = null;
string filename = null;
msg = FileUtils.UploadRandomFile(p, id, content, string.Empty, out fileid, out filename);
msg = p.At("files", fileid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(Utils.ByteArraysAreEqual(content, msg.AsBytes()));
// GET:files/{fileid}/{filename}
// http://developer.mindtouch.com/Deki/API_Reference/GET%3afiles%2f%2f%7bfileid%7d%2f%2f%7bfilename%7d
msg = p.At("files", fileid, "=" + filename).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(Utils.ByteArraysAreEqual(content, msg.AsBytes()));
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetFileRevisions()
{
// GET:files/{fileid}/revisions
// http://developer.mindtouch.com/Deki/API_Reference/GET%3afiles%2f%2f%7bfileid%7d%2f%2frevisions
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string path = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path);
byte[] content = FileUtils.GenerateRandomContent();
string filename = FileUtils.CreateRamdomFile(content);
string fileid = null;
msg = FileUtils.UploadFile(p, id, string.Empty, out fileid, filename);
msg = p.At("files", fileid, "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["@count"].AsInt == 1);
content = FileUtils.GenerateRandomContent();
using (System.IO.FileStream file = System.IO.File.Create(filename))
file.Write(content, 0, content.Length);
msg = FileUtils.UploadFile(p, id, string.Empty, out fileid, filename);
filename = msg.ToDocument()["filename"].AsText;
Assert.IsFalse(string.IsNullOrEmpty(filename));
msg = p.At("files", fileid, "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["@count"].AsInt == 2);
// GET:pages/{pageid}/files/{filename}/revisions
// http://developer.mindtouch.com/Deki/API_Reference/GET%3apages%2f%2f%7bpageid%7d%2f%2ffiles%2f%2f%7bfilename%7d%2f%2frevisions
msg = p.At("pages", id, "files", "=" + filename, "revisions").Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(msg.ToDocument()["@count"].AsInt == 2);
PageUtils.DeletePageByID(p, id, true);
}
[Ignore]
[Test]
public void RetrieveFileAttachmentContent()
{
// HEAD:pages/{pageid}/files/{filename}
// http://developer.mindtouch.com/Deki/API_Reference/HEAD%3apages%2f%2f%7bpageid%7d%2f%2ffiles%2f%2f%7bfilename%7d
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id);
string fileid = null;
string filename = null;
msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename);
msg = p.At("pages", id, "files", "=" + filename).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
// HEAD:files/{fileid}/{filename}
// http://developer.mindtouch.com/Deki/API_Reference/HEAD%3afiles%2f%2f%7bfileid%7d%2f%2f%7bfilename%7d
msg = p.At("files", fileid, "=" + filename).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
// HEAD:files/{fileid}
// http://developer.mindtouch.com/Deki/API_Reference/HEAD%3afiles%2f%2f%7bfileid%7d
msg = p.At("files", fileid).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
// HEAD:files/{name}
// http://developer.mindtouch.com/Deki/API_Reference/HEAD%3afiles%2f%2f%7bname%7d
msg = p.At("files", "=" + filename).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetFileFromAnonymous()
{
//Assumptions:
//
//Actions:
// create page
// upload file to page
// try get file from anonymous account
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id);
byte[] content = FileUtils.GenerateRandomContent();
string fileid = null;
string filename = null;
msg = FileUtils.UploadRandomFile(p, id, content, string.Empty, out fileid, out filename);
p = Utils.BuildPlugForAnonymous();
msg = p.At("files", fileid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsTrue(Utils.ByteArraysAreEqual(content, msg.AsBytes()));
p = Utils.BuildPlugForAdmin();
PageUtils.DeletePageByID(p, id, true);
}
[Test]
public void GetFileSort() {
Plug p = Utils.BuildPlugForAdmin();
string id = null;
DreamMessage msg = PageUtils.CreateRandomPage(p, out id);
string fileid1, fileid2, fileid3 = null;
string filename1 = "ac.txt";
string filename2 = "ab.txt";
string filename3 = "aa.txt";
string tmpPath = Path.GetTempPath();
string filepath1 = Path.Combine(tmpPath, filename1);
string filepath2 = Path.Combine(tmpPath, filename2);
string filepath3 = Path.Combine(tmpPath, filename3);
try {
FileUtils.CreateFile(null, filepath1);
FileUtils.CreateFile(null, filepath2);
FileUtils.CreateFile(null, filepath3);
msg = FileUtils.UploadFile(p, id, "", out fileid1, filepath1);
msg = p.At("pages", id, "files", "=" + filename1).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = FileUtils.UploadFile(p, id, "", out fileid2, filepath2);
msg = p.At("pages", id, "files", "=" + filename2).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = FileUtils.UploadFile(p, id, "", out fileid3, filepath3);
msg = p.At("pages", id, "files", "=" + filename3).Invoke("HEAD", DreamMessage.Ok());
Assert.AreEqual(DreamStatus.Ok, msg.Status);
// check sort order of files via GET:pages/{id}
msg = p.At("pages", id).Get();
List<XDoc> files = msg.ToDocument()["files/file"].ToList();
Assert.IsTrue(1 > StringUtil.CompareInvariant(files[0]["filename"].AsText, files[1]["filename"].AsText));
Assert.IsTrue(1 > StringUtil.CompareInvariant(files[1]["filename"].AsText, files[2]["filename"].AsText));
// check sort order of files via GET:pages/{id}/files
msg = p.At("pages", id, "files").Get();
files = msg.ToDocument()["file"].ToList();
Assert.IsTrue(1 > StringUtil.CompareInvariant(files[0]["filename"].AsText, files[1]["filename"].AsText));
Assert.IsTrue(1 > StringUtil.CompareInvariant(files[1]["filename"].AsText, files[2]["filename"].AsText));
} finally {
File.Delete(filepath1);
File.Delete(filepath2);
File.Delete(filepath3);
}
PageUtils.DeletePageByID(p, id, true);
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using Alphaleonis.Win32.Security;
using Microsoft.Win32.SafeHandles;
namespace Alphaleonis.Win32.Filesystem
{
partial class File
{
/// <summary>Applies access control list (ACL) entries described by a <see cref="FileSecurity"/> FileSecurity object to the specified file.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">A file to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity"/> object that describes an ACL entry to apply to the file described by the <paramref name="path"/> parameter.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(string path, FileSecurity fileSecurity)
{
SetAccessControlCore(path, null, fileSecurity, AccessControlSections.All, PathFormat.RelativePath);
}
/// <summary>Applies access control list (ACL) entries described by a <see cref="DirectorySecurity"/> object to the specified directory.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">A directory to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity "/> object that describes an ACL entry to apply to the directory described by the path parameter.</param>
/// <param name="includeSections">One or more of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to set.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(string path, FileSecurity fileSecurity, AccessControlSections includeSections)
{
SetAccessControlCore(path, null, fileSecurity, includeSections, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Applies access control list (ACL) entries described by a <see cref="FileSecurity"/> FileSecurity object to the specified file.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">A file to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity"/> object that describes an ACL entry to apply to the file described by the <paramref name="path"/> parameter.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(string path, FileSecurity fileSecurity, PathFormat pathFormat)
{
SetAccessControlCore(path, null, fileSecurity, AccessControlSections.All, pathFormat);
}
/// <summary>[AlphaFS] Applies access control list (ACL) entries described by a <see cref="DirectorySecurity"/> object to the specified directory.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">A directory to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity "/> object that describes an ACL entry to apply to the directory described by the path parameter.</param>
/// <param name="includeSections">One or more of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to set.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(string path, FileSecurity fileSecurity, AccessControlSections includeSections, PathFormat pathFormat)
{
SetAccessControlCore(path, null, fileSecurity, includeSections, pathFormat);
}
/// <summary>Applies access control list (ACL) entries described by a <see cref="FileSecurity"/> FileSecurity object to the specified file.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="handle">A <see cref="SafeFileHandle"/> to a file to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity"/> object that describes an ACL entry to apply to the file described by the <paramref name="handle"/> parameter.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(SafeFileHandle handle, FileSecurity fileSecurity)
{
SetAccessControlCore(null, handle, fileSecurity, AccessControlSections.All, PathFormat.LongFullPath);
}
/// <summary>Applies access control list (ACL) entries described by a <see cref="FileSecurity"/> FileSecurity object to the specified file.</summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="handle">A <see cref="SafeFileHandle"/> to a file to add or remove access control list (ACL) entries from.</param>
/// <param name="fileSecurity">A <see cref="FileSecurity"/> object that describes an ACL entry to apply to the file described by the <paramref name="handle"/> parameter.</param>
/// <param name="includeSections">One or more of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to set.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
[SecurityCritical]
public static void SetAccessControl(SafeFileHandle handle, FileSecurity fileSecurity, AccessControlSections includeSections)
{
SetAccessControlCore(null, handle, fileSecurity, includeSections, PathFormat.LongFullPath);
}
/// <summary>[AlphaFS] Applies access control list (ACL) entries described by a <see cref="FileSecurity"/>/<see cref="DirectorySecurity"/> object to the specified file or directory.</summary>
/// <remarks>Use either <paramref name="path"/> or <paramref name="handle"/>, not both.</remarks>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">A file/directory to add or remove access control list (ACL) entries from. This parameter This parameter may be <see langword="null"/>.</param>
/// <param name="handle">A <see cref="SafeFileHandle"/> to add or remove access control list (ACL) entries from. This parameter This parameter may be <see langword="null"/>.</param>
/// <param name="objectSecurity">A <see cref="FileSecurity"/>/<see cref="DirectorySecurity"/> object that describes an ACL entry to apply to the file/directory described by the <paramref name="path"/>/<paramref name="handle"/> parameter.</param>
/// <param name="includeSections">One or more of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to set.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[SecurityCritical]
internal static void SetAccessControlCore(string path, SafeFileHandle handle, ObjectSecurity objectSecurity, AccessControlSections includeSections, PathFormat pathFormat)
{
if (pathFormat == PathFormat.RelativePath)
Path.CheckSupportedPathFormat(path, true, true);
if (objectSecurity == null)
throw new ArgumentNullException("objectSecurity");
byte[] managedDescriptor = objectSecurity.GetSecurityDescriptorBinaryForm();
using (var safeBuffer = new SafeGlobalMemoryBufferHandle(managedDescriptor.Length))
{
string pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);
safeBuffer.CopyFrom(managedDescriptor, 0, managedDescriptor.Length);
SecurityDescriptorControl control;
uint revision;
if (!Security.NativeMethods.GetSecurityDescriptorControl(safeBuffer, out control, out revision))
NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
PrivilegeEnabler privilegeEnabler = null;
try
{
var securityInfo = SecurityInformation.None;
IntPtr pDacl = IntPtr.Zero;
if ((includeSections & AccessControlSections.Access) != 0)
{
bool daclDefaulted, daclPresent;
if (!Security.NativeMethods.GetSecurityDescriptorDacl(safeBuffer, out daclPresent, out pDacl, out daclDefaulted))
NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
if (daclPresent)
{
securityInfo |= SecurityInformation.Dacl;
securityInfo |= (control & SecurityDescriptorControl.DaclProtected) != 0
? SecurityInformation.ProtectedDacl
: SecurityInformation.UnprotectedDacl;
}
}
IntPtr pSacl = IntPtr.Zero;
if ((includeSections & AccessControlSections.Audit) != 0)
{
bool saclDefaulted, saclPresent;
if (!Security.NativeMethods.GetSecurityDescriptorSacl(safeBuffer, out saclPresent, out pSacl, out saclDefaulted))
NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
if (saclPresent)
{
securityInfo |= SecurityInformation.Sacl;
securityInfo |= (control & SecurityDescriptorControl.SaclProtected) != 0
? SecurityInformation.ProtectedSacl
: SecurityInformation.UnprotectedSacl;
privilegeEnabler = new PrivilegeEnabler(Privilege.Security);
}
}
IntPtr pOwner = IntPtr.Zero;
if ((includeSections & AccessControlSections.Owner) != 0)
{
bool ownerDefaulted;
if (!Security.NativeMethods.GetSecurityDescriptorOwner(safeBuffer, out pOwner, out ownerDefaulted))
NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
if (pOwner != IntPtr.Zero)
securityInfo |= SecurityInformation.Owner;
}
IntPtr pGroup = IntPtr.Zero;
if ((includeSections & AccessControlSections.Group) != 0)
{
bool groupDefaulted;
if (!Security.NativeMethods.GetSecurityDescriptorGroup(safeBuffer, out pGroup, out groupDefaulted))
NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp);
if (pGroup != IntPtr.Zero)
securityInfo |= SecurityInformation.Group;
}
uint lastError;
if (!Utils.IsNullOrWhiteSpace(pathLp))
{
// SetNamedSecurityInfo()
// In the ANSI version of this function, the name is limited to MAX_PATH characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
lastError = Security.NativeMethods.SetNamedSecurityInfo(pathLp, ObjectType.FileObject, securityInfo, pOwner, pGroup, pDacl, pSacl);
if (lastError != Win32Errors.ERROR_SUCCESS)
NativeError.ThrowException(lastError, pathLp);
}
else
{
if (NativeMethods.IsValidHandle(handle))
{
lastError = Security.NativeMethods.SetSecurityInfo(handle, ObjectType.FileObject, securityInfo, pOwner, pGroup, pDacl, pSacl);
if (lastError != Win32Errors.ERROR_SUCCESS)
NativeError.ThrowException((int) lastError);
}
}
}
finally
{
if (privilegeEnabler != null)
privilegeEnabler.Dispose();
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
/// Transactional cache tests.
/// </summary>
public abstract class CacheAbstractTransactionalTest : CacheAbstractTest
{
/// <summary>
/// Simple cache lock test (while <see cref="TestLock"/> is ignored).
/// </summary>
[Test]
public void TestLockSimple()
{
var cache = Cache();
const int key = 7;
Action<ICacheLock> checkLock = lck =>
{
using (lck)
{
Assert.Throws<InvalidOperationException>(lck.Exit); // can't exit if not entered
lck.Enter();
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
Assert.IsTrue(lck.TryEnter());
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
}
Assert.Throws<ObjectDisposedException>(lck.Enter); // Can't enter disposed lock
};
checkLock(cache.Lock(key));
checkLock(cache.LockAll(new[] { key, 1, 2, 3 }));
}
/// <summary>
/// Tests cache locks.
/// </summary>
[Test]
[Ignore("IGNITE-835")]
public void TestLock()
{
var cache = Cache();
const int key = 7;
// Lock
CheckLock(cache, key, () => cache.Lock(key));
// LockAll
CheckLock(cache, key, () => cache.LockAll(new[] { key, 2, 3, 4, 5 }));
}
/// <summary>
/// Internal lock test routine.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="key">Key.</param>
/// <param name="getLock">Function to get the lock.</param>
private static void CheckLock(ICache<int, int> cache, int key, Func<ICacheLock> getLock)
{
var sharedLock = getLock();
using (sharedLock)
{
Assert.Throws<InvalidOperationException>(() => sharedLock.Exit()); // can't exit if not entered
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
}
finally
{
sharedLock.Exit();
}
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
Assert.Throws<SynchronizationLockException>(() => sharedLock.Dispose()); // can't dispose while locked
}
finally
{
sharedLock.Exit();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var innerTask = new Task(() =>
{
Assert.IsTrue(sharedLock.TryEnter());
sharedLock.Exit();
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
innerTask.Start();
innerTask.Wait();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var outerTask = new Task(() =>
{
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
outerTask.Start();
outerTask.Wait();
Assert.Throws<ObjectDisposedException>(() => sharedLock.Enter()); // Can't enter disposed lock
}
/// <summary>
/// Ensure that lock cannot be obtained by other threads.
/// </summary>
/// <param name="getLock">Get lock function.</param>
/// <param name="sharedLock">Shared lock.</param>
private static void EnsureCannotLock(Func<ICacheLock> getLock, ICacheLock sharedLock)
{
var task = new Task(() =>
{
Assert.IsFalse(sharedLock.TryEnter());
Assert.IsFalse(sharedLock.TryEnter(TimeSpan.FromMilliseconds(100)));
using (var otherLock = getLock())
{
Assert.IsFalse(otherLock.TryEnter());
Assert.IsFalse(otherLock.TryEnter(TimeSpan.FromMilliseconds(100)));
}
});
task.Start();
task.Wait();
}
/// <summary>
/// Tests that commit applies cache changes.
/// </summary>
[Test]
public void TestTxCommit([Values(true, false)] bool async)
{
var cache = Cache();
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
cache.Put(2, 2);
if (async)
{
var task = tx.CommitAsync();
task.Wait();
Assert.IsTrue(task.IsCompleted);
}
else
tx.Commit();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that rollback reverts cache changes.
/// </summary>
[Test]
public void TestTxRollback()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
tx.Rollback();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that Dispose without Commit reverts changes.
/// </summary>
[Test]
public void TestTxClose()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests all concurrency and isolation modes with and without timeout.
/// </summary>
[Test]
public void TestTxAllModes([Values(true, false)] bool withTimeout)
{
var cache = Cache();
int cntr = 0;
foreach (TransactionConcurrency concurrency in Enum.GetValues(typeof(TransactionConcurrency)))
{
foreach (TransactionIsolation isolation in Enum.GetValues(typeof(TransactionIsolation)))
{
Console.WriteLine("Test tx [concurrency=" + concurrency + ", isolation=" + isolation + "]");
Assert.IsNull(Transactions.Tx);
using (var tx = withTimeout
? Transactions.TxStart(concurrency, isolation, TimeSpan.FromMilliseconds(1100), 10)
: Transactions.TxStart(concurrency, isolation))
{
Assert.AreEqual(concurrency, tx.Concurrency);
Assert.AreEqual(isolation, tx.Isolation);
if (withTimeout)
Assert.AreEqual(1100, tx.Timeout.TotalMilliseconds);
cache.Put(1, cntr);
tx.Commit();
}
Assert.IsNull(Transactions.Tx);
Assert.AreEqual(cntr, cache.Get(1));
cntr++;
}
}
}
/// <summary>
/// Tests that transaction properties are applied and propagated properly.
/// </summary>
[Test]
public void TestTxAttributes()
{
ITransaction tx = Transactions.TxStart(TransactionConcurrency.Optimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.AreEqual(tx.NodeId, GetIgnite(0).GetCluster().GetLocalNode().Id);
DateTime startTime1 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime1, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted,
TimeSpan.FromMilliseconds(3500), 200);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.IsTrue(tx.StartTime > startTime1);
DateTime startTime2 = tx.StartTime;
tx.Rollback();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime2, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead,
TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime > startTime2);
DateTime startTime3 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime3, tx.StartTime);
// Check defaults.
tx = Transactions.TxStart();
Assert.AreEqual(Transactions.DefaultTransactionConcurrency, tx.Concurrency);
Assert.AreEqual(Transactions.DefaultTransactionIsolation, tx.Isolation);
Assert.AreEqual(Transactions.DefaultTimeout, tx.Timeout);
tx.Commit();
}
/// <summary>
/// Tests <see cref="ITransaction.IsRollbackOnly"/> flag.
/// </summary>
[Test]
public void TestTxRollbackOnly()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
var tx = Transactions.TxStart();
cache.Put(1, 10);
cache.Put(2, 20);
Assert.IsFalse(tx.IsRollbackOnly);
tx.SetRollbackonly();
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.MarkedRollback, tx.State);
var ex = Assert.Throws<TransactionRollbackException>(() => tx.Commit());
Assert.IsTrue(ex.Message.StartsWith("Invalid transaction state for prepare [state=MARKED_ROLLBACK"));
tx.Dispose();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests transaction metrics.
/// </summary>
[Test]
public void TestTxMetrics()
{
var cache = Cache();
var startTime = DateTime.UtcNow.AddSeconds(-1);
Transactions.ResetMetrics();
var metrics = Transactions.GetMetrics();
Assert.AreEqual(0, metrics.TxCommits);
Assert.AreEqual(0, metrics.TxRollbacks);
using (Transactions.TxStart())
{
cache.Put(1, 1);
}
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
tx.Commit();
}
metrics = Transactions.GetMetrics();
Assert.AreEqual(1, metrics.TxCommits);
Assert.AreEqual(1, metrics.TxRollbacks);
Assert.LessOrEqual(startTime, metrics.CommitTime);
Assert.LessOrEqual(startTime, metrics.RollbackTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.CommitTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.RollbackTime);
}
/// <summary>
/// Tests transaction state transitions.
/// </summary>
[Test]
public void TestTxStateAndExceptions()
{
var tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, tx.ThreadId);
tx.AddMeta("myMeta", 42);
Assert.AreEqual(42, tx.Meta<int>("myMeta"));
Assert.AreEqual(42, tx.RemoveMeta<int>("myMeta"));
tx.RollbackAsync().Wait();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.Throws<InvalidOperationException>(() => tx.Commit());
tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
tx.CommitAsync().Wait();
Assert.AreEqual(TransactionState.Committed, tx.State);
var task = tx.RollbackAsync(); // Illegal, but should not fail here; will fail in task
Assert.Throws<AggregateException>(() => task.Wait());
}
/// <summary>
/// Tests the transaction deadlock detection.
/// </summary>
[Test]
public void TestTxDeadlockDetection()
{
var cache = Cache();
var keys0 = Enumerable.Range(1, 100).ToArray();
cache.PutAll(keys0.ToDictionary(x => x, x => x));
var barrier = new Barrier(2);
Action<int[]> increment = keys =>
{
using (var tx = Transactions.TxStart(TransactionConcurrency.Pessimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromSeconds(0.5), 0))
{
foreach (var key in keys)
cache[key]++;
barrier.SignalAndWait(500);
tx.Commit();
}
};
// Increment keys within tx in different order to cause a deadlock.
var aex = Assert.Throws<AggregateException>(() =>
Task.WaitAll(Task.Factory.StartNew(() => increment(keys0)),
Task.Factory.StartNew(() => increment(keys0.Reverse().ToArray()))));
Assert.AreEqual(2, aex.InnerExceptions.Count);
var deadlockEx = aex.InnerExceptions.OfType<TransactionDeadlockException>().First();
Assert.IsTrue(deadlockEx.Message.Trim().StartsWith("Deadlock detected:"), deadlockEx.Message);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeSingleCache()
{
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Commit.
using (var ts = new TransactionScope())
{
cache[1] = 10;
cache[2] = 20;
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx);
ts.Complete();
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
// Rollback.
using (new TransactionScope())
{
cache[1] = 100;
cache[2] = 200;
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// with multiple participating caches.
/// </summary>
[Test]
public void TestTransactionScopeMultiCache()
{
var cache1 = Cache();
var cache2 = GetIgnite(0).GetOrCreateCache<int, int>(new CacheConfiguration(cache1.Name + "_")
{
AtomicityMode = CacheAtomicityMode.Transactional
});
cache1[1] = 1;
cache2[1] = 2;
// Commit.
using (var ts = new TransactionScope())
{
cache1[1] = 10;
cache2[1] = 20;
ts.Complete();
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
// Rollback.
using (new TransactionScope())
{
cache1[1] = 100;
cache2[1] = 200;
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// when Ignite tx is started manually.
/// </summary>
[Test]
public void TestTransactionScopeWithManualIgniteTx()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
cache[1] = 1;
// When Ignite tx is started manually, it won't be enlisted in TransactionScope.
using (var tx = transactions.TxStart())
{
using (new TransactionScope())
{
cache[1] = 2;
} // Revert transaction scope.
tx.Commit(); // Commit manual tx.
}
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction with <see cref="TransactionScopeOption.Suppress"/> option.
/// </summary>
[Test]
public void TestSuppressedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
cache[1] = 2;
}
// Even though transaction is not completed, the value is updated, because tx is suppressed.
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> with nested scopes.
/// </summary>
[Test]
public void TestNestedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
foreach (var option in new[] {TransactionScopeOption.Required, TransactionScopeOption.RequiresNew})
{
// Commit.
using (var ts1 = new TransactionScope())
{
using (var ts2 = new TransactionScope(option))
{
cache[1] = 2;
ts2.Complete();
}
cache[1] = 3;
ts1.Complete();
}
Assert.AreEqual(3, cache[1]);
// Rollback.
using (new TransactionScope())
{
using (new TransactionScope(option))
cache[1] = 4;
cache[1] = 5;
}
// In case with Required option there is a single tx
// that gets aborted, second put executes outside the tx.
Assert.AreEqual(option == TransactionScopeOption.Required ? 5 : 3, cache[1], option.ToString());
}
}
/// <summary>
/// Test that ambient <see cref="TransactionScope"/> options propagate to Ignite transaction.
/// </summary>
[Test]
public void TestTransactionScopeOptions()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
var modes = new[]
{
Tuple.Create(IsolationLevel.Serializable, TransactionIsolation.Serializable),
Tuple.Create(IsolationLevel.RepeatableRead, TransactionIsolation.RepeatableRead),
Tuple.Create(IsolationLevel.ReadCommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.ReadUncommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Snapshot, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Chaos, TransactionIsolation.ReadCommitted),
};
foreach (var mode in modes)
{
using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
{
IsolationLevel = mode.Item1
}))
{
cache[1] = 1;
var tx = transactions.Tx;
Assert.AreEqual(mode.Item2, tx.Isolation);
Assert.AreEqual(transactions.DefaultTransactionConcurrency, tx.Concurrency);
}
}
}
/// <summary>
/// Tests all transactional operations with <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeAllOperations()
{
for (var i = 0; i < 10; i++)
{
CheckTxOp((cache, key) => cache.Put(key, -5));
CheckTxOp((cache, key) => cache.PutAsync(key, -5).Wait());
CheckTxOp((cache, key) => cache.PutAll(new Dictionary<int, int> {{key, -7}}));
CheckTxOp((cache, key) => cache.PutAllAsync(new Dictionary<int, int> {{key, -7}}).Wait());
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsentAsync(key, -10).Wait();
});
CheckTxOp((cache, key) => cache.GetAndPut(key, -9));
CheckTxOp((cache, key) => cache.GetAndPutAsync(key, -9).Wait());
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsentAsync(key, -10).Wait();
});
CheckTxOp((cache, key) => cache.GetAndRemove(key));
CheckTxOp((cache, key) => cache.GetAndRemoveAsync(key).Wait());
CheckTxOp((cache, key) => cache.GetAndReplace(key, -11));
CheckTxOp((cache, key) => cache.GetAndReplaceAsync(key, -11).Wait());
CheckTxOp((cache, key) => cache.Invoke(key, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAsync(key, new AddProcessor(), 1).Wait());
CheckTxOp((cache, key) => cache.InvokeAll(new[] {key}, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAllAsync(new[] {key}, new AddProcessor(), 1).Wait());
CheckTxOp((cache, key) => cache.Remove(key));
CheckTxOp((cache, key) => cache.RemoveAsync(key).Wait());
CheckTxOp((cache, key) => cache.RemoveAll(new[] {key}));
CheckTxOp((cache, key) => cache.RemoveAllAsync(new[] {key}).Wait());
CheckTxOp((cache, key) => cache.Replace(key, 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, 100).Wait());
CheckTxOp((cache, key) => cache.Replace(key, cache[key], 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, cache[key], 100).Wait());
}
}
/// <summary>
/// Checks that cache operation behaves transactionally.
/// </summary>
private void CheckTxOp(Action<ICache<int, int>, int> act)
{
var isolationLevels = new[]
{
IsolationLevel.Serializable, IsolationLevel.RepeatableRead, IsolationLevel.ReadCommitted,
IsolationLevel.ReadUncommitted, IsolationLevel.Snapshot, IsolationLevel.Chaos
};
foreach (var isolationLevel in isolationLevels)
{
var txOpts = new TransactionOptions {IsolationLevel = isolationLevel};
const TransactionScopeOption scope = TransactionScopeOption.Required;
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Rollback.
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx, "Transaction has not started.");
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
// Commit.
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.AreEqual(2, cache[2]);
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2);
}
}
[Serializable]
private class AddProcessor : ICacheEntryProcessor<int, int, int, int>
{
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value += arg;
return arg;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MessagePropertyVariants.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Messaging.Interop
{
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
// definition for tagMQPROPVARIANT
[StructLayout(LayoutKind.Explicit)]
internal struct MQPROPVARIANTS
{
// definition for struct tagCAUB
[StructLayout(LayoutKind.Sequential)]
internal struct CAUB
{
internal uint cElems;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr pElems;
}
[FieldOffset(0)]
internal short vt;
[FieldOffset(2)]
internal short wReserved1;
[FieldOffset(4)]
internal short wReserved2;
[FieldOffset(6)]
internal short wReserved3;
[FieldOffset(8)]
internal byte bVal;
[FieldOffset(8)]
internal short iVal;
[FieldOffset(8)]
internal int lVal;
[FieldOffset(8)]
internal long hVal;
[FieldOffset(8)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr ptr;
[FieldOffset(8)]
internal CAUB caub;
}
internal class MessagePropertyVariants
{
private const short VT_UNDEFINED = 0;
public const short VT_EMPTY = short.MaxValue; //this is hack, VT_EMPTY is really 0,
//but redefining VT_UNDEFINED is risky since 0 is a good semantic default for it
public const short VT_ARRAY = 0x2000;
public const short VT_BOOL = 11;
public const short VT_BSTR = 8;
public const short VT_CLSID = 72;
public const short VT_CY = 6;
public const short VT_DATE = 7;
public const short VT_I1 = 16;
public const short VT_I2 = 2;
public const short VT_I4 = 3;
public const short VT_I8 = 20;
public const short VT_LPSTR = 30;
public const short VT_LPWSTR = 31;
public const short VT_NULL = 1;
public const short VT_R4 = 4;
public const short VT_R8 = 5;
public const short VT_STREAMED_OBJECT = 68;
public const short VT_STORED_OBJECT = 69;
public const short VT_UI1 = 17;
public const short VT_UI2 = 18;
public const short VT_UI4 = 19;
public const short VT_UI8 = 21;
public const short VT_VECTOR = 0x1000;
private int MAX_PROPERTIES = 61;
private int basePropertyId = NativeMethods.MESSAGE_PROPID_BASE + 1;
private int propertyCount;
private GCHandle handleVectorProperties;
private GCHandle handleVectorIdentifiers;
private GCHandle handleVectorStatus;
private MQPROPS reference;
private int[] vectorIdentifiers;
private int[] vectorStatus;
private MQPROPVARIANTS[] vectorProperties;
private short[] variantTypes;
private object[] objects;
private object[] handles;
internal MessagePropertyVariants(int maxProperties, int baseId)
{
reference = new MQPROPS();
MAX_PROPERTIES = maxProperties;
basePropertyId = baseId;
variantTypes = new short[MAX_PROPERTIES];
objects = new object[MAX_PROPERTIES];
handles = new object[MAX_PROPERTIES];
}
public MessagePropertyVariants()
{
reference = new MQPROPS();
variantTypes = new short[MAX_PROPERTIES];
objects = new object[MAX_PROPERTIES];
handles = new object[MAX_PROPERTIES];
}
public byte[] GetGuid(int propertyId)
{
return (byte[])objects[propertyId - basePropertyId];
}
public void SetGuid(int propertyId, byte[] value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_CLSID;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public short GetI2(int propertyId)
{
return (short)objects[propertyId - basePropertyId];
}
public void SetI2(int propertyId, short value)
{
if ((variantTypes[propertyId - basePropertyId]) == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_I2;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public int GetI4(int propertyId)
{
return (int)objects[propertyId - basePropertyId];
}
public void SetI4(int propertyId, int value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_I4;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public IntPtr GetStringVectorBasePointer(int propertyId)
{
return (IntPtr)handles[propertyId - basePropertyId];
}
public uint GetStringVectorLength(int propertyId)
{
return (uint)objects[propertyId - basePropertyId];
}
public byte[] GetString(int propertyId)
{
return (byte[])objects[propertyId - basePropertyId];
}
public void SetString(int propertyId, byte[] value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_LPWSTR;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public byte GetUI1(int propertyId)
{
return (byte)objects[propertyId - basePropertyId];
}
public void SetUI1(int propertyId, byte value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UI1;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public byte[] GetUI1Vector(int propertyId)
{
return (byte[])objects[propertyId - basePropertyId];
}
public void SetUI1Vector(int propertyId, byte[] value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = (short)(VT_VECTOR | VT_UI1);
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public short GetUI2(int propertyId)
{
return (short)objects[propertyId - basePropertyId];
}
public void SetUI2(int propertyId, short value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UI2;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public int GetUI4(int propertyId)
{
return (int)objects[propertyId - basePropertyId];
}
public void SetUI4(int propertyId, int value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UI4;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public long GetUI8(int propertyId)
{
return (long)objects[propertyId - basePropertyId];
}
public void SetUI8(int propertyId, long value)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UI8;
++propertyCount;
}
objects[propertyId - basePropertyId] = value;
}
public IntPtr GetIntPtr(int propertyId)
{
//
// Bug 379376: Property access might have been unsuccessful (e.g., getting Id of a private queue),
// in which case the object stored at objects[propertyId - basePropertyId] will be object{uint}
// instead of object{IntPtr}.
// We will return IntPtr.Zero in that case
//
object obj = objects[propertyId - basePropertyId];
if (obj.GetType() == typeof(IntPtr))
return (IntPtr)obj;
return IntPtr.Zero;
}
public virtual void AdjustSize(int propertyId, int size)
{
//I'm going to reuse this field to store the size temporarily.
//Later I'll be storing the handle.
handles[propertyId - basePropertyId] = (uint)size;
}
public virtual void Ghost(int propertyId)
{
if (variantTypes[propertyId - basePropertyId] != VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UNDEFINED;
--propertyCount;
}
}
public virtual MQPROPS Lock()
{
int[] newVectorIdentifiers = new int[propertyCount];
int[] newVectorStatus = new int[propertyCount];
MQPROPVARIANTS[] newVectorProperties = new MQPROPVARIANTS[propertyCount];
int usedProperties = 0;
for (int i = 0; i < MAX_PROPERTIES; ++i)
{
short vt = variantTypes[i];
if (vt != VT_UNDEFINED)
{
//Set PropertyId
newVectorIdentifiers[usedProperties] = i + basePropertyId;
//Set VariantType
newVectorProperties[usedProperties].vt = vt;
if (vt == (short)(VT_VECTOR | VT_UI1))
{
if (handles[i] == null)
newVectorProperties[usedProperties].caub.cElems = (uint)((byte[])objects[i]).Length;
else
newVectorProperties[usedProperties].caub.cElems = (uint)handles[i];
GCHandle handle = GCHandle.Alloc(objects[i], GCHandleType.Pinned);
handles[i] = handle;
newVectorProperties[usedProperties].caub.pElems = handle.AddrOfPinnedObject();
}
else if (vt == VT_UI1 || vt == VT_I1)
newVectorProperties[usedProperties].bVal = (byte)objects[i];
else if (vt == VT_UI2 || vt == VT_I2)
newVectorProperties[usedProperties].iVal = (short)objects[i];
else if (vt == VT_UI4 || vt == VT_I4)
newVectorProperties[usedProperties].lVal = (int)objects[i];
else if (vt == VT_UI8 || vt == VT_I8)
newVectorProperties[usedProperties].hVal = (long)objects[i];
else if (vt == VT_LPWSTR || vt == VT_CLSID)
{
GCHandle handle = GCHandle.Alloc(objects[i], GCHandleType.Pinned);
handles[i] = handle;
newVectorProperties[usedProperties].ptr = handle.AddrOfPinnedObject();
}
else if (vt == VT_EMPTY)
newVectorProperties[usedProperties].vt = 0; //real value for VT_EMPTY
++usedProperties;
if (propertyCount == usedProperties)
break;
}
}
handleVectorIdentifiers = GCHandle.Alloc(newVectorIdentifiers, GCHandleType.Pinned);
handleVectorProperties = GCHandle.Alloc(newVectorProperties, GCHandleType.Pinned);
handleVectorStatus = GCHandle.Alloc(newVectorStatus, GCHandleType.Pinned);
vectorIdentifiers = newVectorIdentifiers;
vectorStatus = newVectorStatus;
vectorProperties = newVectorProperties;
reference.propertyCount = propertyCount;
reference.propertyIdentifiers = handleVectorIdentifiers.AddrOfPinnedObject();
reference.propertyValues = handleVectorProperties.AddrOfPinnedObject();
reference.status = handleVectorStatus.AddrOfPinnedObject();
return reference;
}
public virtual void Remove(int propertyId)
{
if (variantTypes[propertyId - basePropertyId] != VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_UNDEFINED;
objects[propertyId - basePropertyId] = null;
handles[propertyId - basePropertyId] = null;
--propertyCount;
}
}
public virtual void SetNull(int propertyId)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_NULL;
++propertyCount;
}
objects[propertyId - basePropertyId] = null;
}
public virtual void SetEmpty(int propertyId)
{
if (variantTypes[propertyId - basePropertyId] == VT_UNDEFINED)
{
variantTypes[propertyId - basePropertyId] = VT_EMPTY;
++propertyCount;
}
objects[propertyId - basePropertyId] = null;
}
public virtual void Unlock()
{
for (int i = 0; i < vectorIdentifiers.Length; ++i)
{
short vt = (short)vectorProperties[i].vt;
if (variantTypes[vectorIdentifiers[i] - basePropertyId] == VT_NULL)
{
if (vt == (short)(VT_VECTOR | VT_UI1) || vt == VT_NULL)
//Support for MSMQ self memory allocation.
objects[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i].caub.cElems;
else if (vt == (short)(VT_VECTOR | VT_LPWSTR))
{
//Support for MSMQ management apis.
objects[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i * 4].caub.cElems;
handles[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i * 4].caub.pElems;
}
else
objects[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i].ptr;
}
else if (vt == VT_LPWSTR || vt == VT_CLSID || vt == (short)(VT_VECTOR | VT_UI1))
{
((GCHandle)handles[vectorIdentifiers[i] - basePropertyId]).Free();
handles[vectorIdentifiers[i] - basePropertyId] = null;
}
else if (vt == VT_UI1 || vt == VT_I1)
objects[vectorIdentifiers[i] - basePropertyId] = (byte)vectorProperties[i].bVal;
else if (vt == VT_UI2 || vt == VT_I2)
objects[vectorIdentifiers[i] - basePropertyId] = (short)vectorProperties[i].iVal;
else if (vt == VT_UI4 || vt == VT_I4)
objects[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i].lVal;
else if (vt == VT_UI8 || vt == VT_I8)
objects[vectorIdentifiers[i] - basePropertyId] = vectorProperties[i].hVal;
}
handleVectorIdentifiers.Free();
handleVectorProperties.Free();
handleVectorStatus.Free();
}
[StructLayout(LayoutKind.Sequential)]
public class MQPROPS
{
internal int propertyCount;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr propertyIdentifiers;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr propertyValues;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
internal IntPtr status;
}
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
sealed class DuplexSecurityProtocolFactory : SecurityProtocolFactory
{
SecurityProtocolFactory forwardProtocolFactory;
SecurityProtocolFactory reverseProtocolFactory;
bool requireSecurityOnBothDuplexDirections = true;
public DuplexSecurityProtocolFactory()
: base()
{
}
public DuplexSecurityProtocolFactory(SecurityProtocolFactory forwardProtocolFactory, SecurityProtocolFactory reverseProtocolFactory)
: this()
{
this.forwardProtocolFactory = forwardProtocolFactory;
this.reverseProtocolFactory = reverseProtocolFactory;
}
public SecurityProtocolFactory ForwardProtocolFactory
{
get
{
return this.forwardProtocolFactory;
}
set
{
ThrowIfImmutable();
this.forwardProtocolFactory = value;
}
}
SecurityProtocolFactory ProtocolFactoryForIncomingMessages
{
get
{
return this.ActAsInitiator ? this.ReverseProtocolFactory : this.ForwardProtocolFactory;
}
}
SecurityProtocolFactory ProtocolFactoryForOutgoingMessages
{
get
{
return this.ActAsInitiator ? this.ForwardProtocolFactory : this.ReverseProtocolFactory;
}
}
// If RequireSecurityOnBothDuplexDirections is set to false,
// one or both among ForwardProtocolFactory and
// ReverseProtocolFactory will be allowed to be null. The
// message directions corresponding to the null
// ProtocolFactory will have no security applied or verified.
// This mode may be used for GetPolicy message exchanges, for
// example.
public bool RequireSecurityOnBothDuplexDirections
{
get
{
return this.requireSecurityOnBothDuplexDirections;
}
set
{
ThrowIfImmutable();
this.requireSecurityOnBothDuplexDirections = value;
}
}
public SecurityProtocolFactory ReverseProtocolFactory
{
get
{
return this.reverseProtocolFactory;
}
set
{
ThrowIfImmutable();
this.reverseProtocolFactory = value;
}
}
public override bool SupportsDuplex
{
get
{
return true;
}
}
public override bool SupportsReplayDetection
{
get
{
return this.ForwardProtocolFactory != null && this.ForwardProtocolFactory.SupportsReplayDetection &&
this.ReverseProtocolFactory != null && this.ReverseProtocolFactory.SupportsReplayDetection;
}
}
public override bool SupportsRequestReply
{
get
{
return false;
}
}
public override EndpointIdentity GetIdentityOfSelf()
{
SecurityProtocolFactory factory = this.ProtocolFactoryForIncomingMessages;
if (factory != null)
{
return factory.GetIdentityOfSelf();
}
else
{
return base.GetIdentityOfSelf();
}
}
public override void OnAbort()
{
if (this.forwardProtocolFactory != null)
{
this.forwardProtocolFactory.Close(true, TimeSpan.Zero);
}
if (this.reverseProtocolFactory != null)
{
this.reverseProtocolFactory.Close(true, TimeSpan.Zero);
}
}
public override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.forwardProtocolFactory != null)
{
this.forwardProtocolFactory.Close(false, timeoutHelper.RemainingTime());
}
if (this.reverseProtocolFactory != null)
{
this.reverseProtocolFactory.Close(false, timeoutHelper.RemainingTime());
}
// no need to the close the base as it has no settings.
}
protected override SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout)
{
SecurityProtocolFactory outgoingFactory = this.ProtocolFactoryForOutgoingMessages;
SecurityProtocolFactory incomingFactory = this.ProtocolFactoryForIncomingMessages;
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
SecurityProtocol outgoing = outgoingFactory == null ? null : outgoingFactory.CreateSecurityProtocol(target, via, listenerSecurityState, false, timeoutHelper.RemainingTime());
SecurityProtocol incoming = incomingFactory == null ? null : incomingFactory.CreateSecurityProtocol(null, null, listenerSecurityState, false, timeoutHelper.RemainingTime());
return new DuplexSecurityProtocol(outgoing, incoming);
}
public override void OnOpen(TimeSpan timeout)
{
if (this.ForwardProtocolFactory != null && ReferenceEquals(this.ForwardProtocolFactory, this.ReverseProtocolFactory))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ReverseProtocolFactory",
SR.GetString(SR.SameProtocolFactoryCannotBeSetForBothDuplexDirections));
}
if (this.forwardProtocolFactory != null)
{
this.forwardProtocolFactory.ListenUri = this.ListenUri;
}
if (this.reverseProtocolFactory != null)
{
this.reverseProtocolFactory.ListenUri = this.ListenUri;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
Open(this.ForwardProtocolFactory, this.ActAsInitiator, "ForwardProtocolFactory", timeoutHelper.RemainingTime());
Open(this.ReverseProtocolFactory, !this.ActAsInitiator, "ReverseProtocolFactory", timeoutHelper.RemainingTime());
// no need to the open the base as it has no settings.
}
void Open(SecurityProtocolFactory factory, bool actAsInitiator, string propertyName, TimeSpan timeout)
{
if (factory != null)
{
factory.Open(actAsInitiator, timeout);
}
else if (this.RequireSecurityOnBothDuplexDirections)
{
OnPropertySettingsError(propertyName, true);
}
}
sealed class DuplexSecurityProtocol : SecurityProtocol
{
readonly SecurityProtocol outgoingProtocol;
readonly SecurityProtocol incomingProtocol;
public DuplexSecurityProtocol(SecurityProtocol outgoingProtocol, SecurityProtocol incomingProtocol)
: base(incomingProtocol.SecurityProtocolFactory, null, null)
{
this.outgoingProtocol = outgoingProtocol;
this.incomingProtocol = incomingProtocol;
}
public override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.outgoingProtocol.Open(timeoutHelper.RemainingTime());
this.incomingProtocol.Open(timeoutHelper.RemainingTime());
}
public override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.outgoingProtocol.Close(false, timeoutHelper.RemainingTime());
this.incomingProtocol.Close(false, timeoutHelper.RemainingTime());
}
public override void OnAbort()
{
this.outgoingProtocol.Close(true, TimeSpan.Zero);
this.incomingProtocol.Close(true, TimeSpan.Zero);
}
public override IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
if (this.outgoingProtocol != null)
{
return this.outgoingProtocol.BeginSecureOutgoingMessage(message, timeout, callback, state);
}
else
{
return new CompletedAsyncResult<Message>(message, callback, state);
}
}
public override IAsyncResult BeginSecureOutgoingMessage(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState,
AsyncCallback callback, object state)
{
if (this.outgoingProtocol != null)
{
return this.outgoingProtocol.BeginSecureOutgoingMessage(message, timeout, correlationState, callback, state);
}
else
{
return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, null, callback, state);
}
}
public override void EndSecureOutgoingMessage(IAsyncResult result, out Message message)
{
if (this.outgoingProtocol != null)
{
this.outgoingProtocol.EndSecureOutgoingMessage(result, out message);
}
else
{
message = CompletedAsyncResult<Message>.End(result);
}
}
public override void EndSecureOutgoingMessage(IAsyncResult result,
out Message message, out SecurityProtocolCorrelationState newCorrelationState)
{
if (this.outgoingProtocol != null)
{
this.outgoingProtocol.EndSecureOutgoingMessage(result, out message, out newCorrelationState);
}
else
{
message = CompletedAsyncResult<Message, SecurityProtocolCorrelationState>.End(result, out newCorrelationState);
}
}
public override void SecureOutgoingMessage(ref Message message, TimeSpan timeout)
{
if (this.outgoingProtocol != null)
{
this.outgoingProtocol.SecureOutgoingMessage(ref message, timeout);
}
}
public override SecurityProtocolCorrelationState SecureOutgoingMessage(ref Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
{
if (this.outgoingProtocol != null)
{
return this.outgoingProtocol.SecureOutgoingMessage(ref message, timeout, correlationState);
}
else
{
return null;
}
}
public override void VerifyIncomingMessage(ref Message message, TimeSpan timeout)
{
if (this.incomingProtocol != null)
{
this.incomingProtocol.VerifyIncomingMessage(ref message, timeout);
}
}
public override SecurityProtocolCorrelationState VerifyIncomingMessage(ref Message message, TimeSpan timeout,
params SecurityProtocolCorrelationState[] correlationStates)
{
if (this.incomingProtocol != null)
{
return this.incomingProtocol.VerifyIncomingMessage(ref message, timeout, correlationStates);
}
else
{
return null;
}
}
}
}
}
| |
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Directory = Lucene.Net.Store.Directory;
using Document = Lucene.Net.Documents.Document;
using LineFileDocs = Lucene.Net.Util.LineFileDocs;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using TestUtil = Lucene.Net.Util.TestUtil;
using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState;
[TestFixture]
public class TestFlushByRamOrCountsPolicy : LuceneTestCase
{
private static LineFileDocs LineDocFile;
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
LineDocFile = new LineFileDocs(Random(), DefaultCodecSupportsDocValues());
}
[OneTimeTearDown]
public override void AfterClass()
{
LineDocFile.Dispose();
LineDocFile = null;
base.AfterClass();
}
[Test]
public virtual void TestFlushByRam()
{
double ramBuffer = (TEST_NIGHTLY ? 1 : 10) + AtLeast(2) + Random().NextDouble();
RunFlushByRam(1 + Random().Next(TEST_NIGHTLY ? 5 : 1), ramBuffer, false);
}
[Test]
public virtual void TestFlushByRamLargeBuffer()
{
// with a 256 mb ram buffer we should never stall
RunFlushByRam(1 + Random().Next(TEST_NIGHTLY ? 5 : 1), 256d, true);
}
protected internal virtual void RunFlushByRam(int numThreads, double maxRamMB, bool ensureNotStalled)
{
int numDocumentsToIndex = 10 + AtLeast(30);
AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex);
Directory dir = NewDirectory();
MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy();
MockAnalyzer analyzer = new MockAnalyzer(Random());
analyzer.MaxTokenLength = TestUtil.NextInt(Random(), 1, IndexWriter.MAX_TERM_LENGTH);
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetFlushPolicy(flushPolicy);
int numDWPT = 1 + AtLeast(2);
DocumentsWriterPerThreadPool threadPool = new ThreadAffinityDocumentsWriterThreadPool(numDWPT);
iwc.SetIndexerThreadPool(threadPool);
iwc.SetRAMBufferSizeMB(maxRamMB);
iwc.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);
IndexWriter writer = new IndexWriter(dir, iwc);
flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy;
Assert.IsFalse(flushPolicy.FlushOnDocCount);
Assert.IsFalse(flushPolicy.FlushOnDeleteTerms);
Assert.IsTrue(flushPolicy.FlushOnRAM);
DocumentsWriter docsWriter = writer.DocsWriter;
Assert.IsNotNull(docsWriter);
DocumentsWriterFlushControl flushControl = docsWriter.flushControl;
Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init");
IndexThread[] threads = new IndexThread[numThreads];
for (int x = 0; x < threads.Length; x++)
{
threads[x] = new IndexThread(this, numDocs, numThreads, writer, LineDocFile, false);
threads[x].Start();
}
for (int x = 0; x < threads.Length; x++)
{
threads[x].Join();
}
long maxRAMBytes = (long)(iwc.RAMBufferSizeMB * 1024.0 * 1024.0);
Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due numThreads=" + numThreads);
Assert.AreEqual(numDocumentsToIndex, writer.NumDocs);
Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc);
Assert.IsTrue(flushPolicy.PeakBytesWithoutFlush <= maxRAMBytes, "peak bytes without flush exceeded watermark");
AssertActiveBytesAfter(flushControl);
if (flushPolicy.HasMarkedPending)
{
Assert.IsTrue(maxRAMBytes < flushControl.peakActiveBytes);
}
if (ensureNotStalled)
{
Assert.IsFalse(docsWriter.flushControl.stallControl.WasStalled);
}
writer.Dispose();
Assert.AreEqual(0, flushControl.ActiveBytes);
dir.Dispose();
}
[Test]
public virtual void TestFlushDocCount()
{
int[] numThreads = new int[] { 2 + AtLeast(1), 1 };
for (int i = 0; i < numThreads.Length; i++)
{
int numDocumentsToIndex = 50 + AtLeast(30);
AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex);
Directory dir = NewDirectory();
MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetFlushPolicy(flushPolicy);
int numDWPT = 1 + AtLeast(2);
DocumentsWriterPerThreadPool threadPool = new ThreadAffinityDocumentsWriterThreadPool(numDWPT);
iwc.SetIndexerThreadPool(threadPool);
iwc.SetMaxBufferedDocs(2 + AtLeast(10));
iwc.SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);
IndexWriter writer = new IndexWriter(dir, iwc);
flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy;
Assert.IsTrue(flushPolicy.FlushOnDocCount);
Assert.IsFalse(flushPolicy.FlushOnDeleteTerms);
Assert.IsFalse(flushPolicy.FlushOnRAM);
DocumentsWriter docsWriter = writer.DocsWriter;
Assert.IsNotNull(docsWriter);
DocumentsWriterFlushControl flushControl = docsWriter.flushControl;
Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init");
IndexThread[] threads = new IndexThread[numThreads[i]];
for (int x = 0; x < threads.Length; x++)
{
threads[x] = new IndexThread(this, numDocs, numThreads[i], writer, LineDocFile, false);
threads[x].Start();
}
for (int x = 0; x < threads.Length; x++)
{
threads[x].Join();
}
Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due numThreads=" + numThreads[i]);
Assert.AreEqual(numDocumentsToIndex, writer.NumDocs);
Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc);
Assert.IsTrue(flushPolicy.PeakDocCountWithoutFlush <= iwc.MaxBufferedDocs, "peak bytes without flush exceeded watermark");
AssertActiveBytesAfter(flushControl);
writer.Dispose();
Assert.AreEqual(0, flushControl.ActiveBytes);
dir.Dispose();
}
}
[Test]
public virtual void TestRandom()
{
int numThreads = 1 + Random().Next(8);
int numDocumentsToIndex = 50 + AtLeast(70);
AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex);
Directory dir = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy();
iwc.SetFlushPolicy(flushPolicy);
int numDWPT = 1 + Random().Next(8);
DocumentsWriterPerThreadPool threadPool = new ThreadAffinityDocumentsWriterThreadPool(numDWPT);
iwc.SetIndexerThreadPool(threadPool);
IndexWriter writer = new IndexWriter(dir, iwc);
flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy;
DocumentsWriter docsWriter = writer.DocsWriter;
Assert.IsNotNull(docsWriter);
DocumentsWriterFlushControl flushControl = docsWriter.flushControl;
Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init");
IndexThread[] threads = new IndexThread[numThreads];
for (int x = 0; x < threads.Length; x++)
{
threads[x] = new IndexThread(this, numDocs, numThreads, writer, LineDocFile, true);
threads[x].Start();
}
for (int x = 0; x < threads.Length; x++)
{
threads[x].Join();
}
Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due");
Assert.AreEqual(numDocumentsToIndex, writer.NumDocs);
Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc);
if (flushPolicy.FlushOnRAM && !flushPolicy.FlushOnDocCount && !flushPolicy.FlushOnDeleteTerms)
{
long maxRAMBytes = (long)(iwc.RAMBufferSizeMB * 1024.0 * 1024.0);
Assert.IsTrue(flushPolicy.PeakBytesWithoutFlush <= maxRAMBytes, "peak bytes without flush exceeded watermark");
if (flushPolicy.HasMarkedPending)
{
assertTrue("max: " + maxRAMBytes + " " + flushControl.peakActiveBytes, maxRAMBytes <= flushControl.peakActiveBytes);
}
}
AssertActiveBytesAfter(flushControl);
writer.Commit();
Assert.AreEqual(0, flushControl.ActiveBytes);
IndexReader r = DirectoryReader.Open(dir);
Assert.AreEqual(numDocumentsToIndex, r.NumDocs);
Assert.AreEqual(numDocumentsToIndex, r.MaxDoc);
if (!flushPolicy.FlushOnRAM)
{
assertFalse("never stall if we don't flush on RAM", docsWriter.flushControl.stallControl.WasStalled);
assertFalse("never block if we don't flush on RAM", docsWriter.flushControl.stallControl.HasBlocked);
}
r.Dispose();
writer.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestStallControl()
{
int[] numThreads = new int[] { 4 + Random().Next(8), 1 };
int numDocumentsToIndex = 50 + Random().Next(50);
for (int i = 0; i < numThreads.Length; i++)
{
AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex);
MockDirectoryWrapper dir = NewMockDirectory();
// mock a very slow harddisk sometimes here so that flushing is very slow
dir.Throttling = MockDirectoryWrapper.Throttling_e.SOMETIMES;
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
iwc.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);
FlushPolicy flushPolicy = new FlushByRamOrCountsPolicy();
iwc.SetFlushPolicy(flushPolicy);
DocumentsWriterPerThreadPool threadPool = new ThreadAffinityDocumentsWriterThreadPool(numThreads[i] == 1 ? 1 : 2);
iwc.SetIndexerThreadPool(threadPool);
// with such a small ram buffer we should be stalled quiet quickly
iwc.SetRAMBufferSizeMB(0.25);
IndexWriter writer = new IndexWriter(dir, iwc);
IndexThread[] threads = new IndexThread[numThreads[i]];
for (int x = 0; x < threads.Length; x++)
{
threads[x] = new IndexThread(this, numDocs, numThreads[i], writer, LineDocFile, false);
threads[x].Start();
}
for (int x = 0; x < threads.Length; x++)
{
threads[x].Join();
}
DocumentsWriter docsWriter = writer.DocsWriter;
Assert.IsNotNull(docsWriter);
DocumentsWriterFlushControl flushControl = docsWriter.flushControl;
Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due");
Assert.AreEqual(numDocumentsToIndex, writer.NumDocs);
Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc);
if (numThreads[i] == 1)
{
assertFalse("single thread must not block numThreads: " + numThreads[i], docsWriter.flushControl.stallControl.HasBlocked);
}
if (docsWriter.flushControl.peakNetBytes > (2d * iwc.RAMBufferSizeMB * 1024d * 1024d))
{
Assert.IsTrue(docsWriter.flushControl.stallControl.WasStalled);
}
AssertActiveBytesAfter(flushControl);
writer.Dispose(true);
dir.Dispose();
}
}
internal virtual void AssertActiveBytesAfter(DocumentsWriterFlushControl flushControl)
{
IEnumerator<ThreadState> allActiveThreads = flushControl.AllActiveThreadStates();
long bytesUsed = 0;
while (allActiveThreads.MoveNext())
{
ThreadState next = allActiveThreads.Current;
if (next.DocumentsWriterPerThread != null)
{
bytesUsed += next.DocumentsWriterPerThread.BytesUsed;
}
}
Assert.AreEqual(bytesUsed, flushControl.ActiveBytes);
}
public class IndexThread : ThreadClass
{
private readonly TestFlushByRamOrCountsPolicy OuterInstance;
internal IndexWriter Writer;
internal LiveIndexWriterConfig Iwc;
internal LineFileDocs Docs;
internal AtomicInt32 PendingDocs;
internal readonly bool DoRandomCommit;
public IndexThread(TestFlushByRamOrCountsPolicy outerInstance, AtomicInt32 pendingDocs, int numThreads, IndexWriter writer, LineFileDocs docs, bool doRandomCommit)
{
this.OuterInstance = outerInstance;
this.PendingDocs = pendingDocs;
this.Writer = writer;
Iwc = writer.Config;
this.Docs = docs;
this.DoRandomCommit = doRandomCommit;
}
public override void Run()
{
try
{
long ramSize = 0;
while (PendingDocs.DecrementAndGet() > -1)
{
Document doc = Docs.NextDoc();
Writer.AddDocument(doc);
long newRamSize = Writer.RamSizeInBytes();
if (newRamSize != ramSize)
{
ramSize = newRamSize;
}
if (DoRandomCommit)
{
if (Rarely())
{
Writer.Commit();
}
}
}
Writer.Commit();
}
catch (Exception ex)
{
Console.WriteLine("FAILED exc:");
Console.WriteLine(ex.StackTrace);
throw new Exception(ex.Message, ex);
}
}
}
private class MockDefaultFlushPolicy : FlushByRamOrCountsPolicy
{
internal long PeakBytesWithoutFlush = int.MinValue;
internal long PeakDocCountWithoutFlush = int.MinValue;
internal bool HasMarkedPending = false;
public override void OnDelete(DocumentsWriterFlushControl control, ThreadState state)
{
List<ThreadState> pending = new List<ThreadState>();
List<ThreadState> notPending = new List<ThreadState>();
FindPending(control, pending, notPending);
bool flushCurrent = state.IsFlushPending;
ThreadState toFlush;
if (state.IsFlushPending)
{
toFlush = state;
}
else if (FlushOnDeleteTerms && state.DocumentsWriterPerThread.NumDeleteTerms >= m_indexWriterConfig.MaxBufferedDeleteTerms)
{
toFlush = state;
}
else
{
toFlush = null;
}
base.OnDelete(control, state);
if (toFlush != null)
{
if (flushCurrent)
{
Assert.IsTrue(pending.Remove(toFlush));
}
else
{
Assert.IsTrue(notPending.Remove(toFlush));
}
Assert.IsTrue(toFlush.IsFlushPending);
HasMarkedPending = true;
}
foreach (ThreadState threadState in notPending)
{
Assert.IsFalse(threadState.IsFlushPending);
}
}
public override void OnInsert(DocumentsWriterFlushControl control, ThreadState state)
{
List<ThreadState> pending = new List<ThreadState>();
List<ThreadState> notPending = new List<ThreadState>();
FindPending(control, pending, notPending);
bool flushCurrent = state.IsFlushPending;
long activeBytes = control.ActiveBytes;
ThreadState toFlush;
if (state.IsFlushPending)
{
toFlush = state;
}
else if (FlushOnDocCount && state.DocumentsWriterPerThread.NumDocsInRAM >= m_indexWriterConfig.MaxBufferedDocs)
{
toFlush = state;
}
else if (FlushOnRAM && activeBytes >= (long)(m_indexWriterConfig.RAMBufferSizeMB * 1024.0 * 1024.0))
{
toFlush = FindLargestNonPendingWriter(control, state);
Assert.IsFalse(toFlush.IsFlushPending);
}
else
{
toFlush = null;
}
base.OnInsert(control, state);
if (toFlush != null)
{
if (flushCurrent)
{
Assert.IsTrue(pending.Remove(toFlush));
}
else
{
Assert.IsTrue(notPending.Remove(toFlush));
}
Assert.IsTrue(toFlush.IsFlushPending);
HasMarkedPending = true;
}
else
{
PeakBytesWithoutFlush = Math.Max(activeBytes, PeakBytesWithoutFlush);
PeakDocCountWithoutFlush = Math.Max(state.DocumentsWriterPerThread.NumDocsInRAM, PeakDocCountWithoutFlush);
}
foreach (ThreadState threadState in notPending)
{
Assert.IsFalse(threadState.IsFlushPending);
}
}
}
internal static void FindPending(DocumentsWriterFlushControl flushControl, List<ThreadState> pending, List<ThreadState> notPending)
{
IEnumerator<ThreadState> allActiveThreads = flushControl.AllActiveThreadStates();
while (allActiveThreads.MoveNext())
{
ThreadState next = allActiveThreads.Current;
if (next.IsFlushPending)
{
pending.Add(next);
}
else
{
notPending.Add(next);
}
}
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Usage
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnusedParametersAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "Unused parameters";
internal const string Message = "Parameter '{0}' is not used.";
internal const string Category = SupportedCategories.Usage;
const string Description = "When a method declares a parameter and does not use it might bring incorrect conclusions for anyone reading the code and also demands the parameter when the method is called, unnecessarily.\r\n"
+ "You should delete the parameter in such cases.";
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.UnusedParameters.ToDiagnosticId(),
Title,
Message,
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: Description,
customTags: WellKnownDiagnosticTags.Unnecessary,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.UnusedParameters));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration);
private static void Analyzer(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var methodOrConstructor = context.Node as BaseMethodDeclarationSyntax;
if (methodOrConstructor == null) return;
var semanticModel = context.SemanticModel;
if (!IsCandidateForRemoval(methodOrConstructor, semanticModel)) return;
var parameters = methodOrConstructor.ParameterList.Parameters.ToDictionary(p => p, p => semanticModel.GetDeclaredSymbol(p));
var ctor = methodOrConstructor as ConstructorDeclarationSyntax;
if (ctor?.Initializer != null)
{
var symbolsTouched = new List<ISymbol>();
foreach (var arg in ctor.Initializer.ArgumentList.Arguments)
{
var dataFlowAnalysis = semanticModel.AnalyzeDataFlow(arg.Expression);
if (!dataFlowAnalysis.Succeeded) continue;
symbolsTouched.AddRange(dataFlowAnalysis.ReadInside);
symbolsTouched.AddRange(dataFlowAnalysis.WrittenInside);
}
var parametersToRemove = parameters.Where(p => symbolsTouched.Contains(p.Value)).ToList();
foreach (var parameter in parametersToRemove)
parameters.Remove(parameter.Key);
}
var method = methodOrConstructor as MethodDeclarationSyntax;
IEnumerable<SyntaxNode> methodChildren = methodOrConstructor.Body?.Statements;
var expressionBody = (methodOrConstructor as MethodDeclarationSyntax)?.ExpressionBody;
if (methodChildren == null && expressionBody != null)
methodChildren = new[] { expressionBody };
if (methodChildren?.Any() ?? false)
{
var identifiers = methodChildren
.SelectMany(s => s.DescendantNodesAndSelf())
.OfType<IdentifierNameSyntax>()
.ToList();
foreach (var parameter in parameters)
{
var used = identifiers
.Any(iName => IdentifierRefersToParam(iName, parameter.Key));
if (!used)
{
ReportDiagnostic(context, parameter.Key);
}
}
//
// THIS IS THE RIGHT WAY TO DO THIS VERIFICATION.
// BUT, WE HAVE TO WAIT FOR A "BUGFIX" FROM ROSLYN TEAM
// IN DataFlowAnalysis
//
// https://github.com/dotnet/roslyn/issues/6967
//
//var dataFlowAnalysis = semanticModel.AnalyzeDataFlow(methodOrConstructor.Body);
//if (!dataFlowAnalysis.Succeeded) return;
//foreach (var parameter in parameters)
//{
// var parameterSymbol = parameter.Value;
// if (parameterSymbol == null) continue;
// if (!dataFlowAnalysis.ReadInside.Contains(parameterSymbol) &&
// !dataFlowAnalysis.WrittenInside.Contains(parameterSymbol))
// {
// ReportDiagnostic(context, parameter.Key);
// }
//}
}
else
{
foreach (var parameter in parameters.Keys)
ReportDiagnostic(context, parameter);
}
}
private static bool IdentifierRefersToParam(IdentifierNameSyntax iName, ParameterSyntax param)
{
if (iName.Identifier.ToString() != param.Identifier.ToString())
return false;
var mae = iName.Parent as MemberAccessExpressionSyntax;
if (mae == null)
return true;
return mae.DescendantNodes().FirstOrDefault() == iName;
}
private static bool IsCandidateForRemoval(BaseMethodDeclarationSyntax methodOrConstructor, SemanticModel semanticModel)
{
if (methodOrConstructor.Modifiers.Any(m => m.ValueText == "partial" || m.ValueText == "override" || m.ValueText == "abstract" || m.ValueText == "extern")
|| !methodOrConstructor.ParameterList.Parameters.Any())
return false;
var method = methodOrConstructor as MethodDeclarationSyntax;
if (method != null)
{
if (method.ExplicitInterfaceSpecifier != null) return false;
var methodSymbol = semanticModel.GetDeclaredSymbol(method);
if (methodSymbol == null) return false;
var typeSymbol = methodSymbol.ContainingType;
if (typeSymbol.AllInterfaces.SelectMany(i => i.GetMembers())
.Any(member => methodSymbol.Equals(typeSymbol.FindImplementationForInterfaceMember(member))))
return false;
if (IsEventHandlerLike(method, semanticModel)) return false;
if (IsPrivateAndUsedAsMethodGroup(method, methodSymbol, semanticModel)) return false;
if (method.Parent is InterfaceDeclarationSyntax) return false;
}
else
{
var constructor = methodOrConstructor as ConstructorDeclarationSyntax;
if (constructor != null)
{
if (IsSerializationConstructor(constructor, semanticModel)) return false;
}
else
{
return false;
}
}
return true;
}
private static bool IsPrivateAndUsedAsMethodGroup(MethodDeclarationSyntax method, IMethodSymbol methodSymbol, SemanticModel semanticModel)
{
if (methodSymbol.DeclaredAccessibility != Accessibility.Private) return false;
var parentType = method.Parent;
var allTokens = parentType.DescendantTokens();
var tokensThatMatch = from t in allTokens
let text = t.Text
where text == method.Identifier.Text
select t;
foreach (var token in tokensThatMatch)
{
var nodeSymbol = semanticModel.GetSymbolInfo(token.Parent).Symbol;
if (methodSymbol.Equals(nodeSymbol)) return true;
}
return false;
}
private static bool IsSerializationConstructor(ConstructorDeclarationSyntax constructor, SemanticModel semanticModel)
{
if (constructor.ParameterList.Parameters.Count != 2) return false;
var constructorSymbol = semanticModel.GetDeclaredSymbol(constructor);
var typeSymbol = constructorSymbol?.ContainingType;
if (!typeSymbol?.AllInterfaces.Any(i => i.ToString() == "System.Runtime.Serialization.ISerializable") ?? true) return false;
if (!typeSymbol.GetAttributes().Any(a => a.AttributeClass.ToString() == "System.SerializableAttribute")) return false;
var serializationInfoType = semanticModel.GetTypeInfo(constructor.ParameterList.Parameters[0].Type).Type as INamedTypeSymbol;
if (serializationInfoType == null) return false;
if (!serializationInfoType.AllBaseTypesAndSelf().Any(type => type.ToString() == "System.Runtime.Serialization.SerializationInfo"))
return false;
var streamingContextType = semanticModel.GetTypeInfo(constructor.ParameterList.Parameters[1].Type).Type as INamedTypeSymbol;
if (streamingContextType == null) return false;
return streamingContextType.AllBaseTypesAndSelf().Any(type => type.ToString() == "System.Runtime.Serialization.StreamingContext");
}
private static bool IsEventHandlerLike(MethodDeclarationSyntax method, SemanticModel semanticModel)
{
if (method.ParameterList.Parameters.Count != 2
|| method.ReturnType.ToString() != "void")
return false;
var senderType = semanticModel.GetTypeInfo(method.ParameterList.Parameters[0].Type).Type;
if (senderType.SpecialType != SpecialType.System_Object) return false;
var eventArgsType = semanticModel.GetTypeInfo(method.ParameterList.Parameters[1].Type).Type as INamedTypeSymbol;
if (eventArgsType == null) return false;
return eventArgsType.AllBaseTypesAndSelf().Any(type => type.ToString() == "System.EventArgs");
}
private static SyntaxNodeAnalysisContext ReportDiagnostic(SyntaxNodeAnalysisContext context, ParameterSyntax parameter)
{
var props = new Dictionary<string, string> { { "identifier", parameter.Identifier.Text } }.ToImmutableDictionary();
var diagnostic = Diagnostic.Create(Rule, parameter.GetLocation(), props, parameter.Identifier.ValueText);
context.ReportDiagnostic(diagnostic);
return context;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ClipperLib;
namespace PolygonizerLib
{
using Path = List<IntPoint>;
using Paths = List<List<IntPoint>>;
public enum Direction { N, NE, E, SE, S, SW, W, NW };
public class BitMatrix
{
public int width { get; private set; }
public int height { get; private set; }
public bool[] bits;
public BitMatrix(int width, int height)
{
this.width = width;
this.height = height;
this.bits = new bool[width * height];
}
public BitMatrix(int width, int height, bool[] bits) : this(width, height)
{
if (bits.Length != width * height) {
throw new ArgumentException("The length of array does not match given size", "bits");
}
Array.Copy(bits, this.bits, width * height);
}
public bool Equals(BitMatrix b)
{
int length = bits.Length;
if (b.bits.Length != length)
return false;
for (int i = 0; i < length; i++) {
if (bits[i] != b.bits[i])
return false;
}
return true;
}
public void Set(int x, int y, bool v)
{
bits[y * width + x] = v;
}
public void Set(IntPoint pos, bool v)
{
bits[pos.Y * width + pos.X] = v;
}
public bool Get(int x, int y)
{
return bits[y * width + x];
}
public bool Get(IntPoint pos)
{
return bits[pos.Y * width + pos.X];
}
/// <summary>
/// Search clockwise the next Moore neighbour point that is assigned true, handles the boundary.
/// </summary>
/// <returns>The neighbour.</returns>
/// <param name="center">Center point.</param>
/// <param name="origin">Origin must be a moore neighbour of the center. </param>
public IntPoint nextNeighbour(IntPoint center, IntPoint current, bool value=true)
{
if (width + height < 2)
throw new ArgumentException("Current BitMatrix is too small: " + width + "*" + height);
// check boundaries
// stored by N, E, S, W clockwise
bool[] bound = new bool[4];
bound[0] = (center.Y == 0);
bound[1] = (center.X == width - 1);
bound[2] = (center.Y == height - 1);
bound[3] = (center.X == 0);
Direction dir = getDirection(center, current);
int count = 0;
while (count < 9) {
switch (dir) {
case Direction.N:
if (bound[0])
goto case Direction.E;
else
dir = Direction.N;
break;
case Direction.NE:
if (bound[1])
goto case Direction.S;
if (bound[0])
dir = Direction.E;
else
dir = Direction.NE;
break;
case Direction.E:
if (bound[1])
goto case Direction.S;
else
dir = Direction.E;
break;
case Direction.SE:
if (bound[2])
goto case Direction.W;
if (bound[1])
dir = Direction.S;
else
dir = Direction.SE;
break;
case Direction.S:
if (bound[2])
goto case Direction.W;
else
dir = Direction.S;
break;
case Direction.SW:
if (bound[3])
goto case Direction.N;
if (bound[2])
dir = Direction.W;
else
dir = Direction.SW;
break;
case Direction.W:
if (bound[3])
goto case Direction.N;
else
dir = Direction.W;
break;
case Direction.NW:
if (bound[0])
goto case Direction.E;
if (bound[3])
dir = Direction.N;
else
dir = Direction.NW;
break;
}
current = gotoDirection(center, dir);
if (Get(current) == value) break;
dir = (Direction) (((int) dir + 1) % 8);
count++;
}
return count != 9 ? current : new IntPoint(-1, -1);
}
//
// public static Texture2D ToMonoBitmap(BitMatrix bMatrix)
// {
// int width = bMatrix.Width,
// height = bMatrix.Height;
// Texture2D bMap = new Texture2D(width, height);
// Color c;
// for (int y = 0; y < height; y++) {
// // loop through each pixel on current scanline
// for (int x = 0; x < width; x++) {
// c = bMatrix.Get(x, y) ? new Color(0,0,0) : new Color(255, 255, 255);
// // write bits into scanline buffer
// bMap.SetPixel(x, y, c);
// }
// }
//
// return bMap;
// }
/// <summary>
/// Gets the direction from p1 to one of its moore neighbour
/// </summary>
/// <returns>The direction.</returns>
/// <param name="p1">P1.</param>
/// <param name="p2">P2. Must be one of the moore neighbours of p1.</param>
public static Direction getDirection(IntPoint p1, IntPoint p2)
{
int offX = p2.X - p1.X,
offY = p2.Y - p1.Y;
switch (offY * 3 + offX) {
case -4:
return Direction.NW;
case -3:
return Direction.N;
case -2:
return Direction.NE;
case -1:
return Direction.W;
case 1:
return Direction.E;
case 2:
return Direction.SW;
case 3:
return Direction.S;
case 4:
return Direction.SE;
default:
throw new ArgumentException(String.Format("[{0},{1}] is not a moore neighbour of [{2},{3}]: ",p2.X,p2.Y,p1.X,p1.Y));
}
}
public static IntPoint gotoDirection(IntPoint p, Direction d)
{
switch (d) {
case Direction.N:
return new IntPoint(p.X, p.Y - 1);
case Direction.NE:
return new IntPoint(p.X + 1, p.Y - 1);
case Direction.E:
return new IntPoint(p.X + 1, p.Y);
case Direction.SE:
return new IntPoint(p.X + 1, p.Y + 1);
case Direction.S:
return new IntPoint(p.X, p.Y + 1);
case Direction.SW:
return new IntPoint(p.X - 1, p.Y + 1);
case Direction.W:
return new IntPoint(p.X - 1, p.Y);
case Direction.NW:
return new IntPoint(p.X - 1, p.Y - 1);
default:
throw new ArgumentException("Unknown Direction");
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/group_booking_method_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.TenancyConfig.RPC {
public static partial class GroupBookingMethodSvc
{
static readonly string __ServiceName = "holms.types.tenancy_config.rpc.GroupBookingMethodSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse> __Marshaller_GroupBookingSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.Uuid> __Marshaller_Uuid = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.Uuid.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> __Marshaller_GroupBookingMethod = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.GroupBookingMethod.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_GroupBookingSvcAllResponse);
static readonly grpc::Method<global::HOLMS.Types.Primitive.Uuid, global::HOLMS.Types.TenancyConfig.GroupBookingMethod> __Method_GetById = new grpc::Method<global::HOLMS.Types.Primitive.Uuid, global::HOLMS.Types.TenancyConfig.GroupBookingMethod>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_Uuid,
__Marshaller_GroupBookingMethod);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.TenancyConfig.GroupBookingMethod> __Method_Create = new grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.TenancyConfig.GroupBookingMethod>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_GroupBookingMethod,
__Marshaller_GroupBookingMethod);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.TenancyConfig.GroupBookingMethod> __Method_Update = new grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.TenancyConfig.GroupBookingMethod>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_GroupBookingMethod,
__Marshaller_GroupBookingMethod);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.TenancyConfig.GroupBookingMethod, global::HOLMS.Types.Primitive.ServerActionConfirmation>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_GroupBookingMethod,
__Marshaller_ServerActionConfirmation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.TenancyConfig.RPC.GroupBookingMethodSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of GroupBookingMethodSvc</summary>
public abstract partial class GroupBookingMethodSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> Create(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> Update(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for GroupBookingMethodSvc</summary>
public partial class GroupBookingMethodSvcClient : grpc::ClientBase<GroupBookingMethodSvcClient>
{
/// <summary>Creates a new client for GroupBookingMethodSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public GroupBookingMethodSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for GroupBookingMethodSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public GroupBookingMethodSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected GroupBookingMethodSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected GroupBookingMethodSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.GroupBookingSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod GetById(global::HOLMS.Types.Primitive.Uuid request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> GetByIdAsync(global::HOLMS.Types.Primitive.Uuid request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> GetByIdAsync(global::HOLMS.Types.Primitive.Uuid request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod Create(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod Create(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> CreateAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> CreateAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod Update(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.GroupBookingMethod Update(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> UpdateAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.GroupBookingMethod> UpdateAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.GroupBookingMethod request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override GroupBookingMethodSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new GroupBookingMethodSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(GroupBookingMethodSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#endregion
| |
using System;
using System.Xml;
using System.Xml.Schema;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Xml.XMLGen {
//To build substitutionGroups
internal class SubstitutionGroupWrapper {
XmlQualifiedName head;
ArrayList members = new ArrayList();
internal XmlQualifiedName Head {
get {
return head;
}
set {
head = value;
}
}
internal ArrayList Members {
get {
return members;
}
}
}
internal class XmlSampleGenerator {
private XmlSchemaSet schemaSet;
private XmlWriter writer;
private XmlResolver xmlResolver;
private InstanceElement instanceRoot;
private XmlQualifiedName rootElement;
private string rootTargetNamespace;
internal const string NsXsd = "http://www.w3.org/2001/XMLSchema";
internal const string NsXsi = "http://www.w3.org/2001/XMLSchema-instance";
internal const string NsXml = "http://www.w3.org/XML/1998/namespace";
internal XmlQualifiedName QnXsdAnyType = new XmlQualifiedName("anyType", NsXsd);
internal XmlQualifiedName XsdNil = new XmlQualifiedName("nil", NsXsi);
//Default options
private int maxThreshold = 5;
private int listLength = 3;
//To pick-up recursive element defs
private Hashtable elementTypesProcessed;
private Hashtable instanceElementsProcessed;
//Handle substitutionGroups
private Hashtable substitutionGroupsTable;
private XmlSchemaType AnyType;
internal int MaxThreshold {
get {
return maxThreshold;
}
set {
maxThreshold = value;
}
}
internal int ListLength {
get {
return listLength;
}
set {
listLength = value;
}
}
internal XmlResolver XmlResolver {
set {
xmlResolver = value;
}
}
internal XmlSampleGenerator(string url, XmlQualifiedName rootElem = null) : this(XmlSchema.Read(new XmlTextReader(url), new ValidationEventHandler(ValidationCallBack)), rootElem) {
}
internal XmlSampleGenerator(XmlSchema schema, XmlQualifiedName rootElem = null) {
if (schema == null) {
throw new Exception("Provided Schema is null. Xml cannot be generated.");
}
rootElement = rootElem;
schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
if (xmlResolver == null) {
xmlResolver = new XmlUrlResolver();
}
schemaSet.XmlResolver = xmlResolver;
schemaSet.Add(schema);
AnyType = XmlSchemaType.GetBuiltInComplexType(XmlTypeCode.Item);
}
internal XmlSampleGenerator(XmlSchemaSet schemaSet, XmlQualifiedName rootElem = null) {
if (schemaSet == null || schemaSet.Count == 0)
{
throw new Exception("Provided Schema set is empty. Xml cannot be generated.");
}
this.schemaSet = schemaSet;
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
if (xmlResolver == null) {
xmlResolver = new XmlUrlResolver();
}
schemaSet.XmlResolver = xmlResolver;
rootElement = rootElem;
AnyType = XmlSchemaType.GetBuiltInComplexType(XmlTypeCode.Item);
}
internal Dictionary<XmlQualifiedName, string> GenerateAll()
{
Dictionary<XmlQualifiedName, string> data = new Dictionary<XmlQualifiedName, string>();
elementTypesProcessed = new Hashtable();
schemaSet.Compile();
foreach (XmlQualifiedName s in schemaSet.GlobalElements.Names)
{
rootElement = s;
StringBuilder b = new StringBuilder();
this.writer = XmlWriter.Create(b);
if (ProcessSchemaSet())
{ //Only if valid schemas were loaded
if (instanceRoot != null)
{ //If found a root to generate XML
instanceElementsProcessed = new Hashtable();
ProcessInstanceTree(instanceRoot);
}
this.writer.Flush();
}
data.Add(s, b.ToString());
}
return data;
}
internal void WriteXml (XmlWriter writer) {
if (writer == null) {
throw new ArgumentNullException("writer");
}
this.writer = writer;
elementTypesProcessed = new Hashtable();
schemaSet.Compile();
if (ProcessSchemaSet()) { //Only if valid schemas were loaded
if (instanceRoot != null) { //If found a root to generate XML
instanceElementsProcessed = new Hashtable();
ProcessInstanceTree(instanceRoot);
}
this.writer.Flush();
}
}
private bool ProcessSchemaSet() {
//Add all the Elements from all schemas into the Elements table
if (schemaSet.IsCompiled) {
XmlSchemaElement schemaElem = null;
if (rootElement == null) {
rootElement = XmlQualifiedName.Empty;
}
schemaElem = schemaSet.GlobalElements[rootElement] as XmlSchemaElement;
if (schemaElem == null) { //If element by name is not found, Get first non-abstract root element
foreach(XmlSchemaElement elem1 in schemaSet.GlobalElements.Values) {
if (elem1.IsAbstract) {
continue;
}
schemaElem = elem1;
rootElement = schemaElem.QualifiedName;
break;
}
}
if (schemaElem != null) {
rootTargetNamespace = schemaElem.QualifiedName.Namespace;
GenerateElement(schemaElem, true, null, null);
}
else { //No root element found
Console.WriteLine("No root element was found, XML cannot be generated.");
}
return true;
}
return false;
}
private bool GenerateElement(XmlSchemaElement e, bool root, InstanceGroup parentElem, XmlSchemaAny any) {
XmlSchemaElement eGlobalDecl = e;
if (!e.RefName.IsEmpty) {
eGlobalDecl = (XmlSchemaElement)schemaSet.GlobalElements[e.QualifiedName];
}
if (!eGlobalDecl.IsAbstract) {
InstanceElement elem = (InstanceElement)elementTypesProcessed[eGlobalDecl];
if (elem != null) {
Debug.Assert(!root);
if (any == null && e.MinOccurs > 0) { //If not generating for any or optional ref to cyclic global element
decimal occurs = e.MaxOccurs;
if (e.MaxOccurs >= maxThreshold) {
occurs = maxThreshold;
}
if (e.MinOccurs > occurs) {
occurs = e.MinOccurs;
}
parentElem.AddChild(elem.Clone(occurs));
}
return false;
}
elem = new InstanceElement(eGlobalDecl.QualifiedName);
if(root) {
instanceRoot = elem;
}
else {
parentElem.AddChild(elem);
}
//Get minOccurs, maxOccurs alone from the current particle, everything else pick up from globalDecl
if (any != null) { //Element from any
elem.Occurs = any.MaxOccurs >= maxThreshold ? maxThreshold : any.MaxOccurs;
elem.Occurs = any.MinOccurs > elem.Occurs ? any.MinOccurs : elem.Occurs;
}
else {
elem.Occurs = e.MaxOccurs >= maxThreshold ? maxThreshold : e.MaxOccurs;
elem.Occurs = e.MinOccurs > elem.Occurs ? e.MinOccurs : elem.Occurs;
}
elem.DefaultValue = eGlobalDecl.DefaultValue;
elem.FixedValue = eGlobalDecl.FixedValue;
elem.IsNillable = eGlobalDecl.IsNillable;
if (eGlobalDecl.ElementSchemaType == AnyType) {
elem.ValueGenerator = XmlValueGenerator.AnyGenerator;
}
else {
XmlSchemaComplexType ct = eGlobalDecl.ElementSchemaType as XmlSchemaComplexType;
if (ct != null) {
elementTypesProcessed.Add(eGlobalDecl, elem);
if (!ct.IsAbstract) {
elem.IsMixed = ct.IsMixed;
ProcessComplexType(ct, elem);
}
else { // Ct is abstract, need to generate instance elements with xsi:type
XmlSchemaComplexType dt = GetDerivedType(ct);
if (dt != null) {
elem.XsiType = dt.QualifiedName;
ProcessComplexType(dt, elem);
}
}
}
else { //elementType is XmlSchemaSimpleType
elem.ValueGenerator = XmlValueGenerator.CreateGenerator(eGlobalDecl.ElementSchemaType.Datatype, listLength);
}
}
if (elem.ValueGenerator != null && elem.ValueGenerator.Prefix == null) {
elem.ValueGenerator.Prefix = elem.QualifiedName.Name;
}
return true;
} // End of e.IsAbstract
return false;
}
private void ProcessComplexType(XmlSchemaComplexType ct, InstanceElement elem) {
if (ct.ContentModel != null && ct.ContentModel is XmlSchemaSimpleContent) {
elem.ValueGenerator = XmlValueGenerator.CreateGenerator(ct.Datatype, listLength);
}
else {
GenerateParticle(ct.ContentTypeParticle, false, elem);
}
//Check for attribute wild card
if (ct.AttributeWildcard != null) {
GenerateAttributeWildCard(ct, elem);
}
//Check for attributes if simple/complex content
if (ct.AttributeUses.Count > 0) {
GenerateAttribute(ct.AttributeUses, elem);
}
}
private XmlSchemaComplexType GetDerivedType(XmlSchemaType baseType) { //To get derived type of an abstract type for xsi:type value in the instance
foreach(XmlSchemaType type in schemaSet.GlobalTypes.Values) {
XmlSchemaComplexType ct = type as XmlSchemaComplexType;
if (ct != null && !ct.IsAbstract && XmlSchemaType.IsDerivedFrom(ct, baseType, XmlSchemaDerivationMethod.None)) {
return ct;
}
}
return null;
}
private void GenerateAttributeWildCard(XmlSchemaComplexType ct, InstanceElement elem) {
char[] whitespace = new char[] {' ', '\t', '\n', '\r'};
InstanceAttribute attr = null;
XmlSchemaAttribute anyAttr = null;
XmlSchemaAnyAttribute attributeWildCard = ct.AttributeWildcard;
XmlSchemaObjectTable attributes = ct.AttributeUses;
string namespaceList = attributeWildCard.Namespace;
if (namespaceList == null) {
namespaceList = "##any";
}
if (attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Skip || attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Lax) {
if (namespaceList == "##any" || namespaceList == "##targetNamespace") {
attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", rootTargetNamespace));
}
else if (namespaceList == "##local") {
attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", string.Empty));
}
else if (namespaceList == "##other") {
attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", "otherNS"));
}
if (attr != null) {
attr.ValueGenerator = XmlValueGenerator.AnySimpleTypeGenerator;
elem.AddAttribute(attr);
return;
}
}
switch(namespaceList) {
case "##any" :
case "##targetNamespace" :
anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes);
break;
case "##other" :
XmlSchema anySchema = GetParentSchema(attributeWildCard);
anyAttr = GetAttributeFromNS(anySchema.TargetNamespace, true, attributes);
break;
case "##local" : //Shd get local elements in some schema
anyAttr = GetAttributeFromNS(string.Empty, attributes);
break;
default:
foreach(string ns in attributeWildCard.Namespace.Split(whitespace)) {
if (ns == "##local") {
anyAttr = GetAttributeFromNS(string.Empty, attributes);
}
else if (ns == "##targetNamespace") {
anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes);
}
else {
anyAttr = GetAttributeFromNS(ns, attributes);
}
if (anyAttr != null) { //Found match
break;
}
}
break;
}
if (anyAttr != null) {
GenerateInstanceAttribute(anyAttr, elem);
}
else { //Write comment in generated XML that match for wild card cd not be found.
if (elem.Comment.Length == 0) { //For multiple attribute wildcards in the same element, generate comment only once
elem.Comment.Append(" Attribute Wild card could not be matched. Generated XML may not be valid. ");
}
}
}
private XmlSchemaAttribute GetAttributeFromNS(string ns, XmlSchemaObjectTable attributes) {
return GetAttributeFromNS(ns, false, attributes);
}
private XmlSchemaAttribute GetAttributeFromNS(string ns, bool other, XmlSchemaObjectTable attributes) {
if (other) {
foreach(XmlSchemaAttribute attr in schemaSet.GlobalAttributes.Values) {
if (attr.QualifiedName.Namespace != ns && attr.QualifiedName.Namespace != string.Empty && attributes[attr.QualifiedName] == null) {
return attr;
}
}
}
else {
foreach(XmlSchemaAttribute attr in schemaSet.GlobalAttributes.Values) {
if (attr.QualifiedName.Namespace == ns && attributes[attr.QualifiedName] == null) {
return attr;
}
}
}
return null;
}
private void GenerateAttribute(XmlSchemaObjectTable attributes, InstanceElement elem) {
IDictionaryEnumerator ienum = attributes.GetEnumerator();
while (ienum.MoveNext()) {
if (ienum.Value is XmlSchemaAttribute) {
GenerateInstanceAttribute((XmlSchemaAttribute)ienum.Value, elem);
}
}
}
private void GenerateInstanceAttribute(XmlSchemaAttribute attr, InstanceElement elem) {
if (attr.Use == XmlSchemaUse.Prohibited || attr.AttributeSchemaType == null) {
return;
}
InstanceAttribute iAttr = new InstanceAttribute(attr.QualifiedName);
iAttr.DefaultValue = attr.DefaultValue;
iAttr.FixedValue = attr.FixedValue;
iAttr.AttrUse = attr.Use;
iAttr.ValueGenerator = XmlValueGenerator.CreateGenerator(attr.AttributeSchemaType.Datatype, listLength);
if (iAttr.ValueGenerator != null && iAttr.ValueGenerator.Prefix == null) {
iAttr.ValueGenerator.Prefix = iAttr.QualifiedName.Name;
}
elem.AddAttribute(iAttr);
}
private void GenerateParticle(XmlSchemaParticle particle, bool root, InstanceGroup iGrp) {
decimal max;
max = particle.MaxOccurs >= maxThreshold ? maxThreshold : particle.MaxOccurs;
max = particle.MinOccurs > max ? particle.MinOccurs : max;
if (particle is XmlSchemaSequence ) {
XmlSchemaSequence seq = (XmlSchemaSequence)particle;
InstanceGroup grp = new InstanceGroup();
grp.Occurs = max;
iGrp.AddChild(grp);
GenerateGroupBase(seq, grp);
}
else if (particle is XmlSchemaChoice) {
XmlSchemaChoice ch = (XmlSchemaChoice)particle;
if (ch.MaxOccurs == 1) {
XmlSchemaParticle pt = (XmlSchemaParticle)(ch.Items[0]);
GenerateParticle(pt, false, iGrp);
}
else {
InstanceGroup grp = new InstanceGroup();
grp.Occurs = max;
grp.IsChoice = true;
iGrp.AddChild(grp);
GenerateGroupBase(ch,grp);
}
}
else if (particle is XmlSchemaAll) {
GenerateAll((XmlSchemaAll)particle, iGrp);
}
else if (particle is XmlSchemaElement) {
XmlSchemaElement elem = particle as XmlSchemaElement;
XmlSchemaChoice ch = null;
if (!elem.RefName.IsEmpty) {
ch = GetSubstitutionChoice(elem);
}
if (ch != null) {
GenerateParticle(ch, false, iGrp);
}
else {
GenerateElement(elem, false, iGrp, null);
}
}
else if (particle is XmlSchemaAny && particle.MinOccurs > 0) { //Generate any only if we should
GenerateAny((XmlSchemaAny)particle, iGrp);
}
}
private void GenerateGroupBase(XmlSchemaGroupBase gBase, InstanceGroup grp) {
foreach(XmlSchemaParticle particle1 in gBase.Items) {
GenerateParticle(particle1, false, grp);
}
}
private void GenerateAll(XmlSchemaAll all, InstanceGroup grp) {
XmlSchemaParticle pt;
for (int i=all.Items.Count; i > 0; i--) {
pt = (XmlSchemaParticle)(all.Items[i-1]);
GenerateParticle(pt,false, grp);
}
}
private void GenerateAny(XmlSchemaAny any, InstanceGroup grp) {
InstanceElement parentElem = grp as InstanceElement;
char[] whitespace = new char[] {' ', '\t', '\n', '\r'};
InstanceElement elem = null;
XmlSchemaElement anyElem = null;
string namespaceList = any.Namespace;
if (namespaceList == null) { //no namespace defaults to "##any"
namespaceList = "##any";
}
if (any.ProcessContents == XmlSchemaContentProcessing.Skip || any.ProcessContents == XmlSchemaContentProcessing.Lax) {
if (namespaceList == "##any" || namespaceList == "##targetNamespace") {
elem = new InstanceElement(new XmlQualifiedName("any_element", rootTargetNamespace));
}
else if (namespaceList == "##local") {
elem = new InstanceElement(new XmlQualifiedName("any_element", string.Empty));
}
else if (namespaceList == "##other") {
elem = new InstanceElement(new XmlQualifiedName("any_element", "otherNS"));
}
if (elem != null) {
elem.ValueGenerator = XmlValueGenerator.AnyGenerator;
elem.Occurs = any.MaxOccurs >= maxThreshold ? maxThreshold : any.MaxOccurs;
elem.Occurs = any.MinOccurs > elem.Occurs ? any.MinOccurs : elem.Occurs;
grp.AddChild(elem);
return;
}
}
//ProcessContents = strict || namespaceList is actually a list of namespaces
switch(namespaceList) {
case "##any" :
case "##targetNamespace" :
anyElem = GetElementFromNS(rootTargetNamespace);
break;
case "##other" :
XmlSchema anySchema = GetParentSchema(any);
anyElem = GetElementFromNS(anySchema.TargetNamespace, true);
break;
case "##local" : //Shd get local elements in some schema
anyElem = GetElementFromNS(string.Empty);
break;
default:
foreach(string ns in namespaceList.Split(whitespace)) {
if (ns == "##targetNamespace") {
anyElem = GetElementFromNS(rootTargetNamespace);
}
else if (ns == "##local") {
anyElem = GetElementFromNS(string.Empty);
}
else {
anyElem = GetElementFromNS(ns);
}
if (anyElem != null) { //found a match
break;
}
}
break;
}
if (anyElem != null && GenerateElement(anyElem, false, grp, any)) {
return;
}
else { //Write comment in generated XML that match for wild card cd not be found.
if (parentElem == null) {
parentElem = GetParentInstanceElement(grp);
}
if (parentElem.Comment.Length == 0) { //For multiple wildcards in the same element, generate comment only once
parentElem.Comment.Append(" Element Wild card could not be matched. Generated XML may not be valid. ");
}
}
}
//For all of these methods, Shd i store the element the first time and reuse the same
//instead of looking up the hashtable again?
private XmlSchemaElement GetElementFromNS(string ns) {
return GetElementFromNS(ns, false);
}
private XmlSchemaElement GetElementFromNS(string ns, bool other) {
if (other) {
foreach(XmlSchemaElement elem in schemaSet.GlobalElements.Values) {
if(elem.QualifiedName.Namespace != ns && elem.QualifiedName.Namespace != string.Empty) {
return elem;
}
}
}
else {
foreach(XmlSchemaElement elem in schemaSet.GlobalElements.Values) {
if(elem.QualifiedName.Namespace == ns && !elem.QualifiedName.Equals(rootElement)) {
return elem;
}
}
}
return null;
}
private XmlSchema GetParentSchema(XmlSchemaObject currentSchemaObject) {
XmlSchema parentSchema = null;
//Debug.Assert((currentSchemaObject as XmlSchema) == null); //The current object should not be schema
while(parentSchema == null && currentSchemaObject != null) {
currentSchemaObject = currentSchemaObject.Parent;
parentSchema = currentSchemaObject as XmlSchema;
}
return parentSchema;
}
private InstanceElement GetParentInstanceElement(InstanceGroup grp) {
InstanceElement elem = grp as InstanceElement;
while (elem == null && grp != null) {
grp = grp.Parent;
elem = grp as InstanceElement;
}
return elem;
}
private void BuildSubstitutionGroups() {
foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values) {
XmlQualifiedName head = element.SubstitutionGroup;
if (!head.IsEmpty) {
if (substitutionGroupsTable == null) {
substitutionGroupsTable = new Hashtable();
}
SubstitutionGroupWrapper substitutionGroup = (SubstitutionGroupWrapper)substitutionGroupsTable[head];
if (substitutionGroup == null) {
substitutionGroup = new SubstitutionGroupWrapper();
substitutionGroup.Head = head;
substitutionGroupsTable.Add(head, substitutionGroup);
}
ArrayList members = substitutionGroup.Members;
if (!members.Contains(element)) { //Members might contain element if the same schema is included and imported through different paths. Imp, hence will be added to set directly
members.Add(element);
}
}
}
if (substitutionGroupsTable != null) { //There were subst grps in the schema
foreach(SubstitutionGroupWrapper substGroup in substitutionGroupsTable.Values) {
ResolveSubstitutionGroup(substGroup);
}
}
}
private void ResolveSubstitutionGroup(SubstitutionGroupWrapper substitutionGroup) {
ArrayList newMembers = null;
XmlSchemaElement headElement = (XmlSchemaElement)schemaSet.GlobalElements[substitutionGroup.Head];
if (substitutionGroup.Members.Contains(headElement)) {// already checked
return;
}
foreach (XmlSchemaElement element in substitutionGroup.Members) {
//Chain to other head's that are members of this head's substGroup
SubstitutionGroupWrapper g = (SubstitutionGroupWrapper)substitutionGroupsTable[element.QualifiedName];
if (g != null) {
ResolveSubstitutionGroup(g);
foreach (XmlSchemaElement element1 in g.Members) {
if (element1 != element) { //Exclude the head
if (newMembers == null) {
newMembers = new ArrayList();
}
newMembers.Add(element1);
}
}
}
}
if (newMembers != null) {
foreach (XmlSchemaElement newMember in newMembers) {
substitutionGroup.Members.Add(newMember);
}
}
substitutionGroup.Members.Add(headElement);
}
private XmlSchemaChoice GetSubstitutionChoice(XmlSchemaElement element) {
if (substitutionGroupsTable == null) {
BuildSubstitutionGroups();
}
if (substitutionGroupsTable != null) {
SubstitutionGroupWrapper substitutionGroup = (SubstitutionGroupWrapper)substitutionGroupsTable[element.QualifiedName];
if (substitutionGroup != null) { //Element is head of a substitutionGroup
XmlSchemaChoice choice = new XmlSchemaChoice();
foreach(XmlSchemaElement elem in substitutionGroup.Members) {
choice.Items.Add(elem);
}
XmlSchemaElement headElement = (XmlSchemaElement)schemaSet.GlobalElements[element.QualifiedName];
if (headElement.IsAbstract) { //Should not generate the abstract element
choice.Items.Remove(headElement);
}
choice.MinOccurs = element.MinOccurs;
choice.MaxOccurs = element.MaxOccurs;
return choice;
}
}
return null;
}
private void ProcessInstanceTree(InstanceElement rootElement) {
if (rootElement != null) {
instanceElementsProcessed.Add(rootElement, rootElement);
writer.WriteStartElement(rootElement.QualifiedName.Name, rootTargetNamespace);
writer.WriteAttributeString("xmlns", "xsi", null, NsXsi);
ProcessElementAttrs(rootElement);
ProcessComment(rootElement);
CheckIfMixed(rootElement);
if(rootElement.ValueGenerator != null) {
if (rootElement.IsFixed) {
writer.WriteString(rootElement.FixedValue);
}
else if(rootElement.HasDefault) {
writer.WriteString(rootElement.DefaultValue);
}
else {
writer.WriteString(rootElement.ValueGenerator.GenerateValue());
}
}
else {
InstanceGroup group = rootElement.Child;
while (group != null) {
ProcessGroup(group);
group = group.Sibling;
}
}
writer.WriteEndElement();
}
else {
writer.WriteComment("Schema did not lead to generation of a valid XML document");
}
}
private void ProcessGroup(InstanceGroup grp) {
if(grp is InstanceElement) {
ProcessElement((InstanceElement)grp);
}
else { //Its a group node of sequence or choice
if(!grp.IsChoice) {
for (int i=0; i < grp.Occurs; i++) {
InstanceGroup childGroup = grp.Child;
while (childGroup != null) {
ProcessGroup(childGroup);
childGroup = childGroup.Sibling;
}
}
}
else {
ProcessChoiceGroup(grp);
}
}
}
private void ProcessChoiceGroup(InstanceGroup grp) {
for (int i=0; i < grp.Occurs; i++) { //Cyclically iterate over the children of choice
ProcessGroup(grp.GetChild(i % grp.NoOfChildren));
}
}
private void ProcessElement(InstanceElement elem) {
if (instanceElementsProcessed[elem] != null) {
return;
}
instanceElementsProcessed.Add(elem, elem);
for (int i=0; i < elem.Occurs; i++) {
if (elem.IsNillable) {
writer.WriteComment("Optional");
}
writer.WriteStartElement(elem.QualifiedName.Name, elem.QualifiedName.Namespace);
ProcessElementAttrs(elem);
ProcessComment(elem);
CheckIfMixed(elem);
if (elem.IsNillable) {
//if (elem.GenNil)
//{
// WriteNillable();
// elem.GenNil = false;
// writer.WriteEndElement();
// continue;
//}
//else
//{
// elem.GenNil = true;
//}
}
if(elem.ValueGenerator != null) {
if (elem.IsFixed) {
writer.WriteString(elem.FixedValue);
}
else if(elem.HasDefault) {
writer.WriteString(elem.DefaultValue);
}
else {
writer.WriteString(elem.ValueGenerator.GenerateValue());
}
}
else {
InstanceGroup childGroup = elem.Child;
while (childGroup != null) {
ProcessGroup(childGroup);
childGroup = childGroup.Sibling;
}
}
writer.WriteEndElement();
}
instanceElementsProcessed.Remove(elem);
}
private void ProcessComment(InstanceElement elem) {
if (elem.Comment.Length > 0) {
writer.WriteComment(elem.Comment.ToString());
}
}
private void CheckIfMixed(InstanceElement mixedElem) {
if(mixedElem.IsMixed) {
writer.WriteString("text");
}
}
private void WriteNillable() {
writer.WriteStartAttribute(XsdNil.Name, XsdNil.Namespace);
writer.WriteString("true");
writer.WriteEndAttribute();
}
private void ProcessElementAttrs(InstanceElement elem) {
if(elem.XsiType != XmlQualifiedName.Empty) {
if (elem.XsiType.Namespace != string.Empty) {
writer.WriteStartAttribute("xsi", "type", null);
writer.WriteQualifiedName(elem.XsiType.Name, elem.XsiType.Namespace);
writer.WriteEndAttribute();
}
else {
writer.WriteAttributeString("xsi", "type", null, elem.XsiType.Name);
}
}
InstanceAttribute attr = elem.FirstAttribute;
while (attr != null) {
if (attr.AttrUse != XmlSchemaUse.Prohibited) {
if (attr.QualifiedName.Namespace == NsXml) {
writer.WriteStartAttribute("xml", attr.QualifiedName.Name, attr.QualifiedName.Namespace);
}
else {
writer.WriteStartAttribute(attr.QualifiedName.Name, attr.QualifiedName.Namespace);
}
if(attr.HasDefault && !(attr.ValueGenerator is Generator_QName)) {
writer.WriteString(attr.DefaultValue);
}
else if (attr.IsFixed) {
writer.WriteString(attr.FixedValue);
}
else {
writer.WriteString(attr.ValueGenerator.GenerateValue());
}
writer.WriteEndAttribute();
}
attr = attr.NextAttribute;
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs args) {
Console.WriteLine("Error in Schema - ");
Console.WriteLine(args.Message);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
namespace JesseJohnston
{
/// <summary>
/// A node in the filter expression tree. A node may be a terminal expression (i.e. property name, value, and relational operator)
/// or a sub-tree containing a logical operator, left and right terms.
/// </summary>
internal class FilterNode : IEnumerable<FilterNode>
{
#region Types
private class FilterNodeEnumerator : IEnumerator<FilterNode>
{
private FilterNode tree;
private FilterNode current;
private Stack<FilterNode> nodes = new Stack<FilterNode>();
public FilterNodeEnumerator(FilterNode tree)
{
this.tree = tree;
}
#region IEnumerator<FilterNode> Members
public FilterNode Current
{
get
{
if (this.current == null)
throw new InvalidOperationException("Current");
else
return this.current;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get { return ((IEnumerator<FilterNode>)this).Current; }
}
public bool MoveNext()
{
// Initially, current is null, so we traverse the left edge.
if (this.current == null)
{
this.current = this.tree;
if (this.current.left == null && this.current.right == null)
return true;
// don't return it; we want to go down the left side first.
}
else if (this.current.right != null)
{
this.current = this.current.right;
if (this.current.left == null && this.current.right == null)
return true;
// don't return it; we want to go down the left side first.
}
if (this.current.left != null)
{
while (this.current.left != null)
{
this.nodes.Push(this.current);
this.current = this.current.left;
}
return true;
}
else if (this.nodes.Count > 0)
{
this.current = this.nodes.Pop();
return true;
}
else
return false;
}
public void Reset()
{
this.current = null;
this.nodes.Clear();
}
#endregion
}
private enum TokenType
{
Term,
Relation,
Condition,
OpenParen,
CloseParen,
ResolvedExpression,
ResolvedNode
}
private class Token
{
private string term;
private LogicalOperator logOp;
private RelationalOperator relOp;
private RelationalExpression expr;
private FilterNode node;
private TokenType type;
public LogicalOperator Condition
{
get
{
if (type != TokenType.Condition)
throw new StrongTypingException("Token is not a condition.");
return logOp;
}
}
public RelationalOperator Relation
{
get
{
if (this.type != TokenType.Relation)
throw new StrongTypingException("Token is not a relation.");
return relOp;
}
}
public RelationalExpression ResolvedExpression
{
get
{
if (this.type != TokenType.ResolvedExpression)
throw new StrongTypingException("Token is not a resolved expression.");
return this.expr;
}
}
public FilterNode ResolvedNode
{
get
{
if (this.type != TokenType.ResolvedNode)
throw new StrongTypingException("Token is not a resolved node.");
return node;
}
}
public string Term
{
get
{
if (this.type != TokenType.Term)
throw new StrongTypingException("Token is not a term.");
return term;
}
}
public TokenType Type
{
get { return type; }
}
public Token(string term)
{
if (term == "(")
this.type = TokenType.OpenParen;
else if (term == ")")
this.type = TokenType.CloseParen;
else
{
this.type = TokenType.Term;
this.term = term;
}
}
public Token(LogicalOperator condition)
{
this.type = TokenType.Condition;
this.logOp = condition;
}
public Token(RelationalOperator relation)
{
this.type = TokenType.Relation;
this.relOp = relation;
}
public Token(RelationalExpression expression)
{
this.type = TokenType.ResolvedExpression;
this.expr = expression;
}
public Token(FilterNode node)
{
this.type = TokenType.ResolvedNode;
this.node = node;
}
}
private class Tokenizer : IEnumerable<Token>
{
private List<Token> tokens = new List<Token>();
private static Dictionary<string, LogicalOperator> logicalOps = new Dictionary<string,LogicalOperator>();
private static Dictionary<string, RelationalOperator> relationalOps = new Dictionary<string,RelationalOperator>();
private static List<string> multiCharRelationalOps = new List<string>();
static Tokenizer()
{
logicalOps.Add("And", LogicalOperator.And);
logicalOps.Add("Or", LogicalOperator.Or);
relationalOps.Add("=", RelationalOperator.Equal);
relationalOps.Add("==", RelationalOperator.Equal);
relationalOps.Add("!=", RelationalOperator.NotEqual);
relationalOps.Add("<>", RelationalOperator.NotEqual);
relationalOps.Add("<", RelationalOperator.Less);
relationalOps.Add("<=", RelationalOperator.LessEqual);
relationalOps.Add(">", RelationalOperator.Greater);
relationalOps.Add(">=", RelationalOperator.GreaterEqual);
foreach (string op in relationalOps.Keys)
{
if (op.Length > 1)
multiCharRelationalOps.Add(op);
}
}
public Tokenizer(string expression)
{
if (expression == null)
throw new ArgumentNullException("expression");
if (expression == "")
throw new ArgumentException("expression");
// Split into tokens delimited by spaces, relational operators, and parentheses. Remove extra spaces.
ICollection<string> parts = ExtractTokens(expression,
new char[] { ' ', '<', '>', '=', '!', '(', ')' },
new char[] { '<', '>', '=', '!', '(', ')' },
new char[] { '\'', '"' });
if (parts.Count == 0)
throw new ArgumentException("expression");
// Parse into tokens that are either operators, terms or a paren.
Token prevToken = null;
int parenCount = 0;
foreach (string part in parts)
{
Token t = null;
// Because a condition could also be the rvalue of a relation (e.g. State = OR), evaluate as a condition
// only if it does not follow a relational operator.
if (prevToken == null || prevToken.Type != TokenType.Relation)
{
foreach (KeyValuePair<string, LogicalOperator> pair in logicalOps)
{
if (string.Compare(part, pair.Key, true) == 0)
{
if (prevToken == null || (prevToken.Type != TokenType.Term && prevToken.Type != TokenType.CloseParen))
throw new ArgumentException("An operator must be preceded by an expression term or closing paren.", "expression");
t = new Token(pair.Value);
break;
}
}
}
if (t == null)
{
foreach (KeyValuePair<string, RelationalOperator> pair in relationalOps)
{
if (string.Compare(part, pair.Key, true) == 0)
{
if (prevToken == null || prevToken.Type != TokenType.Term)
throw new ArgumentException("An operator must be preceded by an expression term.", "expression");
t = new Token(pair.Value);
break;
}
}
}
if (t == null)
{
if (part == "(")
{
if (prevToken != null && prevToken.Type != TokenType.Condition && prevToken.Type != TokenType.Relation && prevToken.Type != TokenType.OpenParen)
throw new ArgumentException("An opening paren must be preceded by an operator or an opening paren.", "expression");
parenCount++;
}
else if (part == ")")
{
if (prevToken == null || (prevToken.Type != TokenType.Term && prevToken.Type != TokenType.CloseParen))
throw new ArgumentException("A closing paren must be preceded by an expression term or a closing paren.", "expression");
if (parenCount == 0)
throw new ArgumentException("Unbalanced parentheses.", "expression");
parenCount--;
}
else
{
if (prevToken != null && prevToken.Type != TokenType.Condition && prevToken.Type != TokenType.Relation && prevToken.Type != TokenType.OpenParen)
throw new ArgumentException("An expression term must be preceded by an operator or opening paren.", "expression");
}
t = new Token(part);
}
tokens.Add(t);
prevToken = t;
}
// The expression must end with a term or a closing paren.
Token last = tokens[tokens.Count - 1];
if (last.Type != TokenType.Term && last.Type != TokenType.CloseParen)
throw new ArgumentException("An expression must end in an expression term or a closing paren.", "expression");
// The expression must contain at least two terms and a relation.
int terms = 0;
int relations = 0;
foreach (Token t in tokens)
{
if (t.Type == TokenType.Term)
terms++;
else if (t.Type == TokenType.Relation)
relations++;
}
if (terms < 2 || relations == 0)
throw new ArgumentException("An expression must contain at least two terms and a relational operator.", "expression");
}
private ICollection<string> ExtractTokens(string expression, char[] delimiters, char[] delimitersIncludedAsTokens, char[] quotes)
{
List<string> tokens = new List<string>();
List<char> delims = new List<char>(delimiters); // delimiters
List<char> delimTokens = new List<char>(delimitersIncludedAsTokens); // delimiters which are also tokens
List<char> quoteChars = new List<char>(quotes);
int tokenStart = 0;
int tokenEnd = 0;
bool inQuote = false;
char prevQuote = ' ';
// Remove leading and trailing whitespace.
expression = expression.Trim();
for (int i = 0; i < expression.Length; i++)
{
char c = expression[i];
if (i == expression.Length - 1) // Remainder of string (not ending in a delimiter)
{
if (inQuote && c == prevQuote)
tokens.Add(expression.Substring(tokenStart, i - tokenStart));
else if (!delims.Contains(c) || delimTokens.Contains(c))
tokens.Add(expression.Substring(tokenStart));
}
else if (quoteChars.Contains(c)) // Quote found
{
if (inQuote)
{
if (c == prevQuote)
{
inQuote = false;
tokenEnd = i;
if (tokenEnd > tokenStart) // Non-empty?
tokens.Add(expression.Substring(tokenStart, tokenEnd - tokenStart));
tokenStart = i + 1; // Start parsing the next token
}
}
else
{
inQuote = true;
prevQuote = c;
tokenStart = i + 1; // Start parsing the next token
}
}
else if (!inQuote && delims.Contains(c)) // Delimiter found
{
tokenEnd = i;
if (tokenEnd > tokenStart) // Non-empty?
tokens.Add(expression.Substring(tokenStart, tokenEnd - tokenStart));
if (delimTokens.Contains(c)) // If the delimiter is also a token, add it to the token list
tokens.Add(new string(c, 1));
tokenStart = i + 1; // Start parsing the next token
}
}
// Coalesce adjacent operators that form a multi-character operator (e.g. <>, !=, ==)
string prevToken = "";
string[] tokenArray = tokens.ToArray();
int tokensRemoved = 0;
for (int j = 0; j < tokenArray.Length ; j++)
{
string token = tokenArray[j];
string compoundToken = prevToken + token;
if (multiCharRelationalOps.Contains(compoundToken))
{
int newPosition = j - 1 - tokensRemoved;
tokens.RemoveAt(newPosition);
tokens.RemoveAt(newPosition);
tokens.Insert(newPosition, compoundToken);
tokensRemoved++;
}
prevToken = token;
}
return tokens;
}
#region IEnumerable<Token> Members
public IEnumerator<Token> GetEnumerator()
{
return tokens.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)tokens).GetEnumerator();
}
#endregion
}
#endregion
private LogicalOperator op;
private RelationalExpression term;
private FilterNode left;
private FilterNode right;
private bool? evaluated;
public bool? Evaluated
{
get { return this.evaluated; }
}
public FilterNode Left
{
get { return this.left; }
}
public LogicalOperator Operator
{
get { return this.op; }
}
public FilterNode Right
{
get { return this.right; }
}
public RelationalExpression Term
{
get { return this.term; }
}
/// <summary>
/// Initializes a new instance of the <see cref="FilterNode"/> class that is a terminal node.
/// </summary>
/// <remarks>
/// A terminal node is a relational expression, and contains no child nodes.
/// </remarks>
/// <param name="term">The expression term.</param>
public FilterNode(RelationalExpression term)
{
if (term == null)
throw new ArgumentNullException("term");
this.term = term;
}
/// <summary>
/// Initializes a new instance of the <see cref="FilterNode"/> class that is not a terminal node.
/// </summary>
/// <param name="left">The left child node.</param>
/// <param name="right">The right node.</param>
/// <param name="op">The operator relating the child nodes.</param>
public FilterNode(FilterNode left, FilterNode right, LogicalOperator op)
{
if (left == null)
throw new ArgumentNullException("left");
if (right == null)
throw new ArgumentNullException("right");
if (op == LogicalOperator.None)
throw new ArgumentException("op");
this.left = left;
this.right = right;
this.op = op;
}
/// <summary>
/// Parses the specified text into a binary expression tree.
/// </summary>
/// <param name="expression">The expression text to parse.</param>
/// <returns></returns>
public static FilterNode Parse(string expression)
{
List<Token> tokens = new List<Token>(new Tokenizer(expression));
// Combine terms and relational operators into expressions.
while (true)
{
int evaluationIndex = -1;
for (int i = 0; i < tokens.Count; i++)
{
if (tokens[i].Type == TokenType.Relation)
{
evaluationIndex = i;
break;
}
}
if (evaluationIndex > -1)
{
RelationalExpression expr = new RelationalExpression(tokens[evaluationIndex - 1].Term,
tokens[evaluationIndex + 1].Term,
tokens[evaluationIndex].Relation);
tokens.RemoveAt(evaluationIndex - 1);
tokens.RemoveAt(evaluationIndex - 1);
tokens.RemoveAt(evaluationIndex - 1);
tokens.Insert(evaluationIndex - 1, new Token(expr));
// Remove parentheses surrounding a resolved expression.
if (evaluationIndex - 2 > -1 && tokens[evaluationIndex - 2].Type == TokenType.OpenParen &&
evaluationIndex < tokens.Count && tokens[evaluationIndex].Type == TokenType.CloseParen)
{
// New resolved expression is now at evaluationIndex - 1.
tokens.RemoveAt(evaluationIndex - 2);
// New resolved expression is now at evaluationIndex - 2.
tokens.RemoveAt(evaluationIndex - 1);
}
}
else
break;
}
// If the token list contains only a single relational expression, we can return a simple filter node based on that.
if (tokens.Count == 1 && tokens[0].Type == TokenType.ResolvedExpression)
return new FilterNode(tokens[0].ResolvedExpression);
// The token list now contains only RelationalExpressions, conditional operators (AND and OR) and parentheses.
// Combine the expressions and operators into nodes, prioritizing binding according to the natural order of precedence
// for boolean operators and parentheses.
Dictionary<LogicalOperator, int> operatorPriorities = new Dictionary<LogicalOperator, int>();
operatorPriorities.Add(LogicalOperator.Or, 1);
operatorPriorities.Add(LogicalOperator.And, 2);
int parenAddedPriority = operatorPriorities.Count;
while (true)
{
int contextPriority = 0;
int evaluationPriorityMax = -1;
int evaluationIndex = -1;
for (int i = 0; i < tokens.Count; i++)
{
TokenType type = tokens[i].Type;
if (type == TokenType.Condition)
{
int evaluationPriority = operatorPriorities[tokens[i].Condition] + contextPriority;
if (evaluationPriority > evaluationPriorityMax)
{
evaluationIndex = i;
evaluationPriorityMax = evaluationPriority;
}
}
else if (type == TokenType.OpenParen)
{
contextPriority += parenAddedPriority;
}
else if (type == TokenType.CloseParen)
{
contextPriority -= parenAddedPriority;
}
}
if (evaluationIndex > -1)
{
Token prevToken = tokens[evaluationIndex - 1];
Token nextToken = tokens[evaluationIndex + 1];
FilterNode nodeLeft = null;
FilterNode nodeRight = null;
// Tokens surrounding the AND or OR must now be either a relational expression or a resolved FilterNode.
if (prevToken.Type == TokenType.ResolvedExpression)
nodeLeft = new FilterNode(prevToken.ResolvedExpression);
else
nodeLeft = prevToken.ResolvedNode;
if (nextToken.Type == TokenType.ResolvedExpression)
nodeRight = new FilterNode(nextToken.ResolvedExpression);
else
nodeRight = nextToken.ResolvedNode;
FilterNode node = new FilterNode(nodeLeft, nodeRight, tokens[evaluationIndex].Condition);
tokens.RemoveAt(evaluationIndex - 1);
tokens.RemoveAt(evaluationIndex - 1);
tokens.RemoveAt(evaluationIndex - 1);
tokens.Insert(evaluationIndex - 1, new Token(node));
// Remove parentheses surrounding a resolved node.
if (evaluationIndex - 2 > -1 && tokens[evaluationIndex - 2].Type == TokenType.OpenParen &&
evaluationIndex < tokens.Count && tokens[evaluationIndex].Type == TokenType.CloseParen)
{
// New resolved node is now at evaluationIndex - 1.
tokens.RemoveAt(evaluationIndex - 2);
// New resolved node is now at evaluationIndex - 2.
tokens.RemoveAt(evaluationIndex - 1);
}
}
else
break;
}
// The token list should now contain a single FilterNode.
return tokens[0].ResolvedNode;
}
/// <summary>
/// Evaluates the current node and it's child nodes.
/// </summary>
/// <param name="evaluator">The delegate used to evaluate terminal nodes.</param>
/// <returns>True if the current node and it's children evaluate to true; false otherwise.</returns>
public bool Evaluate(ExpressionEvaluator evaluator)
{
FilterNode current = this;
Stack<FilterNode> nodes = new Stack<FilterNode>();
while (true)
{
// A terminal expression?
if (current.op == LogicalOperator.None)
{
current.evaluated = evaluator(current);
}
else
{
if (!current.left.evaluated.HasValue)
{
nodes.Push(current);
current = current.left;
continue;
}
if (!current.right.evaluated.HasValue)
{
nodes.Push(current);
current = current.right;
continue;
}
if (current.op == LogicalOperator.And)
current.evaluated = current.left.evaluated.Value && current.right.evaluated.Value;
else
current.evaluated = current.left.evaluated.Value || current.right.evaluated.Value;
}
if (nodes.Count > 0)
current = nodes.Pop();
else
return current.evaluated.Value;
}
}
/// <summary>
/// Resets the evaluation status for each node in the expression tree, so that it can be re-evaluated.
/// </summary>
public void Reset()
{
foreach (FilterNode node in this)
{
node.evaluated = null;
}
}
#region IEnumerable<FilterNode> Members
public IEnumerator<FilterNode> GetEnumerator()
{
return new FilterNodeEnumerator(this);
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<FilterNode>)this).GetEnumerator();
}
#endregion
}
internal delegate bool ExpressionEvaluator(FilterNode expression);
}
| |
using System;
using NUnit.Framework;
using SharpVectors.Dom.Css;
using System.Diagnostics;
using System.Drawing;
namespace SharpVectors.Dom.Css
{
[TestFixture]
public class CssTests
{
private CssXmlDocument doc;
private CssStyleSheet cssStyleSheet;
private CssStyleRule rule;
private CssStyleDeclaration colorRules;
private bool initDone = false;
#region Setup
[SetUp]
public void Init()
{
if(!initDone)
{
doc = new CssXmlDocument();
doc.AddStyleElement("http://www.w3.org/2000/svg", "style");
doc.Load("http://www.sharpvectors.org/tests/css_unittest_01.svg");
cssStyleSheet = (CssStyleSheet)doc.StyleSheets[0];
colorRules = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[4]).Style;
initDone = true;
}
}
#endregion
#region Basic structure tests
[Test]
public void TestStylesheets()
{
Assert.AreEqual(2, doc.StyleSheets.Length, "Number of stylesheets");
}
[Test]
public void TestCssStyleSheet()
{
Assert.IsTrue(doc.StyleSheets[0] is CssStyleSheet);
cssStyleSheet = (CssStyleSheet)doc.StyleSheets[0];
Assert.IsTrue(cssStyleSheet.AbsoluteHref.AbsolutePath.EndsWith("css_unittest_01.css"), "AbsoluteHref");
Assert.AreEqual(cssStyleSheet.Title, "Test title", "Title");
Assert.AreEqual("text/css", cssStyleSheet.Type);
Assert.AreEqual(false, cssStyleSheet.Disabled);
}
[Test]
public void TestCssRules()
{
Assert.AreEqual(16, cssStyleSheet.CssRules.Length, "CssRules.Length");
Assert.IsTrue(cssStyleSheet.CssRules[0] is CssStyleRule);
}
[Test]
public void TestCssStyleRule()
{
rule = (CssStyleRule)cssStyleSheet.CssRules[0];
Assert.IsNull(rule.ParentRule);
Assert.AreEqual("g", rule.SelectorText);
Assert.AreEqual("g{fill:#123456 !important;opacity:0.5;}", rule.CssText);
Assert.AreEqual(CssRuleType.StyleRule, rule.Type);
Assert.AreSame(cssStyleSheet, rule.ParentStyleSheet);
Assert.IsTrue(rule.Style is CssStyleDeclaration);
}
[Test]
public void TestCssStyleDeclaration()
{
rule = (CssStyleRule)cssStyleSheet.CssRules[0];
CssStyleDeclaration csd = (CssStyleDeclaration)rule.Style;
Assert.AreEqual("fill:#123456 !important;opacity:0.5;", csd.CssText);
Assert.AreEqual(2, csd.Length);
Assert.AreSame(rule, csd.ParentRule);
Assert.AreEqual("important", csd.GetPropertyPriority("fill"));
Assert.AreEqual("0.5", csd.GetPropertyValue("opacity"));
Assert.AreEqual("", csd.GetPropertyPriority("opacity"));
Assert.AreEqual("#123456", csd.GetPropertyValue("fill"));
csd.SetProperty("opacity", "0.8", "");
Assert.AreEqual("0.8", csd.GetPropertyValue("opacity"));
Assert.AreEqual("", csd.GetPropertyPriority("opacity"));
csd.SetProperty("opacity", "0.2", "important");
Assert.AreEqual("0.2", csd.GetPropertyValue("opacity"));
Assert.AreEqual("important", csd.GetPropertyPriority("opacity"));
Assert.AreEqual("0.2", csd.RemoveProperty("opacity"));
Assert.AreEqual(1, csd.Length);
csd.SetProperty("foo", "bar", "");
Assert.AreEqual("bar", csd.GetPropertyValue("foo"));
Assert.AreEqual(2, csd.Length);
// reset values
csd.RemoveProperty("foo");
csd.SetProperty("opacity", "0.5", "");
}
#endregion
#region Color tests
[Test]
public void TestColorLongHexValue()
{
CssValue val = (CssValue)colorRules.GetPropertyCssValue("longhex");
Assert.IsTrue(val is CssPrimitiveValue, "1");
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("longhex");
Assert.AreEqual("rgb(101,67,33)", primValue.CssText, "2");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "3");
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType, "4");
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(101, color.Red.GetFloatValue(CssPrimitiveType.Number), "5");
Assert.AreEqual(67, color.Green.GetFloatValue(CssPrimitiveType.Number), "6");
Assert.AreEqual(33, color.Blue.GetFloatValue(CssPrimitiveType.Number), "7");
Assert.AreEqual(ColorTranslator.FromHtml("#654321"), color.GdiColor, "8");
}
[Test]
public void TestColorShortHexValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("shorthex");
Assert.AreEqual("rgb(17,34,51)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(17, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(34, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(51, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorNameValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("name");
Assert.AreEqual("rgb(60,179,113)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(60, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(179, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(113, color.Blue.GetFloatValue(CssPrimitiveType.Number));
primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("grey-name");
color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(119, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(136, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(153, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorRgbAbsValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("rgbabs");
Assert.AreEqual("rgb(45,78,98)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(45, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(78, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(98, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
[Test]
public void TestColorRgbPercValue()
{
CssPrimitiveValue primValue = (CssPrimitiveValue)colorRules.GetPropertyCssValue("rgbperc");
Assert.AreEqual("rgb(59,115,171)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.RgbColor, primValue.PrimitiveType);
RgbColor color = (RgbColor)primValue.GetRgbColorValue();
Assert.AreEqual(0.23*255, color.Red.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(0.45*255, color.Green.GetFloatValue(CssPrimitiveType.Number));
Assert.AreEqual(0.67*255, color.Blue.GetFloatValue(CssPrimitiveType.Number));
}
#endregion
#region String tests
[Test]
public void TestStringValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[1]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("string");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("string");
Assert.AreEqual("\"a string\"", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.String, primValue.PrimitiveType);
string str = primValue.GetStringValue();
Assert.AreEqual("a string", str);
}
#endregion
#region rect tests
[Test]
public void TestRectValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[1]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("rect");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("rect");
Assert.AreEqual("rect(10cm 23px 45px 89px)", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Rect, primValue.PrimitiveType);
IRect rect = primValue.GetRectValue();
ICssPrimitiveValue rectValue = rect.Top;
Assert.AreEqual(100, rectValue.GetFloatValue(CssPrimitiveType.Mm));
Assert.AreEqual(CssPrimitiveType.Cm, rectValue.PrimitiveType);
rectValue = rect.Right;
Assert.AreEqual(23, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
rectValue = rect.Bottom;
Assert.AreEqual(45, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
rectValue = rect.Left;
Assert.AreEqual(89, rectValue.GetFloatValue(CssPrimitiveType.Px));
Assert.AreEqual(CssPrimitiveType.Px, rectValue.PrimitiveType);
}
#endregion
#region Float tests
[Test]
public void TestFloatPxValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-px");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-px");
Assert.AreEqual("12px", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Px, primValue.PrimitiveType);
double res = primValue.GetFloatValue(CssPrimitiveType.Px);
Assert.AreEqual(12, res);
}
[Test]
public void TestFloatUnitlessValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-unitless");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-unitless");
Assert.AreEqual("67", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Number, primValue.PrimitiveType);
double res = primValue.GetFloatValue(CssPrimitiveType.Number);
Assert.AreEqual(67, res);
}
[Test]
public void TestFloatCmValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-cm");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-cm");
Assert.AreEqual("10cm", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Cm, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Cm));
}
[Test]
public void TestFloatMmValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-mm");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-mm");
Assert.AreEqual("10mm", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.Mm, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Mm));
}
[Test]
public void TestFloatInValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-in");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-in");
Assert.AreEqual("10in", primValue.CssText);
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType);
Assert.AreEqual(CssPrimitiveType.In, primValue.PrimitiveType);
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.In));
}
[Test]
public void TestFloatPcValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-pc");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-pc");
Assert.AreEqual("10pc", primValue.CssText, "CssText");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "CssValueType");
Assert.AreEqual(CssPrimitiveType.Pc, primValue.PrimitiveType, "PrimitiveType");
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Pc), "To PC");
}
[Test]
public void TestFloatPtValue()
{
CssStyleDeclaration csd = (CssStyleDeclaration)((CssStyleRule)cssStyleSheet.CssRules[5]).Style;
CssValue val = (CssValue)csd.GetPropertyCssValue("float-pt");
Assert.IsTrue(val is CssPrimitiveValue);
CssPrimitiveValue primValue = (CssPrimitiveValue)csd.GetPropertyCssValue("float-pt");
Assert.AreEqual("10pt", primValue.CssText, "CssText");
Assert.AreEqual(CssValueType.PrimitiveValue, primValue.CssValueType, "CssValueType");
Assert.AreEqual(CssPrimitiveType.Pt, primValue.PrimitiveType, "PrimitiveType");
Assert.AreEqual(10, primValue.GetFloatValue(CssPrimitiveType.Pt), "To PC");
Assert.AreEqual(10/72D*2.54D, primValue.GetFloatValue(CssPrimitiveType.Cm), "To CM");
Assert.AreEqual(100/72D*2.54D, primValue.GetFloatValue(CssPrimitiveType.Mm), "To MM");
Assert.AreEqual(10/72D, primValue.GetFloatValue(CssPrimitiveType.In), "To IN");
Assert.AreEqual(10/12D, primValue.GetFloatValue(CssPrimitiveType.Pc), "To PT");
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Security;
using System.Security.Permissions;
using System.ServiceModel.Description;
delegate object InvokeDelegate(object target, object[] inputs, object[] outputs);
delegate IAsyncResult InvokeBeginDelegate(object target, object[] inputs, AsyncCallback asyncCallback, object state);
delegate object InvokeEndDelegate(object target, object[] outputs, IAsyncResult result);
delegate object CreateInstanceDelegate();
sealed class InvokerUtil
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that was produced within an assert.")]
[SecurityCritical]
CriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
public InvokerUtil()
{
helper = new CriticalHelper();
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.",
Safe = "Resultant delegate is self-contained and safe for general consumption, nothing else leaks.")]
[SecuritySafeCritical]
internal CreateInstanceDelegate GenerateCreateInstanceDelegate(Type type, ConstructorInfo constructor)
{
return helper.GenerateCreateInstanceDelegate(type, constructor);
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.",
Safe = "Resultant delegate is self-contained and safe for general consumption, parameter counts are safe, nothing else leaks.")]
[SecuritySafeCritical]
internal InvokeDelegate GenerateInvokeDelegate(MethodInfo method, out int inputParameterCount, out int outputParameterCount)
{
return helper.GenerateInvokeDelegate(method, out inputParameterCount, out outputParameterCount);
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.",
Safe = "Resultant delegate is self-contained and safe for general consumption, parameter counts are safe, nothing else leaks.")]
[SecuritySafeCritical]
internal InvokeBeginDelegate GenerateInvokeBeginDelegate(MethodInfo method, out int inputParameterCount)
{
return helper.GenerateInvokeBeginDelegate(method, out inputParameterCount);
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.",
Safe = "Resultant delegate is self-contained and safe for general consumption, parameter counts are safe, nothing else leaks.")]
[SecuritySafeCritical]
internal InvokeEndDelegate GenerateInvokeEndDelegate(MethodInfo method, out int outputParameterCount)
{
return helper.GenerateInvokeEndDelegate(method, out outputParameterCount);
}
[Fx.Tag.SecurityNote(Critical = "Handles all aspects of IL generation including initializing the DynamicMethod, which requires an elevation."
+ "Since the ILGenerator is created under an elevation, we lock down access to every aspect of the generation.")]
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
class CriticalHelper
{
static Type TypeOfObject = typeof(object);
CodeGenerator ilg;
internal CreateInstanceDelegate GenerateCreateInstanceDelegate(Type type, ConstructorInfo constructor)
{
bool requiresMemberAccess = !IsTypeVisible(type) || ConstructorRequiresMemberAccess(constructor);
this.ilg = new CodeGenerator();
try
{
ilg.BeginMethod("Create" + type.FullName, typeof(CreateInstanceDelegate), requiresMemberAccess);
}
catch (SecurityException securityException)
{
if (requiresMemberAccess && securityException.PermissionType.Equals(typeof(ReflectionPermission)))
{
DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustServiceCtorNotVisible,
type.FullName)));
}
else
{
throw;
}
}
if (type.IsValueType)
{
LocalBuilder instanceLocal = ilg.DeclareLocal(type, type.Name + "Instance");
ilg.LoadZeroValueIntoLocal(type, instanceLocal);
ilg.Load(instanceLocal);
}
else
{
ilg.New(constructor);
}
ilg.ConvertValue(type, ilg.CurrentMethod.ReturnType);
return (CreateInstanceDelegate)ilg.EndMethod();
}
internal InvokeDelegate GenerateInvokeDelegate(MethodInfo method, out int inputParameterCount, out int outputParameterCount)
{
bool requiresMemberAccess = MethodRequiresMemberAccess(method);
this.ilg = new CodeGenerator();
try
{
this.ilg.BeginMethod("SyncInvoke" + method.Name, typeof(InvokeDelegate), requiresMemberAccess);
}
catch (SecurityException securityException)
{
if (requiresMemberAccess && securityException.PermissionType.Equals(typeof(ReflectionPermission)))
{
DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustServiceMethodNotVisible,
method.DeclaringType.FullName,
method.Name)));
}
else
{
throw;
}
}
ArgBuilder targetArg = ilg.GetArg(0);
ArgBuilder inputParametersArg = ilg.GetArg(1);
ArgBuilder outputParametersArg = ilg.GetArg(2);
ParameterInfo[] parameters = method.GetParameters();
LocalBuilder returnLocal = ilg.DeclareLocal(ilg.CurrentMethod.ReturnType, "returnParam");
LocalBuilder[] parameterLocals = new LocalBuilder[parameters.Length];
DeclareParameterLocals(parameters, parameterLocals);
LoadInputParametersIntoLocals(parameters, parameterLocals, inputParametersArg, out inputParameterCount);
LoadTarget(targetArg, method.ReflectedType);
LoadParameters(parameters, parameterLocals);
InvokeMethod(method, returnLocal);
LoadOutputParametersIntoArray(parameters, parameterLocals, outputParametersArg, out outputParameterCount);
ilg.Load(returnLocal);
return (InvokeDelegate)this.ilg.EndMethod();
}
internal InvokeBeginDelegate GenerateInvokeBeginDelegate(MethodInfo method, out int inputParameterCount)
{
bool requiresMemberAccess = MethodRequiresMemberAccess(method);
this.ilg = new CodeGenerator();
try
{
this.ilg.BeginMethod("AsyncInvokeBegin" + method.Name, typeof(InvokeBeginDelegate), requiresMemberAccess);
}
catch (SecurityException securityException)
{
if (requiresMemberAccess && securityException.PermissionType.Equals(typeof(ReflectionPermission)))
{
DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustServiceMethodNotVisible,
method.DeclaringType.FullName,
method.Name)));
}
else
{
throw;
}
}
ArgBuilder targetArg = ilg.GetArg(0);
ArgBuilder inputParametersArg = ilg.GetArg(1);
ArgBuilder callbackArg = ilg.GetArg(2);
ArgBuilder stateArg = ilg.GetArg(3);
ParameterInfo[] parameters = method.GetParameters();
LocalBuilder returnLocal = ilg.DeclareLocal(ilg.CurrentMethod.ReturnType, "returnParam");
LocalBuilder[] parameterLocals = new LocalBuilder[parameters.Length - 2];
DeclareParameterLocals(parameters, parameterLocals);
LoadInputParametersIntoLocals(parameters, parameterLocals, inputParametersArg, out inputParameterCount);
LoadTarget(targetArg, method.ReflectedType);
LoadParameters(parameters, parameterLocals);
ilg.Load(callbackArg);
ilg.Load(stateArg);
InvokeMethod(method, returnLocal);
ilg.Load(returnLocal);
return (InvokeBeginDelegate)this.ilg.EndMethod();
}
internal InvokeEndDelegate GenerateInvokeEndDelegate(MethodInfo method, out int outputParameterCount)
{
bool requiresMemberAccess = MethodRequiresMemberAccess(method);
this.ilg = new CodeGenerator();
try
{
this.ilg.BeginMethod("AsyncInvokeEnd" + method.Name, typeof(InvokeEndDelegate), requiresMemberAccess);
}
catch (SecurityException securityException)
{
if (requiresMemberAccess && securityException.PermissionType.Equals(typeof(ReflectionPermission)))
{
DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustServiceMethodNotVisible,
method.DeclaringType.FullName,
method.Name)));
}
else
{
throw;
}
}
ArgBuilder targetArg = ilg.GetArg(0);
ArgBuilder outputParametersArg = ilg.GetArg(1);
ArgBuilder resultArg = ilg.GetArg(2);
ParameterInfo[] parameters = method.GetParameters();
LocalBuilder returnLocal = ilg.DeclareLocal(ilg.CurrentMethod.ReturnType, "returnParam");
LocalBuilder[] parameterLocals = new LocalBuilder[parameters.Length - 1];
DeclareParameterLocals(parameters, parameterLocals);
LoadZeroValueInputParametersIntoLocals(parameters, parameterLocals);
LoadTarget(targetArg, method.ReflectedType);
LoadParameters(parameters, parameterLocals);
ilg.Load(resultArg);
InvokeMethod(method, returnLocal);
LoadOutputParametersIntoArray(parameters, parameterLocals, outputParametersArg, out outputParameterCount);
ilg.Load(returnLocal);
return (InvokeEndDelegate)this.ilg.EndMethod();
}
void DeclareParameterLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals)
{
for (int i = 0; i < parameterLocals.Length; i++)
{
parameterLocals[i] = ilg.DeclareLocal(TypeLoader.GetParameterType(parameters[i]), "param" + i.ToString(CultureInfo.InvariantCulture));
}
}
void LoadInputParametersIntoLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals, ArgBuilder inputParametersArg, out int inputParameterCount)
{
inputParameterCount = 0;
for (int i = 0; i < parameterLocals.Length; i++)
{
if (ServiceReflector.FlowsIn(parameters[i]))
{
Type parameterType = parameterLocals[i].LocalType;
ilg.LoadArrayElement(inputParametersArg, inputParameterCount);
if (!parameterType.IsValueType)
{
ilg.ConvertValue(TypeOfObject, parameterType);
ilg.Store(parameterLocals[i]);
}
else
{
ilg.Dup();
ilg.If();
ilg.ConvertValue(TypeOfObject, parameterType);
ilg.Store(parameterLocals[i]);
ilg.Else();
ilg.Pop();
ilg.LoadZeroValueIntoLocal(parameterType, parameterLocals[i]);
ilg.EndIf();
}
inputParameterCount++;
}
}
}
void LoadZeroValueInputParametersIntoLocals(ParameterInfo[] parameters, LocalBuilder[] parameterLocals)
{
for (int i = 0; i < parameterLocals.Length; i++)
{
if (ServiceReflector.FlowsIn(parameters[i]))
{
ilg.LoadZeroValueIntoLocal(parameterLocals[i].LocalType, parameterLocals[i]);
}
}
}
void LoadTarget(ArgBuilder targetArg, Type targetType)
{
ilg.Load(targetArg);
ilg.ConvertValue(targetArg.ArgType, targetType);
if (targetType.IsValueType)
{
LocalBuilder targetLocal = ilg.DeclareLocal(targetType, "target");
ilg.Store(targetLocal);
ilg.LoadAddress(targetLocal);
}
}
void LoadParameters(ParameterInfo[] parameters, LocalBuilder[] parameterLocals)
{
for (int i = 0; i < parameterLocals.Length; i++)
{
if (parameters[i].ParameterType.IsByRef)
ilg.Ldloca(parameterLocals[i]);
else
ilg.Ldloc(parameterLocals[i]);
}
}
void InvokeMethod(MethodInfo method, LocalBuilder returnLocal)
{
ilg.Call(method);
if (method.ReturnType == typeof(void))
ilg.Load(null);
else
ilg.ConvertValue(method.ReturnType, ilg.CurrentMethod.ReturnType);
ilg.Store(returnLocal);
}
void LoadOutputParametersIntoArray(ParameterInfo[] parameters, LocalBuilder[] parameterLocals, ArgBuilder outputParametersArg, out int outputParameterCount)
{
outputParameterCount = 0;
for (int i = 0; i < parameterLocals.Length; i++)
{
if (ServiceReflector.FlowsOut(parameters[i]))
{
ilg.Load(outputParametersArg);
ilg.Load(outputParameterCount);
ilg.Load(parameterLocals[i]);
ilg.ConvertValue(parameterLocals[i].LocalType, TypeOfObject);
ilg.Stelem(TypeOfObject);
outputParameterCount++;
}
}
}
static bool IsTypeVisible(Type t)
{
if (t.Module == typeof(InvokerUtil).Module)
return true;
if (!t.IsVisible)
return false;
foreach (Type genericType in t.GetGenericArguments())
{
if (!genericType.IsGenericParameter && !IsTypeVisible(genericType))
return false;
}
return true;
}
static bool ConstructorRequiresMemberAccess(ConstructorInfo ctor)
{
return ctor != null && (!ctor.IsPublic || !IsTypeVisible(ctor.DeclaringType)) && ctor.Module != typeof(InvokerUtil).Module;
}
static bool MethodRequiresMemberAccess(MethodInfo method)
{
return method != null && (!method.IsPublic || !IsTypeVisible(method.DeclaringType)) && method.Module != typeof(InvokerUtil).Module;
}
}
}
}
| |
using IrcClientCore;
using OpenGraph_Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using WinIRC.Net;
using WinIRC.Views;
using WinIRC.Views.InlineViewers;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace WinIRC.Ui
{
public sealed partial class MessageLineInner : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register(
"MessageItem",
typeof(Message),
typeof(MessageLine),
new PropertyMetadata(null));
private HyperlinkManager hyperlinkManager;
private Uri lastUri;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Username
{
get
{
if (MessageItem == null) return "";
var user = MessageItem.User ?? "";
if (user.Contains("*"))
{
return "*";
}
if (MessageItem.Type == MessageType.Normal)
{
return String.Format("{0}", user);
}
else if (MessageItem.Type == MessageType.Notice)
{
return String.Format("->{0}<-", user);
}
else
{
return String.Format("* {0}", user);
}
}
}
public bool HasLoaded { get; private set; }
public Message MessageItem
{
get { return (Message)GetValue(MessageProperty); }
set
{
SetValue(MessageProperty, value);
NotifyPropertyChanged("MessageItem");
NotifyPropertyChanged("Username");
NotifyPropertyChanged("UserColorBrush");
NotifyPropertyChanged("MessageColor");
NotifyPropertyChanged("TextIndent");
NotifyPropertyChanged("JoinPart");
UpdateUi();
}
}
public Color MentionRed => ThemeColor(Colors.Red);
public bool JoinPart
{
get
{
return MessageItem.Type == MessageType.JoinPart;
}
}
public SolidColorBrush UserColorBrush
{
get
{
if (MessageItem == null) return null;
return new SolidColorBrush(UserColor);
}
}
public Color UserColor
{
get
{
if (MessageItem == null) return Colors.White;
var color = ThemeColor(ColorUtils.GenerateColor(MessageItem.User));
if (MessageItem.Mention)
{
return MentionRed;
}
return color;
}
}
public SolidColorBrush MessageColor
{
get
{
if (MessageItem == null) return null;
if (MessageItem.Mention)
{
return new SolidColorBrush(MentionRed);
}
Color defaultColor = Config.GetBoolean(Config.DarkTheme, true) ? Colors.White : Colors.Black;
return new SolidColorBrush(defaultColor);
}
}
public MessageLineInner() : this(null)
{
}
private Color ThemeColor(Color color)
{
if (Config.GetBoolean(Config.DarkTheme, true))
{
color = ColorUtils.ChangeColorBrightness(color, 0.2f);
}
else
{
color = ColorUtils.ChangeColorBrightness(color, -0.4f);
}
return color;
}
public MessageLineInner(Message line)
{
this.InitializeComponent();
this.MessageItem = line;
Unloaded += MessageLine_Unloaded;
Loaded += MessageLine_Loaded;
LayoutUpdated += MessageLine_LayoutUpdated;
MainPage.instance.UiUpdated += Instance_UiUpdated;
}
private void Instance_UiUpdated(object sender, EventArgs e)
{
UpdateUi();
NotifyPropertyChanged("UserColor");
NotifyPropertyChanged("MessageColor");
}
private void MessageLine_LayoutUpdated(object sender, object e)
{
var wantedPadding = UsernameBox.ActualWidth + TimestampBox.ActualWidth;
if (MessageParagraph.TextIndent != wantedPadding)
{
MessageParagraph.TextIndent = wantedPadding;
}
}
private void MessageLine_Loaded(object sender, RoutedEventArgs e)
{
UpdateUi();
}
public void UpdateUi()
{
this.hyperlinkManager = new HyperlinkManager();
if (MessageItem != null)
{
PreviewFrame.Visibility = Visibility.Collapsed;
if (hyperlinkManager.LinkClicked != null)
{
hyperlinkManager.LinkClicked -= MediaPreview_Clicked;
}
if (MessageItem.Type == MessageType.Info || MessageItem.Type == MessageType.JoinPart)
{
MessageBox.Style = (Style)Application.Current.Resources["InfoTextRichStyle"];
}
else if (MessageItem.Type == MessageType.Action)
{
MessageBox.FontStyle = Windows.UI.Text.FontStyle.Italic;
}
if (MessageItem.Type == MessageType.MOTD)
{
this.FontFamily = new FontFamily("Consolas");
} else
{
this.FontFamily = new FontFamily(Config.GetString(Config.FontFamily, "Segoe UI"));
this.FontSize = Config.GetInt(Config.FontSize, 14);
}
hyperlinkManager.SetText(MessageParagraph, MessageItem.Text);
hyperlinkManager.LinkClicked += MediaPreview_Clicked;
}
try
{
if (!hyperlinkManager.InlineLink && hyperlinkManager.FirstLink != null && Config.GetBoolean(Config.ShowMetadata, true))
{
Task.Run(async () =>
{
var graph = await OpenGraph.ParseUrlAsync(hyperlinkManager.FirstLink);
if (graph.Values.Count > 0 && graph.Title != "" && graph["description"] != "")
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
PreviewFrame.Visibility = Visibility.Visible;
PreviewFrame.Navigate(typeof(LinkView), graph, new SuppressNavigationTransitionInfo());
});
}
});
}
}
catch { } // swallow exceptions
this.HasLoaded = true;
UpdateLayout();
}
private void MessageLine_Unloaded(object sender, RoutedEventArgs e)
{
PreviewFrame.Navigate(typeof(Page));
hyperlinkManager.SetText(MessageParagraph, "");
hyperlinkManager.LinkClicked -= MediaPreview_Clicked;
hyperlinkManager = null;
MainPage.instance.UiUpdated -= Instance_UiUpdated;
UpdateLayout();
}
private void MediaPreview_Clicked(Uri uri)
{
if (PreviewFrame.Visibility == Visibility.Collapsed)
{
PreviewFrame.Visibility = Visibility.Visible;
if (uri != lastUri)
{
if (uri.Host.Contains("twitter.com"))
PreviewFrame.Navigate(typeof(TwitterView), uri, new SuppressNavigationTransitionInfo());
else if (uri.Host.Contains("youtube.com") || uri.Host.Contains("youtu.be"))
PreviewFrame.Navigate(typeof(YoutubeView), uri, new SuppressNavigationTransitionInfo());
else if (HyperlinkManager.isImage(uri.ToString()))
PreviewFrame.Navigate(typeof(ImageView), uri, new SuppressNavigationTransitionInfo());
}
lastUri = uri;
}
else
{
PreviewFrame.Visibility = Visibility.Collapsed;
}
}
private void Share_Click(object sender, RoutedEventArgs e)
{
if (hyperlinkManager.FirstLink == null) return;
DataTransferManager.ShowShareUI();
DataTransferManager.GetForCurrentView().DataRequested += MessageLine_DataRequested;
}
private void MessageLine_DataRequested(Windows.ApplicationModel.DataTransfer.DataTransferManager sender, Windows.ApplicationModel.DataTransfer.DataRequestedEventArgs args)
{
args.Request.Data.SetWebLink(hyperlinkManager.FirstLink);
args.Request.Data.Properties.Title = Windows.ApplicationModel.Package.Current.DisplayName;
DataTransferManager.GetForCurrentView().DataRequested -= MessageLine_DataRequested;
}
private void Copy_Click(object sender, RoutedEventArgs e)
{
DataPackage dataPackage = new DataPackage
{
RequestedOperation = DataPackageOperation.Copy
};
dataPackage.SetText(hyperlinkManager.FirstLink.ToString());
Clipboard.SetContent(dataPackage);
}
private void PreviewFrame_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
ShareFlyout.ShowAt(sender as FrameworkElement);
}
}
}
| |
#region Header
// Revit MEP API sample application
//
// Copyright (C) 2007-2021 by Jeremy Tammik, Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software
// for any purpose and without fee is hereby granted, provided
// that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.
// AUTODESK, INC. DOES NOT WARRANT THAT THE OPERATION OF THE
// PROGRAM WILL BE UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject
// to restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
#endregion // Header
#region Namespaces
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
#endregion // Namespaces
namespace AdnRme
{
/// <summary>
/// This MEP sample demonstrates use of the generic and the MEP
/// specific parts of the Revit API for tasks in Revit MEP.
///
/// The following HVAC tasks are adressed using the generic API:
///
/// - determine air terminals for each space.
/// - assign flow to the air terminals depending on the space's calculated supply air flow.
/// - change size of diffuser, i.e. type, based on flow.
/// - populate the value of the 'CFM per SF' variable on all spaces.
/// - enter two element id's and create a 3D sectioned box view of their extents.
/// - determine unhosted elements (cf. SPR 134098).
/// - reset demo to original state.
///
/// CFM = cubic feet per second, SF = square feet.
/// Revit internal units are feet and seconds, so we need to multiply by 60 to get CFM.
///
/// The electrical conection hierarchy is determined and displayed in a tree view
/// using both the generic Revit API, based on parameters, and the MEP specific API,
/// based on connectors.
///
/// For Revit 2009, we implemented an external application demonstrating how to create
/// an own add-in menu. In Revit 2010, this was migrated to the ribbon and a custom panel.
/// One can also use RvtSamples from the Revit SDK Samples directory to load
/// this MEP sample, with the following additional entries in RvtSamples.txt:
///
/// ADN Rme
/// About...
/// About ADN RME API Samples
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdAbout
///
/// ADN Rme
/// Electrical System Browser
/// Inspect electrical systems in model and reproduce system browser info using parameter data only
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdElectricalSystemBrowser
///
/// #ADN Rme
/// #Electrical Hierarchy
/// #Inspect electrical systems in model and display full connection hierarchy tree structure
/// #LargeImage:
/// #Image:
/// #C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// #mep.CmdElectricalHierarchy
/// #
/// #ADN Rme
/// #Electrical Hierarchy 2
/// #Inspect electrical systems in model and display full connection hierarchy tree structure
/// #LargeImage:
/// #Image:
/// #C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// #mep.CmdElectricalHierarchy2
///
/// ADN Rme
/// Electrical Hierarchy Tree
/// Inspect electrical systems and connectors in model and display full hierarchy tree structure
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdElectricalConnectors
///
/// ADN Rme
/// HVAC Assign flow to terminals
/// Assign flow to terminals
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdAssignFlowToTerminals
///
/// ADN Rme
/// HVAC Change size
/// Change terminal sizes
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdChangeSize
///
/// ADN Rme
/// HVAC Populate CFM per SF on rooms
/// Populate CFM per SF variable on rooms
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdPopulateCfmPerSf
///
/// ADN Rme
/// HVAC Reset demo
/// Reset ADN RME API Demo
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdResetDemo
///
/// ADN Rme
/// Unhosted elements
/// List unhosted elementes
/// LargeImage:
/// Image:
/// C:\a\j\adn\train\revit\2011\src\rme\mep\bin\Debug\mep.dll
/// mep.CmdUnhostedElements
/// </summary>
class App : IExternalApplication
{
/// <summary>
/// Create a ribbon panel for the MEP sample application.
/// We present a column of three buttons: Electrical, HVAC and About.
/// The first two include subitems, the third does not.
/// </summary>
static void AddRibbonPanel(
UIControlledApplication a )
{
const int nElectricalCommands = 3;
const string m = "AdnRme.Cmd"; // namespace and command prefix
string path = Assembly.GetExecutingAssembly().Location;
string[] text = new string[] {
"Electrical Connectors",
"Electrical System Browser",
//"Electrical Hierarchy",
//"Electrical Hierarchy 2",
"Unhosted elements",
"Assign flow to terminals",
"Change size",
"Populate CFM per SF on spaces",
"Reset demo",
"About..."
};
string[] classNameStem = new string[] {
"ElectricalConnectors",
"ElectricalSystemBrowser",
//"ElectricalHierarchy",
//"ElectricalHierarchy2",
"UnhostedElements",
"AssignFlowToTerminals",
"ChangeSize",
"PopulateCfmPerSf",
"ResetDemo",
"About"
};
int n = classNameStem.Length;
Debug.Assert( text.Length == n,
"expected equal number of text and class name entries" );
// Create three stacked buttons for the HVAC,
// electrical and about commands, respectively:
RibbonPanel panel = a.CreateRibbonPanel(
"MEP Sample" );
PulldownButtonData d1 = new PulldownButtonData(
"Electrical", "Electrical" );
d1.ToolTip = "Electrical Commands";
PulldownButtonData d2 = new PulldownButtonData(
"Hvac", "HVAC" );
d2.ToolTip = "HVAC Commands";
n = n - 1;
PushButtonData d3 = new PushButtonData(
classNameStem[n], text[n], path, m + classNameStem[n] );
d3.ToolTip = "About the HVAC and Electrical MEP Sample.";
IList<RibbonItem> ribbonItems = panel.AddStackedItems(
d1, d2, d3 );
// Add subitems to the HVAC and
// electrical pulldown buttons:
PulldownButton pulldown;
PushButton pb;
int i, j;
for( i = 0; i < n; ++i )
{
j = i < nElectricalCommands ? 0 : 1;
pulldown = ribbonItems[j] as PulldownButton;
PushButtonData pbd = new PushButtonData(
text[i], text[i], path, m + classNameStem[i] );
pb = pulldown.AddPushButton( pbd );
pb.ToolTip = text[i];
}
}
public Result OnStartup( UIControlledApplication a )
{
// only create a new ribbon panel in Revit MEP:
ProductType pt = a.ControlledApplication.Product;
//if( ProductType.MEP == pt ) // 2012
if( ProductType.MEP == pt
|| ProductType.Revit == pt ) // 2013
{
AddRibbonPanel( a );
return Result.Succeeded;
}
return Result.Cancelled;
}
public Result OnShutdown( UIControlledApplication a )
{
return Result.Succeeded;
}
}
}
// C:\Program Files\Autodesk\Revit Architecture 2011\Program\Revit.exe
// C:\a\j\adn\train\revit\2011\src\rme\test\hvac_project.rvt
// C:\Program Files\Autodesk\Revit MEP 2011\Program\Revit.exe
// C:\a\j\adn\train\revit\2011\src\rme\test\elec_project.rvt
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using Avalonia.OpenGL;
using Avalonia.OpenGL.Egl;
using Avalonia.OpenGL.Surfaces;
using Avalonia.Platform.Interop;
using static Avalonia.LinuxFramebuffer.NativeUnsafeMethods;
using static Avalonia.LinuxFramebuffer.Output.LibDrm;
using static Avalonia.LinuxFramebuffer.Output.LibDrm.GbmColorFormats;
namespace Avalonia.LinuxFramebuffer.Output
{
public unsafe class DrmOutput : IGlOutputBackend, IGlPlatformSurface
{
private DrmCard _card;
private readonly EglGlPlatformSurface _eglPlatformSurface;
public PixelSize PixelSize => _mode.Resolution;
public double Scaling { get; set; }
public IGlContext PrimaryContext => _deferredContext;
private EglPlatformOpenGlInterface _platformGl;
public IPlatformOpenGlInterface PlatformOpenGlInterface => _platformGl;
public DrmOutput(string path = null)
{
var card = new DrmCard(path);
var resources = card.GetResources();
var connector =
resources.Connectors.FirstOrDefault(x => x.Connection == DrmModeConnection.DRM_MODE_CONNECTED);
if(connector == null)
throw new InvalidOperationException("Unable to find connected DRM connector");
var mode = connector.Modes.OrderByDescending(x => x.IsPreferred)
.ThenByDescending(x => x.Resolution.Width * x.Resolution.Height)
//.OrderByDescending(x => x.Resolution.Width * x.Resolution.Height)
.FirstOrDefault();
if(mode == null)
throw new InvalidOperationException("Unable to find a usable DRM mode");
Init(card, resources, connector, mode);
}
public DrmOutput(DrmCard card, DrmResources resources, DrmConnector connector, DrmModeInfo modeInfo)
{
Init(card, resources, connector, modeInfo);
}
[DllImport("libEGL.so.1")]
static extern IntPtr eglGetProcAddress(Utf8Buffer proc);
private GbmBoUserDataDestroyCallbackDelegate FbDestroyDelegate;
private drmModeModeInfo _mode;
private EglDisplay _eglDisplay;
private EglSurface _eglSurface;
private EglContext _deferredContext;
private IntPtr _currentBo;
private IntPtr _gbmTargetSurface;
private uint _crtcId;
void FbDestroyCallback(IntPtr bo, IntPtr userData)
{
drmModeRmFB(_card.Fd, userData.ToInt32());
}
uint GetFbIdForBo(IntPtr bo)
{
if (bo == IntPtr.Zero)
throw new ArgumentException("bo is 0");
var data = gbm_bo_get_user_data(bo);
if (data != IntPtr.Zero)
return (uint)data.ToInt32();
var w = gbm_bo_get_width(bo);
var h = gbm_bo_get_height(bo);
var stride = gbm_bo_get_stride(bo);
var handle = gbm_bo_get_handle(bo).u32;
var format = gbm_bo_get_format(bo);
// prepare for the new ioctl call
var handles = new uint[] {handle, 0, 0, 0};
var pitches = new uint[] {stride, 0, 0, 0};
var offsets = new uint[] {};
var ret = drmModeAddFB2(_card.Fd, w, h, format, handles, pitches,
offsets, out var fbHandle, 0);
if (ret != 0)
{
// legacy fallback
ret = drmModeAddFB(_card.Fd, w, h, 24, 32, stride, (uint)handle,
out fbHandle);
if (ret != 0)
throw new Win32Exception(ret, $"drmModeAddFb failed {ret}");
}
gbm_bo_set_user_data(bo, new IntPtr((int)fbHandle), FbDestroyDelegate);
return fbHandle;
}
void Init(DrmCard card, DrmResources resources, DrmConnector connector, DrmModeInfo modeInfo)
{
FbDestroyDelegate = FbDestroyCallback;
_card = card;
uint GetCrtc()
{
if (resources.Encoders.TryGetValue(connector.EncoderId, out var encoder))
{
// Not sure why that should work
return encoder.Encoder.crtc_id;
}
else
{
foreach (var encId in connector.EncoderIds)
{
if (resources.Encoders.TryGetValue(encId, out encoder)
&& encoder.PossibleCrtcs.Count>0)
return encoder.PossibleCrtcs.First().crtc_id;
}
throw new InvalidOperationException("Unable to find CRTC matching the desired mode");
}
}
_crtcId = GetCrtc();
var device = gbm_create_device(card.Fd);
_gbmTargetSurface = gbm_surface_create(device, modeInfo.Resolution.Width, modeInfo.Resolution.Height,
GbmColorFormats.GBM_FORMAT_XRGB8888, GbmBoFlags.GBM_BO_USE_SCANOUT | GbmBoFlags.GBM_BO_USE_RENDERING);
if(_gbmTargetSurface == null)
throw new InvalidOperationException("Unable to create GBM surface");
_eglDisplay = new EglDisplay(new EglInterface(eglGetProcAddress), false, 0x31D7, device, null);
_platformGl = new EglPlatformOpenGlInterface(_eglDisplay);
_eglSurface = _platformGl.CreateWindowSurface(_gbmTargetSurface);
_deferredContext = _platformGl.PrimaryEglContext;
using (_deferredContext.MakeCurrent(_eglSurface))
{
_deferredContext.GlInterface.ClearColor(0, 0, 0, 0);
_deferredContext.GlInterface.Clear(GlConsts.GL_COLOR_BUFFER_BIT | GlConsts.GL_STENCIL_BUFFER_BIT);
_eglSurface.SwapBuffers();
}
var bo = gbm_surface_lock_front_buffer(_gbmTargetSurface);
var fbId = GetFbIdForBo(bo);
var connectorId = connector.Id;
var mode = modeInfo.Mode;
var res = drmModeSetCrtc(_card.Fd, _crtcId, fbId, 0, 0, &connectorId, 1, &mode);
if (res != 0)
throw new Win32Exception(res, "drmModeSetCrtc failed");
_mode = mode;
_currentBo = bo;
// Go trough two cycles of buffer swapping (there are render artifacts otherwise)
for(var c=0;c<2;c++)
using (CreateGlRenderTarget().BeginDraw())
{
_deferredContext.GlInterface.ClearColor(0, 0, 0, 0);
_deferredContext.GlInterface.Clear(GlConsts.GL_COLOR_BUFFER_BIT | GlConsts.GL_STENCIL_BUFFER_BIT);
}
}
public IGlPlatformSurfaceRenderTarget CreateGlRenderTarget()
{
return new RenderTarget(this);
}
class RenderTarget : IGlPlatformSurfaceRenderTarget
{
private readonly DrmOutput _parent;
public RenderTarget(DrmOutput parent)
{
_parent = parent;
}
public void Dispose()
{
// We are wrapping GBM buffer chain associated with CRTC, and don't free it on a whim
}
class RenderSession : IGlPlatformSurfaceRenderingSession
{
private readonly DrmOutput _parent;
private readonly IDisposable _clearContext;
public RenderSession(DrmOutput parent, IDisposable clearContext)
{
_parent = parent;
_clearContext = clearContext;
}
public void Dispose()
{
_parent._deferredContext.GlInterface.Flush();
_parent._eglSurface.SwapBuffers();
var nextBo = gbm_surface_lock_front_buffer(_parent._gbmTargetSurface);
if (nextBo == IntPtr.Zero)
{
// Not sure what else can be done
Console.WriteLine("gbm_surface_lock_front_buffer failed");
}
else
{
var fb = _parent.GetFbIdForBo(nextBo);
bool waitingForFlip = true;
drmModePageFlip(_parent._card.Fd, _parent._crtcId, fb, DrmModePageFlip.Event, null);
DrmEventPageFlipHandlerDelegate flipCb =
(int fd, uint sequence, uint tv_sec, uint tv_usec, void* user_data) =>
{
waitingForFlip = false;
};
var cbHandle = GCHandle.Alloc(flipCb);
var ctx = new DrmEventContext
{
version = 4, page_flip_handler = Marshal.GetFunctionPointerForDelegate(flipCb)
};
while (waitingForFlip)
{
var pfd = new pollfd {events = 1, fd = _parent._card.Fd};
poll(&pfd, new IntPtr(1), -1);
drmHandleEvent(_parent._card.Fd, &ctx);
}
cbHandle.Free();
gbm_surface_release_buffer(_parent._gbmTargetSurface, _parent._currentBo);
_parent._currentBo = nextBo;
}
_clearContext.Dispose();
}
public IGlContext Context => _parent._deferredContext;
public PixelSize Size => _parent._mode.Resolution;
public double Scaling => _parent.Scaling;
public bool IsYFlipped { get; }
}
public IGlPlatformSurfaceRenderingSession BeginDraw()
{
return new RenderSession(_parent, _parent._deferredContext.MakeCurrent(_parent._eglSurface));
}
}
public IGlContext CreateContext()
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.InternalAbstractions;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.MultilevelSDKLookup
{
public class GivenThatICareAboutMultilevelSDKLookup : IDisposable
{
private static IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>()
{
{"COREHOST_TRACE", "1" },
// The SDK being used may be crossgen'd for a different architecture than we are building for.
// Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process.
{"COMPlus_ReadyToRun", "0" },
};
private RepoDirectoriesProvider RepoDirectories;
private TestProjectFixture PreviouslyBuiltAndRestoredPortableTestProjectFixture;
private string _currentWorkingDir;
private string _userDir;
private string _executableDir;
private string _cwdSdkBaseDir;
private string _userSdkBaseDir;
private string _exeSdkBaseDir;
private string _cwdSelectedMessage;
private string _userSelectedMessage;
private string _exeSelectedMessage;
private string _sdkDir;
private string _multilevelDir;
private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]";
public GivenThatICareAboutMultilevelSDKLookup()
{
// From the artifacts dir, it's possible to find where the sharedFrameworkPublish folder is. We need
// to locate it because we'll copy its contents into other folders
string artifactsDir = Environment.GetEnvironmentVariable("TEST_ARTIFACTS");
string builtDotnet = Path.Combine(artifactsDir, "sharedFrameworkPublish");
// The dotnetMultilevelSDKLookup dir will contain some folders and files that will be
// necessary to perform the tests
string baseMultilevelDir = Path.Combine(artifactsDir, "dotnetMultilevelSDKLookup");
_multilevelDir = SharedFramework.CalculateUniqueTestDirectory(baseMultilevelDir);
// The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported.
// All dirs will be placed inside the multilevel folder
_currentWorkingDir = Path.Combine(_multilevelDir, "cwd");
_userDir = Path.Combine(_multilevelDir, "user");
_executableDir = Path.Combine(_multilevelDir, "exe");
// It's necessary to copy the entire publish folder to the exe dir because
// we'll need to build from it. The CopyDirectory method automatically creates the dest dir
SharedFramework.CopyDirectory(builtDotnet, _executableDir);
RepoDirectories = new RepoDirectoriesProvider(builtDotnet: _executableDir);
// SdkBaseDirs contain all available version folders
_cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk");
_userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk");
_exeSdkBaseDir = Path.Combine(_executableDir, "sdk");
// Create directories
Directory.CreateDirectory(_cwdSdkBaseDir);
Directory.CreateDirectory(_userSdkBaseDir);
Directory.CreateDirectory(_exeSdkBaseDir);
// Restore and build PortableApp from exe dir
PreviouslyBuiltAndRestoredPortableTestProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories)
.EnsureRestored(RepoDirectories.CorehostPackages)
.BuildProject();
var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture;
// Set a dummy framework version (9999.0.0) in the exe sharedFx location. We will
// always pick the framework from this to avoid interference with the sharedFxLookup
string exeDirDummyFxVersion = Path.Combine(_executableDir, "shared", "Microsoft.NETCore.App", "9999.0.0");
string builtSharedFxDir = fixture.BuiltDotnet.GreatestVersionSharedFxPath;
SharedFramework.CopyDirectory(builtSharedFxDir, exeDirDummyFxVersion);
// The actual SDK version can be obtained from the built fixture. We'll use it to
// locate the sdkDir from which we can get the files contained in the version folder
string sdkBaseDir = Path.Combine(fixture.SdkDotnet.BinPath, "sdk");
var sdkVersionDirs = Directory.EnumerateDirectories(sdkBaseDir)
.Select(p => Path.GetFileName(p));
string greatestVersionSdk = sdkVersionDirs
.Where(p => !string.Equals(p, "NuGetFallbackFolder", StringComparison.OrdinalIgnoreCase))
.OrderByDescending(p => p.ToLower())
.First();
_sdkDir = Path.Combine(sdkBaseDir, greatestVersionSdk);
// Trace messages used to identify from which folder the SDK was picked
_cwdSelectedMessage = $"Using dotnet SDK dll=[{_cwdSdkBaseDir}";
_userSelectedMessage = $"Using dotnet SDK dll=[{_userSdkBaseDir}";
_exeSelectedMessage = $"Using dotnet SDK dll=[{_exeSdkBaseDir}";
}
public void Dispose()
{
PreviouslyBuiltAndRestoredPortableTestProjectFixture.Dispose();
if (!TestProject.PreserveTestRuns())
{
Directory.Delete(_multilevelDir, true);
}
}
[Fact]
public void SdkLookup_Global_Json_Single_Digit_Patch_Rollup()
{
var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
// Set specified CLI version = 9999.3.4-global-dummy
SetGlobalJsonVersion("SingleDigit-global.json");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: empty
// Expected: no compatible version and a specific error messages
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.HaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add some dummy versions
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy
// Expected: no compatible version and a specific error message
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.NotHaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.3");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3
// Expected: no compatible version and a specific error message
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.NotHaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4
// Expected: 9999.3.4 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.5-dummy");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy
// Expected: 9999.3.5-dummy from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600
// Expected: 9999.3.5-dummy from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy");
// Specified CLI version: 9999.3.4-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600, 9999.3.4-global-dummy
// Expected: 9999.3.4-global-dummy from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator));
// Verify we have the expected sdk versions
dotnet.Exec("--list-sdks")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.Execute()
.Should()
.Pass()
.And
.HaveStdOutContaining("9999.3.4-dummy")
.And
.HaveStdOutContaining("9999.3.4-global-dummy")
.And
.HaveStdOutContaining("9999.4.1")
.And
.HaveStdOutContaining("9999.3.3")
.And
.HaveStdOutContaining("9999.3.4")
.And
.HaveStdOutContaining("9999.3.600")
.And
.HaveStdOutContaining("9999.3.5-dummy");
}
[Fact]
public void SdkLookup_Global_Json_Two_Part_Patch_Rollup()
{
var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
// Set specified CLI version = 9999.3.304-global-dummy
SetGlobalJsonVersion("TwoPart-global.json");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: empty
// Expected: no compatible version and a specific error messages
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.HaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add some dummy versions
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.57", "9999.3.4-dummy");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.3.57, 9999.3.4-dummy
// Expected: no compatible version and a specific error message
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.NotHaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy
// Expected: no compatible version and a specific error message
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("A compatible installed dotnet SDK for global.json version")
.And
.NotHaveStdErrContaining("It was not possible to find any installed dotnet SDKs");
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 99999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304
// Expected: 9999.3.304 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400
// Expected: 9999.3.399 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400, 9999.3.3004");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004
// Expected: 9999.3.399 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator));
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304-global-dummy");
// Specified CLI version: 9999.3.304-global-dummy
// CWD: empty
// User: empty
// Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy
// Expected: 9999.3.304-global-dummy from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator));
// Verify we have the expected sdk versions
dotnet.Exec("--list-sdks")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.Execute()
.Should()
.Pass()
.And
.HaveStdOutContaining("9999.3.57")
.And
.HaveStdOutContaining("9999.3.4-dummy")
.And
.HaveStdOutContaining("9999.3.300")
.And
.HaveStdOutContaining("9999.7.304-global-dummy")
.And
.HaveStdOutContaining("9999.3.399")
.And
.HaveStdOutContaining("9999.3.399-dummy")
.And
.HaveStdOutContaining("9999.3.400")
.And
.HaveStdOutContaining("9999.3.2400")
.And
.HaveStdOutContaining("9999.3.3004")
.And
.HaveStdOutContaining("9999.3.304")
.And
.HaveStdOutContaining("9999.3.304-global-dummy");
}
[Fact]
public void SdkLookup_Negative_Version()
{
var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
// Add a negative CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "-1.-1.-1");
// Specified CLI version: none
// CWD: empty
// User: empty
// Exe: -1.-1.-1
// Expected: no compatible version and a specific error messages
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute(fExpectedToFail: true)
.Should()
.Fail()
.And
.HaveStdErrContaining("It was not possible to find any installed dotnet SDKs")
.And
.HaveStdErrContaining("Did you mean to run dotnet SDK commands? Please install dotnet SDK from");
// Add specified CLI version
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4");
// Specified CLI version: none
// CWD: empty
// User: empty
// Exe: -1.-1.-1, 9999.0.4
// Expected: 9999.0.4 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator));
// Verify we have the expected sdk versions
dotnet.Exec("--list-sdks")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0")
.CaptureStdOut()
.Execute()
.Should()
.Pass()
.And
.HaveStdOutContaining("9999.0.4");
}
[Fact]
public void SdkLookup_Must_Pick_The_Highest_Semantic_Version()
{
var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture
.Copy();
var dotnet = fixture.BuiltDotnet;
// Add dummy versions in the exe dir
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0", "9999.0.3-dummy");
// Specified CLI version: none
// CWD: empty
// User: empty
// Exe: 9999.0.0, 9999.0.3-dummy
// Expected: 9999.0.3-dummy from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3-dummy", _dotnetSdkDllMessageTerminator));
// Add dummy versions in the exe dir
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3");
// Specified CLI version: none
// CWD: empty
// User: empty
// Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3
// Expected: 9999.0.3 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator));
// Add dummy versions
AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200");
AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0");
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100");
// Specified CLI version: none
// CWD: 10000.0.0 --> should not be picked
// User: 9999.0.200 --> should not be picked
// Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100
// Expected: 9999.0.100 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator));
// Add a dummy version in the exe dir
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80");
// Specified CLI version: none
// CWD: 10000.0.0 --> should not be picked
// User: 9999.0.200 --> should not be picked
// Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80
// Expected: 9999.0.100 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator));
// Add a dummy version in the user dir
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000");
// Specified CLI version: none
// CWD: 10000.0.0 --> should not be picked
// User: 9999.0.200 --> should not be picked
// Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000
// Expected: 9999.0.5500000 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator));
// Add a dummy version in the user dir
AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.52000000");
// Specified CLI version: none
// CWD: 10000.0.0 --> should not be picked
// User: 9999.0.200 --> should not be picked
// Exe: 9999.0.0, 9999.0.3-dummy, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000, 9999.0.52000000
// Expected: 9999.0.5500000 from exe dir
dotnet.Exec("help")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.Pass()
.And
.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator));
// Verify we have the expected sdk versions
dotnet.Exec("--list-sdks")
.WorkingDirectory(_currentWorkingDir)
.WithUserProfile(_userDir)
.Environment(s_DefaultEnvironment)
.CaptureStdOut()
.Execute()
.Should()
.Pass()
.And
.HaveStdOutContaining("9999.0.0")
.And
.HaveStdOutContaining("9999.0.3-dummy")
.And
.HaveStdOutContaining("9999.0.3")
.And
.HaveStdOutContaining("9999.0.100")
.And
.HaveStdOutContaining("9999.0.80")
.And
.HaveStdOutContaining("9999.0.5500000")
.And
.HaveStdOutContaining("9999.0.52000000");
}
// This method adds a list of new sdk version folders in the specified
// sdkBaseDir. The files are copied from the _sdkDir. Also, the dotnet.runtimeconfig.json
// file is overwritten in order to use a dummy framework version (9999.0.0)
// Remarks:
// - If the sdkBaseDir does not exist, then a DirectoryNotFoundException
// is thrown.
// - If a specified version folder already exists, then it is deleted and replaced
// with the contents of the _builtSharedFxDir.
private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions)
{
DirectoryInfo sdkBaseDirInfo = new DirectoryInfo(sdkBaseDir);
if (!sdkBaseDirInfo.Exists)
{
throw new DirectoryNotFoundException();
}
string dummyRuntimeConfig = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils",
"SDKLookup", "dotnet.runtimeconfig.json");
foreach (string version in availableVersions)
{
string newSdkDir = Path.Combine(sdkBaseDir, version);
SharedFramework.CopyDirectory(_sdkDir, newSdkDir);
string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json");
File.Copy(dummyRuntimeConfig, runtimeConfig, true);
}
}
// Put a global.json file in the cwd in order to specify a CLI
public void SetGlobalJsonVersion(string globalJsonFileName)
{
string destFile = Path.Combine(_currentWorkingDir, "global.json");
string srcFile = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils",
"SDKLookup", globalJsonFileName);
File.Copy(srcFile, destFile, true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
/*=============================================================================
**
**
**
** Purpose: Class for creating and managing a thread.
**
**
=============================================================================*/
using Internal.Runtime.Augments;
namespace System.Threading
{
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
internal delegate Object InternalCrossContextDelegate(Object[] args);
internal class ThreadHelper
{
private Delegate _start;
private Object _startArg = null;
private ExecutionContext _executionContext = null;
internal ThreadHelper(Delegate start)
{
_start = start;
}
internal void SetExecutionContextHelper(ExecutionContext ec)
{
_executionContext = ec;
}
static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context);
static private void ThreadStart_Context(Object state)
{
ThreadHelper t = (ThreadHelper)state;
if (t._start is ThreadStart)
{
((ThreadStart)t._start)();
}
else
{
((ParameterizedThreadStart)t._start)(t._startArg);
}
}
// call back helper
internal void ThreadStart(object obj)
{
_startArg = obj;
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, _ccb, (Object)this);
}
else
{
((ParameterizedThreadStart)_start)(obj);
}
}
// call back helper
internal void ThreadStart()
{
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, _ccb, (Object)this);
}
else
{
((ThreadStart)_start)();
}
}
}
internal struct ThreadHandle
{
private IntPtr m_ptr;
internal ThreadHandle(IntPtr pThread)
{
m_ptr = pThread;
}
}
internal sealed class Thread : RuntimeThread
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** ThreadBaseObject to maintain alignment between the two classes.
** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h
=========================================================================*/
private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
private SynchronizationContext m_SynchronizationContext; // On CoreCLR, this is maintained separately from ExecutionContext
private String m_Name;
private Delegate m_Delegate; // Delegate
private Object m_ThreadStartArg;
/*=========================================================================
** The base implementation of Thread is all native. The following fields
** should never be used in the C# code. They are here to define the proper
** space so the thread object may be allocated. DON'T CHANGE THESE UNLESS
** YOU MODIFY ThreadBaseObject in vm\object.h
=========================================================================*/
#pragma warning disable 169
#pragma warning disable 414 // These fields are not used from managed.
// IntPtrs need to be together, and before ints, because IntPtrs are 64-bit
// fields on 64-bit platforms, where they will be sorted together.
private IntPtr DONT_USE_InternalThread; // Pointer
private int m_Priority; // INT32
// The following field is required for interop with the VS Debugger
// Prior to making any changes to this field, please reach out to the VS Debugger
// team to make sure that your changes are not going to prevent the debugger
// from working.
private int _managedThreadId; // INT32
#pragma warning restore 414
#pragma warning restore 169
private bool m_ExecutionContextBelongsToOuterScope;
#if DEBUG
private bool m_ForbidExecutionContextMutation;
#endif
// Do not move! Order of above fields needs to be preserved for alignment
// with native code
// See code:#threadCultureInfo
[ThreadStatic]
internal static CultureInfo m_CurrentCulture;
[ThreadStatic]
internal static CultureInfo m_CurrentUICulture;
// Adding an empty default ctor for annotation purposes
internal Thread() { }
/*=========================================================================
** Creates a new Thread object which will begin execution at
** start.ThreadStart on a new thread when the Start method is called.
**
** Exceptions: ArgumentNullException if start == null.
=========================================================================*/
public Thread(ThreadStart start)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0); //0 will setup Thread with default stackSize
}
internal Thread(ThreadStart start, int maxStackSize)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
public Thread(ParameterizedThreadStart start)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0);
}
internal Thread(ParameterizedThreadStart start, int maxStackSize)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
public override int GetHashCode()
{
return _managedThreadId;
}
extern public new int ManagedThreadId
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal unsafe ThreadHandle GetNativeHandle()
{
IntPtr thread = DONT_USE_InternalThread;
// This should never happen under normal circumstances. m_assembly is always assigned before it is handed out to the user.
// There are ways how to create an unitialized objects through remoting, etc. Avoid AVing in the EE by throwing a nice
// exception here.
if (thread.IsNull())
throw new ArgumentException(null, SR.Argument_InvalidHandle);
return new ThreadHandle(thread);
}
/*=========================================================================
** Spawns off a new thread which will begin executing at the ThreadStart
** method on the IThreadable interface passed in the constructor. Once the
** thread is dead, it cannot be restarted with another call to Start.
**
** Exceptions: ThreadStateException if the thread has already been started.
=========================================================================*/
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public new void Start()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Start(ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public new void Start(object parameter)
{
//In the case of a null delegate (second call to start on same thread)
// StartInternal method will take care of the error reporting
if (m_Delegate is ThreadStart)
{
//We expect the thread to be setup with a ParameterizedThreadStart
// if this constructor is called.
//If we got here then that wasn't the case
throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart);
}
m_ThreadStartArg = parameter;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Start(ref stackMark);
}
private void Start(ref StackCrawlMark stackMark)
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
// Eagerly initialize the COM Apartment state of the thread if we're allowed to.
StartupSetApartmentStateInternal();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
// Attach current thread's security principal object to the new
// thread. Be careful not to bind the current thread to a principal
// if it's not already bound.
if (m_Delegate != null)
{
// If we reach here with a null delegate, something is broken. But we'll let the StartInternal method take care of
// reporting an error. Just make sure we dont try to dereference a null delegate.
ThreadHelper t = (ThreadHelper)(m_Delegate.Target);
ExecutionContext ec = ExecutionContext.Capture();
t.SetExecutionContextHelper(ec);
}
StartInternal(ref stackMark);
}
internal ExecutionContext ExecutionContext
{
get { return m_ExecutionContext; }
set { m_ExecutionContext = value; }
}
internal SynchronizationContext SynchronizationContext
{
get { return m_SynchronizationContext; }
set { m_SynchronizationContext = value; }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartInternal(ref StackCrawlMark stackMark);
// Helper method to get a logical thread ID for StringBuilder (for
// correctness) and for FileStream's async code path (for perf, to
// avoid creating a Thread instance).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IntPtr InternalGetCurrentThread();
/*=========================================================================
** Suspends the current thread for timeout milliseconds. If timeout == 0,
** forces the thread to give up the remainer of its timeslice. If timeout
** == Timeout.Infinite, no timeout will occur.
**
** Exceptions: ArgumentException if timeout < 0.
** ThreadInterruptedException if the thread is interrupted while sleeping.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void SleepInternal(int millisecondsTimeout);
public static new void Sleep(int millisecondsTimeout)
{
SleepInternal(millisecondsTimeout);
}
public static void Sleep(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Sleep((int)tm);
}
/* wait for a length of time proportial to 'iterations'. Each iteration is should
only take a few machine instructions. Calling this API is preferable to coding
a explict busy loop because the hardware can be informed that it is busy waiting. */
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void SpinWaitInternal(int iterations);
public static new void SpinWait(int iterations)
{
SpinWaitInternal(iterations);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool YieldInternal();
internal static new bool Yield()
{
return YieldInternal();
}
public static new Thread CurrentThread
{
get
{
Contract.Ensures(Contract.Result<Thread>() != null);
return GetCurrentThreadNative();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern Thread GetCurrentThreadNative();
private void SetStartHelper(Delegate start, int maxStackSize)
{
Debug.Assert(maxStackSize >= 0);
ThreadHelper threadStartCallBack = new ThreadHelper(start);
if (start is ThreadStart)
{
SetStart(new ThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
}
else
{
SetStart(new ParameterizedThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
}
}
/*=========================================================================
** PRIVATE Sets the IThreadable interface for the thread. Assumes that
** start != null.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void SetStart(Delegate start, int maxStackSize);
/*=========================================================================
** Clean up the thread when it goes away.
=========================================================================*/
~Thread()
{
// Delegate to the unmanaged portion.
InternalFinalize();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void InternalFinalize();
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartupSetApartmentStateInternal();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
// #threadCultureInfo
//
// Background:
// In the desktop runtime, we allow a thread's cultures to travel with the thread
// across AppDomain boundaries. Furthermore we update the native thread with the
// culture of the managed thread. Because of security concerns and potential SxS
// effects, in Silverlight we are making the changes listed below.
//
// Silverlight Changes:
// - thread instance member cultures (CurrentCulture and CurrentUICulture)
// confined within AppDomains
// - changes to these properties don't affect the underlying native thread
//
// Implementation notes:
// In Silverlight, culture members thread static (per Thread, per AppDomain).
//
// Quirks:
// An interesting side-effect of isolating cultures within an AppDomain is that we
// now need to special case resource lookup for mscorlib, which transitions to the
// default domain to lookup resources. See Environment.cs for more details.
//
// As the culture can be customized object then we cannot hold any
// reference to it before we check if it is safe because the app domain
// owning this customized culture may get unloaded while executing this
// code. To achieve that we have to do the check using nativeGetSafeCulture
// as the thread cannot get interrupted during the FCALL.
// If the culture is safe (not customized or created in current app domain)
// then the FCALL will return a reference to that culture otherwise the
// FCALL will return failure. In case of failure we'll return the default culture.
// If the app domain owning a customized culture that is set to the thread and this
// app domain get unloaded there is a code to clean up the culture from the thread
// using the code in AppDomain::ReleaseDomainStores.
public CultureInfo CurrentUICulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return CultureInfo.CurrentUICulture;
}
set
{
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentUICulture.set.
if (m_CurrentUICulture == null && m_CurrentCulture == null)
nativeInitCultureAccessors();
CultureInfo.CurrentUICulture = value;
}
}
// This returns the exposed context for a given context ID.
// As the culture can be customized object then we cannot hold any
// reference to it before we check if it is safe because the app domain
// owning this customized culture may get unloaded while executing this
// code. To achieve that we have to do the check using nativeGetSafeCulture
// as the thread cannot get interrupted during the FCALL.
// If the culture is safe (not customized or created in current app domain)
// then the FCALL will return a reference to that culture otherwise the
// FCALL will return failure. In case of failure we'll return the default culture.
// If the app domain owning a customized culture that is set to the thread and this
// app domain get unloaded there is a code to clean up the culture from the thread
// using the code in AppDomain::ReleaseDomainStores.
public CultureInfo CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return CultureInfo.CurrentCulture;
}
set
{
Contract.EndContractBlock();
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentCulture.set.
if (m_CurrentCulture == null && m_CurrentUICulture == null)
nativeInitCultureAccessors();
CultureInfo.CurrentCulture = value;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nativeInitCultureAccessors();
/*======================================================================
** Returns the current domain in which current thread is running.
======================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AppDomain GetDomainInternal();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AppDomain GetFastDomainInternal();
internal static AppDomain GetDomain()
{
Contract.Ensures(Contract.Result<AppDomain>() != null);
AppDomain ad;
ad = GetFastDomainInternal();
if (ad == null)
ad = GetDomainInternal();
return ad;
}
/*
* This returns a unique id to identify an appdomain.
*/
internal static int GetDomainID()
{
return GetDomain().GetId();
}
// Retrieves the name of the thread.
//
public new String Name
{
get
{
return m_Name;
}
set
{
lock (this)
{
if (m_Name != null)
throw new InvalidOperationException(SR.InvalidOperation_WriteOnce);
m_Name = value;
InformThreadNameChange(GetNativeHandle(), value, (value != null) ? value.Length : 0);
}
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void InformThreadNameChange(ThreadHandle t, String name, int len);
} // End of class Thread
// declaring a local var of this enum type and passing it by ref into a function that needs to do a
// stack crawl will both prevent inlining of the calle and pass an ESP point to stack crawl to
// Declaring these in EH clauses is illegal; they must declared in the main method body
internal enum StackCrawlMark
{
LookForMe = 0,
LookForMyCaller = 1,
LookForMyCallersCaller = 2,
LookForThread = 3
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Adxstudio.Xrm.Forums;
using Adxstudio.Xrm.Performance;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Web.Mvc.Liquid;
using DotLiquid;
using DotLiquid.Exceptions;
using DotLiquid.NamingConventions;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Web.Mvc.Html
{
/// <summary>
/// Liquid Templating Extensions
/// </summary>
public static class LiquidExtensions
{
internal const bool LiquidEnabledDefault = true;
static LiquidExtensions()
{
// Call the DotLiquid.Liquid class's constructor first before registering our custom tags and filters.
// Need to do this because DotLiquid has (and may again in the future) introduce tags/filters with the
// same name as our custom ones. So we need to add ours AFTER in order for ours to take precedent.
InitializeDotLiquid();
Template.RegisterTag<Liquid.Tags.Editable>("editable");
Template.RegisterTag<Liquid.Tags.EntityList>("entitylist");
Template.RegisterTag<Liquid.Tags.EntityForm>("entityform");
Template.RegisterTag<Liquid.Tags.WebForm>("webform");
Template.RegisterTag<Liquid.Tags.EntityView>("entityview");
Template.RegisterTag<Liquid.Tags.FetchXml>("fetchxml");
Template.RegisterTag<Liquid.Tags.OutputCache>("outputcache");
Template.RegisterTag<Liquid.Tags.SearchIndex>("searchindex");
Template.RegisterTag<Liquid.Tags.Chart>("chart");
Template.RegisterTag<Liquid.Tags.Redirect>("redirect");
Template.RegisterTag<Liquid.Tags.Rating>("rating");
Template.RegisterTag<Liquid.Tags.Substitution>("substitution");
Template.RegisterFilter(typeof(Filters));
Template.RegisterFilter(typeof(DateFilters));
Template.RegisterFilter(typeof(EntityListFilters));
Template.RegisterFilter(typeof(EnumerableFilters));
Template.RegisterFilter(typeof(MathFilters));
Template.RegisterFilter(typeof(TypeFilters));
Template.RegisterFilter(typeof(StringFilters));
Template.RegisterFilter(typeof(NumberFormatFilters));
Template.RegisterFilter(typeof(UrlFilters));
Template.RegisterFilter(typeof(SearchFilterOptionFilters));
Template.NamingConvention = new InvariantCultureNamingConvention();
}
/// <summary>
/// Calls the constructor of DotLiquid.Liquid class.
/// </summary>
private static void InitializeDotLiquid()
{
// Force a call to the static constructor.
var temp = DotLiquid.Liquid.UseRubyDateFormat;
}
/// <summary>
/// Invariant Culture Naming convention for Liquid- For Turkish, the field "id" does not get mapped correctly to the .net property.
/// Using toLowerInvariant for member name check below fixes the problem
/// </summary>
private class InvariantCultureNamingConvention : INamingConvention
{
private readonly Regex _regex1 = new Regex(@"([A-Z]+)([A-Z][a-z])");
private readonly Regex _regex2 = new Regex(@"([a-z\d])([A-Z])");
public StringComparer StringComparer
{
get { return StringComparer.OrdinalIgnoreCase; }
}
public string GetMemberName(string name)
{
return _regex2.Replace(_regex1.Replace(name, "$1_$2"), "$1_$2").ToLowerInvariant();
}
}
private static IDictionary<string, Func<HtmlHelper, object>> _globalVariableFactories = new Dictionary<string, Func<HtmlHelper, object>>();
/// <summary>
/// Add a named variable value to be included in the global rendering scope.
/// </summary>
/// <param name="name">Variable name.</param>
/// <param name="factory">Delegate to create the Liquid drop object.</param>
public static void RegisterGlobalVariable(string name, Func<HtmlHelper, object> factory)
{
_globalVariableFactories[name] = factory;
}
private class LiquidEnvironment
{
public LiquidEnvironment(Hash globals, Hash registers)
{
if (globals == null) throw new ArgumentNullException("globals");
if (registers == null) throw new ArgumentNullException("registers");
Globals = globals;
Registers = registers;
}
public Hash Globals { get; private set; }
public Hash Registers { get; private set; }
}
private static LiquidEnvironment GetLiquidEnvironment(this HtmlHelper html)
{
const string environmentKey = "Adxstudio.Xrm.Web.Mvc.LiquidExtensions.GetLiquidEnvironment:Data";
LiquidEnvironment environment;
object data;
if (html.ViewContext.TempData.TryGetValue(environmentKey, out data))
{
environment = data as LiquidEnvironment;
if (environment != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Reusing Liquid environment.");
return environment;
}
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Creating new Liquid environment.");
var portal = PortalCrmConfigurationManager.CreatePortalContext();
var portalViewContext = PortalExtensions.GetPortalViewContext(html);
var portalLiquidContext = new PortalLiquidContext(html, portalViewContext);
var forumDependencies = new PortalContextDataAdapterDependencies(
portal,
new PaginatedLatestPostUrlProvider("page", html.IntegerSetting("Forums/PostsPerPage").GetValueOrDefault(20)));
var blogDependencies = new Blogs.PortalConfigurationDataAdapterDependencies();
var knowledgeDependencies = new KnowledgeArticles.PortalConfigurationDataAdapterDependencies();
var contextDrop = new PortalViewContextDrop(portalLiquidContext, forumDependencies);
var requestDrop = RequestDrop.FromHtmlHelper(portalLiquidContext, html);
var siteMapDrop = new SiteMapDrop(portalLiquidContext, portalViewContext.SiteMapProvider);
var globals = new Hash
{
{ "context", contextDrop },
{ "entities", new EntitiesDrop(portalLiquidContext) },
{ "now", DateTime.UtcNow },
{ "params", requestDrop == null ? null : requestDrop.Params },
{ "request", requestDrop },
{ "settings", new SettingsDrop(portalViewContext.Settings) },
{ "sharepoint", new SharePointDrop(portalLiquidContext) },
{ "sitemap", siteMapDrop },
{ "sitemarkers", new SiteMarkersDrop(portalLiquidContext, portalViewContext.SiteMarkers) },
{ "snippets", new SnippetsDrop(portalLiquidContext, portalViewContext.Snippets) },
{ "user", contextDrop.User },
{ "weblinks", new WebLinkSetsDrop(portalLiquidContext, portalViewContext.WebLinks) },
{ "ads", new AdsDrop(portalLiquidContext, portalViewContext.Ads) },
{ "polls", new PollsDrop(portalLiquidContext, portalViewContext.Polls) },
{ "forums", new ForumsDrop(portalLiquidContext, forumDependencies) },
{ "events", new EventsDrop(portalLiquidContext, forumDependencies) },
{ "blogs", new BlogsDrop(portalLiquidContext, blogDependencies) },
{ "website", contextDrop.Website },
{ "resx", new ResourceManagerDrop(portalLiquidContext) },
{ "knowledge", new KnowledgeDrop(portalLiquidContext, knowledgeDependencies) },
{ "uniqueId", new UniqueDrop() }
};
if (portalViewContext.Entity != null && siteMapDrop.Current != null)
{
globals["page"] = new PageDrop(portalLiquidContext, portalViewContext.Entity, siteMapDrop.Current);
}
foreach (var factory in _globalVariableFactories)
{
globals[factory.Key] = factory.Value(html);
}
environment = new LiquidEnvironment(globals, new Hash
{
{ "htmlHelper", html },
{ "file_system", new CompositeFileSystem(
new EntityFileSystem(portalViewContext, "adx_webtemplate", "adx_name", "adx_source"),
new EmbeddedResourceFileSystem(typeof(LiquidExtensions).Assembly, "Adxstudio.Xrm.Liquid")) },
{ "portalLiquidContext", portalLiquidContext }
});
html.ViewContext.TempData[environmentKey] = environment;
return environment;
}
/// <summary>
/// Given a <paramref name="webTemplateReference">Web Template (adx_webtemplate) reference</paramref>, render
/// its Source (adx_source) attribute as a Liquid template.
/// </summary>
/// <param name="html"></param>
/// <param name="webTemplateReference">The Web Template (adx_webtemplate) to render.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
/// <param name="fallback">Optional fallback function to execute in the case that <paramref name="webTemplateReference"/> is null, or the full entity is not found.</param>
public static string WebTemplate(this HtmlHelper html, EntityReference webTemplateReference, IDictionary<string, object> variables = null, Action fallback = null)
{
using (var output = new StringWriter())
{
RenderWebTemplate(html, webTemplateReference, output, variables, fallback);
return output.ToString();
}
}
/// <summary>
/// Given a <paramref name="webTemplateReference">Web Template (adx_webtemplate) reference</paramref>, render
/// its Source (adx_source) attribute as a Liquid template.
/// </summary>
/// <param name="html"></param>
/// <param name="webTemplateReference">The Web Template (adx_webtemplate) to render.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
/// <param name="fallback">Optional fallback function to execute in the case that <paramref name="webTemplateReference"/> is null, or the full entity is not found.</param>
public static void RenderWebTemplate(this HtmlHelper html, EntityReference webTemplateReference, IDictionary<string, object> variables = null, Action fallback = null)
{
RenderWebTemplate(html, webTemplateReference, html.ViewContext.Writer, variables, fallback);
}
/// <summary>
/// Given a <paramref name="webTemplateReference">Web Template (adx_webtemplate) reference</paramref>, render
/// its Source (adx_source) attribute as a Liquid template.
/// </summary>
/// <param name="html"></param>
/// <param name="webTemplateReference">The Web Template (adx_webtemplate) to render.</param>
/// <param name="output">Output to which rendered Liquid will be written.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
/// <param name="fallback">Optional fallback function to execute in the case that <paramref name="webTemplateReference"/> is null, or the full entity is not found.</param>
public static void RenderWebTemplate(this HtmlHelper html, EntityReference webTemplateReference, TextWriter output, IDictionary<string, object> variables = null, Action fallback = null)
{
if (webTemplateReference == null)
{
if (fallback != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No template reference provided, rendering fallback.");
fallback();
}
return;
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Rendering template {0}:{1}", webTemplateReference.LogicalName, webTemplateReference.Id));
var webTemplate = FetchWebTemplate(html, webTemplateReference.Id);
if (webTemplate == null)
{
if (fallback != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Template {0}:{1} not found, rendering fallback.", webTemplateReference.LogicalName, webTemplateReference.Id));
fallback();
}
return;
}
RenderLiquid(html, webTemplate.GetAttributeValue<string>("adx_source"), string.Format("{0}:{1}", webTemplateReference.LogicalName, webTemplateReference.Id), output, variables);
}
internal static string WebTemplate(this HtmlHelper html, EntityReference webTemplateReference, Context context)
{
if (webTemplateReference == null) throw new ArgumentNullException("webTemplateReference");
using (var output = new StringWriter())
{
RenderWebTemplate(html, webTemplateReference, output, context);
return output.ToString();
}
}
internal static void RenderWebTemplate(this HtmlHelper html, EntityReference webTemplateReference, TextWriter output, Context context)
{
if (webTemplateReference == null) throw new ArgumentNullException("webTemplateReference");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Rendering template {0}:{1}", webTemplateReference.LogicalName, webTemplateReference.Id));
var webTemplate = FetchWebTemplate(html, webTemplateReference.Id);
if (webTemplate == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Template {0}:{1} not found.", webTemplateReference.LogicalName, webTemplateReference.Id));
return;
}
InternalRenderLiquid(webTemplate.GetAttributeValue<string>("adx_source"), string.Format("{0}:{1}", webTemplateReference.LogicalName, webTemplateReference.Id), output, context);
}
/// <summary>
/// Fetches a web template with the given ID. Only attribute fetched is "adx_source". If none is found, null will be returned.
/// </summary>
/// <param name="html">Html context.</param>
/// <param name="webTemplateId">ID of the web template to fetch.</param>
/// <returns>Fetched web template entity.</returns>
private static Entity FetchWebTemplate(HtmlHelper html, Guid webTemplateId)
{
var fetch = new Fetch
{
Entity = new FetchEntity("adx_webtemplate")
{
Attributes = new[] { new FetchAttribute("adx_source") },
Filters = new[]
{
new Services.Query.Filter
{
Conditions = new[]
{
new Services.Query.Condition("adx_webtemplateid", ConditionOperator.Equal, webTemplateId),
new Services.Query.Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
};
var portalOrgService = html.ViewContext.HttpContext.GetOrganizationService();
var webTemplate = portalOrgService.RetrieveSingle(fetch);
return webTemplate;
}
/// <summary>
/// Render a Liquid template source string.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
/// <returns>Source string with Liquid tags and variables rendered.</returns>
public static string Liquid(this HtmlHelper html, IHtmlString source, IDictionary<string, object> variables = null)
{
return Liquid(html, source.ToString(), variables);
}
/// <summary>
/// Render a Liquid template source string.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
/// <returns>Source string with Liquid tags and variables rendered.</returns>
public static string Liquid(this HtmlHelper html, string source, IDictionary<string, object> variables = null)
{
using (var output = new StringWriter())
{
RenderLiquid(html, source, null, output, variables);
return output.ToString();
}
}
internal static string Liquid(this HtmlHelper html, string source, Context context)
{
using (var output = new StringWriter())
{
InternalRenderLiquid(source, null, output, context);
return output.ToString();
}
}
/// <summary>
/// Render a Liquid template source string to the current output stream.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
public static void RenderLiquid(this HtmlHelper html, IHtmlString source, IDictionary<string, object> variables = null)
{
RenderLiquid(html, source.ToString(), variables);
}
/// <summary>
/// Render a Liquid template source string to the current output stream.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
public static void RenderLiquid(this HtmlHelper html, string source, IDictionary<string, object> variables = null)
{
RenderLiquid(html, source, null, html.ViewContext.Writer, variables);
}
/// <summary>
/// Render a Liquid template source string to a given output stream.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="output">Output to which rendered Liquid will be written.</param>
/// <param name="variables">Named variable values to include in the global rendering scope.</param>
public static void RenderLiquid(this HtmlHelper html, string source, TextWriter output, object variables)
{
RenderLiquid(html, source, null, output, Hash.FromAnonymousObject(variables));
}
/// <summary>
/// Render a Liquid template source string to a given output stream.
/// </summary>
/// <param name="html"></param>
/// <param name="source">The Liquid template source string.</param>
/// <param name="sourceIdentifier">For telemetry purposes, optional string identifying what's being rendered.</param>
/// <param name="output">Output to which rendered Liquid will be written.</param>
/// <param name="variables">Optional named variable values to include in the global rendering scope.</param>
public static void RenderLiquid(this HtmlHelper html, string source, string sourceIdentifier, TextWriter output, IDictionary<string, object> variables = null)
{
if (string.IsNullOrEmpty(source))
{
return;
}
if (!html.BooleanSetting("Liquid/Enabled").GetValueOrDefault(true))
{
output.Write(source);
return;
}
var environment = html.GetLiquidEnvironment();
var localVariables = Hash.FromDictionary(environment.Globals);
if (variables != null)
{
localVariables.Merge(variables);
}
// Save a reference to this HtmlHelper to the liquid context so that any child "Donut Drops" can
// also access the same custom ViewBag information like "ViewSupportsDonuts".
var registers = Hash.FromDictionary(environment.Registers);
registers["htmlHelper"] = html;
var context = new Context(new List<Hash> { localVariables }, new Hash(), registers, false);
InternalRenderLiquid(source, sourceIdentifier, output, context);
}
/// <summary>
/// Actually use DotLiquid to render a liquid string into output.
/// </summary>
/// <param name="source">Liquid source to render.</param>
/// <param name="sourceIdentifier">For telemetry purposes, optional string identifying what's being rendered.</param>
/// <param name="output">TextWriter to render output to.</param>
/// <param name="context">DotLiquid context.</param>
private static void InternalRenderLiquid(string source, string sourceIdentifier, TextWriter output, Context context)
{
Template template;
if (!string.IsNullOrEmpty(sourceIdentifier))
{
sourceIdentifier = string.Format(" ({0})", sourceIdentifier);
}
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.LiquidExtension, PerformanceMarkerArea.Liquid, PerformanceMarkerTagName.LiquidSourceParsed))
{
template = Template.Parse(source);
}
}
catch (SyntaxException e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Liquid parse error{0}: {1}", sourceIdentifier, e.ToString()));
output.Write(e.Message);
return;
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Rendering Liquid{0}", sourceIdentifier));
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.LiquidExtension, PerformanceMarkerArea.Liquid, PerformanceMarkerTagName.RenderLiquid))
{
template.Render(output, RenderParameters.FromContext(context));
}
foreach (var error in template.Errors)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Liquid rendering error{0}: {1}", sourceIdentifier, error.ToString()));
}
}
}
}
| |
// 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.Runtime;
using System.Runtime.Serialization;
using System.Reflection;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class JsonDataContract
{
private JsonDataContractCriticalHelper _helper;
protected JsonDataContract(DataContract traditionalDataContract)
{
_helper = new JsonDataContractCriticalHelper(traditionalDataContract);
}
protected JsonDataContract(JsonDataContractCriticalHelper helper)
{
_helper = helper;
}
internal virtual string TypeName => null;
protected JsonDataContractCriticalHelper Helper => _helper;
protected DataContract TraditionalDataContract => _helper.TraditionalDataContract;
private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _helper.KnownDataContracts;
public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c)
{
// this method used to be rewritten by an IL transform
// with the restructuring for multi-file, this is no longer true - instead
// this has become a normal method
JsonReadWriteDelegates result;
#if NET_NATIVE
// The c passed in could be a clone which is different from the original key,
// We'll need to get the original key data contract from generated assembly.
DataContract keyDc = (c?.UnderlyingType != null) ?
DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType)
: null;
return (keyDc != null && JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result)) ? result : null;
#else
return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null;
#endif
}
internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
{
JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
if (result == null)
{
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString()));
}
else
{
return result;
}
}
internal static JsonReadWriteDelegates TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
{
JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
return result;
}
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
}
public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
PushKnownDataContracts(context);
object deserializedObject = ReadJsonValueCore(jsonReader, context);
PopKnownDataContracts(context);
return deserializedObject;
}
public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
return TraditionalDataContract.ReadXmlValue(jsonReader, context);
}
public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
PushKnownDataContracts(context);
WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
PopKnownDataContracts(context);
}
public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
}
protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString))
{
reader.Skip();
reader.MoveToElement();
return true;
}
reader.MoveToElement();
return false;
}
protected void PopKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Pop();
}
}
protected void PushKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Push(KnownDataContracts);
}
}
internal class JsonDataContractCriticalHelper
{
private static object s_cacheLock = new object();
private static object s_createDataContractLock = new object();
private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32];
private static int s_dataContractID = 0;
private static TypeHandleRef s_typeHandleRef = new TypeHandleRef();
private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts;
private DataContract _traditionalDataContract;
private string _typeName;
internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
{
_traditionalDataContract = traditionalDataContract;
AddCollectionItemContractsToKnownDataContracts();
_typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
}
internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _knownDataContracts;
internal DataContract TraditionalDataContract => _traditionalDataContract;
internal virtual string TypeName => _typeName;
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle);
JsonDataContract dataContract = s_dataContractCache[id];
if (dataContract == null)
{
dataContract = CreateJsonDataContract(id, traditionalDataContract);
s_dataContractCache[id] = dataContract;
}
return dataContract;
}
internal static int GetId(RuntimeTypeHandle typeHandle)
{
lock (s_cacheLock)
{
IntRef id;
s_typeHandleRef.Value = typeHandle;
if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id))
{
int value = s_dataContractID++;
if (value >= s_dataContractCache.Length)
{
int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
if (newSize <= value)
{
Fx.Assert("DataContract cache overflow");
throw new SerializationException(SR.DataContractCacheOverflow);
}
Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize);
}
id = new IntRef(value);
try
{
s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
}
}
return id.Value;
}
}
private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
{
lock (s_createDataContractLock)
{
JsonDataContract dataContract = s_dataContractCache[id];
if (dataContract == null)
{
Type traditionalDataContractType = traditionalDataContract.GetType();
if (traditionalDataContractType == typeof(ObjectDataContract))
{
dataContract = new JsonObjectDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(StringDataContract))
{
dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(UriDataContract))
{
dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(QNameDataContract))
{
dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ByteArrayDataContract))
{
dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
}
else if (traditionalDataContract.IsPrimitive ||
traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ClassDataContract))
{
dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(EnumDataContract))
{
dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
}
else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
(traditionalDataContractType == typeof(SpecialTypeDataContract)))
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(CollectionDataContract))
{
dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(XmlDataContract))
{
dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
}
else
{
throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract));
}
}
return dataContract;
}
}
private void AddCollectionItemContractsToKnownDataContracts()
{
if (_traditionalDataContract.KnownDataContracts != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts)
{
if (!object.ReferenceEquals(knownDataContract, null))
{
CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
if (_knownDataContracts == null)
{
_knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
}
if (!_knownDataContracts.ContainsKey(itemContract.StableName))
{
_knownDataContracts.Add(itemContract.StableName, itemContract);
}
if (collectionDataContract.ItemType.IsGenericType
&& collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GenericTypeArguments));
if (!_knownDataContracts.ContainsKey(itemDataContract.StableName))
{
_knownDataContracts.Add(itemDataContract.StableName, itemDataContract);
}
}
if (!(itemContract is CollectionDataContract))
{
break;
}
collectionDataContract = itemContract as CollectionDataContract;
}
}
}
}
}
}
}
#if NET_NATIVE
public class JsonReadWriteDelegates
#else
internal class JsonReadWriteDelegates
#endif
{
// this is the global dictionary for JSON delegates introduced for multi-file
private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>();
public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates()
{
return s_jsonDelegates;
}
public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; }
public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; }
public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; }
public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; }
public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; }
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipeWriterCopyToAsyncTests
{
[Fact]
public async Task CopyToAsyncThrowsArgumentNullExceptionForNullSource()
{
var pipe = new Pipe();
MemoryStream stream = null;
var ex = await Assert.ThrowsAsync<ArgumentNullException>(() => stream.CopyToAsync(pipe.Writer));
Assert.Equal("source", ex.ParamName);
}
[Fact]
public async Task CopyToAsyncThrowsArgumentNullExceptionForNullDestination()
{
var stream = new MemoryStream();
var ex = await Assert.ThrowsAsync<ArgumentNullException>(() => stream.CopyToAsync(null));
Assert.Equal("destination", ex.ParamName);
}
[Fact]
public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken()
{
var pipe = new Pipe();
await Assert.ThrowsAsync<TaskCanceledException>(() => new MemoryStream().CopyToAsync(pipe.Writer, new CancellationToken(true)));
}
[Fact]
public async Task CopyToAsyncWorks()
{
var helloBytes = Encoding.UTF8.GetBytes("Hello World");
var pipe = new Pipe();
var stream = new MemoryStream(helloBytes);
await stream.CopyToAsync(pipe.Writer);
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(helloBytes, result.Buffer.ToArray());
pipe.Reader.AdvanceTo(result.Buffer.End);
pipe.Reader.Complete();
pipe.Writer.Complete();
}
[Fact]
public async Task CopyToAsyncCalledMultipleTimesWorks()
{
var hello = "Hello World";
var helloBytes = Encoding.UTF8.GetBytes(hello);
var expected = Encoding.UTF8.GetBytes(hello + hello + hello);
var pipe = new Pipe();
await new MemoryStream(helloBytes).CopyToAsync(pipe.Writer);
await new MemoryStream(helloBytes).CopyToAsync(pipe.Writer);
await new MemoryStream(helloBytes).CopyToAsync(pipe.Writer);
pipe.Writer.Complete();
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(expected, result.Buffer.ToArray());
pipe.Reader.AdvanceTo(result.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
public async Task StreamCopyToAsyncWorks()
{
var helloBytes = Encoding.UTF8.GetBytes("Hello World");
var pipe = new Pipe();
var stream = new MemoryStream(helloBytes);
await stream.CopyToAsync(pipe.Writer);
ReadResult result = await pipe.Reader.ReadAsync();
Assert.Equal(helloBytes, result.Buffer.ToArray());
pipe.Reader.AdvanceTo(result.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
public async Task CancelingViaCancelPendingFlushThrows()
{
var helloBytes = Encoding.UTF8.GetBytes("Hello World");
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
var stream = new MemoryStream(helloBytes);
Task task = stream.CopyToAsync(pipe.Writer);
Assert.False(task.IsCompleted);
pipe.Writer.CancelPendingFlush();
await Assert.ThrowsAsync<OperationCanceledException>(() => task);
pipe.Writer.Complete();
pipe.Reader.Complete();
}
[Fact]
public async Task CancelingViaCancellationTokenThrows()
{
var helloBytes = Encoding.UTF8.GetBytes("Hello World");
var pipe = new Pipe(new PipeOptions(pauseWriterThreshold: helloBytes.Length - 1, resumeWriterThreshold: 0));
var stream = new MemoryStream(helloBytes);
var cts = new CancellationTokenSource();
Task task = stream.CopyToAsync(pipe.Writer, cts.Token);
Assert.False(task.IsCompleted);
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => task);
pipe.Writer.Complete();
pipe.Reader.Complete();
}
[Fact]
public async Task CancelingStreamViaCancellationTokenThrows()
{
var pipe = new Pipe();
var stream = new CancelledReadsStream();
var cts = new CancellationTokenSource();
Task task = stream.CopyToAsync(pipe.Writer, cts.Token);
Assert.False(task.IsCompleted);
cts.Cancel();
stream.WaitForReadTask.TrySetResult(null);
await Assert.ThrowsAsync<OperationCanceledException>(() => task);
pipe.Writer.Complete();
pipe.Reader.Complete();
}
private class CancelledReadsStream : ReadOnlyStream
{
public TaskCompletionSource<object> WaitForReadTask = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await WaitForReadTask.Task;
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
#if !netstandard
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await WaitForReadTask.Task;
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
#endif
}
private abstract class ReadOnlyStream : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush()
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;
namespace libsecondlife.StructuredData
{
/// <summary>
///
/// </summary>
public static partial class LLSDParser
{
private static XmlSchema XmlSchema;
private static XmlTextReader XmlTextReader;
private static string LastXmlErrors = String.Empty;
private static object XmlValidationLock = new object();
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static LLSD DeserializeXml(byte[] xmlData)
{
return DeserializeXml(new XmlTextReader(new MemoryStream(xmlData, false)));
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static LLSD DeserializeXml(string xmlData)
{
byte[] bytes = Helpers.StringToField(xmlData);
return DeserializeXml(new XmlTextReader(new MemoryStream(bytes, false)));
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static LLSD DeserializeXml(XmlTextReader xmlData)
{
xmlData.Read();
SkipWhitespace(xmlData);
xmlData.Read();
LLSD ret = ParseXmlElement(xmlData);
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] SerializeXmlBytes(LLSD data)
{
return Encoding.UTF8.GetBytes(SerializeXmlString(data));
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SerializeXmlString(LLSD data)
{
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.None;
writer.WriteStartElement(String.Empty, "llsd", String.Empty);
SerializeXmlElement(writer, data);
writer.WriteEndElement();
writer.Close();
return sw.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
/// <param name="data"></param>
public static void SerializeXmlElement(XmlTextWriter writer, LLSD data)
{
switch (data.Type)
{
case LLSDType.Unknown:
writer.WriteStartElement(String.Empty, "undef", String.Empty);
writer.WriteEndElement();
break;
case LLSDType.Boolean:
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.Integer:
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.Real:
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.String:
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.UUID:
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.Date:
writer.WriteStartElement(String.Empty, "date", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.URI:
writer.WriteStartElement(String.Empty, "uri", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.Binary:
writer.WriteStartElement(String.Empty, "binary", String.Empty);
writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
writer.WriteString("base64");
writer.WriteEndAttribute();
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case LLSDType.Map:
LLSDMap map = (LLSDMap)data;
writer.WriteStartElement(String.Empty, "map", String.Empty);
foreach (KeyValuePair<string, LLSD> kvp in map)
{
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(kvp.Key);
writer.WriteEndElement();
SerializeXmlElement(writer, kvp.Value);
}
writer.WriteEndElement();
break;
case LLSDType.Array:
LLSDArray array = (LLSDArray)data;
writer.WriteStartElement(String.Empty, "array", String.Empty);
for (int i = 0; i < array.Count; i++)
{
SerializeXmlElement(writer, array[i]);
}
writer.WriteEndElement();
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <param name="error"></param>
/// <returns></returns>
public static bool TryValidate(XmlTextReader xmlData, out string error)
{
lock (XmlValidationLock)
{
LastXmlErrors = String.Empty;
XmlTextReader = xmlData;
CreateSchema();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas.Add(XmlSchema);
readerSettings.ValidationEventHandler += new ValidationEventHandler(SchemaValidationHandler);
XmlReader reader = XmlReader.Create(xmlData, readerSettings);
try
{
while (reader.Read()) { }
}
catch (XmlException)
{
error = LastXmlErrors;
return false;
}
if (LastXmlErrors == String.Empty)
{
error = null;
return true;
}
else
{
error = LastXmlErrors;
return false;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static LLSD ParseXmlElement(XmlTextReader reader)
{
SkipWhitespace(reader);
if (reader.NodeType != XmlNodeType.Element)
throw new LLSDException("Expected an element");
string type = reader.LocalName;
LLSD ret;
switch (type)
{
case "undef":
if (reader.IsEmptyElement)
{
reader.Read();
return new LLSD();
}
reader.Read();
SkipWhitespace(reader);
ret = new LLSD();
break;
case "boolean":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromBoolean(false);
}
if (reader.Read())
{
string s = reader.ReadString().Trim();
if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1"))
{
ret = LLSD.FromBoolean(true);
break;
}
}
ret = LLSD.FromBoolean(false);
break;
case "integer":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromInteger(0);
}
if (reader.Read())
{
int value = 0;
Helpers.TryParse(reader.ReadString().Trim(), out value);
ret = LLSD.FromInteger(value);
break;
}
ret = LLSD.FromInteger(0);
break;
case "real":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromReal(0d);
}
if (reader.Read())
{
double value = 0d;
string str = reader.ReadString().Trim().ToLower();
if (str == "nan")
value = Double.NaN;
else
Helpers.TryParse(str, out value);
ret = LLSD.FromReal(value);
break;
}
ret = LLSD.FromReal(0d);
break;
case "uuid":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromUUID(LLUUID.Zero);
}
if (reader.Read())
{
LLUUID value = LLUUID.Zero;
LLUUID.TryParse(reader.ReadString().Trim(), out value);
ret = LLSD.FromUUID(value);
break;
}
ret = LLSD.FromUUID(LLUUID.Zero);
break;
case "date":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromDate(Helpers.Epoch);
}
if (reader.Read())
{
DateTime value = Helpers.Epoch;
Helpers.TryParse(reader.ReadString().Trim(), out value);
ret = LLSD.FromDate(value);
break;
}
ret = LLSD.FromDate(Helpers.Epoch);
break;
case "string":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromString(String.Empty);
}
if (reader.Read())
{
ret = LLSD.FromString(reader.ReadString());
break;
}
ret = LLSD.FromString(String.Empty);
break;
case "binary":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromBinary(new byte[0]);
}
if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64")
throw new LLSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding"));
if (reader.Read())
{
try
{
ret = LLSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim()));
break;
}
catch (FormatException ex)
{
throw new LLSDException("Binary decoding exception: " + ex.Message);
}
}
ret = LLSD.FromBinary(new byte[0]);
break;
case "uri":
if (reader.IsEmptyElement)
{
reader.Read();
return LLSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute));
}
if (reader.Read())
{
ret = LLSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute));
break;
}
ret = LLSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute));
break;
case "map":
return ParseXmlMap(reader);
case "array":
return ParseXmlArray(reader);
default:
reader.Read();
ret = null;
break;
}
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type)
{
throw new LLSDException("Expected </" + type + ">");
}
else
{
reader.Read();
return ret;
}
}
private static LLSDMap ParseXmlMap(XmlTextReader reader)
{
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map")
throw new NotImplementedException("Expected <map>");
LLSDMap map = new LLSDMap();
if (reader.IsEmptyElement)
{
reader.Read();
return map;
}
if (reader.Read())
{
while (true)
{
SkipWhitespace(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map")
{
reader.Read();
break;
}
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key")
throw new LLSDException("Expected <key>");
string key = reader.ReadString();
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key")
throw new LLSDException("Expected </key>");
if (reader.Read())
map[key] = ParseXmlElement(reader);
else
throw new LLSDException("Failed to parse a value for key " + key);
}
}
return map;
}
private static LLSDArray ParseXmlArray(XmlTextReader reader)
{
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array")
throw new LLSDException("Expected <array>");
LLSDArray array = new LLSDArray();
if (reader.IsEmptyElement)
{
reader.Read();
return array;
}
if (reader.Read())
{
while (true)
{
SkipWhitespace(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array")
{
reader.Read();
break;
}
array.Add(ParseXmlElement(reader));
}
}
return array;
}
private static void SkipWhitespace(XmlTextReader reader)
{
while (
reader.NodeType == XmlNodeType.Comment ||
reader.NodeType == XmlNodeType.Whitespace ||
reader.NodeType == XmlNodeType.SignificantWhitespace ||
reader.NodeType == XmlNodeType.XmlDeclaration)
{
reader.Read();
}
}
private static void CreateSchema()
{
if (XmlSchema == null)
{
#region XSD
string schemaText = @"
<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import schemaLocation=""xml.xsd"" namespace=""http://www.w3.org/XML/1998/namespace"" />
<xs:element name=""uri"" type=""xs:string"" />
<xs:element name=""uuid"" type=""xs:string"" />
<xs:element name=""KEYDATA"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""key"" />
<xs:element ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""date"" type=""xs:string"" />
<xs:element name=""key"" type=""xs:string"" />
<xs:element name=""boolean"" type=""xs:string"" />
<xs:element name=""undef"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""EMPTY"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""map"">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""KEYDATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""real"" type=""xs:string"" />
<xs:element name=""ATOMIC"">
<xs:complexType>
<xs:choice>
<xs:element ref=""undef"" />
<xs:element ref=""boolean"" />
<xs:element ref=""integer"" />
<xs:element ref=""real"" />
<xs:element ref=""uuid"" />
<xs:element ref=""string"" />
<xs:element ref=""date"" />
<xs:element ref=""uri"" />
<xs:element ref=""binary"" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name=""DATA"">
<xs:complexType>
<xs:choice>
<xs:element ref=""ATOMIC"" />
<xs:element ref=""map"" />
<xs:element ref=""array"" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name=""llsd"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""binary"">
<xs:complexType>
<xs:simpleContent>
<xs:extension base=""xs:string"">
<xs:attribute default=""base64"" name=""encoding"" type=""xs:string"" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name=""array"">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""integer"" type=""xs:string"" />
<xs:element name=""string"">
<xs:complexType>
<xs:simpleContent>
<xs:extension base=""xs:string"">
<xs:attribute ref=""xml:space"" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
";
#endregion XSD
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(schemaText));
XmlSchema = new XmlSchema();
XmlSchema = XmlSchema.Read(stream, new ValidationEventHandler(SchemaValidationHandler));
}
}
private static void SchemaValidationHandler(object sender, ValidationEventArgs args)
{
string error = String.Format("Line: {0} - Position: {1} - {2}", XmlTextReader.LineNumber, XmlTextReader.LinePosition,
args.Message);
if (LastXmlErrors == String.Empty)
LastXmlErrors = error;
else
LastXmlErrors += Helpers.NewLine + error;
}
}
}
| |
// CRC32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 18:25:54>
//
// ------------------------------------------------------------------
//
// This module defines the CRC32 class, which can do the CRC32 algorithm, using
// arbitrary starting polynomials, and bit reversal. The bit reversal is what
// distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP
// files, or GZIP files. This class does both.
//
// ------------------------------------------------------------------
using System;
namespace Cimbalino.Phone.Toolkit.Compression
{
/// <summary>
/// Computes a CRC-32. The CRC-32 algorithm is parameterized - you
/// can set the polynomial and enable or disable bit
/// reversal. This can be used for GZIP, BZip2, or ZIP.
/// </summary>
/// <remarks>
/// This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip
/// archive files.
/// </remarks>
public class CRC32
{
/// <summary>
/// Indicates the total number of bytes applied to the CRC.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
return unchecked((Int32)(~_register));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
if (input == null)
throw new Exception("The input stream must not be null.");
unchecked
{
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_register);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a
/// computation defined by PKzip for PKZIP 2.0 (weak) encryption.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new Exception("The data buffer must not be null.");
// bzip algorithm
for (int i = 0; i < count; i++)
{
int x = offset + i;
byte b = block[x];
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
_TotalBytesRead += count;
}
/// <summary>
/// Process one byte in the CRC.
/// </summary>
/// <param name = "b">the byte to include into the CRC . </param>
public void UpdateCRC(byte b)
{
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
/// <summary>
/// Process a run of N identical bytes into the CRC.
/// </summary>
/// <remarks>
/// <para>
/// This method serves as an optimization for updating the CRC when a
/// run of identical bytes is found. Rather than passing in a buffer of
/// length n, containing all identical bytes b, this method accepts the
/// byte value and the length of the (virtual) buffer - the length of
/// the run.
/// </para>
/// </remarks>
/// <param name = "b">the byte to include into the CRC. </param>
/// <param name = "n">the number of times that byte should be repeated. </param>
public void UpdateCRC(byte b, int n)
{
while (n-- > 0)
{
if (this.reverseBits)
{
uint temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
}
}
private static uint ReverseBits(uint data)
{
unchecked
{
uint ret = data;
ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555;
ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333;
ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F;
ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24);
return ret;
}
}
private static byte ReverseBits(byte data)
{
unchecked
{
uint u = (uint)data * 0x00020202;
uint m = 0x01044010;
uint s = u & m;
uint t = (u << 2) & (m << 1);
return (byte)((0x01001001 * (s + t)) >> 24);
}
}
private void GenerateLookupTable()
{
crc32Table = new UInt32[256];
unchecked
{
UInt32 dwCrc;
byte i = 0;
do
{
dwCrc = i;
for (byte j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
if (reverseBits)
{
crc32Table[ReverseBits(i)] = ReverseBits(dwCrc);
}
else
{
crc32Table[i] = dwCrc;
}
i++;
} while (i!=0);
}
#if VERBOSE
Console.WriteLine();
Console.WriteLine("private static readonly UInt32[] crc32Table = {");
for (int i = 0; i < crc32Table.Length; i+=4)
{
Console.Write(" ");
for (int j=0; j < 4; j++)
{
Console.Write(" 0x{0:X8}U,", crc32Table[i+j]);
}
Console.WriteLine();
}
Console.WriteLine("};");
Console.WriteLine();
#endif
}
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i=0;
while (vec != 0)
{
if ((vec & 0x01)== 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to
/// calculating a CRC. Multiple threads can each calculate a
/// CRC32 on a segment of the data, and then combine the
/// individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1= ~_register;
uint crc2= (uint) crc;
// put operator for one zero bit in odd
odd[0] = this.dwPolynomial; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
uint len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)== 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)==1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
_register= ~crc1;
//return (int) crc1;
return;
}
/// <summary>
/// Create an instance of the CRC32 class using the default settings: no
/// bit reversal, and a polynomial of 0xEDB88320.
/// </summary>
public CRC32() : this(false)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying whether to reverse
/// data bits or not.
/// </summary>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here. In the CRC-32 used by GZIP and PKZIP, the bits are not
/// reversed; Therefore if you want a CRC32 with compatibility with
/// those, you should pass false.
/// </para>
/// </remarks>
public CRC32(bool reverseBits) :
this( unchecked((int)0xEDB88320), reverseBits)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying the polynomial and
/// whether to reverse data bits or not.
/// </summary>
/// <param name='polynomial'>
/// The polynomial to use for the CRC, expressed in the reversed (LSB)
/// format: the highest ordered bit in the polynomial value is the
/// coefficient of the 0th power; the second-highest order bit is the
/// coefficient of the 1 power, and so on. Expressed this way, the
/// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
/// </param>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
///
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here for the <c>reverseBits</c> parameter. In the CRC-32 used by
/// GZIP and PKZIP, the bits are not reversed; Therefore if you want a
/// CRC32 with compatibility with those, you should pass false for the
/// <c>reverseBits</c> parameter.
/// </para>
/// </remarks>
public CRC32(int polynomial, bool reverseBits)
{
this.reverseBits = reverseBits;
this.dwPolynomial = (uint) polynomial;
this.GenerateLookupTable();
}
/// <summary>
/// Reset the CRC-32 class - clear the CRC "remainder register."
/// </summary>
/// <remarks>
/// <para>
/// Use this when employing a single instance of this class to compute
/// multiple, distinct CRCs on multiple, distinct data blocks.
/// </para>
/// </remarks>
public void Reset()
{
_register = 0xFFFFFFFFU;
}
// private member vars
private UInt32 dwPolynomial;
private Int64 _TotalBytesRead;
private bool reverseBits;
private UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _register = 0xFFFFFFFFU;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when
/// reading from a stream, or to calculate a CRC when writing to a
/// stream. The stream should be used to either read, or write, but
/// not both. If you intermix reads and writes, the results are not
/// defined.
/// </para>
///
/// <para>
/// This class is intended primarily for use internally by the
/// DotNetZip library.
/// </para>
/// </remarks>
public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
{
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
private CRC32 _Crc32;
private Int64 _lengthLimit = -99;
private bool _leaveOpen;
/// <summary>
/// The default constructor.
/// </summary>
/// <remarks>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close(). The stream uses the default CRC32
/// algorithm, which implies a polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// The constructor allows the caller to specify how to handle the
/// underlying stream at close.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
: this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close().
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: this(true, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close().
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
: this(leaveOpen, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close(), and the CRC32 instance to use.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the specified CRC32 instance, which allows the
/// application to specify how the CRC gets calculated.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
/// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen,
CRC32 crc32)
: this(leaveOpen, length, stream, crc32)
{
if (length < 0)
throw new ArgumentException("length");
}
// This ctor is private - no validation is done here. This is to allow the use
// of a (specific) negative value for the _lengthLimit, to indicate that there
// is no length set. So we validate the length limit in those ctors that use an
// explicit param, otherwise we don't validate, because it could be our special
// value.
private CrcCalculatorStream
(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32)
: base()
{
_innerStream = stream;
_Crc32 = crc32 ?? new CRC32();
_lengthLimit = length;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number of
/// bytes written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
/// <remarks>
/// <para>
/// The running total of the CRC is kept as data is written or read
/// through the stream. read this property after all reads or writes to
/// get an accurate CRC for the entire stream.
/// </para>
/// </remarks>
public Int32 Crc
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Indicates whether the underlying stream will be left open when the
/// <c>CrcCalculatorStream</c> is Closed.
/// </summary>
/// <remarks>
/// <para>
/// Set this at any point before calling <see cref="Close()"/>.
/// </para>
/// </remarks>
public bool LeaveOpen
{
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
// a definite length. This is especially useful when returning a stream for
// the uncompressed data directly to the application. The app won't
// necessarily read only the UncompressedSize number of bytes. For example
// wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
{
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _innerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
/// <remarks>
/// <para>
/// Always returns false.
/// </para>
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Returns the length of the underlying stream.
/// </summary>
public override long Length
{
get
{
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
}
}
/// <summary>
/// The getter for this property returns the total bytes read.
/// If you use the setter, it will throw
/// <see cref="NotSupportedException"/>.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Seeking is not supported on this stream. This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
Close();
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
base.Close();
if (!_leaveOpen)
_innerStream.Close();
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Tests;
using System.Security.Principal;
using Xunit;
namespace System.Security.Claims
{
public class ClaimsPrincipalTests
{
[Fact]
public void Ctor_Default()
{
var cp = new ClaimsPrincipal();
Assert.NotNull(cp.Identities);
Assert.Equal(0, cp.Identities.Count());
Assert.NotNull(cp.Claims);
Assert.Equal(0, cp.Claims.Count());
Assert.Null(cp.Identity);
}
[Fact]
public void Ctor_IIdentity()
{
var id = new ClaimsIdentity(
new List<Claim> { new Claim("claim_type", "claim_value") },
"");
var cp = new ClaimsPrincipal(id);
Assert.NotNull(cp.Identities);
Assert.Equal(1, cp.Identities.Count());
Assert.Same(id, cp.Identities.First());
Assert.Same(id, cp.Identity);
Assert.NotNull(cp.Claims);
Assert.Equal(1, cp.Claims.Count());
Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value"));
}
[Fact]
public void Ctor_IIdentity_NonClaims()
{
var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" };
var cp = new ClaimsPrincipal(id);
Assert.NotNull(cp.Identities);
Assert.Equal(1, cp.Identities.Count());
Assert.NotSame(id, cp.Identities.First());
Assert.NotSame(id, cp.Identity);
Assert.Equal(id.Name, cp.Identity.Name);
Assert.NotNull(cp.Claims);
Assert.Equal(1, cp.Claims.Count());
Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name"));
}
[Fact]
public void Ctor_IPrincipal()
{
var baseId = new ClaimsIdentity(
new List<Claim> { new Claim("claim_type", "claim_value") },
"");
var basePrincipal = new ClaimsPrincipal();
basePrincipal.AddIdentity(baseId);
var cp = new ClaimsPrincipal(basePrincipal);
Assert.NotNull(cp.Identities);
Assert.Equal(1, cp.Identities.Count());
Assert.Same(baseId, cp.Identities.First());
Assert.Same(baseId, cp.Identity);
Assert.NotNull(cp.Claims);
Assert.Equal(1, cp.Claims.Count());
Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7");
}
[Fact]
public void Ctor_NonClaimsIPrincipal_NonClaimsIdentity()
{
var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" };
var basePrincipal = new NonClaimsPrincipal { Identity = id };
var cp = new ClaimsPrincipal(basePrincipal);
Assert.NotNull(cp.Identities);
Assert.Equal(1, cp.Identities.Count());
Assert.NotSame(id, cp.Identities.First());
Assert.NotSame(id, cp.Identity);
Assert.Equal(id.Name, cp.Identity.Name);
Assert.NotNull(cp.Claims);
Assert.Equal(1, cp.Claims.Count());
Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name"));
}
[Fact]
public void Ctor_NonClaimsIPrincipal_NoIdentity()
{
var p = new ClaimsPrincipal(new NonClaimsPrincipal());
Assert.NotNull(p.Identities);
Assert.Equal(1, p.Identities.Count());
Assert.NotNull(p.Claims);
Assert.Equal(0, p.Claims.Count());
Assert.NotNull(p.Identity);
Assert.False(p.Identity.IsAuthenticated);
}
[Fact]
public void Ctor_IPrincipal_NoIdentity()
{
var cp = new ClaimsPrincipal(new ClaimsPrincipal());
Assert.NotNull(cp.Identities);
Assert.Equal(0, cp.Identities.Count());
Assert.NotNull(cp.Claims);
Assert.Equal(0, cp.Claims.Count());
Assert.Null(cp.Identity);
}
[Fact]
public void Ctor_IPrincipal_MultipleIdentities()
{
var baseId1 = new ClaimsIdentity("baseId1");
var baseId2 = new GenericIdentity("generic_name", "baseId2");
var baseId3 = new ClaimsIdentity("customType");
var basePrincipal = new ClaimsPrincipal(baseId1);
basePrincipal.AddIdentity(baseId2);
basePrincipal.AddIdentity(baseId3);
var cp = new ClaimsPrincipal(basePrincipal);
Assert.NotNull(cp.Identities);
Assert.Equal(3, cp.Identities.Count());
Assert.NotNull(cp.Claims);
Assert.Equal(1, cp.Claims.Count());
Assert.Equal(baseId1, cp.Identity);
Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name"));
Assert.Equal(baseId2.Claims.First(), cp.Claims.First());
}
[Fact]
public void Ctor_IEnumerableClaimsIdentity_Empty()
{
var cp = new ClaimsPrincipal(new ClaimsIdentity[0]);
Assert.NotNull(cp.Identities);
Assert.Equal(0, cp.Identities.Count());
Assert.NotNull(cp.Claims);
Assert.Equal(0, cp.Claims.Count());
Assert.Null(cp.Identity);
}
[Fact]
public void Ctor_IEnumerableClaimsIdentity_Multiple()
{
var baseId1 = new ClaimsIdentity("baseId1");
var baseId2 = new GenericIdentity("generic_name2", "baseId2");
var baseId3 = new GenericIdentity("generic_name3", "baseId3");
var cp = new ClaimsPrincipal(new List<ClaimsIdentity> { baseId1, baseId2, baseId3 });
Assert.NotNull(cp.Identities);
Assert.Equal(3, cp.Identities.Count());
Assert.NotNull(cp.Claims);
Assert.Equal(2, cp.Claims.Count());
Assert.Equal(baseId1, cp.Identity);
Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2"));
Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3"));
Assert.Equal(baseId2.Claims.First(), cp.Claims.First());
Assert.Equal(baseId3.Claims.Last(), cp.Claims.Last());
}
[Fact]
public void Ctor_ArgumentValidation()
{
AssertExtensions.Throws<ArgumentNullException>("identities", () => new ClaimsPrincipal((IEnumerable<ClaimsIdentity>)null));
AssertExtensions.Throws<ArgumentNullException>("identity", () => new ClaimsPrincipal((IIdentity)null));
AssertExtensions.Throws<ArgumentNullException>("principal", () => new ClaimsPrincipal((IPrincipal)null));
AssertExtensions.Throws<ArgumentNullException>("reader", () => new ClaimsPrincipal((BinaryReader)null));
}
private class NonClaimsPrincipal : IPrincipal
{
public IIdentity Identity { get; set; }
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace System.Net
{
using System;
using System.IO;
using System.Text;
/// <summary>
/// Represents a response to a request being handled by an
/// <see cref="System.Net.HttpListener"/> object.
/// </summary>
public sealed class HttpListenerResponse : IDisposable
{
/// <summary>
/// A flag that indicates whether the response was already sent.
/// </summary>
private bool m_wasResponseSent = false;
/// <summary>
/// A flag that indicates that the response was closed.
/// Writing to client is not allowed after response is closed.
/// </summary>
private bool m_isResponseClosed = false;
/// <summary>
/// The length of the content of the response.
/// </summary>
long m_contentLength = -1;
/// <summary>
/// The response headers from the HTTP client.
/// </summary>
private WebHeaderCollection m_httpResponseHeaders = new WebHeaderCollection(true);
/// <summary>
/// The HTTP version for the response.
/// </summary>
private Version m_version = new Version(1, 1);
/// <summary>
/// Indicates whether the server requests a persistent connection.
/// Persistent connection is used if KeepAlive is <itemref>true</itemref>
/// in both the request and the response.
/// </summary>
private bool m_keepAlive = false;
/// <summary>
/// Encoding for this response's OutputStream.
/// </summary>
private Encoding m_encoding = Encoding.UTF8;
/// <summary>
/// Keeps content type for the response, set by user application.
/// </summary>
private string m_contentType;
/// <summary>
/// Response status code.
/// </summary>
private int m_responseStatusCode = (int)HttpStatusCode.OK;
/// <summary>
/// Array of connected client streams
/// </summary>
private HttpListener m_listener;
/// <summary>
/// Member with network stream connected to client.
/// After call to Close() the stream is closed, no further writing allowed.
/// </summary>
private OutputNetworkStreamWrapper m_clientStream;
/// <summary>
/// The value of the HTTP Location header in this response.
/// </summary>
private string m_redirectLocation;
/// <summary>
/// Response uses chunked transfer encoding.
/// </summary>
private bool m_sendChunked = false;
/// <summary>
/// text description of the HTTP status code returned to the client.
/// </summary>
private string m_statusDescription;
/// <summary>
/// Throws InvalidOperationException is HTTP response was sent.
/// Called before setting of properties.
/// </summary>
private void ThrowIfResponseSent( )
{
if(m_wasResponseSent)
{
throw new InvalidOperationException( );
}
}
/// <summary>
/// HttpListenerResponse is created by HttpListenerContext
/// </summary>
/// <param name="clientStream">Network stream to the client</param>
/// <param name="httpListener">TBD</param>
internal HttpListenerResponse( OutputNetworkStreamWrapper clientStream, HttpListener httpListener )
{
// Sets the delegate, so SendHeaders will be called on first write.
clientStream.HeadersDelegate = new OutputNetworkStreamWrapper.SendHeadersDelegate( SendHeaders );
// Saves network stream as member.
m_clientStream = clientStream;
// Saves list of client streams. m_clientStream is removed from clientStreamsList during Close().
m_listener = httpListener;
}
/// <summary>
/// Updates the HTTP WEB header collection to prepare it for request.
/// For each property set it adds member to m_httpResponseHeaders.
/// m_httpResponseHeaders is serializes to string and sent to client.
/// </summary>
private void PrepareHeaders( )
{
// Adds content length if it was present.
if(m_contentLength != -1)
{
m_httpResponseHeaders.ChangeInternal( HttpKnownHeaderNames.ContentLength, m_contentLength.ToString( ) );
}
// Since we do not support persistent connection, send close always.
string connection = m_keepAlive ? "Keep-Alive" : "Close";
m_httpResponseHeaders.ChangeInternal( HttpKnownHeaderNames.Connection, connection );
// Adds content type if user set it:
if(m_contentType != null)
{
m_httpResponseHeaders.AddWithoutValidate( HttpKnownHeaderNames.ContentType, m_contentType );
}
if(m_redirectLocation != null)
{
m_httpResponseHeaders.AddWithoutValidate( HttpKnownHeaderNames.Location, m_redirectLocation );
m_responseStatusCode = (int)HttpStatusCode.Redirect;
}
}
/// <summary>
/// Composes HTTP response line based on
/// </summary>
/// <returns></returns>
private string ComposeHTTPResponse( )
{
// Starts with HTTP
string resp = "HTTP/";
// Adds version of HTTP
resp += m_version.ToString( );
// Add status code.
resp += " " + m_responseStatusCode;
// Adds description
if(m_statusDescription == null)
{
resp += " " + GetStatusDescription( m_responseStatusCode );
}
else // User provided description is present.
{
resp += " " + m_statusDescription;
}
// Add line termindation.
resp += "\r\n";
return resp;
}
/// <summary>
/// Sends HTTP status and headers to client.
/// </summary>
private void SendHeaders( )
{
// As first step we disable the callback to SendHeaders, so m_clientStream.Write would not call
// SendHeaders() again.
m_clientStream.HeadersDelegate = null;
// Creates encoder, generates headers and sends the data.
Encoding encoder = Encoding.UTF8;
byte[] statusLine = encoder.GetBytes(ComposeHTTPResponse());
m_clientStream.Write( statusLine, 0, statusLine.Length );
// Prepares/Updates WEB header collection.
PrepareHeaders( );
// Serialise WEB header collection to byte array.
byte[] pHeaders = m_httpResponseHeaders.ToByteArray();
// Sends the headers
m_clientStream.Write( pHeaders, 0, pHeaders.Length );
m_wasResponseSent = true;
}
/// <summary>
/// Gets or sets the HTTP status code to be returned to the client.
/// </summary>
/// <value>An <itemref>Int32</itemref> value that specifies the
/// <see cref="System.Net.HttpStatusCode"/> for the requested resource.
/// The default is <itemref>OK</itemref>, indicating that the server
/// successfully processed the client's request and included the
/// requested resource in the response body.</value>
public int StatusCode
{
get { return m_responseStatusCode; }
set
{
ThrowIfResponseSent( );
m_responseStatusCode = value;
}
}
/// <summary>
/// Gets or sets the number of bytes in the body data included in the
/// response.
/// </summary>
/// <value>The value of the response's <itemref>Content-Length</itemref>
/// header.</value>
public long ContentLength64
{
get { return m_contentLength; }
set
{
ThrowIfResponseSent( );
m_contentLength = value;
}
}
/// <summary>
/// Gets or sets the collection of header name/value pairs that is
/// returned by the server.
/// </summary>
/// <value>A <itemref>WebHeaderCollection</itemref> instance that
/// contains all the explicitly set HTTP headers to be included in the
/// response.</value>
public WebHeaderCollection Headers
{
get { return m_httpResponseHeaders; }
set
{
ThrowIfResponseSent( );
m_httpResponseHeaders = value;
}
}
/// <summary>
/// Gets or sets whether the server requests a persistent connection.
/// </summary>
/// <value><itemref>true</itemref> if the server requests a persistent
/// connection; otherwise, <itemref>false</itemref>. The default is
/// <itemref>true</itemref>.</value>
public bool KeepAlive
{
get { return m_keepAlive; }
set { m_keepAlive = value; }
}
/// <summary>
/// Gets a <itemref>Stream</itemref> object to which a response can be
/// written.
/// </summary>
/// <value>A <itemref>Stream</itemref> object to which a response can be
/// written.</value>
/// <remarks>
/// The first write to the output stream sends a response to the client.
/// </remarks>
public Stream OutputStream
{
get
{
if(m_isResponseClosed)
{
throw new ObjectDisposedException( "Response has been sent" );
}
return m_clientStream;
}
}
/// <summary>
/// Gets or sets the HTTP version that is used for the response.
/// </summary>
/// <value>A <itemref>Version</itemref> object indicating the version of
/// HTTP used when responding to the client. This property is obsolete.
/// </value>
public Version ProtocolVersion
{
get { return m_version; }
set
{
ThrowIfResponseSent( );
m_version = value;
}
}
/// <summary>
/// Gets or sets the value of the HTTP <itemref>Location</itemref>
/// header in this response.
/// </summary>
/// <value>A <itemref>String</itemref> that contains the absolute URL to
/// be sent to the client in the <itemref>Location</itemref> header.
/// </value>
public string RedirectLocation
{
get { return m_redirectLocation; }
set
{
ThrowIfResponseSent( );
m_redirectLocation = value;
}
}
/// <summary>
/// Gets or sets whether the response uses chunked transfer encoding.
/// </summary>
/// <value><itemref>true</itemref> if the response is set to use chunked
/// transfer encoding; otherwise, <itemref>false</itemref>. The default
/// is <itemref>false</itemref>.</value>
public bool SendChunked
{
get { return m_sendChunked; }
set
{
ThrowIfResponseSent( );
m_sendChunked = value;
}
}
/// <summary>
/// Gets or sets the encoding for this response's
/// <itemref>OutputStream</itemref>.
/// </summary>
/// <value>An <itemref>Encoding</itemref> object suitable for use with
/// the data in the
/// <see cref="System.Net.HttpListenerResponse.OutputStream"/> property,
/// or <itemref>null</itemref> reference if no encoding is specified.
/// </value>
/// <remarks>
/// Only UTF8 encoding is supported.
/// </remarks>
public Encoding ContentEncoding
{
get { return m_encoding; }
set
{
ThrowIfResponseSent( );
m_encoding = value;
}
}
/// <summary>
/// Gets or sets the MIME type of the returned content.
/// </summary>
/// <value>A <itemref>String</itemref> instance that contains the text
/// of the response's <itemref>Content-Type</itemref> header.</value>
public string ContentType
{
get { return m_contentType; }
set
{
ThrowIfResponseSent( );
m_contentType = value;
}
}
/// <summary>
/// Gets or sets a text description of the HTTP status code that is
/// returned to the client.
/// </summary>
/// <value>The text description of the HTTP status code returned to the
/// client.</value>
public string StatusDescription
{
get { return m_statusDescription; }
set
{
ThrowIfResponseSent( );
m_statusDescription = value;
}
}
public void Detach( )
{
if(!m_isResponseClosed)
{
if(!m_wasResponseSent)
{
SendHeaders( );
}
m_isResponseClosed = true;
}
}
/// <summary>
/// Sends the response to the client and releases the resources held by
/// this HttpListenerResponse instance.
/// </summary>
/// <remarks>
/// This method flushes data to the client and closes the network
/// connection.
/// </remarks>
public void Close( )
{
if(!m_isResponseClosed)
{
try
{
if(!m_wasResponseSent)
{
SendHeaders( );
}
}
finally
{
// Removes from the list of streams and closes the socket.
( (IDisposable)this ).Dispose( );
}
}
}
/// <summary>
/// Closes the socket and sends the response if it was not done earlier
/// and the socket is present.
/// </summary>
void IDisposable.Dispose( )
{
if(!m_isResponseClosed)
{
try
{
// Iterates over list of client connections and remove its stream from it.
m_listener.RemoveClientStream( m_clientStream );
m_clientStream.Flush( );
// If KeepAlive is true,
if(m_keepAlive)
{ // Then socket is tramsferred to the list of waiting for new data.
m_listener.AddToWaitingConnections( m_clientStream );
}
else // If not KeepAlive then close
{
m_clientStream.Dispose( );
}
}
catch { }
m_isResponseClosed = true;
}
GC.SuppressFinalize( this );
}
/// <summary>
/// Called to close the socket if necessary.
/// </summary>
~HttpListenerResponse( )
{
( (IDisposable)this ).Dispose( );
}
/// <summary>
/// Return default Description based in response status code.
/// </summary>
/// <param name="code">HTTP status code</param>
/// <returns>
/// Default string with description.
/// </returns>
internal static string GetStatusDescription( int code )
{
switch(code)
{
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request-Uri Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 422: return "Unprocessable Entity";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "Http Version Not Supported";
case 507: return "Insufficient Storage";
}
return "";
}
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Core.CIM; //CIM
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout class
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export
using ArcGIS.Core.Geometry;
namespace Layout_HelpExamples
{
internal class MethodSnippets : Button
{
protected override void OnClick()
{
//Snippets.LayoutClassSnippets();
//Snippets.ElementSnippets();
Snippets.GraphicElementSnippets();
//Snippets.TextElementSnippets();
//Snippets.MapFrameSnippets();
Snippets.ExportSnippets();
}
}
public class Snippets
{
//async public static void CreateElementSnippets()
//{
// //There are already many Create element snippets in the PRO snippets section. This section will only contain examples that are NOT in the Pro snippets section
// //Pro snippets region names includes:
// // Create point graphic with symbology
// // Create line graphic with symbology
// // Create rectangle graphic with simple symbology
// // Create text element with basic font properties
// // Create rectangle text with more advanced symbol settings
// // Create a new picture element with advanced symbol settings
// // Create a map frame and zoom to a bookmark
// // Create a legend for a specific map frame
// // Creating group elements
// LayoutView lytView = LayoutView.Active;
// Layout layout = lytView.Layout;
// #region Create_BeizierCurve
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D pt1 = new Coordinate2D(1, 7.5);
// Coordinate2D pt2 = new Coordinate2D(1.66, 8);
// Coordinate2D pt3 = new Coordinate2D(2.33, 7.1);
// Coordinate2D pt4 = new Coordinate2D(3, 7.5);
// CubicBezierBuilder bez = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
// CubicBezierSegment bezSeg = bez.ToSegment();
// Polyline bezPl = PolylineBuilder.CreatePolyline(bezSeg);
// //Set symbology, create and add element to layout
// CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 4.0, SimpleLineStyle.DashDot);
// GraphicElement bezElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, bezPl, lineSym);
// bezElm.SetName("New Bezier Curve");
// });
// #endregion Create_BeizierCurve
// #region Create_freehand
// await QueuedTask.Run(() =>
// {
// //Build geometry
// List<Coordinate2D> plCoords = new List<Coordinate2D>();
// plCoords.Add(new Coordinate2D(1.5, 10.5));
// plCoords.Add(new Coordinate2D(1.25, 9.5));
// plCoords.Add(new Coordinate2D(1, 10.5));
// plCoords.Add(new Coordinate2D(0.75, 9.5));
// plCoords.Add(new Coordinate2D(0.5, 10.5));
// plCoords.Add(new Coordinate2D(0.5, 1));
// plCoords.Add(new Coordinate2D(0.75, 2));
// plCoords.Add(new Coordinate2D(1, 1));
// Polyline linePl = PolylineBuilder.CreatePolyline(plCoords);
// //Set symbolology, create and add element to layout
// CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
// GraphicElement lineElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, linePl, lineSym);
// lineElm.SetName("New Freehand");
// });
// #endregion Create_freehand
// #region Create_polygon_poly
// await QueuedTask.Run(() =>
// {
// //Build geometry
// List<Coordinate2D> plyCoords = new List<Coordinate2D>();
// plyCoords.Add(new Coordinate2D(1, 7));
// plyCoords.Add(new Coordinate2D(2, 7));
// plyCoords.Add(new Coordinate2D(2, 6.7));
// plyCoords.Add(new Coordinate2D(3, 6.7));
// plyCoords.Add(new Coordinate2D(3, 6.1));
// plyCoords.Add(new Coordinate2D(1, 6.1));
// Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);
// //Set symbolology, create and add element to layout
// CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.DashDotDot);
// CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
// GraphicElement polyElm = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
// polyElm.SetName("New Polygon");
// });
// #endregion Create_polygon_poly
// #region Create_polygon_env
// await QueuedTask.Run(() =>
// {
// //Build 2D envelope
// Coordinate2D env_ll = new Coordinate2D(1.0, 4.75);
// Coordinate2D env_ur = new Coordinate2D(3.0, 5.75);
// Envelope env = EnvelopeBuilder.CreateEnvelope(env_ll, env_ur);
// //Set symbolology, create and add element to layout
// CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.DashDotDot);
// CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
// GraphicElement polyElm = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, env, polySym);
// polyElm.SetName("New Polygon");
// });
// #endregion Create_polygon_env
// #region Create_circle
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D center = new Coordinate2D(2, 4);
// EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
// EllipticArcSegment cir = eabCir.ToSegment();
// //Set symbolology, create and add element to layout
// CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Dash);
// CIMPolygonSymbol circleSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);
// GraphicElement cirElm = LayoutElementFactory.Instance.CreateCircleGraphicElement(layout, cir, circleSym);
// cirElm.SetName("New Circle");
// });
// #endregion Create_circle
// #region Create_ellipse
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D center = new Coordinate2D(2, 2.75);
// EllipticArcBuilder eabElp = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
// EllipticArcSegment ellipse = eabElp.ToSegment();
// //Set symbolology, create and add element to layout
// CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB, 2.0, SimpleLineStyle.Dot);
// CIMPolygonSymbol ellipseSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreyRGB, SimpleFillStyle.Vertical, outline);
// GraphicElement elpElm = LayoutElementFactory.Instance.CreateEllipseGraphicElement(layout, ellipse, ellipseSym);
// elpElm.SetName("New Ellipse");
// });
// #endregion Create_ellipse
// #region Create_lasso
// await QueuedTask.Run(() =>
// {
// //Build geometry
// List<Coordinate2D> plyCoords = new List<Coordinate2D>();
// plyCoords.Add(new Coordinate2D(1, 1));
// plyCoords.Add(new Coordinate2D(1.25, 2));
// plyCoords.Add(new Coordinate2D(1.5, 1.1));
// plyCoords.Add(new Coordinate2D(1.75, 2));
// plyCoords.Add(new Coordinate2D(2, 1.1));
// plyCoords.Add(new Coordinate2D(2.25, 2));
// plyCoords.Add(new Coordinate2D(2.5, 1.1));
// plyCoords.Add(new Coordinate2D(2.75, 2));
// plyCoords.Add(new Coordinate2D(3, 1));
// Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);
// //Set symbolology, create and add element to layout
// CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
// CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
// GraphicElement polyElm = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
// polyElm.SetName("New Lasso");
// });
// #endregion Create_lasso
// #region Create_CurveText
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D pt1 = new Coordinate2D(3.6, 7.5);
// Coordinate2D pt2 = new Coordinate2D(4.26, 8);
// Coordinate2D pt3 = new Coordinate2D(4.93, 7.1);
// Coordinate2D pt4 = new Coordinate2D(5.6, 7.5);
// CubicBezierBuilder bez = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
// CubicBezierSegment bezSeg = bez.ToSegment();
// Polyline bezPl = PolylineBuilder.CreatePolyline(bezSeg);
// //Set symbolology, create and add element to layout
// CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 24, "Comic Sans MS", "Regular");
// GraphicElement bezTxtElm = LayoutElementFactory.Instance.CreateCurvedTextGraphicElement(layout, bezPl, "Curved Text", sym);
// bezTxtElm.SetName("New Splinned Text");
// });
// #endregion Create_CurveText
// #region Create_PolygonText
// await QueuedTask.Run(() =>
// {
// //Build geometry
// List<Coordinate2D> plyCoords = new List<Coordinate2D>();
// plyCoords.Add(new Coordinate2D(3.5, 7));
// plyCoords.Add(new Coordinate2D(4.5, 7));
// plyCoords.Add(new Coordinate2D(4.5, 6.7));
// plyCoords.Add(new Coordinate2D(5.5, 6.7));
// plyCoords.Add(new Coordinate2D(5.5, 6.1));
// plyCoords.Add(new Coordinate2D(3.5, 6.1));
// Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);
// //Set symbolology, create and add element to layout
// CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 10, "Arial", "Regular");
// string text = "Some Text String that is really long and is <BOL>forced to wrap to other lines</BOL> so that we can see the effects." as String;
// GraphicElement polyTxtElm = LayoutElementFactory.Instance.CreatePolygonParagraphGraphicElement(layout, poly, text, sym);
// polyTxtElm.SetName("New Polygon Text");
// //(Optionally) Modify paragraph border
// CIMGraphic polyTxtGra = polyTxtElm.Graphic;
// CIMParagraphTextGraphic cimPolyTxtGra = polyTxtGra as CIMParagraphTextGraphic;
// cimPolyTxtGra.Frame.BorderSymbol = new CIMSymbolReference();
// cimPolyTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
// polyTxtElm.SetGraphic(polyTxtGra);
// });
// #endregion Create_PolygonText
// #region Create_CircleText
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D center = new Coordinate2D(4.5, 4);
// EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
// EllipticArcSegment cir = eabCir.ToSegment();
// //Set symbolology, create and add element to layout
// CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreenRGB, 10, "Arial", "Regular");
// string text = "Circle, circle, circle, circle, circle, circle, circle, circle, circle, circle, circle";
// GraphicElement cirTxtElm = LayoutElementFactory.Instance.CreateCircleParagraphGraphicElement(layout, cir, text, sym);
// cirTxtElm.SetName("New Circle Text");
// //(Optionally) Modify paragraph border
// CIMGraphic cirTxtGra = cirTxtElm.Graphic;
// CIMParagraphTextGraphic cimCirTxtGra = cirTxtGra as CIMParagraphTextGraphic;
// cimCirTxtGra.Frame.BorderSymbol = new CIMSymbolReference();
// cimCirTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
// cirTxtElm.SetGraphic(cirTxtGra);
// });
// #endregion Create_CircleText
// #region Create_EllipseText
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D center = new Coordinate2D(4.5, 2.75);
// EllipticArcBuilder eabElp = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
// EllipticArcSegment ellipse = eabElp.ToSegment();
// //Set symbolology, create and add element to layout
// CIMTextSymbol sym = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB, 10, "Arial", "Regular");
// string text = "Ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse";
// GraphicElement elpTxtElm = LayoutElementFactory.Instance.CreateEllipseParagraphGraphicElement(layout, ellipse, text, sym);
// elpTxtElm.SetName("New Ellipse Text");
// //(Optionally) Modify paragraph border
// CIMGraphic elpTxtGra = elpTxtElm.Graphic;
// CIMParagraphTextGraphic cimElpTxtGra = elpTxtGra as CIMParagraphTextGraphic;
// cimElpTxtGra.Frame.BorderSymbol = new CIMSymbolReference();
// cimElpTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
// elpTxtElm.SetGraphic(elpTxtGra);
// });
// #endregion Create_EllipseText
// MapFrame mfElm = null;
// #region Create_MapFrame
// //This example creates a new map frame and changes the camera scale.
// await QueuedTask.Run(() =>
// {
// //Build geometry
// Coordinate2D ll = new Coordinate2D(6.0, 8.5);
// Coordinate2D ur = new Coordinate2D(8.0, 10.5);
// Envelope env = EnvelopeBuilder.CreateEnvelope(ll, ur);
// //Reference map, create MF and add to layout
// MapProjectItem mapPrjItem = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map"));
// Map mfMap = mapPrjItem.GetMap();
// mfElm = LayoutElementFactory.Instance.CreateMapFrame(layout, env, mfMap);
// mfElm.SetName("New Map Frame");
// //Set the camera
// Camera camera = mfElm.Camera;
// camera.Scale = 24000;
// mfElm.SetCamera(camera);
// });
// #endregion Create_MapFrame
// #region Create_ScaleBar
// await QueuedTask.Run(() =>
// {
// //Reference a North Arrow in a style
// StyleProjectItem stylePrjItm = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
// ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars("Double Alternating Scale Bar 1")[0];
// //Build geometry
// Coordinate2D center = new Coordinate2D(7, 8);
// //Reference MF, create north arrow and add to layout
// MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
// if (mf == null)
// {
// ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
// return;
// }
// ScaleBar sbElm = LayoutElementFactory.Instance.CreateScaleBar(layout, center, mf, sbStyleItm);
// sbElm.SetName("New Scale Bar");
// sbElm.SetWidth(2);
// sbElm.SetX(6);
// sbElm.SetY(7.5);
// });
// #endregion Create_ScaleBar
// #region Create_NorthArrow
// await QueuedTask.Run(() =>
// {
// //Reference a North Arrow in a style
// StyleProjectItem stylePrjItm = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
// NorthArrowStyleItem naStyleItm = stylePrjItm.SearchNorthArrows("ArcGIS North 10")[0];
// //Build geometry
// Coordinate2D center = new Coordinate2D(7, 5.5);
// //Reference MF, create north arrow and add to layout
// MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
// if (mf == null)
// {
// ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
// return;
// }
// NorthArrow arrowElm = LayoutElementFactory.Instance.CreateNorthArrow(layout, center, mf, naStyleItm);
// arrowElm.SetName("New North Arrow");
// arrowElm.SetHeight(1.75);
// arrowElm.SetX(7);
// arrowElm.SetY(6);
// });
// #endregion Create_NorthArrow
// #region Create_Group_Root
// //Create an empty group element at the root level of the contents pane
// //Note: call within QueuedTask.Run()
// GroupElement grp1 = LayoutElementFactory.Instance.CreateGroupElement(layout);
// grp1.SetName("Group");
// #endregion
// #region Create_Group_Group
// //Create a group element inside another group element
// //Note: call within QueuedTask.Run()
// GroupElement grp2 = LayoutElementFactory.Instance.CreateGroupElement(grp1);
// grp2.SetName("Group in Group");
// #endregion
//}
async public static void GraphicElementSnippets()
{
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout lyt = await QueuedTask.Run(() => layoutItem.GetLayout());
GraphicElement graElm = lyt.FindElement("Rectangle") as GraphicElement;
CIMGraphic CIMGra = graElm.GetGraphic() as CIMGraphic;
await QueuedTask.Run(() =>
{
// cref: GraphicElement_Clone;ArcGIS.Desktop.Layouts.GraphicElement.Clone(System.String)
#region GraphicElement_Clone
//Note: call within QueuedTask.Run()
GraphicElement cloneElm = graElm.Clone("Clone");
#endregion GraphicElement_Clone
// cref: GraphicElement_SetGraphic;ArcGIS.Desktop.Layouts.GraphicElement.SetGraphic(ArcGIS.Core.CIM.CIMGraphic)
#region GraphicElement_SetGraphic
//Note: call within QueuedTask.Run()
graElm.SetGraphic(CIMGra);
#endregion GraphicElement_SetGraphic
});
}
async public static void TextElementSnippets()
{
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout lyt = await QueuedTask.Run(() => layoutItem.GetLayout());
TextElement txtElm = lyt.FindElement("Text") as TextElement;
#region TextElement_TextPropertiesConstructor
TextProperties txtProp = new TextProperties("String", "Times New Roman", 24, "Regular");
#endregion TextElement_TextPropertiesConstructor
#region TextElement_SetTextProperties
txtElm.SetTextProperties(txtProp);
#endregion TextElement_SetTextProperties
}
async public static void PictureElementSnippets()
{
// cref: PictureElement_SetSourcePath;ArcGIS.Desktop.Layouts.PictureElement.SetSourcePath(System.String)
#region PictureElement_SetSourcePath
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
await QueuedTask.Run(() =>
{
Layout layout = layoutItem.GetLayout();
PictureElement picElm = layout.FindElement("Rectangle") as PictureElement;
picElm.SetSourcePath(@"C:\Some\New\Path\And\file.ext");
});
#endregion PictureElement_SetSourcePath
}
async public static void MapSurroundSnippets()
{
// cref: MapSurround_SetMapFrame;ArcGIS.Desktop.Layouts.MapSurround.SetMapFrame(ArcGIS.Desktop.Layouts.MapFrame)
#region MapSurround_SetMapFrame
await QueuedTask.Run(() =>
{
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout lyt = layoutItem.GetLayout();
MapFrame mf = lyt.FindElement("Map1 Map Frame") as MapFrame;
MapSurround ms = lyt.FindElement("Scale Bar") as MapSurround;
ms.SetMapFrame(mf);
});
#endregion MapSurround_SetMapFrame
}
async public static void ExportSnippets()
{
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout lyt = await QueuedTask.Run(() => layoutItem.GetLayout());
MapFrame mf = lyt.FindElement("Map1 Map Frame") as MapFrame;
// cref: BMP_Constructor;ArcGIS.Desktop.Mapping.BMPFormat.#ctor
#region BMP_Constructor
BMPFormat BMP = new BMPFormat();
#endregion BMP_Constructor
// cref: EMF_Constructor;ArcGIS.Desktop.Mapping.EMFFormat.#ctor
#region EMF_Constructor
EMFFormat EMF = new EMFFormat();
#endregion EMF_Constructor
// cref: EPS_Constructor;ArcGIS.Desktop.Mapping.EPSFormat.#ctor
#region EPS_Constructor
EPSFormat EPS = new EPSFormat();
#endregion EPS_Constructor
// cref: GIF_Constructor;ArcGIS.Desktop.Mapping.GIFFormat.#ctor
#region GIF_Constructor
GIFFormat GIF = new GIFFormat();
#endregion GIF_Constructor
// cref: JPEG_Constructor;ArcGIS.Desktop.Mapping.JPEGFormat.#ctor
#region JPEG_Constructor
JPEGFormat JPEG = new JPEGFormat();
#endregion JPEG_Constructor
// cref: PNG_Constructor;ArcGIS.Desktop.Mapping.PNGFormat.#ctor
#region PNG_Constructor
PNGFormat PNG = new PNGFormat();
#endregion PNG_Constructor
// cref: PDF_Constructor;ArcGIS.Desktop.Mapping.PDFFormat.#ctor
#region PDF_Constructor
PDFFormat PDF = new PDFFormat();
#endregion PDF_Constructor
// cref: SVG_Constructor;ArcGIS.Desktop.Mapping.SVGFormat.#ctor
#region SVG_Constructor
SVGFormat SVG = new SVGFormat();
#endregion SVG_Constructor
// cref: TGA_Constructor;ArcGIS.Desktop.Mapping.TGAFormat.#ctor
#region TGA_Constructor
TGAFormat TGA = new TGAFormat();
#endregion TGA_Constructor
// cref: TIFF_Constructor;ArcGIS.Desktop.Mapping.TIFFFormat.#ctor
#region TIFF_Constructor
TIFFFormat TIFF = new TIFFFormat();
#endregion TIFF_Constructor
PDF.OutputFileName = @"C:\Temp\output.pdf";
#region PDF_lyt_Export
lyt.Export(PDF);
#endregion PDF_lyt_Export
}
}
}
| |
/*****************************************************************************
The MIT License (MIT)
Copyright (c) 2014 [email protected]
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.
******************************************************************************
LightInject.WebApi version 1.0.0.4
http://www.lightinject.net/
http://twitter.com/bernhardrichter
******************************************************************************/
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Reviewed")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:PrefixLocalCallsWithThis", Justification = "No inheritance")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Single source file deployment.")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1403:FileMayOnlyContainASingleNamespace", Justification = "Extension methods must be visible")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:FileMustHaveHeader", Justification = "Custom header.")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "All public members are documented.")]
namespace NEventStore.Viewer.Api.LightInject
{
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using LightInject.WebApi;
/// <summary>
/// Extends the <see cref="IServiceContainer"/> interface with methods that
/// enables dependency injection in a Web API application.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal static class WebApiContainerExtensions
{
/// <summary>
/// Enables dependency injection in a Web API application.
/// </summary>
/// <param name="serviceContainer">The target <see cref="IServiceContainer"/>.</param>
/// <param name="httpConfiguration">The <see cref="HttpConfiguration"/> that represents the configuration of this Web API application.</param>
public static void EnableWebApi(this IServiceContainer serviceContainer, HttpConfiguration httpConfiguration)
{
httpConfiguration.DependencyResolver = new LightInjectWebApiDependencyResolver(serviceContainer);
var provider = httpConfiguration.Services.GetFilterProviders();
httpConfiguration.Services.RemoveAll(typeof(IFilterProvider), o => true);
httpConfiguration.Services.Add(typeof(IFilterProvider), new LightInjectWebApiFilterProvider(serviceContainer, provider));
}
/// <summary>
/// Registers all <see cref="ApiController"/> implementations found in the given <paramref name="assemblies"/>.
/// </summary>
/// <param name="serviceRegistry">The target <see cref="IServiceRegistry"/>.</param>
/// <param name="assemblies">A list of assemblies from which to register <see cref="ApiController"/> implementations.</param>
public static void RegisterApiControllers(this IServiceRegistry serviceRegistry, params Assembly[] assemblies)
{
foreach (var assembly in assemblies)
{
var controllerTypes = assembly.GetTypes().Where(t => !t.IsAbstract && typeof(IHttpController).IsAssignableFrom(t));
foreach (var controllerType in controllerTypes)
{
serviceRegistry.Register(controllerType, new PerRequestLifeTime());
}
}
}
/// <summary>
/// Registers all <see cref="ApiController"/> implementations found in this assembly.
/// </summary>
/// <param name="serviceRegistry">The target <see cref="IServiceRegistry"/>.</param>
public static void RegisterApiControllers(this IServiceRegistry serviceRegistry)
{
RegisterApiControllers(serviceRegistry, Assembly.GetCallingAssembly());
}
}
}
namespace NEventStore.Viewer.Api.LightInject.WebApi
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dependencies;
using System.Web.Http.Filters;
/// <summary>
/// An <see cref="IDependencyResolver"/> adapter for the LightInject service container
/// that enables <see cref="ApiController"/> instances and their dependencies to be
/// resolved through the service container.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class LightInjectWebApiDependencyResolver : IDependencyResolver
{
private readonly IServiceContainer serviceContainer;
/// <summary>
/// Initializes a new instance of the <see cref="LightInjectWebApiDependencyResolver"/> class.
/// </summary>
/// <param name="serviceContainer">The <see cref="IServiceContainer"/> instance to
/// be used for resolving service instances.</param>
internal LightInjectWebApiDependencyResolver(IServiceContainer serviceContainer)
{
this.serviceContainer = serviceContainer;
}
/// <summary>
/// Disposes the underlying <see cref="IServiceContainer"/>.
/// </summary>
public void Dispose()
{
serviceContainer.Dispose();
}
/// <summary>
/// Gets an instance of the given <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">The type of the requested service.</param>
/// <returns>The requested service instance if available, otherwise null.</returns>
public object GetService(Type serviceType)
{
return serviceContainer.TryGetInstance(serviceType);
}
/// <summary>
/// Gets all instance of the given <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">The type of services to resolve.</param>
/// <returns>A list that contains all implementations of the <paramref name="serviceType"/>.</returns>
public IEnumerable<object> GetServices(Type serviceType)
{
return serviceContainer.GetAllInstances(serviceType);
}
/// <summary>
/// Starts a new <see cref="IDependencyScope"/> that represents
/// the scope for services registered with <see cref="PerScopeLifetime"/>.
/// </summary>
/// <returns>
/// A new <see cref="IDependencyScope"/>.
/// </returns>
public IDependencyScope BeginScope()
{
return new LightInjectWebApiDependencyScope(serviceContainer, serviceContainer.BeginScope());
}
}
/// <summary>
/// An <see cref="IDependencyScope"/> implementation that wraps a <see cref="Scope"/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class LightInjectWebApiDependencyScope : IDependencyScope
{
private readonly IServiceContainer serviceContainer;
private readonly Scope scope;
/// <summary>
/// Initializes a new instance of the <see cref="LightInjectWebApiDependencyScope"/> class.
/// </summary>
/// <param name="serviceContainer">The target <see cref="IServiceContainer"/>.</param>
/// <param name="scope">The wrapped <see cref="Scope"/>.</param>
public LightInjectWebApiDependencyScope(IServiceContainer serviceContainer, Scope scope)
{
this.serviceContainer = serviceContainer;
this.scope = scope;
}
/// <summary>
/// Gets an instance of the given <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">The type of the requested service.</param>
/// <returns>The requested service instance if available, otherwise null.</returns>
public object GetService(Type serviceType)
{
return serviceContainer.TryGetInstance(serviceType);
}
/// <summary>
/// Gets all instance of the given <paramref name="serviceType"/>.
/// </summary>
/// <param name="serviceType">The type of services to resolve.</param>
/// <returns>A list that contains all implementations of the <paramref name="serviceType"/>.</returns>
public IEnumerable<object> GetServices(Type serviceType)
{
return serviceContainer.GetAllInstances(serviceType);
}
/// <summary>
/// Disposes the <see cref="Scope"/>.
/// </summary>
public void Dispose()
{
scope.Dispose();
}
}
/// <summary>
/// A <see cref="IFilterProvider"/> that uses an <see cref="IServiceContainer"/>
/// to inject property dependencies into <see cref="IFilter"/> instances.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class LightInjectWebApiFilterProvider : IFilterProvider
{
private readonly IServiceContainer serviceContainer;
private readonly IEnumerable<IFilterProvider> filterProviders;
/// <summary>
/// Initializes a new instance of the <see cref="LightInjectWebApiFilterProvider"/> class.
/// </summary>
/// <param name="serviceContainer">The <see cref="IServiceContainer"/> instance
/// used to inject property dependencies.</param>
/// <param name="filterProviders">The list of existing filter providers.</param>
public LightInjectWebApiFilterProvider(IServiceContainer serviceContainer, IEnumerable<IFilterProvider> filterProviders)
{
this.serviceContainer = serviceContainer;
this.filterProviders = filterProviders;
}
/// <summary>
/// Returns an enumeration of filters.
/// </summary>
/// <returns>
/// An enumeration of filters.
/// </returns>
/// <param name="configuration">The HTTP configuration.</param><param name="actionDescriptor">The action descriptor.</param>
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
var filters = filterProviders.SelectMany(p => p.GetFilters(configuration, actionDescriptor)).ToArray();
foreach (var filterInfo in filters)
{
serviceContainer.InjectProperties(filterInfo.Instance);
}
return filters;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: ComEventsMethod
**
** Purpose: part of ComEventHelpers APIs which allow binding
** managed delegates to COM's connection point based events.
**
** Date: April 2008
**/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
namespace System.Runtime.InteropServices {
// see code:ComEventsHelper#ComEventsArchitecture
internal class ComEventsMethod {
// This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's
// existence is that under certain circumstances we need to coerce arguments to types expected by the
// delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion
// correctly but one known case is when the expected signature is 'ref Enum' - in this case
// reflection by design does not do the coercion. Since we need to be compatible with COM interop
// handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums'
// and cache the types required for such coercion.
internal class DelegateWrapper {
private Delegate _d;
private bool _once = false;
private int _expectedParamsCount;
private Type[] _cachedTargetTypes;
public DelegateWrapper(Delegate d) {
_d = d;
}
public Delegate Delegate {
get { return _d; }
set { _d = value; }
}
public object Invoke(object[] args) {
if (_d == null)
return null;
if (_once == false) {
PreProcessSignature();
_once = true;
}
if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) {
for (int i = 0; i < _expectedParamsCount; i++) {
if (_cachedTargetTypes[i] != null) {
args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]);
}
}
}
return _d.DynamicInvoke(args);
}
private void PreProcessSignature() {
ParameterInfo[] parameters = _d.Method.GetParameters();
_expectedParamsCount = parameters.Length;
Type[] enumTypes = new Type[_expectedParamsCount];
bool needToHandleCoercion = false;
for (int i = 0; i < _expectedParamsCount; i++) {
ParameterInfo pi = parameters[i];
// recognize only 'ref Enum' signatures and cache
// both enum type and the underlying type.
if (pi.ParameterType.IsByRef &&
pi.ParameterType.HasElementType &&
pi.ParameterType.GetElementType().IsEnum) {
needToHandleCoercion = true;
enumTypes[i] = pi.ParameterType.GetElementType();
}
}
if (needToHandleCoercion == true) {
_cachedTargetTypes = enumTypes;
}
}
}
#region private fields
/// <summary>
/// Invoking ComEventsMethod means invoking a multi-cast delegate attached to it.
/// Since multicast delegate's built-in chaining supports only chaining instances of the same type,
/// we need to complement this design by using an explicit linked list data structure.
/// </summary>
private DelegateWrapper [] _delegateWrappers;
private int _dispid;
private ComEventsMethod _next;
#endregion
#region ctor
internal ComEventsMethod(int dispid) {
_delegateWrappers = null;
_dispid = dispid;
}
#endregion
#region static internal methods
internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) {
while (methods != null && methods._dispid != dispid) {
methods = methods._next;
}
return methods;
}
internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) {
method._next = methods;
return method;
}
internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) {
if (methods == method) {
methods = methods._next;
} else {
ComEventsMethod current = methods;
while (current != null && current._next != method)
current = current._next;
if (current != null)
current._next = method._next;
}
return methods;
}
#endregion
#region public properties / methods
internal int DispId {
get { return _dispid; }
}
internal bool Empty {
get { return _delegateWrappers == null || _delegateWrappers.Length == 0; }
}
internal void AddDelegate(Delegate d) {
int count = 0;
if (_delegateWrappers != null) {
count = _delegateWrappers.Length;
}
for (int i = 0; i < count; i++) {
if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
_delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d);
return;
}
}
DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1];
if (count > 0) {
_delegateWrappers.CopyTo(newDelegateWrappers, 0);
}
DelegateWrapper wrapper = new DelegateWrapper(d);
newDelegateWrappers[count] = wrapper;
_delegateWrappers = newDelegateWrappers;
}
internal void RemoveDelegate(Delegate d) {
int count = _delegateWrappers.Length;
int removeIdx = -1;
for (int i = 0; i < count; i++) {
if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
removeIdx = i;
break;
}
}
if (removeIdx < 0)
return;
Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d);
if (newDelegate != null) {
_delegateWrappers[removeIdx].Delegate = newDelegate;
return;
}
// now remove the found entry from the _delegates array
if (count == 1) {
_delegateWrappers = null;
return;
}
DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1];
int j = 0;
while (j < removeIdx) {
newDelegateWrappers[j] = _delegateWrappers[j];
j++;
}
while (j < count-1) {
newDelegateWrappers[j] = _delegateWrappers[j + 1];
j++;
}
_delegateWrappers = newDelegateWrappers;
}
internal object Invoke(object[] args) {
BCLDebug.Assert(Empty == false, "event sink is executed but delegates list is empty");
// Issue: see code:ComEventsHelper#ComEventsRetValIssue
object result = null;
DelegateWrapper[] invocationList = _delegateWrappers;
foreach (DelegateWrapper wrapper in invocationList) {
if (wrapper == null || wrapper.Delegate == null)
continue;
result = wrapper.Invoke(args);
}
return result;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Security.Principal;
using System.Threading;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Filter;
using log4net.Repository;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Logging;
namespace Umbraco.Tests.Logging
{
[TestFixture]
public class ParallelForwarderTest : IDisposable
{
private ParallelForwardingAppender asyncForwardingAppender;
private DebugAppender debugAppender;
private ILoggerRepository repository;
private ILog log;
[SetUp]
public void TestFixtureSetUp()
{
debugAppender = new DebugAppender();
debugAppender.ActivateOptions();
asyncForwardingAppender = new ParallelForwardingAppender();
asyncForwardingAppender.AddAppender(debugAppender);
asyncForwardingAppender.ActivateOptions();
repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
BasicConfigurator.Configure(repository, asyncForwardingAppender);
log = LogManager.GetLogger(repository.Name, "TestLogger");
}
[TearDown]
public void TearDown()
{
LogManager.Shutdown();
}
[Test]
public void CanHandleNullLoggingEvent()
{
// Arrange
// Act
asyncForwardingAppender.DoAppend((LoggingEvent)null);
log.Info("SusequentMessage");
asyncForwardingAppender.Close();
// Assert - should not have had an exception from previous call
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(1), "Expected subsequent message only");
Assert.That(debugAppender.GetEvents()[0].MessageObject, Is.EqualTo("SusequentMessage"));
}
[Test]
public void CanHandleNullLoggingEvents()
{
// Arrange
// Act
asyncForwardingAppender.DoAppend((LoggingEvent[])null);
log.Info("SusequentMessage");
asyncForwardingAppender.Close();
// Assert - should not have had an exception from previous call
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(1), "Expected subsequent message only");
Assert.That(debugAppender.GetEvents()[0].MessageObject, Is.EqualTo("SusequentMessage"));
}
[Test]
public void CanHandleAppenderThrowing()
{
// Arrange
var badAppender = new Mock<IAppender>();
asyncForwardingAppender.AddAppender(badAppender.Object);
badAppender
.Setup(ba => ba.DoAppend(It.IsAny<LoggingEvent>()))
.Throws(new Exception("Bad Appender"));
//.Verifiable();
// Act
log.Info("InitialMessage");
log.Info("SusequentMessage");
asyncForwardingAppender.Close();
// Assert
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(2));
Assert.That(debugAppender.GetEvents()[1].MessageObject, Is.EqualTo("SusequentMessage"));
badAppender.Verify(appender => appender.DoAppend(It.IsAny<LoggingEvent>()), Times.Exactly(2));
}
[Test]
public void WillLogFastWhenThereIsASlowAppender()
{
const int testSize = 1000;
// Arrange
debugAppender.AppendDelay = TimeSpan.FromSeconds(10);
var watch = new Stopwatch();
// Act
watch.Start();
for (int i = 0; i < testSize; i++)
{
log.Error("Exception");
}
watch.Stop();
// Assert
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(0));
Assert.That(watch.ElapsedMilliseconds, Is.LessThan(testSize));
Console.WriteLine("Logged {0} errors in {1}ms", testSize, watch.ElapsedMilliseconds);
debugAppender.Cancel = true;
}
[Test]
public void WillNotOverflow()
{
const int testSize = 1000;
// Arrange
debugAppender.AppendDelay = TimeSpan.FromMilliseconds(1);
asyncForwardingAppender.BufferSize = 100;
// Act
for (int i = 0; i < testSize; i++)
{
log.Error("Exception");
}
while (asyncForwardingAppender.BufferEntryCount > 0) ;
asyncForwardingAppender.Close();
// Assert
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(testSize));
}
[Test]
public void WillTryToFlushBufferOnShutdown()
{
const int testSize = 250;
// Arrange
debugAppender.AppendDelay = TimeSpan.FromMilliseconds(1);
// Act
for (int i = 0; i < testSize; i++)
{
log.Error("Exception");
}
Thread.Sleep(50);
var numberLoggedBeforeClose = debugAppender.LoggedEventCount;
asyncForwardingAppender.Close();
var numberLoggedAfterClose = debugAppender.LoggedEventCount;
// Assert
//We can't use specific numbers here because the timing and counts will be different on different systems.
Assert.That(numberLoggedBeforeClose, Is.GreaterThan(0), "Some number of Logging events should be logged prior to appender close.");
//On some systems, we may not be able to flush all events prior to close, but it is reasonable to assume in this test case
//that some events should be logged after close.
Assert.That(numberLoggedAfterClose, Is.GreaterThan(numberLoggedBeforeClose), "Some number of LoggingEvents should be logged after close.");
Console.WriteLine("Flushed {0} events during shutdown", numberLoggedAfterClose - numberLoggedBeforeClose);
}
[Test, Explicit("Long-running")]
public void WillShutdownIfBufferCannotBeFlushedFastEnough()
{
const int testSize = 250;
// Arrange
debugAppender.AppendDelay = TimeSpan.FromSeconds(1);
Stopwatch watch = new Stopwatch();
// Act
for (int i = 0; i < testSize; i++)
{
log.Error("Exception");
}
Thread.Sleep(TimeSpan.FromSeconds(2));
var numberLoggedBeforeClose = debugAppender.LoggedEventCount;
watch.Start();
asyncForwardingAppender.Close();
watch.Stop();
var numberLoggedAfterClose = debugAppender.LoggedEventCount;
// Assert
Assert.That(numberLoggedBeforeClose, Is.GreaterThan(0));
Assert.That(numberLoggedAfterClose, Is.GreaterThan(numberLoggedBeforeClose));
Assert.That(numberLoggedAfterClose, Is.LessThan(testSize));
//We can't assume what the shutdown time will be. It will vary from system to system. Don't test shutdown time.
var events = debugAppender.GetEvents();
var evnt = events[events.Length - 1];
Assert.That(evnt.MessageObject, Is.EqualTo("The buffer was not able to be flushed before timeout occurred."));
Console.WriteLine("Flushed {0} events during shutdown which lasted {1}ms", numberLoggedAfterClose - numberLoggedBeforeClose, watch.ElapsedMilliseconds);
}
[Test]
public void ThreadContextPropertiesArePreserved()
{
// Arrange
ThreadContext.Properties["TestProperty"] = "My Value";
Assert.That(asyncForwardingAppender.Fix & FixFlags.Properties, Is.EqualTo(FixFlags.Properties), "Properties must be fixed if they are to be preserved");
// Act
log.Info("Information");
asyncForwardingAppender.Close();
// Assert
var lastLoggedEvent = debugAppender.GetEvents()[0];
Assert.That(lastLoggedEvent.Properties["TestProperty"], Is.EqualTo("My Value"));
}
[Test]
public void MessagesExcludedByFilterShouldNotBeAppended()
{
// Arrange
var levelFilter =
new LevelRangeFilter
{
LevelMin = Level.Warn,
LevelMax = Level.Error,
};
asyncForwardingAppender.AddFilter(levelFilter);
// Act
log.Info("Info");
log.Warn("Warn");
log.Error("Error");
log.Fatal("Fatal");
asyncForwardingAppender.Close();
//Assert
Assert.That(debugAppender.LoggedEventCount, Is.EqualTo(2));
}
[Test]
public void HelperCanGenerateLoggingEventWithAllProperties()
{
// Arrange
var helper = new LoggingEventHelper("TestLoggerName", FixFlags.All);
ThreadContext.Properties["MyProperty"] = "MyValue";
var exception = new Exception("SomeError");
var stackFrame = new StackFrame(0);
var currentUser = WindowsIdentity.GetCurrent();
var loggingTime = DateTime.Now; // Log4Net does not seem to be using UtcNow
// Act
var loggingEvent = helper.CreateLoggingEvent(Level.Emergency, "Who's on live support?", exception);
Thread.Sleep(50); // to make sure the time stamp is actually captured
// Assert
Assert.That(loggingEvent.Domain, Is.EqualTo(AppDomain.CurrentDomain.FriendlyName), "Domain");
//The identity assigned to new threads is dependent upon AppDomain principal policy.
//Background information here:http://www.neovolve.com/post/2010/10/21/Unit-testing-a-workflow-that-relies-on-ThreadCurrentPrincipalIdentityName.aspx
//VS2013 does have a principal assigned to new threads in the unit test.
//It's probably best not to test that the identity has been set.
//Assert.That(loggingEvent.Identity, Is.Empty, "Identity: always empty for some reason");
Assert.That(loggingEvent.UserName, Is.EqualTo(currentUser == null ? String.Empty : currentUser.Name), "UserName");
Assert.That(loggingEvent.ThreadName, Is.EqualTo(Thread.CurrentThread.Name), "ThreadName");
Assert.That(loggingEvent.Repository, Is.Null, "Repository: Helper does not have access to this");
Assert.That(loggingEvent.LoggerName, Is.EqualTo("TestLoggerName"), "LoggerName");
Assert.That(loggingEvent.Level, Is.EqualTo(Level.Emergency), "Level");
//Raised time to within 10 ms. However, this may not be a valid test. The time is going to vary from system to system. The
//tolerance setting here is arbitrary.
Assert.That(loggingEvent.TimeStamp, Is.EqualTo(loggingTime).Within(TimeSpan.FromMilliseconds(10)), "TimeStamp");
Assert.That(loggingEvent.ExceptionObject, Is.EqualTo(exception), "ExceptionObject");
Assert.That(loggingEvent.MessageObject, Is.EqualTo("Who's on live support?"), "MessageObject");
Assert.That(loggingEvent.LocationInformation.MethodName, Is.EqualTo(stackFrame.GetMethod().Name), "LocationInformation");
Assert.That(loggingEvent.Properties["MyProperty"], Is.EqualTo("MyValue"), "Properties");
}
private bool _disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (asyncForwardingAppender != null)
{
asyncForwardingAppender.Dispose();
asyncForwardingAppender = null;
}
}
// Free your own state (unmanaged objects).
// Set large fields to null.
_disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~ParallelForwarderTest()
{
// Simply call Dispose(false).
Dispose(false);
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright [email protected]
// Copyright iced contributors
using System;
namespace Generator.Enums {
[Enum("Code", Documentation = "x86 instruction code", Public = true)]
enum Code {
[Comment("It's an invalid instruction, eg. it's a new unknown instruction, garbage or there's not enough bytes to decode the instruction etc.")]
INVALID,
[Comment("A #(c:db)#/#(c:.byte)# asm directive that can store 1-16 bytes")]
DeclareByte,
[Comment("A #(c:dw)#/#(c:.word)# asm directive that can store 1-8 words")]
DeclareWord,
[Comment("A #(c:dd)#/#(c:.int)# asm directive that can store 1-4 dwords")]
DeclareDword,
[Comment("A #(c:dq)#/#(c:.quad)# asm directive that can store 1-2 qwords")]
DeclareQword,
Add_rm8_r8,
Add_rm16_r16,
Add_rm32_r32,
Add_rm64_r64,
Add_r8_rm8,
Add_r16_rm16,
Add_r32_rm32,
Add_r64_rm64,
Add_AL_imm8,
Add_AX_imm16,
Add_EAX_imm32,
Add_RAX_imm32,
Pushw_ES,
Pushd_ES,
Popw_ES,
Popd_ES,
Or_rm8_r8,
Or_rm16_r16,
Or_rm32_r32,
Or_rm64_r64,
Or_r8_rm8,
Or_r16_rm16,
Or_r32_rm32,
Or_r64_rm64,
Or_AL_imm8,
Or_AX_imm16,
Or_EAX_imm32,
Or_RAX_imm32,
Pushw_CS,
Pushd_CS,
Popw_CS,
Adc_rm8_r8,
Adc_rm16_r16,
Adc_rm32_r32,
Adc_rm64_r64,
Adc_r8_rm8,
Adc_r16_rm16,
Adc_r32_rm32,
Adc_r64_rm64,
Adc_AL_imm8,
Adc_AX_imm16,
Adc_EAX_imm32,
Adc_RAX_imm32,
Pushw_SS,
Pushd_SS,
Popw_SS,
Popd_SS,
Sbb_rm8_r8,
Sbb_rm16_r16,
Sbb_rm32_r32,
Sbb_rm64_r64,
Sbb_r8_rm8,
Sbb_r16_rm16,
Sbb_r32_rm32,
Sbb_r64_rm64,
Sbb_AL_imm8,
Sbb_AX_imm16,
Sbb_EAX_imm32,
Sbb_RAX_imm32,
Pushw_DS,
Pushd_DS,
Popw_DS,
Popd_DS,
And_rm8_r8,
And_rm16_r16,
And_rm32_r32,
And_rm64_r64,
And_r8_rm8,
And_r16_rm16,
And_r32_rm32,
And_r64_rm64,
And_AL_imm8,
And_AX_imm16,
And_EAX_imm32,
And_RAX_imm32,
Daa,
Sub_rm8_r8,
Sub_rm16_r16,
Sub_rm32_r32,
Sub_rm64_r64,
Sub_r8_rm8,
Sub_r16_rm16,
Sub_r32_rm32,
Sub_r64_rm64,
Sub_AL_imm8,
Sub_AX_imm16,
Sub_EAX_imm32,
Sub_RAX_imm32,
Das,
Xor_rm8_r8,
Xor_rm16_r16,
Xor_rm32_r32,
Xor_rm64_r64,
Xor_r8_rm8,
Xor_r16_rm16,
Xor_r32_rm32,
Xor_r64_rm64,
Xor_AL_imm8,
Xor_AX_imm16,
Xor_EAX_imm32,
Xor_RAX_imm32,
Aaa,
Cmp_rm8_r8,
Cmp_rm16_r16,
Cmp_rm32_r32,
Cmp_rm64_r64,
Cmp_r8_rm8,
Cmp_r16_rm16,
Cmp_r32_rm32,
Cmp_r64_rm64,
Cmp_AL_imm8,
Cmp_AX_imm16,
Cmp_EAX_imm32,
Cmp_RAX_imm32,
Aas,
Inc_r16,
Inc_r32,
Dec_r16,
Dec_r32,
Push_r16,
Push_r32,
Push_r64,
Pop_r16,
Pop_r32,
Pop_r64,
Pushaw,
Pushad,
Popaw,
Popad,
Bound_r16_m1616,
Bound_r32_m3232,
Arpl_rm16_r16,
Arpl_r32m16_r32,
Movsxd_r16_rm16,
Movsxd_r32_rm32,
Movsxd_r64_rm32,
Push_imm16,
Pushd_imm32,
Pushq_imm32,
Imul_r16_rm16_imm16,
Imul_r32_rm32_imm32,
Imul_r64_rm64_imm32,
Pushw_imm8,
Pushd_imm8,
Pushq_imm8,
Imul_r16_rm16_imm8,
Imul_r32_rm32_imm8,
Imul_r64_rm64_imm8,
Insb_m8_DX,
Insw_m16_DX,
Insd_m32_DX,
Outsb_DX_m8,
Outsw_DX_m16,
Outsd_DX_m32,
Jo_rel8_16,
Jo_rel8_32,
Jo_rel8_64,
Jno_rel8_16,
Jno_rel8_32,
Jno_rel8_64,
Jb_rel8_16,
Jb_rel8_32,
Jb_rel8_64,
Jae_rel8_16,
Jae_rel8_32,
Jae_rel8_64,
Je_rel8_16,
Je_rel8_32,
Je_rel8_64,
Jne_rel8_16,
Jne_rel8_32,
Jne_rel8_64,
Jbe_rel8_16,
Jbe_rel8_32,
Jbe_rel8_64,
Ja_rel8_16,
Ja_rel8_32,
Ja_rel8_64,
Js_rel8_16,
Js_rel8_32,
Js_rel8_64,
Jns_rel8_16,
Jns_rel8_32,
Jns_rel8_64,
Jp_rel8_16,
Jp_rel8_32,
Jp_rel8_64,
Jnp_rel8_16,
Jnp_rel8_32,
Jnp_rel8_64,
Jl_rel8_16,
Jl_rel8_32,
Jl_rel8_64,
Jge_rel8_16,
Jge_rel8_32,
Jge_rel8_64,
Jle_rel8_16,
Jle_rel8_32,
Jle_rel8_64,
Jg_rel8_16,
Jg_rel8_32,
Jg_rel8_64,
Add_rm8_imm8,
Or_rm8_imm8,
Adc_rm8_imm8,
Sbb_rm8_imm8,
And_rm8_imm8,
Sub_rm8_imm8,
Xor_rm8_imm8,
Cmp_rm8_imm8,
Add_rm16_imm16,
Add_rm32_imm32,
Add_rm64_imm32,
Or_rm16_imm16,
Or_rm32_imm32,
Or_rm64_imm32,
Adc_rm16_imm16,
Adc_rm32_imm32,
Adc_rm64_imm32,
Sbb_rm16_imm16,
Sbb_rm32_imm32,
Sbb_rm64_imm32,
And_rm16_imm16,
And_rm32_imm32,
And_rm64_imm32,
Sub_rm16_imm16,
Sub_rm32_imm32,
Sub_rm64_imm32,
Xor_rm16_imm16,
Xor_rm32_imm32,
Xor_rm64_imm32,
Cmp_rm16_imm16,
Cmp_rm32_imm32,
Cmp_rm64_imm32,
Add_rm8_imm8_82,
Or_rm8_imm8_82,
Adc_rm8_imm8_82,
Sbb_rm8_imm8_82,
And_rm8_imm8_82,
Sub_rm8_imm8_82,
Xor_rm8_imm8_82,
Cmp_rm8_imm8_82,
Add_rm16_imm8,
Add_rm32_imm8,
Add_rm64_imm8,
Or_rm16_imm8,
Or_rm32_imm8,
Or_rm64_imm8,
Adc_rm16_imm8,
Adc_rm32_imm8,
Adc_rm64_imm8,
Sbb_rm16_imm8,
Sbb_rm32_imm8,
Sbb_rm64_imm8,
And_rm16_imm8,
And_rm32_imm8,
And_rm64_imm8,
Sub_rm16_imm8,
Sub_rm32_imm8,
Sub_rm64_imm8,
Xor_rm16_imm8,
Xor_rm32_imm8,
Xor_rm64_imm8,
Cmp_rm16_imm8,
Cmp_rm32_imm8,
Cmp_rm64_imm8,
Test_rm8_r8,
Test_rm16_r16,
Test_rm32_r32,
Test_rm64_r64,
Xchg_rm8_r8,
Xchg_rm16_r16,
Xchg_rm32_r32,
Xchg_rm64_r64,
Mov_rm8_r8,
Mov_rm16_r16,
Mov_rm32_r32,
Mov_rm64_r64,
Mov_r8_rm8,
Mov_r16_rm16,
Mov_r32_rm32,
Mov_r64_rm64,
Mov_rm16_Sreg,
Mov_r32m16_Sreg,
Mov_r64m16_Sreg,
Lea_r16_m,
Lea_r32_m,
Lea_r64_m,
Mov_Sreg_rm16,
Mov_Sreg_r32m16,
Mov_Sreg_r64m16,
Pop_rm16,
Pop_rm32,
Pop_rm64,
Nopw,
Nopd,
Nopq,
Xchg_r16_AX,
Xchg_r32_EAX,
Xchg_r64_RAX,
Pause,
Cbw,
Cwde,
Cdqe,
Cwd,
Cdq,
Cqo,
Call_ptr1616,
Call_ptr1632,
Wait,
Pushfw,
Pushfd,
Pushfq,
Popfw,
Popfd,
Popfq,
Sahf,
Lahf,
Mov_AL_moffs8,
Mov_AX_moffs16,
Mov_EAX_moffs32,
Mov_RAX_moffs64,
Mov_moffs8_AL,
Mov_moffs16_AX,
Mov_moffs32_EAX,
Mov_moffs64_RAX,
Movsb_m8_m8,
Movsw_m16_m16,
Movsd_m32_m32,
Movsq_m64_m64,
Cmpsb_m8_m8,
Cmpsw_m16_m16,
Cmpsd_m32_m32,
Cmpsq_m64_m64,
Test_AL_imm8,
Test_AX_imm16,
Test_EAX_imm32,
Test_RAX_imm32,
Stosb_m8_AL,
Stosw_m16_AX,
Stosd_m32_EAX,
Stosq_m64_RAX,
Lodsb_AL_m8,
Lodsw_AX_m16,
Lodsd_EAX_m32,
Lodsq_RAX_m64,
Scasb_AL_m8,
Scasw_AX_m16,
Scasd_EAX_m32,
Scasq_RAX_m64,
Mov_r8_imm8,
Mov_r16_imm16,
Mov_r32_imm32,
Mov_r64_imm64,
Rol_rm8_imm8,
Ror_rm8_imm8,
Rcl_rm8_imm8,
Rcr_rm8_imm8,
Shl_rm8_imm8,
Shr_rm8_imm8,
Sal_rm8_imm8,
Sar_rm8_imm8,
Rol_rm16_imm8,
Rol_rm32_imm8,
Rol_rm64_imm8,
Ror_rm16_imm8,
Ror_rm32_imm8,
Ror_rm64_imm8,
Rcl_rm16_imm8,
Rcl_rm32_imm8,
Rcl_rm64_imm8,
Rcr_rm16_imm8,
Rcr_rm32_imm8,
Rcr_rm64_imm8,
Shl_rm16_imm8,
Shl_rm32_imm8,
Shl_rm64_imm8,
Shr_rm16_imm8,
Shr_rm32_imm8,
Shr_rm64_imm8,
Sal_rm16_imm8,
Sal_rm32_imm8,
Sal_rm64_imm8,
Sar_rm16_imm8,
Sar_rm32_imm8,
Sar_rm64_imm8,
Retnw_imm16,
Retnd_imm16,
Retnq_imm16,
Retnw,
Retnd,
Retnq,
Les_r16_m1616,
Les_r32_m1632,
Lds_r16_m1616,
Lds_r32_m1632,
Mov_rm8_imm8,
Xabort_imm8,
Mov_rm16_imm16,
Mov_rm32_imm32,
Mov_rm64_imm32,
Xbegin_rel16,
Xbegin_rel32,
Enterw_imm16_imm8,
Enterd_imm16_imm8,
Enterq_imm16_imm8,
Leavew,
Leaved,
Leaveq,
Retfw_imm16,
Retfd_imm16,
Retfq_imm16,
Retfw,
Retfd,
Retfq,
Int3,
Int_imm8,
Into,
Iretw,
Iretd,
Iretq,
Rol_rm8_1,
Ror_rm8_1,
Rcl_rm8_1,
Rcr_rm8_1,
Shl_rm8_1,
Shr_rm8_1,
Sal_rm8_1,
Sar_rm8_1,
Rol_rm16_1,
Rol_rm32_1,
Rol_rm64_1,
Ror_rm16_1,
Ror_rm32_1,
Ror_rm64_1,
Rcl_rm16_1,
Rcl_rm32_1,
Rcl_rm64_1,
Rcr_rm16_1,
Rcr_rm32_1,
Rcr_rm64_1,
Shl_rm16_1,
Shl_rm32_1,
Shl_rm64_1,
Shr_rm16_1,
Shr_rm32_1,
Shr_rm64_1,
Sal_rm16_1,
Sal_rm32_1,
Sal_rm64_1,
Sar_rm16_1,
Sar_rm32_1,
Sar_rm64_1,
Rol_rm8_CL,
Ror_rm8_CL,
Rcl_rm8_CL,
Rcr_rm8_CL,
Shl_rm8_CL,
Shr_rm8_CL,
Sal_rm8_CL,
Sar_rm8_CL,
Rol_rm16_CL,
Rol_rm32_CL,
Rol_rm64_CL,
Ror_rm16_CL,
Ror_rm32_CL,
Ror_rm64_CL,
Rcl_rm16_CL,
Rcl_rm32_CL,
Rcl_rm64_CL,
Rcr_rm16_CL,
Rcr_rm32_CL,
Rcr_rm64_CL,
Shl_rm16_CL,
Shl_rm32_CL,
Shl_rm64_CL,
Shr_rm16_CL,
Shr_rm32_CL,
Shr_rm64_CL,
Sal_rm16_CL,
Sal_rm32_CL,
Sal_rm64_CL,
Sar_rm16_CL,
Sar_rm32_CL,
Sar_rm64_CL,
Aam_imm8,
Aad_imm8,
Salc,
Xlat_m8,
Fadd_m32fp,
Fmul_m32fp,
Fcom_m32fp,
Fcomp_m32fp,
Fsub_m32fp,
Fsubr_m32fp,
Fdiv_m32fp,
Fdivr_m32fp,
Fadd_st0_sti,
Fmul_st0_sti,
Fcom_st0_sti,
Fcomp_st0_sti,
Fsub_st0_sti,
Fsubr_st0_sti,
Fdiv_st0_sti,
Fdivr_st0_sti,
Fld_m32fp,
Fst_m32fp,
Fstp_m32fp,
Fldenv_m14byte,
Fldenv_m28byte,
Fldcw_m2byte,
Fnstenv_m14byte,
Fstenv_m14byte,
Fnstenv_m28byte,
Fstenv_m28byte,
Fnstcw_m2byte,
Fstcw_m2byte,
Fld_sti,
Fxch_st0_sti,
Fnop,
Fstpnce_sti,
Fchs,
Fabs,
Ftst,
Fxam,
Fld1,
Fldl2t,
Fldl2e,
Fldpi,
Fldlg2,
Fldln2,
Fldz,
F2xm1,
Fyl2x,
Fptan,
Fpatan,
Fxtract,
Fprem1,
Fdecstp,
Fincstp,
Fprem,
Fyl2xp1,
Fsqrt,
Fsincos,
Frndint,
Fscale,
Fsin,
Fcos,
Fiadd_m32int,
Fimul_m32int,
Ficom_m32int,
Ficomp_m32int,
Fisub_m32int,
Fisubr_m32int,
Fidiv_m32int,
Fidivr_m32int,
Fcmovb_st0_sti,
Fcmove_st0_sti,
Fcmovbe_st0_sti,
Fcmovu_st0_sti,
Fucompp,
Fild_m32int,
Fisttp_m32int,
Fist_m32int,
Fistp_m32int,
Fld_m80fp,
Fstp_m80fp,
Fcmovnb_st0_sti,
Fcmovne_st0_sti,
Fcmovnbe_st0_sti,
Fcmovnu_st0_sti,
Fneni,
Feni,
Fndisi,
Fdisi,
Fnclex,
Fclex,
Fninit,
Finit,
Fnsetpm,
Fsetpm,
Frstpm,
Fucomi_st0_sti,
Fcomi_st0_sti,
Fadd_m64fp,
Fmul_m64fp,
Fcom_m64fp,
Fcomp_m64fp,
Fsub_m64fp,
Fsubr_m64fp,
Fdiv_m64fp,
Fdivr_m64fp,
Fadd_sti_st0,
Fmul_sti_st0,
Fcom_st0_sti_DCD0,
Fcomp_st0_sti_DCD8,
Fsubr_sti_st0,
Fsub_sti_st0,
Fdivr_sti_st0,
Fdiv_sti_st0,
Fld_m64fp,
Fisttp_m64int,
Fst_m64fp,
Fstp_m64fp,
Frstor_m94byte,
Frstor_m108byte,
Fnsave_m94byte,
Fsave_m94byte,
Fnsave_m108byte,
Fsave_m108byte,
Fnstsw_m2byte,
Fstsw_m2byte,
Ffree_sti,
Fxch_st0_sti_DDC8,
Fst_sti,
Fstp_sti,
Fucom_st0_sti,
Fucomp_st0_sti,
Fiadd_m16int,
Fimul_m16int,
Ficom_m16int,
Ficomp_m16int,
Fisub_m16int,
Fisubr_m16int,
Fidiv_m16int,
Fidivr_m16int,
Faddp_sti_st0,
Fmulp_sti_st0,
Fcomp_st0_sti_DED0,
Fcompp,
Fsubrp_sti_st0,
Fsubp_sti_st0,
Fdivrp_sti_st0,
Fdivp_sti_st0,
Fild_m16int,
Fisttp_m16int,
Fist_m16int,
Fistp_m16int,
Fbld_m80bcd,
Fild_m64int,
Fbstp_m80bcd,
Fistp_m64int,
Ffreep_sti,
Fxch_st0_sti_DFC8,
Fstp_sti_DFD0,
Fstp_sti_DFD8,
Fnstsw_AX,
Fstsw_AX,
Fstdw_AX,
Fstsg_AX,
Fucomip_st0_sti,
Fcomip_st0_sti,
Loopne_rel8_16_CX,
Loopne_rel8_32_CX,
Loopne_rel8_16_ECX,
Loopne_rel8_32_ECX,
Loopne_rel8_64_ECX,
Loopne_rel8_16_RCX,
Loopne_rel8_64_RCX,
Loope_rel8_16_CX,
Loope_rel8_32_CX,
Loope_rel8_16_ECX,
Loope_rel8_32_ECX,
Loope_rel8_64_ECX,
Loope_rel8_16_RCX,
Loope_rel8_64_RCX,
Loop_rel8_16_CX,
Loop_rel8_32_CX,
Loop_rel8_16_ECX,
Loop_rel8_32_ECX,
Loop_rel8_64_ECX,
Loop_rel8_16_RCX,
Loop_rel8_64_RCX,
Jcxz_rel8_16,
Jcxz_rel8_32,
Jecxz_rel8_16,
Jecxz_rel8_32,
Jecxz_rel8_64,
Jrcxz_rel8_16,
Jrcxz_rel8_64,
In_AL_imm8,
In_AX_imm8,
In_EAX_imm8,
Out_imm8_AL,
Out_imm8_AX,
Out_imm8_EAX,
Call_rel16,
Call_rel32_32,
Call_rel32_64,
Jmp_rel16,
Jmp_rel32_32,
Jmp_rel32_64,
Jmp_ptr1616,
Jmp_ptr1632,
Jmp_rel8_16,
Jmp_rel8_32,
Jmp_rel8_64,
In_AL_DX,
In_AX_DX,
In_EAX_DX,
Out_DX_AL,
Out_DX_AX,
Out_DX_EAX,
Int1,
Hlt,
Cmc,
Test_rm8_imm8,
Test_rm8_imm8_F6r1,
Not_rm8,
Neg_rm8,
Mul_rm8,
Imul_rm8,
Div_rm8,
Idiv_rm8,
Test_rm16_imm16,
Test_rm32_imm32,
Test_rm64_imm32,
Test_rm16_imm16_F7r1,
Test_rm32_imm32_F7r1,
Test_rm64_imm32_F7r1,
Not_rm16,
Not_rm32,
Not_rm64,
Neg_rm16,
Neg_rm32,
Neg_rm64,
Mul_rm16,
Mul_rm32,
Mul_rm64,
Imul_rm16,
Imul_rm32,
Imul_rm64,
Div_rm16,
Div_rm32,
Div_rm64,
Idiv_rm16,
Idiv_rm32,
Idiv_rm64,
Clc,
Stc,
Cli,
Sti,
Cld,
Std,
Inc_rm8,
Dec_rm8,
Inc_rm16,
Inc_rm32,
Inc_rm64,
Dec_rm16,
Dec_rm32,
Dec_rm64,
Call_rm16,
Call_rm32,
Call_rm64,
Call_m1616,
Call_m1632,
Call_m1664,
Jmp_rm16,
Jmp_rm32,
Jmp_rm64,
Jmp_m1616,
Jmp_m1632,
Jmp_m1664,
Push_rm16,
Push_rm32,
Push_rm64,
Sldt_rm16,
Sldt_r32m16,
Sldt_r64m16,
Str_rm16,
Str_r32m16,
Str_r64m16,
Lldt_rm16,
Lldt_r32m16,
Lldt_r64m16,
Ltr_rm16,
Ltr_r32m16,
Ltr_r64m16,
Verr_rm16,
Verr_r32m16,
Verr_r64m16,
Verw_rm16,
Verw_r32m16,
Verw_r64m16,
Jmpe_rm16,
Jmpe_rm32,
Sgdt_m1632_16,
Sgdt_m1632,
Sgdt_m1664,
Sidt_m1632_16,
Sidt_m1632,
Sidt_m1664,
Lgdt_m1632_16,
Lgdt_m1632,
Lgdt_m1664,
Lidt_m1632_16,
Lidt_m1632,
Lidt_m1664,
Smsw_rm16,
Smsw_r32m16,
Smsw_r64m16,
Rstorssp_m64,
Lmsw_rm16,
Lmsw_r32m16,
Lmsw_r64m16,
Invlpg_m,
Enclv,
Vmcall,
Vmlaunch,
Vmresume,
Vmxoff,
Pconfig,
Monitorw,
Monitord,
Monitorq,
Mwait,
Clac,
Stac,
Encls,
Xgetbv,
Xsetbv,
Vmfunc,
Xend,
Xtest,
Enclu,
Vmrunw,
Vmrund,
Vmrunq,
Vmmcall,
Vmloadw,
Vmloadd,
Vmloadq,
Vmsavew,
Vmsaved,
Vmsaveq,
Stgi,
Clgi,
Skinit,
Invlpgaw,
Invlpgad,
Invlpgaq,
Setssbsy,
Saveprevssp,
Rdpkru,
Wrpkru,
Swapgs,
Rdtscp,
Monitorxw,
Monitorxd,
Monitorxq,
Mcommit,
Mwaitx,
Clzerow,
Clzerod,
Clzeroq,
Rdpru,
Lar_r16_rm16,
Lar_r32_r32m16,
Lar_r64_r64m16,
Lsl_r16_rm16,
Lsl_r32_r32m16,
Lsl_r64_r64m16,
Loadallreset286,
Loadall286,
Syscall,
Clts,
Loadall386,
Sysretd,
Sysretq,
Invd,
Wbinvd,
Wbnoinvd,
Cl1invmb,
Ud2,
Reservednop_rm16_r16_0F0D,
Reservednop_rm32_r32_0F0D,
Reservednop_rm64_r64_0F0D,
Prefetch_m8,
Prefetchw_m8,
Prefetchwt1_m8,
Femms,
Umov_rm8_r8,
Umov_rm16_r16,
Umov_rm32_r32,
Umov_r8_rm8,
Umov_r16_rm16,
Umov_r32_rm32,
Movups_xmm_xmmm128,
VEX_Vmovups_xmm_xmmm128,
VEX_Vmovups_ymm_ymmm256,
EVEX_Vmovups_xmm_k1z_xmmm128,
EVEX_Vmovups_ymm_k1z_ymmm256,
EVEX_Vmovups_zmm_k1z_zmmm512,
Movupd_xmm_xmmm128,
VEX_Vmovupd_xmm_xmmm128,
VEX_Vmovupd_ymm_ymmm256,
EVEX_Vmovupd_xmm_k1z_xmmm128,
EVEX_Vmovupd_ymm_k1z_ymmm256,
EVEX_Vmovupd_zmm_k1z_zmmm512,
Movss_xmm_xmmm32,
VEX_Vmovss_xmm_xmm_xmm,
VEX_Vmovss_xmm_m32,
EVEX_Vmovss_xmm_k1z_xmm_xmm,
EVEX_Vmovss_xmm_k1z_m32,
Movsd_xmm_xmmm64,
VEX_Vmovsd_xmm_xmm_xmm,
VEX_Vmovsd_xmm_m64,
EVEX_Vmovsd_xmm_k1z_xmm_xmm,
EVEX_Vmovsd_xmm_k1z_m64,
Movups_xmmm128_xmm,
VEX_Vmovups_xmmm128_xmm,
VEX_Vmovups_ymmm256_ymm,
EVEX_Vmovups_xmmm128_k1z_xmm,
EVEX_Vmovups_ymmm256_k1z_ymm,
EVEX_Vmovups_zmmm512_k1z_zmm,
Movupd_xmmm128_xmm,
VEX_Vmovupd_xmmm128_xmm,
VEX_Vmovupd_ymmm256_ymm,
EVEX_Vmovupd_xmmm128_k1z_xmm,
EVEX_Vmovupd_ymmm256_k1z_ymm,
EVEX_Vmovupd_zmmm512_k1z_zmm,
Movss_xmmm32_xmm,
VEX_Vmovss_xmm_xmm_xmm_0F11,
VEX_Vmovss_m32_xmm,
EVEX_Vmovss_xmm_k1z_xmm_xmm_0F11,
EVEX_Vmovss_m32_k1_xmm,
Movsd_xmmm64_xmm,
VEX_Vmovsd_xmm_xmm_xmm_0F11,
VEX_Vmovsd_m64_xmm,
EVEX_Vmovsd_xmm_k1z_xmm_xmm_0F11,
EVEX_Vmovsd_m64_k1_xmm,
Movhlps_xmm_xmm,
Movlps_xmm_m64,
VEX_Vmovhlps_xmm_xmm_xmm,
VEX_Vmovlps_xmm_xmm_m64,
EVEX_Vmovhlps_xmm_xmm_xmm,
EVEX_Vmovlps_xmm_xmm_m64,
Movlpd_xmm_m64,
VEX_Vmovlpd_xmm_xmm_m64,
EVEX_Vmovlpd_xmm_xmm_m64,
Movsldup_xmm_xmmm128,
VEX_Vmovsldup_xmm_xmmm128,
VEX_Vmovsldup_ymm_ymmm256,
EVEX_Vmovsldup_xmm_k1z_xmmm128,
EVEX_Vmovsldup_ymm_k1z_ymmm256,
EVEX_Vmovsldup_zmm_k1z_zmmm512,
Movddup_xmm_xmmm64,
VEX_Vmovddup_xmm_xmmm64,
VEX_Vmovddup_ymm_ymmm256,
EVEX_Vmovddup_xmm_k1z_xmmm64,
EVEX_Vmovddup_ymm_k1z_ymmm256,
EVEX_Vmovddup_zmm_k1z_zmmm512,
Movlps_m64_xmm,
VEX_Vmovlps_m64_xmm,
EVEX_Vmovlps_m64_xmm,
Movlpd_m64_xmm,
VEX_Vmovlpd_m64_xmm,
EVEX_Vmovlpd_m64_xmm,
Unpcklps_xmm_xmmm128,
VEX_Vunpcklps_xmm_xmm_xmmm128,
VEX_Vunpcklps_ymm_ymm_ymmm256,
EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vunpcklps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vunpcklps_zmm_k1z_zmm_zmmm512b32,
Unpcklpd_xmm_xmmm128,
VEX_Vunpcklpd_xmm_xmm_xmmm128,
VEX_Vunpcklpd_ymm_ymm_ymmm256,
EVEX_Vunpcklpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vunpcklpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vunpcklpd_zmm_k1z_zmm_zmmm512b64,
Unpckhps_xmm_xmmm128,
VEX_Vunpckhps_xmm_xmm_xmmm128,
VEX_Vunpckhps_ymm_ymm_ymmm256,
EVEX_Vunpckhps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vunpckhps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vunpckhps_zmm_k1z_zmm_zmmm512b32,
Unpckhpd_xmm_xmmm128,
VEX_Vunpckhpd_xmm_xmm_xmmm128,
VEX_Vunpckhpd_ymm_ymm_ymmm256,
EVEX_Vunpckhpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vunpckhpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vunpckhpd_zmm_k1z_zmm_zmmm512b64,
Movlhps_xmm_xmm,
VEX_Vmovlhps_xmm_xmm_xmm,
EVEX_Vmovlhps_xmm_xmm_xmm,
Movhps_xmm_m64,
VEX_Vmovhps_xmm_xmm_m64,
EVEX_Vmovhps_xmm_xmm_m64,
Movhpd_xmm_m64,
VEX_Vmovhpd_xmm_xmm_m64,
EVEX_Vmovhpd_xmm_xmm_m64,
Movshdup_xmm_xmmm128,
VEX_Vmovshdup_xmm_xmmm128,
VEX_Vmovshdup_ymm_ymmm256,
EVEX_Vmovshdup_xmm_k1z_xmmm128,
EVEX_Vmovshdup_ymm_k1z_ymmm256,
EVEX_Vmovshdup_zmm_k1z_zmmm512,
Movhps_m64_xmm,
VEX_Vmovhps_m64_xmm,
EVEX_Vmovhps_m64_xmm,
Movhpd_m64_xmm,
VEX_Vmovhpd_m64_xmm,
EVEX_Vmovhpd_m64_xmm,
Reservednop_rm16_r16_0F18,
Reservednop_rm32_r32_0F18,
Reservednop_rm64_r64_0F18,
Reservednop_rm16_r16_0F19,
Reservednop_rm32_r32_0F19,
Reservednop_rm64_r64_0F19,
Reservednop_rm16_r16_0F1A,
Reservednop_rm32_r32_0F1A,
Reservednop_rm64_r64_0F1A,
Reservednop_rm16_r16_0F1B,
Reservednop_rm32_r32_0F1B,
Reservednop_rm64_r64_0F1B,
Reservednop_rm16_r16_0F1C,
Reservednop_rm32_r32_0F1C,
Reservednop_rm64_r64_0F1C,
Reservednop_rm16_r16_0F1D,
Reservednop_rm32_r32_0F1D,
Reservednop_rm64_r64_0F1D,
Reservednop_rm16_r16_0F1E,
Reservednop_rm32_r32_0F1E,
Reservednop_rm64_r64_0F1E,
Reservednop_rm16_r16_0F1F,
Reservednop_rm32_r32_0F1F,
Reservednop_rm64_r64_0F1F,
Prefetchnta_m8,
Prefetcht0_m8,
Prefetcht1_m8,
Prefetcht2_m8,
Bndldx_bnd_mib,
Bndmov_bnd_bndm64,
Bndmov_bnd_bndm128,
Bndcl_bnd_rm32,
Bndcl_bnd_rm64,
Bndcu_bnd_rm32,
Bndcu_bnd_rm64,
Bndstx_mib_bnd,
Bndmov_bndm64_bnd,
Bndmov_bndm128_bnd,
Bndmk_bnd_m32,
Bndmk_bnd_m64,
Bndcn_bnd_rm32,
Bndcn_bnd_rm64,
Cldemote_m8,
Rdsspd_r32,
Rdsspq_r64,
Endbr64,
Endbr32,
Nop_rm16,
Nop_rm32,
Nop_rm64,
Mov_r32_cr,
Mov_r64_cr,
Mov_r32_dr,
Mov_r64_dr,
Mov_cr_r32,
Mov_cr_r64,
Mov_dr_r32,
Mov_dr_r64,
Mov_r32_tr,
Mov_tr_r32,
Movaps_xmm_xmmm128,
VEX_Vmovaps_xmm_xmmm128,
VEX_Vmovaps_ymm_ymmm256,
EVEX_Vmovaps_xmm_k1z_xmmm128,
EVEX_Vmovaps_ymm_k1z_ymmm256,
EVEX_Vmovaps_zmm_k1z_zmmm512,
Movapd_xmm_xmmm128,
VEX_Vmovapd_xmm_xmmm128,
VEX_Vmovapd_ymm_ymmm256,
EVEX_Vmovapd_xmm_k1z_xmmm128,
EVEX_Vmovapd_ymm_k1z_ymmm256,
EVEX_Vmovapd_zmm_k1z_zmmm512,
Movaps_xmmm128_xmm,
VEX_Vmovaps_xmmm128_xmm,
VEX_Vmovaps_ymmm256_ymm,
EVEX_Vmovaps_xmmm128_k1z_xmm,
EVEX_Vmovaps_ymmm256_k1z_ymm,
EVEX_Vmovaps_zmmm512_k1z_zmm,
Movapd_xmmm128_xmm,
VEX_Vmovapd_xmmm128_xmm,
VEX_Vmovapd_ymmm256_ymm,
EVEX_Vmovapd_xmmm128_k1z_xmm,
EVEX_Vmovapd_ymmm256_k1z_ymm,
EVEX_Vmovapd_zmmm512_k1z_zmm,
Cvtpi2ps_xmm_mmm64,
Cvtpi2pd_xmm_mmm64,
Cvtsi2ss_xmm_rm32,
Cvtsi2ss_xmm_rm64,
VEX_Vcvtsi2ss_xmm_xmm_rm32,
VEX_Vcvtsi2ss_xmm_xmm_rm64,
EVEX_Vcvtsi2ss_xmm_xmm_rm32_er,
EVEX_Vcvtsi2ss_xmm_xmm_rm64_er,
Cvtsi2sd_xmm_rm32,
Cvtsi2sd_xmm_rm64,
VEX_Vcvtsi2sd_xmm_xmm_rm32,
VEX_Vcvtsi2sd_xmm_xmm_rm64,
EVEX_Vcvtsi2sd_xmm_xmm_rm32_er,
EVEX_Vcvtsi2sd_xmm_xmm_rm64_er,
Movntps_m128_xmm,
VEX_Vmovntps_m128_xmm,
VEX_Vmovntps_m256_ymm,
EVEX_Vmovntps_m128_xmm,
EVEX_Vmovntps_m256_ymm,
EVEX_Vmovntps_m512_zmm,
Movntpd_m128_xmm,
VEX_Vmovntpd_m128_xmm,
VEX_Vmovntpd_m256_ymm,
EVEX_Vmovntpd_m128_xmm,
EVEX_Vmovntpd_m256_ymm,
EVEX_Vmovntpd_m512_zmm,
Movntss_m32_xmm,
Movntsd_m64_xmm,
Cvttps2pi_mm_xmmm64,
Cvttpd2pi_mm_xmmm128,
Cvttss2si_r32_xmmm32,
Cvttss2si_r64_xmmm32,
VEX_Vcvttss2si_r32_xmmm32,
VEX_Vcvttss2si_r64_xmmm32,
EVEX_Vcvttss2si_r32_xmmm32_sae,
EVEX_Vcvttss2si_r64_xmmm32_sae,
Cvttsd2si_r32_xmmm64,
Cvttsd2si_r64_xmmm64,
VEX_Vcvttsd2si_r32_xmmm64,
VEX_Vcvttsd2si_r64_xmmm64,
EVEX_Vcvttsd2si_r32_xmmm64_sae,
EVEX_Vcvttsd2si_r64_xmmm64_sae,
Cvtps2pi_mm_xmmm64,
Cvtpd2pi_mm_xmmm128,
Cvtss2si_r32_xmmm32,
Cvtss2si_r64_xmmm32,
VEX_Vcvtss2si_r32_xmmm32,
VEX_Vcvtss2si_r64_xmmm32,
EVEX_Vcvtss2si_r32_xmmm32_er,
EVEX_Vcvtss2si_r64_xmmm32_er,
Cvtsd2si_r32_xmmm64,
Cvtsd2si_r64_xmmm64,
VEX_Vcvtsd2si_r32_xmmm64,
VEX_Vcvtsd2si_r64_xmmm64,
EVEX_Vcvtsd2si_r32_xmmm64_er,
EVEX_Vcvtsd2si_r64_xmmm64_er,
Ucomiss_xmm_xmmm32,
VEX_Vucomiss_xmm_xmmm32,
EVEX_Vucomiss_xmm_xmmm32_sae,
Ucomisd_xmm_xmmm64,
VEX_Vucomisd_xmm_xmmm64,
EVEX_Vucomisd_xmm_xmmm64_sae,
Comiss_xmm_xmmm32,
Comisd_xmm_xmmm64,
VEX_Vcomiss_xmm_xmmm32,
VEX_Vcomisd_xmm_xmmm64,
EVEX_Vcomiss_xmm_xmmm32_sae,
EVEX_Vcomisd_xmm_xmmm64_sae,
Wrmsr,
Rdtsc,
Rdmsr,
Rdpmc,
Sysenter,
Sysexitd,
Sysexitq,
Getsecd,
Cmovo_r16_rm16,
Cmovo_r32_rm32,
Cmovo_r64_rm64,
Cmovno_r16_rm16,
Cmovno_r32_rm32,
Cmovno_r64_rm64,
Cmovb_r16_rm16,
Cmovb_r32_rm32,
Cmovb_r64_rm64,
Cmovae_r16_rm16,
Cmovae_r32_rm32,
Cmovae_r64_rm64,
Cmove_r16_rm16,
Cmove_r32_rm32,
Cmove_r64_rm64,
Cmovne_r16_rm16,
Cmovne_r32_rm32,
Cmovne_r64_rm64,
Cmovbe_r16_rm16,
Cmovbe_r32_rm32,
Cmovbe_r64_rm64,
Cmova_r16_rm16,
Cmova_r32_rm32,
Cmova_r64_rm64,
Cmovs_r16_rm16,
Cmovs_r32_rm32,
Cmovs_r64_rm64,
Cmovns_r16_rm16,
Cmovns_r32_rm32,
Cmovns_r64_rm64,
Cmovp_r16_rm16,
Cmovp_r32_rm32,
Cmovp_r64_rm64,
Cmovnp_r16_rm16,
Cmovnp_r32_rm32,
Cmovnp_r64_rm64,
Cmovl_r16_rm16,
Cmovl_r32_rm32,
Cmovl_r64_rm64,
Cmovge_r16_rm16,
Cmovge_r32_rm32,
Cmovge_r64_rm64,
Cmovle_r16_rm16,
Cmovle_r32_rm32,
Cmovle_r64_rm64,
Cmovg_r16_rm16,
Cmovg_r32_rm32,
Cmovg_r64_rm64,
VEX_Kandw_kr_kr_kr,
VEX_Kandq_kr_kr_kr,
VEX_Kandb_kr_kr_kr,
VEX_Kandd_kr_kr_kr,
VEX_Kandnw_kr_kr_kr,
VEX_Kandnq_kr_kr_kr,
VEX_Kandnb_kr_kr_kr,
VEX_Kandnd_kr_kr_kr,
VEX_Knotw_kr_kr,
VEX_Knotq_kr_kr,
VEX_Knotb_kr_kr,
VEX_Knotd_kr_kr,
VEX_Korw_kr_kr_kr,
VEX_Korq_kr_kr_kr,
VEX_Korb_kr_kr_kr,
VEX_Kord_kr_kr_kr,
VEX_Kxnorw_kr_kr_kr,
VEX_Kxnorq_kr_kr_kr,
VEX_Kxnorb_kr_kr_kr,
VEX_Kxnord_kr_kr_kr,
VEX_Kxorw_kr_kr_kr,
VEX_Kxorq_kr_kr_kr,
VEX_Kxorb_kr_kr_kr,
VEX_Kxord_kr_kr_kr,
VEX_Kaddw_kr_kr_kr,
VEX_Kaddq_kr_kr_kr,
VEX_Kaddb_kr_kr_kr,
VEX_Kaddd_kr_kr_kr,
VEX_Kunpckwd_kr_kr_kr,
VEX_Kunpckdq_kr_kr_kr,
VEX_Kunpckbw_kr_kr_kr,
Movmskps_r32_xmm,
Movmskps_r64_xmm,
VEX_Vmovmskps_r32_xmm,
VEX_Vmovmskps_r64_xmm,
VEX_Vmovmskps_r32_ymm,
VEX_Vmovmskps_r64_ymm,
Movmskpd_r32_xmm,
Movmskpd_r64_xmm,
VEX_Vmovmskpd_r32_xmm,
VEX_Vmovmskpd_r64_xmm,
VEX_Vmovmskpd_r32_ymm,
VEX_Vmovmskpd_r64_ymm,
Sqrtps_xmm_xmmm128,
VEX_Vsqrtps_xmm_xmmm128,
VEX_Vsqrtps_ymm_ymmm256,
EVEX_Vsqrtps_xmm_k1z_xmmm128b32,
EVEX_Vsqrtps_ymm_k1z_ymmm256b32,
EVEX_Vsqrtps_zmm_k1z_zmmm512b32_er,
Sqrtpd_xmm_xmmm128,
VEX_Vsqrtpd_xmm_xmmm128,
VEX_Vsqrtpd_ymm_ymmm256,
EVEX_Vsqrtpd_xmm_k1z_xmmm128b64,
EVEX_Vsqrtpd_ymm_k1z_ymmm256b64,
EVEX_Vsqrtpd_zmm_k1z_zmmm512b64_er,
Sqrtss_xmm_xmmm32,
VEX_Vsqrtss_xmm_xmm_xmmm32,
EVEX_Vsqrtss_xmm_k1z_xmm_xmmm32_er,
Sqrtsd_xmm_xmmm64,
VEX_Vsqrtsd_xmm_xmm_xmmm64,
EVEX_Vsqrtsd_xmm_k1z_xmm_xmmm64_er,
Rsqrtps_xmm_xmmm128,
VEX_Vrsqrtps_xmm_xmmm128,
VEX_Vrsqrtps_ymm_ymmm256,
Rsqrtss_xmm_xmmm32,
VEX_Vrsqrtss_xmm_xmm_xmmm32,
Rcpps_xmm_xmmm128,
VEX_Vrcpps_xmm_xmmm128,
VEX_Vrcpps_ymm_ymmm256,
Rcpss_xmm_xmmm32,
VEX_Vrcpss_xmm_xmm_xmmm32,
Andps_xmm_xmmm128,
VEX_Vandps_xmm_xmm_xmmm128,
VEX_Vandps_ymm_ymm_ymmm256,
EVEX_Vandps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vandps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vandps_zmm_k1z_zmm_zmmm512b32,
Andpd_xmm_xmmm128,
VEX_Vandpd_xmm_xmm_xmmm128,
VEX_Vandpd_ymm_ymm_ymmm256,
EVEX_Vandpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vandpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vandpd_zmm_k1z_zmm_zmmm512b64,
Andnps_xmm_xmmm128,
VEX_Vandnps_xmm_xmm_xmmm128,
VEX_Vandnps_ymm_ymm_ymmm256,
EVEX_Vandnps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vandnps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vandnps_zmm_k1z_zmm_zmmm512b32,
Andnpd_xmm_xmmm128,
VEX_Vandnpd_xmm_xmm_xmmm128,
VEX_Vandnpd_ymm_ymm_ymmm256,
EVEX_Vandnpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vandnpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vandnpd_zmm_k1z_zmm_zmmm512b64,
Orps_xmm_xmmm128,
VEX_Vorps_xmm_xmm_xmmm128,
VEX_Vorps_ymm_ymm_ymmm256,
EVEX_Vorps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vorps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vorps_zmm_k1z_zmm_zmmm512b32,
Orpd_xmm_xmmm128,
VEX_Vorpd_xmm_xmm_xmmm128,
VEX_Vorpd_ymm_ymm_ymmm256,
EVEX_Vorpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vorpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vorpd_zmm_k1z_zmm_zmmm512b64,
Xorps_xmm_xmmm128,
VEX_Vxorps_xmm_xmm_xmmm128,
VEX_Vxorps_ymm_ymm_ymmm256,
EVEX_Vxorps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vxorps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vxorps_zmm_k1z_zmm_zmmm512b32,
Xorpd_xmm_xmmm128,
VEX_Vxorpd_xmm_xmm_xmmm128,
VEX_Vxorpd_ymm_ymm_ymmm256,
EVEX_Vxorpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vxorpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vxorpd_zmm_k1z_zmm_zmmm512b64,
Addps_xmm_xmmm128,
VEX_Vaddps_xmm_xmm_xmmm128,
VEX_Vaddps_ymm_ymm_ymmm256,
EVEX_Vaddps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vaddps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vaddps_zmm_k1z_zmm_zmmm512b32_er,
Addpd_xmm_xmmm128,
VEX_Vaddpd_xmm_xmm_xmmm128,
VEX_Vaddpd_ymm_ymm_ymmm256,
EVEX_Vaddpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vaddpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vaddpd_zmm_k1z_zmm_zmmm512b64_er,
Addss_xmm_xmmm32,
VEX_Vaddss_xmm_xmm_xmmm32,
EVEX_Vaddss_xmm_k1z_xmm_xmmm32_er,
Addsd_xmm_xmmm64,
VEX_Vaddsd_xmm_xmm_xmmm64,
EVEX_Vaddsd_xmm_k1z_xmm_xmmm64_er,
Mulps_xmm_xmmm128,
VEX_Vmulps_xmm_xmm_xmmm128,
VEX_Vmulps_ymm_ymm_ymmm256,
EVEX_Vmulps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vmulps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vmulps_zmm_k1z_zmm_zmmm512b32_er,
Mulpd_xmm_xmmm128,
VEX_Vmulpd_xmm_xmm_xmmm128,
VEX_Vmulpd_ymm_ymm_ymmm256,
EVEX_Vmulpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vmulpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vmulpd_zmm_k1z_zmm_zmmm512b64_er,
Mulss_xmm_xmmm32,
VEX_Vmulss_xmm_xmm_xmmm32,
EVEX_Vmulss_xmm_k1z_xmm_xmmm32_er,
Mulsd_xmm_xmmm64,
VEX_Vmulsd_xmm_xmm_xmmm64,
EVEX_Vmulsd_xmm_k1z_xmm_xmmm64_er,
Cvtps2pd_xmm_xmmm64,
VEX_Vcvtps2pd_xmm_xmmm64,
VEX_Vcvtps2pd_ymm_xmmm128,
EVEX_Vcvtps2pd_xmm_k1z_xmmm64b32,
EVEX_Vcvtps2pd_ymm_k1z_xmmm128b32,
EVEX_Vcvtps2pd_zmm_k1z_ymmm256b32_sae,
Cvtpd2ps_xmm_xmmm128,
VEX_Vcvtpd2ps_xmm_xmmm128,
VEX_Vcvtpd2ps_xmm_ymmm256,
EVEX_Vcvtpd2ps_xmm_k1z_xmmm128b64,
EVEX_Vcvtpd2ps_xmm_k1z_ymmm256b64,
EVEX_Vcvtpd2ps_ymm_k1z_zmmm512b64_er,
Cvtss2sd_xmm_xmmm32,
VEX_Vcvtss2sd_xmm_xmm_xmmm32,
EVEX_Vcvtss2sd_xmm_k1z_xmm_xmmm32_sae,
Cvtsd2ss_xmm_xmmm64,
VEX_Vcvtsd2ss_xmm_xmm_xmmm64,
EVEX_Vcvtsd2ss_xmm_k1z_xmm_xmmm64_er,
Cvtdq2ps_xmm_xmmm128,
VEX_Vcvtdq2ps_xmm_xmmm128,
VEX_Vcvtdq2ps_ymm_ymmm256,
EVEX_Vcvtdq2ps_xmm_k1z_xmmm128b32,
EVEX_Vcvtdq2ps_ymm_k1z_ymmm256b32,
EVEX_Vcvtdq2ps_zmm_k1z_zmmm512b32_er,
EVEX_Vcvtqq2ps_xmm_k1z_xmmm128b64,
EVEX_Vcvtqq2ps_xmm_k1z_ymmm256b64,
EVEX_Vcvtqq2ps_ymm_k1z_zmmm512b64_er,
Cvtps2dq_xmm_xmmm128,
VEX_Vcvtps2dq_xmm_xmmm128,
VEX_Vcvtps2dq_ymm_ymmm256,
EVEX_Vcvtps2dq_xmm_k1z_xmmm128b32,
EVEX_Vcvtps2dq_ymm_k1z_ymmm256b32,
EVEX_Vcvtps2dq_zmm_k1z_zmmm512b32_er,
Cvttps2dq_xmm_xmmm128,
VEX_Vcvttps2dq_xmm_xmmm128,
VEX_Vcvttps2dq_ymm_ymmm256,
EVEX_Vcvttps2dq_xmm_k1z_xmmm128b32,
EVEX_Vcvttps2dq_ymm_k1z_ymmm256b32,
EVEX_Vcvttps2dq_zmm_k1z_zmmm512b32_sae,
Subps_xmm_xmmm128,
VEX_Vsubps_xmm_xmm_xmmm128,
VEX_Vsubps_ymm_ymm_ymmm256,
EVEX_Vsubps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vsubps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vsubps_zmm_k1z_zmm_zmmm512b32_er,
Subpd_xmm_xmmm128,
VEX_Vsubpd_xmm_xmm_xmmm128,
VEX_Vsubpd_ymm_ymm_ymmm256,
EVEX_Vsubpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vsubpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vsubpd_zmm_k1z_zmm_zmmm512b64_er,
Subss_xmm_xmmm32,
VEX_Vsubss_xmm_xmm_xmmm32,
EVEX_Vsubss_xmm_k1z_xmm_xmmm32_er,
Subsd_xmm_xmmm64,
VEX_Vsubsd_xmm_xmm_xmmm64,
EVEX_Vsubsd_xmm_k1z_xmm_xmmm64_er,
Minps_xmm_xmmm128,
VEX_Vminps_xmm_xmm_xmmm128,
VEX_Vminps_ymm_ymm_ymmm256,
EVEX_Vminps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vminps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vminps_zmm_k1z_zmm_zmmm512b32_sae,
Minpd_xmm_xmmm128,
VEX_Vminpd_xmm_xmm_xmmm128,
VEX_Vminpd_ymm_ymm_ymmm256,
EVEX_Vminpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vminpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vminpd_zmm_k1z_zmm_zmmm512b64_sae,
Minss_xmm_xmmm32,
VEX_Vminss_xmm_xmm_xmmm32,
EVEX_Vminss_xmm_k1z_xmm_xmmm32_sae,
Minsd_xmm_xmmm64,
VEX_Vminsd_xmm_xmm_xmmm64,
EVEX_Vminsd_xmm_k1z_xmm_xmmm64_sae,
Divps_xmm_xmmm128,
VEX_Vdivps_xmm_xmm_xmmm128,
VEX_Vdivps_ymm_ymm_ymmm256,
EVEX_Vdivps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vdivps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vdivps_zmm_k1z_zmm_zmmm512b32_er,
Divpd_xmm_xmmm128,
VEX_Vdivpd_xmm_xmm_xmmm128,
VEX_Vdivpd_ymm_ymm_ymmm256,
EVEX_Vdivpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vdivpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vdivpd_zmm_k1z_zmm_zmmm512b64_er,
Divss_xmm_xmmm32,
VEX_Vdivss_xmm_xmm_xmmm32,
EVEX_Vdivss_xmm_k1z_xmm_xmmm32_er,
Divsd_xmm_xmmm64,
VEX_Vdivsd_xmm_xmm_xmmm64,
EVEX_Vdivsd_xmm_k1z_xmm_xmmm64_er,
Maxps_xmm_xmmm128,
VEX_Vmaxps_xmm_xmm_xmmm128,
VEX_Vmaxps_ymm_ymm_ymmm256,
EVEX_Vmaxps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vmaxps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vmaxps_zmm_k1z_zmm_zmmm512b32_sae,
Maxpd_xmm_xmmm128,
VEX_Vmaxpd_xmm_xmm_xmmm128,
VEX_Vmaxpd_ymm_ymm_ymmm256,
EVEX_Vmaxpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vmaxpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vmaxpd_zmm_k1z_zmm_zmmm512b64_sae,
Maxss_xmm_xmmm32,
VEX_Vmaxss_xmm_xmm_xmmm32,
EVEX_Vmaxss_xmm_k1z_xmm_xmmm32_sae,
Maxsd_xmm_xmmm64,
VEX_Vmaxsd_xmm_xmm_xmmm64,
EVEX_Vmaxsd_xmm_k1z_xmm_xmmm64_sae,
Punpcklbw_mm_mmm32,
Punpcklbw_xmm_xmmm128,
VEX_Vpunpcklbw_xmm_xmm_xmmm128,
VEX_Vpunpcklbw_ymm_ymm_ymmm256,
EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128,
EVEX_Vpunpcklbw_ymm_k1z_ymm_ymmm256,
EVEX_Vpunpcklbw_zmm_k1z_zmm_zmmm512,
Punpcklwd_mm_mmm32,
Punpcklwd_xmm_xmmm128,
VEX_Vpunpcklwd_xmm_xmm_xmmm128,
VEX_Vpunpcklwd_ymm_ymm_ymmm256,
EVEX_Vpunpcklwd_xmm_k1z_xmm_xmmm128,
EVEX_Vpunpcklwd_ymm_k1z_ymm_ymmm256,
EVEX_Vpunpcklwd_zmm_k1z_zmm_zmmm512,
Punpckldq_mm_mmm32,
Punpckldq_xmm_xmmm128,
VEX_Vpunpckldq_xmm_xmm_xmmm128,
VEX_Vpunpckldq_ymm_ymm_ymmm256,
EVEX_Vpunpckldq_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpunpckldq_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpunpckldq_zmm_k1z_zmm_zmmm512b32,
Packsswb_mm_mmm64,
Packsswb_xmm_xmmm128,
VEX_Vpacksswb_xmm_xmm_xmmm128,
VEX_Vpacksswb_ymm_ymm_ymmm256,
EVEX_Vpacksswb_xmm_k1z_xmm_xmmm128,
EVEX_Vpacksswb_ymm_k1z_ymm_ymmm256,
EVEX_Vpacksswb_zmm_k1z_zmm_zmmm512,
Pcmpgtb_mm_mmm64,
Pcmpgtb_xmm_xmmm128,
VEX_Vpcmpgtb_xmm_xmm_xmmm128,
VEX_Vpcmpgtb_ymm_ymm_ymmm256,
EVEX_Vpcmpgtb_kr_k1_xmm_xmmm128,
EVEX_Vpcmpgtb_kr_k1_ymm_ymmm256,
EVEX_Vpcmpgtb_kr_k1_zmm_zmmm512,
Pcmpgtw_mm_mmm64,
Pcmpgtw_xmm_xmmm128,
VEX_Vpcmpgtw_xmm_xmm_xmmm128,
VEX_Vpcmpgtw_ymm_ymm_ymmm256,
EVEX_Vpcmpgtw_kr_k1_xmm_xmmm128,
EVEX_Vpcmpgtw_kr_k1_ymm_ymmm256,
EVEX_Vpcmpgtw_kr_k1_zmm_zmmm512,
Pcmpgtd_mm_mmm64,
Pcmpgtd_xmm_xmmm128,
VEX_Vpcmpgtd_xmm_xmm_xmmm128,
VEX_Vpcmpgtd_ymm_ymm_ymmm256,
EVEX_Vpcmpgtd_kr_k1_xmm_xmmm128b32,
EVEX_Vpcmpgtd_kr_k1_ymm_ymmm256b32,
EVEX_Vpcmpgtd_kr_k1_zmm_zmmm512b32,
Packuswb_mm_mmm64,
Packuswb_xmm_xmmm128,
VEX_Vpackuswb_xmm_xmm_xmmm128,
VEX_Vpackuswb_ymm_ymm_ymmm256,
EVEX_Vpackuswb_xmm_k1z_xmm_xmmm128,
EVEX_Vpackuswb_ymm_k1z_ymm_ymmm256,
EVEX_Vpackuswb_zmm_k1z_zmm_zmmm512,
Punpckhbw_mm_mmm64,
Punpckhbw_xmm_xmmm128,
VEX_Vpunpckhbw_xmm_xmm_xmmm128,
VEX_Vpunpckhbw_ymm_ymm_ymmm256,
EVEX_Vpunpckhbw_xmm_k1z_xmm_xmmm128,
EVEX_Vpunpckhbw_ymm_k1z_ymm_ymmm256,
EVEX_Vpunpckhbw_zmm_k1z_zmm_zmmm512,
Punpckhwd_mm_mmm64,
Punpckhwd_xmm_xmmm128,
VEX_Vpunpckhwd_xmm_xmm_xmmm128,
VEX_Vpunpckhwd_ymm_ymm_ymmm256,
EVEX_Vpunpckhwd_xmm_k1z_xmm_xmmm128,
EVEX_Vpunpckhwd_ymm_k1z_ymm_ymmm256,
EVEX_Vpunpckhwd_zmm_k1z_zmm_zmmm512,
Punpckhdq_mm_mmm64,
Punpckhdq_xmm_xmmm128,
VEX_Vpunpckhdq_xmm_xmm_xmmm128,
VEX_Vpunpckhdq_ymm_ymm_ymmm256,
EVEX_Vpunpckhdq_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpunpckhdq_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpunpckhdq_zmm_k1z_zmm_zmmm512b32,
Packssdw_mm_mmm64,
Packssdw_xmm_xmmm128,
VEX_Vpackssdw_xmm_xmm_xmmm128,
VEX_Vpackssdw_ymm_ymm_ymmm256,
EVEX_Vpackssdw_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpackssdw_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpackssdw_zmm_k1z_zmm_zmmm512b32,
Punpcklqdq_xmm_xmmm128,
VEX_Vpunpcklqdq_xmm_xmm_xmmm128,
VEX_Vpunpcklqdq_ymm_ymm_ymmm256,
EVEX_Vpunpcklqdq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpunpcklqdq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpunpcklqdq_zmm_k1z_zmm_zmmm512b64,
Punpckhqdq_xmm_xmmm128,
VEX_Vpunpckhqdq_xmm_xmm_xmmm128,
VEX_Vpunpckhqdq_ymm_ymm_ymmm256,
EVEX_Vpunpckhqdq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpunpckhqdq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpunpckhqdq_zmm_k1z_zmm_zmmm512b64,
Movd_mm_rm32,
Movq_mm_rm64,
Movd_xmm_rm32,
Movq_xmm_rm64,
VEX_Vmovd_xmm_rm32,
VEX_Vmovq_xmm_rm64,
EVEX_Vmovd_xmm_rm32,
EVEX_Vmovq_xmm_rm64,
Movq_mm_mmm64,
Movdqa_xmm_xmmm128,
VEX_Vmovdqa_xmm_xmmm128,
VEX_Vmovdqa_ymm_ymmm256,
EVEX_Vmovdqa32_xmm_k1z_xmmm128,
EVEX_Vmovdqa32_ymm_k1z_ymmm256,
EVEX_Vmovdqa32_zmm_k1z_zmmm512,
EVEX_Vmovdqa64_xmm_k1z_xmmm128,
EVEX_Vmovdqa64_ymm_k1z_ymmm256,
EVEX_Vmovdqa64_zmm_k1z_zmmm512,
Movdqu_xmm_xmmm128,
VEX_Vmovdqu_xmm_xmmm128,
VEX_Vmovdqu_ymm_ymmm256,
EVEX_Vmovdqu32_xmm_k1z_xmmm128,
EVEX_Vmovdqu32_ymm_k1z_ymmm256,
EVEX_Vmovdqu32_zmm_k1z_zmmm512,
EVEX_Vmovdqu64_xmm_k1z_xmmm128,
EVEX_Vmovdqu64_ymm_k1z_ymmm256,
EVEX_Vmovdqu64_zmm_k1z_zmmm512,
EVEX_Vmovdqu8_xmm_k1z_xmmm128,
EVEX_Vmovdqu8_ymm_k1z_ymmm256,
EVEX_Vmovdqu8_zmm_k1z_zmmm512,
EVEX_Vmovdqu16_xmm_k1z_xmmm128,
EVEX_Vmovdqu16_ymm_k1z_ymmm256,
EVEX_Vmovdqu16_zmm_k1z_zmmm512,
Pshufw_mm_mmm64_imm8,
Pshufd_xmm_xmmm128_imm8,
VEX_Vpshufd_xmm_xmmm128_imm8,
VEX_Vpshufd_ymm_ymmm256_imm8,
EVEX_Vpshufd_xmm_k1z_xmmm128b32_imm8,
EVEX_Vpshufd_ymm_k1z_ymmm256b32_imm8,
EVEX_Vpshufd_zmm_k1z_zmmm512b32_imm8,
Pshufhw_xmm_xmmm128_imm8,
VEX_Vpshufhw_xmm_xmmm128_imm8,
VEX_Vpshufhw_ymm_ymmm256_imm8,
EVEX_Vpshufhw_xmm_k1z_xmmm128_imm8,
EVEX_Vpshufhw_ymm_k1z_ymmm256_imm8,
EVEX_Vpshufhw_zmm_k1z_zmmm512_imm8,
Pshuflw_xmm_xmmm128_imm8,
VEX_Vpshuflw_xmm_xmmm128_imm8,
VEX_Vpshuflw_ymm_ymmm256_imm8,
EVEX_Vpshuflw_xmm_k1z_xmmm128_imm8,
EVEX_Vpshuflw_ymm_k1z_ymmm256_imm8,
EVEX_Vpshuflw_zmm_k1z_zmmm512_imm8,
Psrlw_mm_imm8,
Psrlw_xmm_imm8,
VEX_Vpsrlw_xmm_xmm_imm8,
VEX_Vpsrlw_ymm_ymm_imm8,
EVEX_Vpsrlw_xmm_k1z_xmmm128_imm8,
EVEX_Vpsrlw_ymm_k1z_ymmm256_imm8,
EVEX_Vpsrlw_zmm_k1z_zmmm512_imm8,
Psraw_mm_imm8,
Psraw_xmm_imm8,
VEX_Vpsraw_xmm_xmm_imm8,
VEX_Vpsraw_ymm_ymm_imm8,
EVEX_Vpsraw_xmm_k1z_xmmm128_imm8,
EVEX_Vpsraw_ymm_k1z_ymmm256_imm8,
EVEX_Vpsraw_zmm_k1z_zmmm512_imm8,
Psllw_mm_imm8,
Psllw_xmm_imm8,
VEX_Vpsllw_xmm_xmm_imm8,
VEX_Vpsllw_ymm_ymm_imm8,
EVEX_Vpsllw_xmm_k1z_xmmm128_imm8,
EVEX_Vpsllw_ymm_k1z_ymmm256_imm8,
EVEX_Vpsllw_zmm_k1z_zmmm512_imm8,
EVEX_Vprord_xmm_k1z_xmmm128b32_imm8,
EVEX_Vprord_ymm_k1z_ymmm256b32_imm8,
EVEX_Vprord_zmm_k1z_zmmm512b32_imm8,
EVEX_Vprorq_xmm_k1z_xmmm128b64_imm8,
EVEX_Vprorq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vprorq_zmm_k1z_zmmm512b64_imm8,
EVEX_Vprold_xmm_k1z_xmmm128b32_imm8,
EVEX_Vprold_ymm_k1z_ymmm256b32_imm8,
EVEX_Vprold_zmm_k1z_zmmm512b32_imm8,
EVEX_Vprolq_xmm_k1z_xmmm128b64_imm8,
EVEX_Vprolq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vprolq_zmm_k1z_zmmm512b64_imm8,
Psrld_mm_imm8,
Psrld_xmm_imm8,
VEX_Vpsrld_xmm_xmm_imm8,
VEX_Vpsrld_ymm_ymm_imm8,
EVEX_Vpsrld_xmm_k1z_xmmm128b32_imm8,
EVEX_Vpsrld_ymm_k1z_ymmm256b32_imm8,
EVEX_Vpsrld_zmm_k1z_zmmm512b32_imm8,
Psrad_mm_imm8,
Psrad_xmm_imm8,
VEX_Vpsrad_xmm_xmm_imm8,
VEX_Vpsrad_ymm_ymm_imm8,
EVEX_Vpsrad_xmm_k1z_xmmm128b32_imm8,
EVEX_Vpsrad_ymm_k1z_ymmm256b32_imm8,
EVEX_Vpsrad_zmm_k1z_zmmm512b32_imm8,
EVEX_Vpsraq_xmm_k1z_xmmm128b64_imm8,
EVEX_Vpsraq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpsraq_zmm_k1z_zmmm512b64_imm8,
Pslld_mm_imm8,
Pslld_xmm_imm8,
VEX_Vpslld_xmm_xmm_imm8,
VEX_Vpslld_ymm_ymm_imm8,
EVEX_Vpslld_xmm_k1z_xmmm128b32_imm8,
EVEX_Vpslld_ymm_k1z_ymmm256b32_imm8,
EVEX_Vpslld_zmm_k1z_zmmm512b32_imm8,
Psrlq_mm_imm8,
Psrlq_xmm_imm8,
VEX_Vpsrlq_xmm_xmm_imm8,
VEX_Vpsrlq_ymm_ymm_imm8,
EVEX_Vpsrlq_xmm_k1z_xmmm128b64_imm8,
EVEX_Vpsrlq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpsrlq_zmm_k1z_zmmm512b64_imm8,
Psrldq_xmm_imm8,
VEX_Vpsrldq_xmm_xmm_imm8,
VEX_Vpsrldq_ymm_ymm_imm8,
EVEX_Vpsrldq_xmm_xmmm128_imm8,
EVEX_Vpsrldq_ymm_ymmm256_imm8,
EVEX_Vpsrldq_zmm_zmmm512_imm8,
Psllq_mm_imm8,
Psllq_xmm_imm8,
VEX_Vpsllq_xmm_xmm_imm8,
VEX_Vpsllq_ymm_ymm_imm8,
EVEX_Vpsllq_xmm_k1z_xmmm128b64_imm8,
EVEX_Vpsllq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpsllq_zmm_k1z_zmmm512b64_imm8,
Pslldq_xmm_imm8,
VEX_Vpslldq_xmm_xmm_imm8,
VEX_Vpslldq_ymm_ymm_imm8,
EVEX_Vpslldq_xmm_xmmm128_imm8,
EVEX_Vpslldq_ymm_ymmm256_imm8,
EVEX_Vpslldq_zmm_zmmm512_imm8,
Pcmpeqb_mm_mmm64,
Pcmpeqb_xmm_xmmm128,
VEX_Vpcmpeqb_xmm_xmm_xmmm128,
VEX_Vpcmpeqb_ymm_ymm_ymmm256,
EVEX_Vpcmpeqb_kr_k1_xmm_xmmm128,
EVEX_Vpcmpeqb_kr_k1_ymm_ymmm256,
EVEX_Vpcmpeqb_kr_k1_zmm_zmmm512,
Pcmpeqw_mm_mmm64,
Pcmpeqw_xmm_xmmm128,
VEX_Vpcmpeqw_xmm_xmm_xmmm128,
VEX_Vpcmpeqw_ymm_ymm_ymmm256,
EVEX_Vpcmpeqw_kr_k1_xmm_xmmm128,
EVEX_Vpcmpeqw_kr_k1_ymm_ymmm256,
EVEX_Vpcmpeqw_kr_k1_zmm_zmmm512,
Pcmpeqd_mm_mmm64,
Pcmpeqd_xmm_xmmm128,
VEX_Vpcmpeqd_xmm_xmm_xmmm128,
VEX_Vpcmpeqd_ymm_ymm_ymmm256,
EVEX_Vpcmpeqd_kr_k1_xmm_xmmm128b32,
EVEX_Vpcmpeqd_kr_k1_ymm_ymmm256b32,
EVEX_Vpcmpeqd_kr_k1_zmm_zmmm512b32,
Emms,
VEX_Vzeroupper,
VEX_Vzeroall,
Vmread_rm32_r32,
Vmread_rm64_r64,
EVEX_Vcvttps2udq_xmm_k1z_xmmm128b32,
EVEX_Vcvttps2udq_ymm_k1z_ymmm256b32,
EVEX_Vcvttps2udq_zmm_k1z_zmmm512b32_sae,
EVEX_Vcvttpd2udq_xmm_k1z_xmmm128b64,
EVEX_Vcvttpd2udq_xmm_k1z_ymmm256b64,
EVEX_Vcvttpd2udq_ymm_k1z_zmmm512b64_sae,
Extrq_xmm_imm8_imm8,
EVEX_Vcvttps2uqq_xmm_k1z_xmmm64b32,
EVEX_Vcvttps2uqq_ymm_k1z_xmmm128b32,
EVEX_Vcvttps2uqq_zmm_k1z_ymmm256b32_sae,
EVEX_Vcvttpd2uqq_xmm_k1z_xmmm128b64,
EVEX_Vcvttpd2uqq_ymm_k1z_ymmm256b64,
EVEX_Vcvttpd2uqq_zmm_k1z_zmmm512b64_sae,
EVEX_Vcvttss2usi_r32_xmmm32_sae,
EVEX_Vcvttss2usi_r64_xmmm32_sae,
Insertq_xmm_xmm_imm8_imm8,
EVEX_Vcvttsd2usi_r32_xmmm64_sae,
EVEX_Vcvttsd2usi_r64_xmmm64_sae,
Vmwrite_r32_rm32,
Vmwrite_r64_rm64,
EVEX_Vcvtps2udq_xmm_k1z_xmmm128b32,
EVEX_Vcvtps2udq_ymm_k1z_ymmm256b32,
EVEX_Vcvtps2udq_zmm_k1z_zmmm512b32_er,
EVEX_Vcvtpd2udq_xmm_k1z_xmmm128b64,
EVEX_Vcvtpd2udq_xmm_k1z_ymmm256b64,
EVEX_Vcvtpd2udq_ymm_k1z_zmmm512b64_er,
Extrq_xmm_xmm,
EVEX_Vcvtps2uqq_xmm_k1z_xmmm64b32,
EVEX_Vcvtps2uqq_ymm_k1z_xmmm128b32,
EVEX_Vcvtps2uqq_zmm_k1z_ymmm256b32_er,
EVEX_Vcvtpd2uqq_xmm_k1z_xmmm128b64,
EVEX_Vcvtpd2uqq_ymm_k1z_ymmm256b64,
EVEX_Vcvtpd2uqq_zmm_k1z_zmmm512b64_er,
EVEX_Vcvtss2usi_r32_xmmm32_er,
EVEX_Vcvtss2usi_r64_xmmm32_er,
Insertq_xmm_xmm,
EVEX_Vcvtsd2usi_r32_xmmm64_er,
EVEX_Vcvtsd2usi_r64_xmmm64_er,
EVEX_Vcvttps2qq_xmm_k1z_xmmm64b32,
EVEX_Vcvttps2qq_ymm_k1z_xmmm128b32,
EVEX_Vcvttps2qq_zmm_k1z_ymmm256b32_sae,
EVEX_Vcvttpd2qq_xmm_k1z_xmmm128b64,
EVEX_Vcvttpd2qq_ymm_k1z_ymmm256b64,
EVEX_Vcvttpd2qq_zmm_k1z_zmmm512b64_sae,
EVEX_Vcvtudq2pd_xmm_k1z_xmmm64b32,
EVEX_Vcvtudq2pd_ymm_k1z_xmmm128b32,
EVEX_Vcvtudq2pd_zmm_k1z_ymmm256b32_er,
EVEX_Vcvtuqq2pd_xmm_k1z_xmmm128b64,
EVEX_Vcvtuqq2pd_ymm_k1z_ymmm256b64,
EVEX_Vcvtuqq2pd_zmm_k1z_zmmm512b64_er,
EVEX_Vcvtudq2ps_xmm_k1z_xmmm128b32,
EVEX_Vcvtudq2ps_ymm_k1z_ymmm256b32,
EVEX_Vcvtudq2ps_zmm_k1z_zmmm512b32_er,
EVEX_Vcvtuqq2ps_xmm_k1z_xmmm128b64,
EVEX_Vcvtuqq2ps_xmm_k1z_ymmm256b64,
EVEX_Vcvtuqq2ps_ymm_k1z_zmmm512b64_er,
EVEX_Vcvtps2qq_xmm_k1z_xmmm64b32,
EVEX_Vcvtps2qq_ymm_k1z_xmmm128b32,
EVEX_Vcvtps2qq_zmm_k1z_ymmm256b32_er,
EVEX_Vcvtpd2qq_xmm_k1z_xmmm128b64,
EVEX_Vcvtpd2qq_ymm_k1z_ymmm256b64,
EVEX_Vcvtpd2qq_zmm_k1z_zmmm512b64_er,
EVEX_Vcvtusi2ss_xmm_xmm_rm32_er,
EVEX_Vcvtusi2ss_xmm_xmm_rm64_er,
EVEX_Vcvtusi2sd_xmm_xmm_rm32_er,
EVEX_Vcvtusi2sd_xmm_xmm_rm64_er,
Haddpd_xmm_xmmm128,
VEX_Vhaddpd_xmm_xmm_xmmm128,
VEX_Vhaddpd_ymm_ymm_ymmm256,
Haddps_xmm_xmmm128,
VEX_Vhaddps_xmm_xmm_xmmm128,
VEX_Vhaddps_ymm_ymm_ymmm256,
Hsubpd_xmm_xmmm128,
VEX_Vhsubpd_xmm_xmm_xmmm128,
VEX_Vhsubpd_ymm_ymm_ymmm256,
Hsubps_xmm_xmmm128,
VEX_Vhsubps_xmm_xmm_xmmm128,
VEX_Vhsubps_ymm_ymm_ymmm256,
Movd_rm32_mm,
Movq_rm64_mm,
Movd_rm32_xmm,
Movq_rm64_xmm,
VEX_Vmovd_rm32_xmm,
VEX_Vmovq_rm64_xmm,
EVEX_Vmovd_rm32_xmm,
EVEX_Vmovq_rm64_xmm,
Movq_xmm_xmmm64,
VEX_Vmovq_xmm_xmmm64,
EVEX_Vmovq_xmm_xmmm64,
Movq_mmm64_mm,
Movdqa_xmmm128_xmm,
VEX_Vmovdqa_xmmm128_xmm,
VEX_Vmovdqa_ymmm256_ymm,
EVEX_Vmovdqa32_xmmm128_k1z_xmm,
EVEX_Vmovdqa32_ymmm256_k1z_ymm,
EVEX_Vmovdqa32_zmmm512_k1z_zmm,
EVEX_Vmovdqa64_xmmm128_k1z_xmm,
EVEX_Vmovdqa64_ymmm256_k1z_ymm,
EVEX_Vmovdqa64_zmmm512_k1z_zmm,
Movdqu_xmmm128_xmm,
VEX_Vmovdqu_xmmm128_xmm,
VEX_Vmovdqu_ymmm256_ymm,
EVEX_Vmovdqu32_xmmm128_k1z_xmm,
EVEX_Vmovdqu32_ymmm256_k1z_ymm,
EVEX_Vmovdqu32_zmmm512_k1z_zmm,
EVEX_Vmovdqu64_xmmm128_k1z_xmm,
EVEX_Vmovdqu64_ymmm256_k1z_ymm,
EVEX_Vmovdqu64_zmmm512_k1z_zmm,
EVEX_Vmovdqu8_xmmm128_k1z_xmm,
EVEX_Vmovdqu8_ymmm256_k1z_ymm,
EVEX_Vmovdqu8_zmmm512_k1z_zmm,
EVEX_Vmovdqu16_xmmm128_k1z_xmm,
EVEX_Vmovdqu16_ymmm256_k1z_ymm,
EVEX_Vmovdqu16_zmmm512_k1z_zmm,
Jo_rel16,
Jo_rel32_32,
Jo_rel32_64,
Jno_rel16,
Jno_rel32_32,
Jno_rel32_64,
Jb_rel16,
Jb_rel32_32,
Jb_rel32_64,
Jae_rel16,
Jae_rel32_32,
Jae_rel32_64,
Je_rel16,
Je_rel32_32,
Je_rel32_64,
Jne_rel16,
Jne_rel32_32,
Jne_rel32_64,
Jbe_rel16,
Jbe_rel32_32,
Jbe_rel32_64,
Ja_rel16,
Ja_rel32_32,
Ja_rel32_64,
Js_rel16,
Js_rel32_32,
Js_rel32_64,
Jns_rel16,
Jns_rel32_32,
Jns_rel32_64,
Jp_rel16,
Jp_rel32_32,
Jp_rel32_64,
Jnp_rel16,
Jnp_rel32_32,
Jnp_rel32_64,
Jl_rel16,
Jl_rel32_32,
Jl_rel32_64,
Jge_rel16,
Jge_rel32_32,
Jge_rel32_64,
Jle_rel16,
Jle_rel32_32,
Jle_rel32_64,
Jg_rel16,
Jg_rel32_32,
Jg_rel32_64,
Seto_rm8,
Setno_rm8,
Setb_rm8,
Setae_rm8,
Sete_rm8,
Setne_rm8,
Setbe_rm8,
Seta_rm8,
Sets_rm8,
Setns_rm8,
Setp_rm8,
Setnp_rm8,
Setl_rm8,
Setge_rm8,
Setle_rm8,
Setg_rm8,
VEX_Kmovw_kr_km16,
VEX_Kmovq_kr_km64,
VEX_Kmovb_kr_km8,
VEX_Kmovd_kr_km32,
VEX_Kmovw_m16_kr,
VEX_Kmovq_m64_kr,
VEX_Kmovb_m8_kr,
VEX_Kmovd_m32_kr,
VEX_Kmovw_kr_r32,
VEX_Kmovb_kr_r32,
VEX_Kmovd_kr_r32,
VEX_Kmovq_kr_r64,
VEX_Kmovw_r32_kr,
VEX_Kmovb_r32_kr,
VEX_Kmovd_r32_kr,
VEX_Kmovq_r64_kr,
VEX_Kortestw_kr_kr,
VEX_Kortestq_kr_kr,
VEX_Kortestb_kr_kr,
VEX_Kortestd_kr_kr,
VEX_Ktestw_kr_kr,
VEX_Ktestq_kr_kr,
VEX_Ktestb_kr_kr,
VEX_Ktestd_kr_kr,
Pushw_FS,
Pushd_FS,
Pushq_FS,
Popw_FS,
Popd_FS,
Popq_FS,
Cpuid,
Bt_rm16_r16,
Bt_rm32_r32,
Bt_rm64_r64,
Shld_rm16_r16_imm8,
Shld_rm32_r32_imm8,
Shld_rm64_r64_imm8,
Shld_rm16_r16_CL,
Shld_rm32_r32_CL,
Shld_rm64_r64_CL,
Montmul_16,
Montmul_32,
Montmul_64,
Xsha1_16,
Xsha1_32,
Xsha1_64,
Xsha256_16,
Xsha256_32,
Xsha256_64,
Xbts_r16_rm16,
Xbts_r32_rm32,
Xstore_16,
Xstore_32,
Xstore_64,
Xcryptecb_16,
Xcryptecb_32,
Xcryptecb_64,
Xcryptcbc_16,
Xcryptcbc_32,
Xcryptcbc_64,
Xcryptctr_16,
Xcryptctr_32,
Xcryptctr_64,
Xcryptcfb_16,
Xcryptcfb_32,
Xcryptcfb_64,
Xcryptofb_16,
Xcryptofb_32,
Xcryptofb_64,
Ibts_rm16_r16,
Ibts_rm32_r32,
Cmpxchg486_rm8_r8,
Cmpxchg486_rm16_r16,
Cmpxchg486_rm32_r32,
Pushw_GS,
Pushd_GS,
Pushq_GS,
Popw_GS,
Popd_GS,
Popq_GS,
Rsm,
Bts_rm16_r16,
Bts_rm32_r32,
Bts_rm64_r64,
Shrd_rm16_r16_imm8,
Shrd_rm32_r32_imm8,
Shrd_rm64_r64_imm8,
Shrd_rm16_r16_CL,
Shrd_rm32_r32_CL,
Shrd_rm64_r64_CL,
Fxsave_m512byte,
Fxsave64_m512byte,
Rdfsbase_r32,
Rdfsbase_r64,
Fxrstor_m512byte,
Fxrstor64_m512byte,
Rdgsbase_r32,
Rdgsbase_r64,
Ldmxcsr_m32,
Wrfsbase_r32,
Wrfsbase_r64,
VEX_Vldmxcsr_m32,
Stmxcsr_m32,
Wrgsbase_r32,
Wrgsbase_r64,
VEX_Vstmxcsr_m32,
Xsave_mem,
Xsave64_mem,
Ptwrite_rm32,
Ptwrite_rm64,
Xrstor_mem,
Xrstor64_mem,
Incsspd_r32,
Incsspq_r64,
Xsaveopt_mem,
Xsaveopt64_mem,
Clwb_m8,
Tpause_r32,
Tpause_r64,
Clrssbsy_m64,
Umonitor_r16,
Umonitor_r32,
Umonitor_r64,
Umwait_r32,
Umwait_r64,
Clflush_m8,
Clflushopt_m8,
Lfence,
Lfence_E9,
Lfence_EA,
Lfence_EB,
Lfence_EC,
Lfence_ED,
Lfence_EE,
Lfence_EF,
Mfence,
Mfence_F1,
Mfence_F2,
Mfence_F3,
Mfence_F4,
Mfence_F5,
Mfence_F6,
Mfence_F7,
Sfence,
Sfence_F9,
Sfence_FA,
Sfence_FB,
Sfence_FC,
Sfence_FD,
Sfence_FE,
Sfence_FF,
Pcommit,
Imul_r16_rm16,
Imul_r32_rm32,
Imul_r64_rm64,
Cmpxchg_rm8_r8,
Cmpxchg_rm16_r16,
Cmpxchg_rm32_r32,
Cmpxchg_rm64_r64,
Lss_r16_m1616,
Lss_r32_m1632,
Lss_r64_m1664,
Btr_rm16_r16,
Btr_rm32_r32,
Btr_rm64_r64,
Lfs_r16_m1616,
Lfs_r32_m1632,
Lfs_r64_m1664,
Lgs_r16_m1616,
Lgs_r32_m1632,
Lgs_r64_m1664,
Movzx_r16_rm8,
Movzx_r32_rm8,
Movzx_r64_rm8,
Movzx_r16_rm16,
Movzx_r32_rm16,
Movzx_r64_rm16,
Jmpe_disp16,
Jmpe_disp32,
Popcnt_r16_rm16,
Popcnt_r32_rm32,
Popcnt_r64_rm64,
Ud1_r16_rm16,
Ud1_r32_rm32,
Ud1_r64_rm64,
Bt_rm16_imm8,
Bt_rm32_imm8,
Bt_rm64_imm8,
Bts_rm16_imm8,
Bts_rm32_imm8,
Bts_rm64_imm8,
Btr_rm16_imm8,
Btr_rm32_imm8,
Btr_rm64_imm8,
Btc_rm16_imm8,
Btc_rm32_imm8,
Btc_rm64_imm8,
Btc_rm16_r16,
Btc_rm32_r32,
Btc_rm64_r64,
Bsf_r16_rm16,
Bsf_r32_rm32,
Bsf_r64_rm64,
Tzcnt_r16_rm16,
Tzcnt_r32_rm32,
Tzcnt_r64_rm64,
Bsr_r16_rm16,
Bsr_r32_rm32,
Bsr_r64_rm64,
Lzcnt_r16_rm16,
Lzcnt_r32_rm32,
Lzcnt_r64_rm64,
Movsx_r16_rm8,
Movsx_r32_rm8,
Movsx_r64_rm8,
Movsx_r16_rm16,
Movsx_r32_rm16,
Movsx_r64_rm16,
Xadd_rm8_r8,
Xadd_rm16_r16,
Xadd_rm32_r32,
Xadd_rm64_r64,
Cmpps_xmm_xmmm128_imm8,
VEX_Vcmpps_xmm_xmm_xmmm128_imm8,
VEX_Vcmpps_ymm_ymm_ymmm256_imm8,
EVEX_Vcmpps_kr_k1_xmm_xmmm128b32_imm8,
EVEX_Vcmpps_kr_k1_ymm_ymmm256b32_imm8,
EVEX_Vcmpps_kr_k1_zmm_zmmm512b32_imm8_sae,
Cmppd_xmm_xmmm128_imm8,
VEX_Vcmppd_xmm_xmm_xmmm128_imm8,
VEX_Vcmppd_ymm_ymm_ymmm256_imm8,
EVEX_Vcmppd_kr_k1_xmm_xmmm128b64_imm8,
EVEX_Vcmppd_kr_k1_ymm_ymmm256b64_imm8,
EVEX_Vcmppd_kr_k1_zmm_zmmm512b64_imm8_sae,
Cmpss_xmm_xmmm32_imm8,
VEX_Vcmpss_xmm_xmm_xmmm32_imm8,
EVEX_Vcmpss_kr_k1_xmm_xmmm32_imm8_sae,
Cmpsd_xmm_xmmm64_imm8,
VEX_Vcmpsd_xmm_xmm_xmmm64_imm8,
EVEX_Vcmpsd_kr_k1_xmm_xmmm64_imm8_sae,
Movnti_m32_r32,
Movnti_m64_r64,
Pinsrw_mm_r32m16_imm8,
Pinsrw_mm_r64m16_imm8,
Pinsrw_xmm_r32m16_imm8,
Pinsrw_xmm_r64m16_imm8,
VEX_Vpinsrw_xmm_xmm_r32m16_imm8,
VEX_Vpinsrw_xmm_xmm_r64m16_imm8,
EVEX_Vpinsrw_xmm_xmm_r32m16_imm8,
EVEX_Vpinsrw_xmm_xmm_r64m16_imm8,
Pextrw_r32_mm_imm8,
Pextrw_r64_mm_imm8,
Pextrw_r32_xmm_imm8,
Pextrw_r64_xmm_imm8,
VEX_Vpextrw_r32_xmm_imm8,
VEX_Vpextrw_r64_xmm_imm8,
EVEX_Vpextrw_r32_xmm_imm8,
EVEX_Vpextrw_r64_xmm_imm8,
Shufps_xmm_xmmm128_imm8,
VEX_Vshufps_xmm_xmm_xmmm128_imm8,
VEX_Vshufps_ymm_ymm_ymmm256_imm8,
EVEX_Vshufps_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vshufps_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vshufps_zmm_k1z_zmm_zmmm512b32_imm8,
Shufpd_xmm_xmmm128_imm8,
VEX_Vshufpd_xmm_xmm_xmmm128_imm8,
VEX_Vshufpd_ymm_ymm_ymmm256_imm8,
EVEX_Vshufpd_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vshufpd_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vshufpd_zmm_k1z_zmm_zmmm512b64_imm8,
Cmpxchg8b_m64,
Cmpxchg16b_m128,
Xrstors_mem,
Xrstors64_mem,
Xsavec_mem,
Xsavec64_mem,
Xsaves_mem,
Xsaves64_mem,
Vmptrld_m64,
Vmclear_m64,
Vmxon_m64,
Rdrand_r16,
Rdrand_r32,
Rdrand_r64,
Vmptrst_m64,
Rdseed_r16,
Rdseed_r32,
Rdseed_r64,
Rdpid_r32,
Rdpid_r64,
Bswap_r16,
Bswap_r32,
Bswap_r64,
Addsubpd_xmm_xmmm128,
VEX_Vaddsubpd_xmm_xmm_xmmm128,
VEX_Vaddsubpd_ymm_ymm_ymmm256,
Addsubps_xmm_xmmm128,
VEX_Vaddsubps_xmm_xmm_xmmm128,
VEX_Vaddsubps_ymm_ymm_ymmm256,
Psrlw_mm_mmm64,
Psrlw_xmm_xmmm128,
VEX_Vpsrlw_xmm_xmm_xmmm128,
VEX_Vpsrlw_ymm_ymm_xmmm128,
EVEX_Vpsrlw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsrlw_ymm_k1z_ymm_xmmm128,
EVEX_Vpsrlw_zmm_k1z_zmm_xmmm128,
Psrld_mm_mmm64,
Psrld_xmm_xmmm128,
VEX_Vpsrld_xmm_xmm_xmmm128,
VEX_Vpsrld_ymm_ymm_xmmm128,
EVEX_Vpsrld_xmm_k1z_xmm_xmmm128,
EVEX_Vpsrld_ymm_k1z_ymm_xmmm128,
EVEX_Vpsrld_zmm_k1z_zmm_xmmm128,
Psrlq_mm_mmm64,
Psrlq_xmm_xmmm128,
VEX_Vpsrlq_xmm_xmm_xmmm128,
VEX_Vpsrlq_ymm_ymm_xmmm128,
EVEX_Vpsrlq_xmm_k1z_xmm_xmmm128,
EVEX_Vpsrlq_ymm_k1z_ymm_xmmm128,
EVEX_Vpsrlq_zmm_k1z_zmm_xmmm128,
Paddq_mm_mmm64,
Paddq_xmm_xmmm128,
VEX_Vpaddq_xmm_xmm_xmmm128,
VEX_Vpaddq_ymm_ymm_ymmm256,
EVEX_Vpaddq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpaddq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpaddq_zmm_k1z_zmm_zmmm512b64,
Pmullw_mm_mmm64,
Pmullw_xmm_xmmm128,
VEX_Vpmullw_xmm_xmm_xmmm128,
VEX_Vpmullw_ymm_ymm_ymmm256,
EVEX_Vpmullw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmullw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmullw_zmm_k1z_zmm_zmmm512,
Movq_xmmm64_xmm,
VEX_Vmovq_xmmm64_xmm,
EVEX_Vmovq_xmmm64_xmm,
Movq2dq_xmm_mm,
Movdq2q_mm_xmm,
Pmovmskb_r32_mm,
Pmovmskb_r64_mm,
Pmovmskb_r32_xmm,
Pmovmskb_r64_xmm,
VEX_Vpmovmskb_r32_xmm,
VEX_Vpmovmskb_r64_xmm,
VEX_Vpmovmskb_r32_ymm,
VEX_Vpmovmskb_r64_ymm,
Psubusb_mm_mmm64,
Psubusb_xmm_xmmm128,
VEX_Vpsubusb_xmm_xmm_xmmm128,
VEX_Vpsubusb_ymm_ymm_ymmm256,
EVEX_Vpsubusb_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubusb_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubusb_zmm_k1z_zmm_zmmm512,
Psubusw_mm_mmm64,
Psubusw_xmm_xmmm128,
VEX_Vpsubusw_xmm_xmm_xmmm128,
VEX_Vpsubusw_ymm_ymm_ymmm256,
EVEX_Vpsubusw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubusw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubusw_zmm_k1z_zmm_zmmm512,
Pminub_mm_mmm64,
Pminub_xmm_xmmm128,
VEX_Vpminub_xmm_xmm_xmmm128,
VEX_Vpminub_ymm_ymm_ymmm256,
EVEX_Vpminub_xmm_k1z_xmm_xmmm128,
EVEX_Vpminub_ymm_k1z_ymm_ymmm256,
EVEX_Vpminub_zmm_k1z_zmm_zmmm512,
Pand_mm_mmm64,
Pand_xmm_xmmm128,
VEX_Vpand_xmm_xmm_xmmm128,
VEX_Vpand_ymm_ymm_ymmm256,
EVEX_Vpandd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpandd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpandd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpandq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpandq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpandq_zmm_k1z_zmm_zmmm512b64,
Paddusb_mm_mmm64,
Paddusb_xmm_xmmm128,
VEX_Vpaddusb_xmm_xmm_xmmm128,
VEX_Vpaddusb_ymm_ymm_ymmm256,
EVEX_Vpaddusb_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddusb_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddusb_zmm_k1z_zmm_zmmm512,
Paddusw_mm_mmm64,
Paddusw_xmm_xmmm128,
VEX_Vpaddusw_xmm_xmm_xmmm128,
VEX_Vpaddusw_ymm_ymm_ymmm256,
EVEX_Vpaddusw_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddusw_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddusw_zmm_k1z_zmm_zmmm512,
Pmaxub_mm_mmm64,
Pmaxub_xmm_xmmm128,
VEX_Vpmaxub_xmm_xmm_xmmm128,
VEX_Vpmaxub_ymm_ymm_ymmm256,
EVEX_Vpmaxub_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaxub_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaxub_zmm_k1z_zmm_zmmm512,
Pandn_mm_mmm64,
Pandn_xmm_xmmm128,
VEX_Vpandn_xmm_xmm_xmmm128,
VEX_Vpandn_ymm_ymm_ymmm256,
EVEX_Vpandnd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpandnd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpandnd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpandnq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpandnq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpandnq_zmm_k1z_zmm_zmmm512b64,
Pavgb_mm_mmm64,
Pavgb_xmm_xmmm128,
VEX_Vpavgb_xmm_xmm_xmmm128,
VEX_Vpavgb_ymm_ymm_ymmm256,
EVEX_Vpavgb_xmm_k1z_xmm_xmmm128,
EVEX_Vpavgb_ymm_k1z_ymm_ymmm256,
EVEX_Vpavgb_zmm_k1z_zmm_zmmm512,
Psraw_mm_mmm64,
Psraw_xmm_xmmm128,
VEX_Vpsraw_xmm_xmm_xmmm128,
VEX_Vpsraw_ymm_ymm_xmmm128,
EVEX_Vpsraw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsraw_ymm_k1z_ymm_xmmm128,
EVEX_Vpsraw_zmm_k1z_zmm_xmmm128,
Psrad_mm_mmm64,
Psrad_xmm_xmmm128,
VEX_Vpsrad_xmm_xmm_xmmm128,
VEX_Vpsrad_ymm_ymm_xmmm128,
EVEX_Vpsrad_xmm_k1z_xmm_xmmm128,
EVEX_Vpsrad_ymm_k1z_ymm_xmmm128,
EVEX_Vpsrad_zmm_k1z_zmm_xmmm128,
EVEX_Vpsraq_xmm_k1z_xmm_xmmm128,
EVEX_Vpsraq_ymm_k1z_ymm_xmmm128,
EVEX_Vpsraq_zmm_k1z_zmm_xmmm128,
Pavgw_mm_mmm64,
Pavgw_xmm_xmmm128,
VEX_Vpavgw_xmm_xmm_xmmm128,
VEX_Vpavgw_ymm_ymm_ymmm256,
EVEX_Vpavgw_xmm_k1z_xmm_xmmm128,
EVEX_Vpavgw_ymm_k1z_ymm_ymmm256,
EVEX_Vpavgw_zmm_k1z_zmm_zmmm512,
Pmulhuw_mm_mmm64,
Pmulhuw_xmm_xmmm128,
VEX_Vpmulhuw_xmm_xmm_xmmm128,
VEX_Vpmulhuw_ymm_ymm_ymmm256,
EVEX_Vpmulhuw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmulhuw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmulhuw_zmm_k1z_zmm_zmmm512,
Pmulhw_mm_mmm64,
Pmulhw_xmm_xmmm128,
VEX_Vpmulhw_xmm_xmm_xmmm128,
VEX_Vpmulhw_ymm_ymm_ymmm256,
EVEX_Vpmulhw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmulhw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmulhw_zmm_k1z_zmm_zmmm512,
Cvttpd2dq_xmm_xmmm128,
VEX_Vcvttpd2dq_xmm_xmmm128,
VEX_Vcvttpd2dq_xmm_ymmm256,
EVEX_Vcvttpd2dq_xmm_k1z_xmmm128b64,
EVEX_Vcvttpd2dq_xmm_k1z_ymmm256b64,
EVEX_Vcvttpd2dq_ymm_k1z_zmmm512b64_sae,
Cvtdq2pd_xmm_xmmm64,
VEX_Vcvtdq2pd_xmm_xmmm64,
VEX_Vcvtdq2pd_ymm_xmmm128,
EVEX_Vcvtdq2pd_xmm_k1z_xmmm64b32,
EVEX_Vcvtdq2pd_ymm_k1z_xmmm128b32,
EVEX_Vcvtdq2pd_zmm_k1z_ymmm256b32_er,
EVEX_Vcvtqq2pd_xmm_k1z_xmmm128b64,
EVEX_Vcvtqq2pd_ymm_k1z_ymmm256b64,
EVEX_Vcvtqq2pd_zmm_k1z_zmmm512b64_er,
Cvtpd2dq_xmm_xmmm128,
VEX_Vcvtpd2dq_xmm_xmmm128,
VEX_Vcvtpd2dq_xmm_ymmm256,
EVEX_Vcvtpd2dq_xmm_k1z_xmmm128b64,
EVEX_Vcvtpd2dq_xmm_k1z_ymmm256b64,
EVEX_Vcvtpd2dq_ymm_k1z_zmmm512b64_er,
Movntq_m64_mm,
Movntdq_m128_xmm,
VEX_Vmovntdq_m128_xmm,
VEX_Vmovntdq_m256_ymm,
EVEX_Vmovntdq_m128_xmm,
EVEX_Vmovntdq_m256_ymm,
EVEX_Vmovntdq_m512_zmm,
Psubsb_mm_mmm64,
Psubsb_xmm_xmmm128,
VEX_Vpsubsb_xmm_xmm_xmmm128,
VEX_Vpsubsb_ymm_ymm_ymmm256,
EVEX_Vpsubsb_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubsb_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubsb_zmm_k1z_zmm_zmmm512,
Psubsw_mm_mmm64,
Psubsw_xmm_xmmm128,
VEX_Vpsubsw_xmm_xmm_xmmm128,
VEX_Vpsubsw_ymm_ymm_ymmm256,
EVEX_Vpsubsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubsw_zmm_k1z_zmm_zmmm512,
Pminsw_mm_mmm64,
Pminsw_xmm_xmmm128,
VEX_Vpminsw_xmm_xmm_xmmm128,
VEX_Vpminsw_ymm_ymm_ymmm256,
EVEX_Vpminsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpminsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpminsw_zmm_k1z_zmm_zmmm512,
Por_mm_mmm64,
Por_xmm_xmmm128,
VEX_Vpor_xmm_xmm_xmmm128,
VEX_Vpor_ymm_ymm_ymmm256,
EVEX_Vpord_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpord_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpord_zmm_k1z_zmm_zmmm512b32,
EVEX_Vporq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vporq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vporq_zmm_k1z_zmm_zmmm512b64,
Paddsb_mm_mmm64,
Paddsb_xmm_xmmm128,
VEX_Vpaddsb_xmm_xmm_xmmm128,
VEX_Vpaddsb_ymm_ymm_ymmm256,
EVEX_Vpaddsb_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddsb_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddsb_zmm_k1z_zmm_zmmm512,
Paddsw_mm_mmm64,
Paddsw_xmm_xmmm128,
VEX_Vpaddsw_xmm_xmm_xmmm128,
VEX_Vpaddsw_ymm_ymm_ymmm256,
EVEX_Vpaddsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddsw_zmm_k1z_zmm_zmmm512,
Pmaxsw_mm_mmm64,
Pmaxsw_xmm_xmmm128,
VEX_Vpmaxsw_xmm_xmm_xmmm128,
VEX_Vpmaxsw_ymm_ymm_ymmm256,
EVEX_Vpmaxsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaxsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaxsw_zmm_k1z_zmm_zmmm512,
Pxor_mm_mmm64,
Pxor_xmm_xmmm128,
VEX_Vpxor_xmm_xmm_xmmm128,
VEX_Vpxor_ymm_ymm_ymmm256,
EVEX_Vpxord_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpxord_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpxord_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpxorq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpxorq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpxorq_zmm_k1z_zmm_zmmm512b64,
Lddqu_xmm_m128,
VEX_Vlddqu_xmm_m128,
VEX_Vlddqu_ymm_m256,
Psllw_mm_mmm64,
Psllw_xmm_xmmm128,
VEX_Vpsllw_xmm_xmm_xmmm128,
VEX_Vpsllw_ymm_ymm_xmmm128,
EVEX_Vpsllw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsllw_ymm_k1z_ymm_xmmm128,
EVEX_Vpsllw_zmm_k1z_zmm_xmmm128,
Pslld_mm_mmm64,
Pslld_xmm_xmmm128,
VEX_Vpslld_xmm_xmm_xmmm128,
VEX_Vpslld_ymm_ymm_xmmm128,
EVEX_Vpslld_xmm_k1z_xmm_xmmm128,
EVEX_Vpslld_ymm_k1z_ymm_xmmm128,
EVEX_Vpslld_zmm_k1z_zmm_xmmm128,
Psllq_mm_mmm64,
Psllq_xmm_xmmm128,
VEX_Vpsllq_xmm_xmm_xmmm128,
VEX_Vpsllq_ymm_ymm_xmmm128,
EVEX_Vpsllq_xmm_k1z_xmm_xmmm128,
EVEX_Vpsllq_ymm_k1z_ymm_xmmm128,
EVEX_Vpsllq_zmm_k1z_zmm_xmmm128,
Pmuludq_mm_mmm64,
Pmuludq_xmm_xmmm128,
VEX_Vpmuludq_xmm_xmm_xmmm128,
VEX_Vpmuludq_ymm_ymm_ymmm256,
EVEX_Vpmuludq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmuludq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmuludq_zmm_k1z_zmm_zmmm512b64,
Pmaddwd_mm_mmm64,
Pmaddwd_xmm_xmmm128,
VEX_Vpmaddwd_xmm_xmm_xmmm128,
VEX_Vpmaddwd_ymm_ymm_ymmm256,
EVEX_Vpmaddwd_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaddwd_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaddwd_zmm_k1z_zmm_zmmm512,
Psadbw_mm_mmm64,
Psadbw_xmm_xmmm128,
VEX_Vpsadbw_xmm_xmm_xmmm128,
VEX_Vpsadbw_ymm_ymm_ymmm256,
EVEX_Vpsadbw_xmm_xmm_xmmm128,
EVEX_Vpsadbw_ymm_ymm_ymmm256,
EVEX_Vpsadbw_zmm_zmm_zmmm512,
Maskmovq_rDI_mm_mm,
Maskmovdqu_rDI_xmm_xmm,
VEX_Vmaskmovdqu_rDI_xmm_xmm,
Psubb_mm_mmm64,
Psubb_xmm_xmmm128,
VEX_Vpsubb_xmm_xmm_xmmm128,
VEX_Vpsubb_ymm_ymm_ymmm256,
EVEX_Vpsubb_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubb_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubb_zmm_k1z_zmm_zmmm512,
Psubw_mm_mmm64,
Psubw_xmm_xmmm128,
VEX_Vpsubw_xmm_xmm_xmmm128,
VEX_Vpsubw_ymm_ymm_ymmm256,
EVEX_Vpsubw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsubw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsubw_zmm_k1z_zmm_zmmm512,
Psubd_mm_mmm64,
Psubd_xmm_xmmm128,
VEX_Vpsubd_xmm_xmm_xmmm128,
VEX_Vpsubd_ymm_ymm_ymmm256,
EVEX_Vpsubd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpsubd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpsubd_zmm_k1z_zmm_zmmm512b32,
Psubq_mm_mmm64,
Psubq_xmm_xmmm128,
VEX_Vpsubq_xmm_xmm_xmmm128,
VEX_Vpsubq_ymm_ymm_ymmm256,
EVEX_Vpsubq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpsubq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpsubq_zmm_k1z_zmm_zmmm512b64,
Paddb_mm_mmm64,
Paddb_xmm_xmmm128,
VEX_Vpaddb_xmm_xmm_xmmm128,
VEX_Vpaddb_ymm_ymm_ymmm256,
EVEX_Vpaddb_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddb_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddb_zmm_k1z_zmm_zmmm512,
Paddw_mm_mmm64,
Paddw_xmm_xmmm128,
VEX_Vpaddw_xmm_xmm_xmmm128,
VEX_Vpaddw_ymm_ymm_ymmm256,
EVEX_Vpaddw_xmm_k1z_xmm_xmmm128,
EVEX_Vpaddw_ymm_k1z_ymm_ymmm256,
EVEX_Vpaddw_zmm_k1z_zmm_zmmm512,
Paddd_mm_mmm64,
Paddd_xmm_xmmm128,
VEX_Vpaddd_xmm_xmm_xmmm128,
VEX_Vpaddd_ymm_ymm_ymmm256,
EVEX_Vpaddd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpaddd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpaddd_zmm_k1z_zmm_zmmm512b32,
Ud0_r16_rm16,
Ud0_r32_rm32,
Ud0_r64_rm64,
Pshufb_mm_mmm64,
Pshufb_xmm_xmmm128,
VEX_Vpshufb_xmm_xmm_xmmm128,
VEX_Vpshufb_ymm_ymm_ymmm256,
EVEX_Vpshufb_xmm_k1z_xmm_xmmm128,
EVEX_Vpshufb_ymm_k1z_ymm_ymmm256,
EVEX_Vpshufb_zmm_k1z_zmm_zmmm512,
Phaddw_mm_mmm64,
Phaddw_xmm_xmmm128,
VEX_Vphaddw_xmm_xmm_xmmm128,
VEX_Vphaddw_ymm_ymm_ymmm256,
Phaddd_mm_mmm64,
Phaddd_xmm_xmmm128,
VEX_Vphaddd_xmm_xmm_xmmm128,
VEX_Vphaddd_ymm_ymm_ymmm256,
Phaddsw_mm_mmm64,
Phaddsw_xmm_xmmm128,
VEX_Vphaddsw_xmm_xmm_xmmm128,
VEX_Vphaddsw_ymm_ymm_ymmm256,
Pmaddubsw_mm_mmm64,
Pmaddubsw_xmm_xmmm128,
VEX_Vpmaddubsw_xmm_xmm_xmmm128,
VEX_Vpmaddubsw_ymm_ymm_ymmm256,
EVEX_Vpmaddubsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaddubsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaddubsw_zmm_k1z_zmm_zmmm512,
Phsubw_mm_mmm64,
Phsubw_xmm_xmmm128,
VEX_Vphsubw_xmm_xmm_xmmm128,
VEX_Vphsubw_ymm_ymm_ymmm256,
Phsubd_mm_mmm64,
Phsubd_xmm_xmmm128,
VEX_Vphsubd_xmm_xmm_xmmm128,
VEX_Vphsubd_ymm_ymm_ymmm256,
Phsubsw_mm_mmm64,
Phsubsw_xmm_xmmm128,
VEX_Vphsubsw_xmm_xmm_xmmm128,
VEX_Vphsubsw_ymm_ymm_ymmm256,
Psignb_mm_mmm64,
Psignb_xmm_xmmm128,
VEX_Vpsignb_xmm_xmm_xmmm128,
VEX_Vpsignb_ymm_ymm_ymmm256,
Psignw_mm_mmm64,
Psignw_xmm_xmmm128,
VEX_Vpsignw_xmm_xmm_xmmm128,
VEX_Vpsignw_ymm_ymm_ymmm256,
Psignd_mm_mmm64,
Psignd_xmm_xmmm128,
VEX_Vpsignd_xmm_xmm_xmmm128,
VEX_Vpsignd_ymm_ymm_ymmm256,
Pmulhrsw_mm_mmm64,
Pmulhrsw_xmm_xmmm128,
VEX_Vpmulhrsw_xmm_xmm_xmmm128,
VEX_Vpmulhrsw_ymm_ymm_ymmm256,
EVEX_Vpmulhrsw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmulhrsw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmulhrsw_zmm_k1z_zmm_zmmm512,
VEX_Vpermilps_xmm_xmm_xmmm128,
VEX_Vpermilps_ymm_ymm_ymmm256,
EVEX_Vpermilps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpermilps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermilps_zmm_k1z_zmm_zmmm512b32,
VEX_Vpermilpd_xmm_xmm_xmmm128,
VEX_Vpermilpd_ymm_ymm_ymmm256,
EVEX_Vpermilpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpermilpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermilpd_zmm_k1z_zmm_zmmm512b64,
VEX_Vtestps_xmm_xmmm128,
VEX_Vtestps_ymm_ymmm256,
VEX_Vtestpd_xmm_xmmm128,
VEX_Vtestpd_ymm_ymmm256,
Pblendvb_xmm_xmmm128,
EVEX_Vpsrlvw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsrlvw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsrlvw_zmm_k1z_zmm_zmmm512,
EVEX_Vpmovuswb_xmmm64_k1z_xmm,
EVEX_Vpmovuswb_xmmm128_k1z_ymm,
EVEX_Vpmovuswb_ymmm256_k1z_zmm,
EVEX_Vpsravw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsravw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsravw_zmm_k1z_zmm_zmmm512,
EVEX_Vpmovusdb_xmmm32_k1z_xmm,
EVEX_Vpmovusdb_xmmm64_k1z_ymm,
EVEX_Vpmovusdb_xmmm128_k1z_zmm,
EVEX_Vpsllvw_xmm_k1z_xmm_xmmm128,
EVEX_Vpsllvw_ymm_k1z_ymm_ymmm256,
EVEX_Vpsllvw_zmm_k1z_zmm_zmmm512,
EVEX_Vpmovusqb_xmmm16_k1z_xmm,
EVEX_Vpmovusqb_xmmm32_k1z_ymm,
EVEX_Vpmovusqb_xmmm64_k1z_zmm,
VEX_Vcvtph2ps_xmm_xmmm64,
VEX_Vcvtph2ps_ymm_xmmm128,
EVEX_Vcvtph2ps_xmm_k1z_xmmm64,
EVEX_Vcvtph2ps_ymm_k1z_xmmm128,
EVEX_Vcvtph2ps_zmm_k1z_ymmm256_sae,
EVEX_Vpmovusdw_xmmm64_k1z_xmm,
EVEX_Vpmovusdw_xmmm128_k1z_ymm,
EVEX_Vpmovusdw_ymmm256_k1z_zmm,
Blendvps_xmm_xmmm128,
EVEX_Vprorvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vprorvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vprorvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vprorvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vprorvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vprorvq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpmovusqw_xmmm32_k1z_xmm,
EVEX_Vpmovusqw_xmmm64_k1z_ymm,
EVEX_Vpmovusqw_xmmm128_k1z_zmm,
Blendvpd_xmm_xmmm128,
EVEX_Vprolvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vprolvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vprolvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vprolvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vprolvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vprolvq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpmovusqd_xmmm64_k1z_xmm,
EVEX_Vpmovusqd_xmmm128_k1z_ymm,
EVEX_Vpmovusqd_ymmm256_k1z_zmm,
VEX_Vpermps_ymm_ymm_ymmm256,
EVEX_Vpermps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermps_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermpd_zmm_k1z_zmm_zmmm512b64,
Ptest_xmm_xmmm128,
VEX_Vptest_xmm_xmmm128,
VEX_Vptest_ymm_ymmm256,
VEX_Vbroadcastss_xmm_m32,
VEX_Vbroadcastss_ymm_m32,
EVEX_Vbroadcastss_xmm_k1z_xmmm32,
EVEX_Vbroadcastss_ymm_k1z_xmmm32,
EVEX_Vbroadcastss_zmm_k1z_xmmm32,
VEX_Vbroadcastsd_ymm_m64,
EVEX_Vbroadcastf32x2_ymm_k1z_xmmm64,
EVEX_Vbroadcastf32x2_zmm_k1z_xmmm64,
EVEX_Vbroadcastsd_ymm_k1z_xmmm64,
EVEX_Vbroadcastsd_zmm_k1z_xmmm64,
VEX_Vbroadcastf128_ymm_m128,
EVEX_Vbroadcastf32x4_ymm_k1z_m128,
EVEX_Vbroadcastf32x4_zmm_k1z_m128,
EVEX_Vbroadcastf64x2_ymm_k1z_m128,
EVEX_Vbroadcastf64x2_zmm_k1z_m128,
EVEX_Vbroadcastf32x8_zmm_k1z_m256,
EVEX_Vbroadcastf64x4_zmm_k1z_m256,
Pabsb_mm_mmm64,
Pabsb_xmm_xmmm128,
VEX_Vpabsb_xmm_xmmm128,
VEX_Vpabsb_ymm_ymmm256,
EVEX_Vpabsb_xmm_k1z_xmmm128,
EVEX_Vpabsb_ymm_k1z_ymmm256,
EVEX_Vpabsb_zmm_k1z_zmmm512,
Pabsw_mm_mmm64,
Pabsw_xmm_xmmm128,
VEX_Vpabsw_xmm_xmmm128,
VEX_Vpabsw_ymm_ymmm256,
EVEX_Vpabsw_xmm_k1z_xmmm128,
EVEX_Vpabsw_ymm_k1z_ymmm256,
EVEX_Vpabsw_zmm_k1z_zmmm512,
Pabsd_mm_mmm64,
Pabsd_xmm_xmmm128,
VEX_Vpabsd_xmm_xmmm128,
VEX_Vpabsd_ymm_ymmm256,
EVEX_Vpabsd_xmm_k1z_xmmm128b32,
EVEX_Vpabsd_ymm_k1z_ymmm256b32,
EVEX_Vpabsd_zmm_k1z_zmmm512b32,
EVEX_Vpabsq_xmm_k1z_xmmm128b64,
EVEX_Vpabsq_ymm_k1z_ymmm256b64,
EVEX_Vpabsq_zmm_k1z_zmmm512b64,
Pmovsxbw_xmm_xmmm64,
VEX_Vpmovsxbw_xmm_xmmm64,
VEX_Vpmovsxbw_ymm_xmmm128,
EVEX_Vpmovsxbw_xmm_k1z_xmmm64,
EVEX_Vpmovsxbw_ymm_k1z_xmmm128,
EVEX_Vpmovsxbw_zmm_k1z_ymmm256,
EVEX_Vpmovswb_xmmm64_k1z_xmm,
EVEX_Vpmovswb_xmmm128_k1z_ymm,
EVEX_Vpmovswb_ymmm256_k1z_zmm,
Pmovsxbd_xmm_xmmm32,
VEX_Vpmovsxbd_xmm_xmmm32,
VEX_Vpmovsxbd_ymm_xmmm64,
EVEX_Vpmovsxbd_xmm_k1z_xmmm32,
EVEX_Vpmovsxbd_ymm_k1z_xmmm64,
EVEX_Vpmovsxbd_zmm_k1z_xmmm128,
EVEX_Vpmovsdb_xmmm32_k1z_xmm,
EVEX_Vpmovsdb_xmmm64_k1z_ymm,
EVEX_Vpmovsdb_xmmm128_k1z_zmm,
Pmovsxbq_xmm_xmmm16,
VEX_Vpmovsxbq_xmm_xmmm16,
VEX_Vpmovsxbq_ymm_xmmm32,
EVEX_Vpmovsxbq_xmm_k1z_xmmm16,
EVEX_Vpmovsxbq_ymm_k1z_xmmm32,
EVEX_Vpmovsxbq_zmm_k1z_xmmm64,
EVEX_Vpmovsqb_xmmm16_k1z_xmm,
EVEX_Vpmovsqb_xmmm32_k1z_ymm,
EVEX_Vpmovsqb_xmmm64_k1z_zmm,
Pmovsxwd_xmm_xmmm64,
VEX_Vpmovsxwd_xmm_xmmm64,
VEX_Vpmovsxwd_ymm_xmmm128,
EVEX_Vpmovsxwd_xmm_k1z_xmmm64,
EVEX_Vpmovsxwd_ymm_k1z_xmmm128,
EVEX_Vpmovsxwd_zmm_k1z_ymmm256,
EVEX_Vpmovsdw_xmmm64_k1z_xmm,
EVEX_Vpmovsdw_xmmm128_k1z_ymm,
EVEX_Vpmovsdw_ymmm256_k1z_zmm,
Pmovsxwq_xmm_xmmm32,
VEX_Vpmovsxwq_xmm_xmmm32,
VEX_Vpmovsxwq_ymm_xmmm64,
EVEX_Vpmovsxwq_xmm_k1z_xmmm32,
EVEX_Vpmovsxwq_ymm_k1z_xmmm64,
EVEX_Vpmovsxwq_zmm_k1z_xmmm128,
EVEX_Vpmovsqw_xmmm32_k1z_xmm,
EVEX_Vpmovsqw_xmmm64_k1z_ymm,
EVEX_Vpmovsqw_xmmm128_k1z_zmm,
Pmovsxdq_xmm_xmmm64,
VEX_Vpmovsxdq_xmm_xmmm64,
VEX_Vpmovsxdq_ymm_xmmm128,
EVEX_Vpmovsxdq_xmm_k1z_xmmm64,
EVEX_Vpmovsxdq_ymm_k1z_xmmm128,
EVEX_Vpmovsxdq_zmm_k1z_ymmm256,
EVEX_Vpmovsqd_xmmm64_k1z_xmm,
EVEX_Vpmovsqd_xmmm128_k1z_ymm,
EVEX_Vpmovsqd_ymmm256_k1z_zmm,
EVEX_Vptestmb_kr_k1_xmm_xmmm128,
EVEX_Vptestmb_kr_k1_ymm_ymmm256,
EVEX_Vptestmb_kr_k1_zmm_zmmm512,
EVEX_Vptestmw_kr_k1_xmm_xmmm128,
EVEX_Vptestmw_kr_k1_ymm_ymmm256,
EVEX_Vptestmw_kr_k1_zmm_zmmm512,
EVEX_Vptestnmb_kr_k1_xmm_xmmm128,
EVEX_Vptestnmb_kr_k1_ymm_ymmm256,
EVEX_Vptestnmb_kr_k1_zmm_zmmm512,
EVEX_Vptestnmw_kr_k1_xmm_xmmm128,
EVEX_Vptestnmw_kr_k1_ymm_ymmm256,
EVEX_Vptestnmw_kr_k1_zmm_zmmm512,
EVEX_Vptestmd_kr_k1_xmm_xmmm128b32,
EVEX_Vptestmd_kr_k1_ymm_ymmm256b32,
EVEX_Vptestmd_kr_k1_zmm_zmmm512b32,
EVEX_Vptestmq_kr_k1_xmm_xmmm128b64,
EVEX_Vptestmq_kr_k1_ymm_ymmm256b64,
EVEX_Vptestmq_kr_k1_zmm_zmmm512b64,
EVEX_Vptestnmd_kr_k1_xmm_xmmm128b32,
EVEX_Vptestnmd_kr_k1_ymm_ymmm256b32,
EVEX_Vptestnmd_kr_k1_zmm_zmmm512b32,
EVEX_Vptestnmq_kr_k1_xmm_xmmm128b64,
EVEX_Vptestnmq_kr_k1_ymm_ymmm256b64,
EVEX_Vptestnmq_kr_k1_zmm_zmmm512b64,
Pmuldq_xmm_xmmm128,
VEX_Vpmuldq_xmm_xmm_xmmm128,
VEX_Vpmuldq_ymm_ymm_ymmm256,
EVEX_Vpmuldq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmuldq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmuldq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpmovm2b_xmm_kr,
EVEX_Vpmovm2b_ymm_kr,
EVEX_Vpmovm2b_zmm_kr,
EVEX_Vpmovm2w_xmm_kr,
EVEX_Vpmovm2w_ymm_kr,
EVEX_Vpmovm2w_zmm_kr,
Pcmpeqq_xmm_xmmm128,
VEX_Vpcmpeqq_xmm_xmm_xmmm128,
VEX_Vpcmpeqq_ymm_ymm_ymmm256,
EVEX_Vpcmpeqq_kr_k1_xmm_xmmm128b64,
EVEX_Vpcmpeqq_kr_k1_ymm_ymmm256b64,
EVEX_Vpcmpeqq_kr_k1_zmm_zmmm512b64,
EVEX_Vpmovb2m_kr_xmm,
EVEX_Vpmovb2m_kr_ymm,
EVEX_Vpmovb2m_kr_zmm,
EVEX_Vpmovw2m_kr_xmm,
EVEX_Vpmovw2m_kr_ymm,
EVEX_Vpmovw2m_kr_zmm,
Movntdqa_xmm_m128,
VEX_Vmovntdqa_xmm_m128,
VEX_Vmovntdqa_ymm_m256,
EVEX_Vmovntdqa_xmm_m128,
EVEX_Vmovntdqa_ymm_m256,
EVEX_Vmovntdqa_zmm_m512,
EVEX_Vpbroadcastmb2q_xmm_kr,
EVEX_Vpbroadcastmb2q_ymm_kr,
EVEX_Vpbroadcastmb2q_zmm_kr,
Packusdw_xmm_xmmm128,
VEX_Vpackusdw_xmm_xmm_xmmm128,
VEX_Vpackusdw_ymm_ymm_ymmm256,
EVEX_Vpackusdw_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpackusdw_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpackusdw_zmm_k1z_zmm_zmmm512b32,
VEX_Vmaskmovps_xmm_xmm_m128,
VEX_Vmaskmovps_ymm_ymm_m256,
EVEX_Vscalefps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vscalefps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vscalefps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vscalefpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vscalefpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vscalefpd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vmaskmovpd_xmm_xmm_m128,
VEX_Vmaskmovpd_ymm_ymm_m256,
EVEX_Vscalefss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vscalefsd_xmm_k1z_xmm_xmmm64_er,
VEX_Vmaskmovps_m128_xmm_xmm,
VEX_Vmaskmovps_m256_ymm_ymm,
VEX_Vmaskmovpd_m128_xmm_xmm,
VEX_Vmaskmovpd_m256_ymm_ymm,
Pmovzxbw_xmm_xmmm64,
VEX_Vpmovzxbw_xmm_xmmm64,
VEX_Vpmovzxbw_ymm_xmmm128,
EVEX_Vpmovzxbw_xmm_k1z_xmmm64,
EVEX_Vpmovzxbw_ymm_k1z_xmmm128,
EVEX_Vpmovzxbw_zmm_k1z_ymmm256,
EVEX_Vpmovwb_xmmm64_k1z_xmm,
EVEX_Vpmovwb_xmmm128_k1z_ymm,
EVEX_Vpmovwb_ymmm256_k1z_zmm,
Pmovzxbd_xmm_xmmm32,
VEX_Vpmovzxbd_xmm_xmmm32,
VEX_Vpmovzxbd_ymm_xmmm64,
EVEX_Vpmovzxbd_xmm_k1z_xmmm32,
EVEX_Vpmovzxbd_ymm_k1z_xmmm64,
EVEX_Vpmovzxbd_zmm_k1z_xmmm128,
EVEX_Vpmovdb_xmmm32_k1z_xmm,
EVEX_Vpmovdb_xmmm64_k1z_ymm,
EVEX_Vpmovdb_xmmm128_k1z_zmm,
Pmovzxbq_xmm_xmmm16,
VEX_Vpmovzxbq_xmm_xmmm16,
VEX_Vpmovzxbq_ymm_xmmm32,
EVEX_Vpmovzxbq_xmm_k1z_xmmm16,
EVEX_Vpmovzxbq_ymm_k1z_xmmm32,
EVEX_Vpmovzxbq_zmm_k1z_xmmm64,
EVEX_Vpmovqb_xmmm16_k1z_xmm,
EVEX_Vpmovqb_xmmm32_k1z_ymm,
EVEX_Vpmovqb_xmmm64_k1z_zmm,
Pmovzxwd_xmm_xmmm64,
VEX_Vpmovzxwd_xmm_xmmm64,
VEX_Vpmovzxwd_ymm_xmmm128,
EVEX_Vpmovzxwd_xmm_k1z_xmmm64,
EVEX_Vpmovzxwd_ymm_k1z_xmmm128,
EVEX_Vpmovzxwd_zmm_k1z_ymmm256,
EVEX_Vpmovdw_xmmm64_k1z_xmm,
EVEX_Vpmovdw_xmmm128_k1z_ymm,
EVEX_Vpmovdw_ymmm256_k1z_zmm,
Pmovzxwq_xmm_xmmm32,
VEX_Vpmovzxwq_xmm_xmmm32,
VEX_Vpmovzxwq_ymm_xmmm64,
EVEX_Vpmovzxwq_xmm_k1z_xmmm32,
EVEX_Vpmovzxwq_ymm_k1z_xmmm64,
EVEX_Vpmovzxwq_zmm_k1z_xmmm128,
EVEX_Vpmovqw_xmmm32_k1z_xmm,
EVEX_Vpmovqw_xmmm64_k1z_ymm,
EVEX_Vpmovqw_xmmm128_k1z_zmm,
Pmovzxdq_xmm_xmmm64,
VEX_Vpmovzxdq_xmm_xmmm64,
VEX_Vpmovzxdq_ymm_xmmm128,
EVEX_Vpmovzxdq_xmm_k1z_xmmm64,
EVEX_Vpmovzxdq_ymm_k1z_xmmm128,
EVEX_Vpmovzxdq_zmm_k1z_ymmm256,
EVEX_Vpmovqd_xmmm64_k1z_xmm,
EVEX_Vpmovqd_xmmm128_k1z_ymm,
EVEX_Vpmovqd_ymmm256_k1z_zmm,
VEX_Vpermd_ymm_ymm_ymmm256,
EVEX_Vpermd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermq_zmm_k1z_zmm_zmmm512b64,
Pcmpgtq_xmm_xmmm128,
VEX_Vpcmpgtq_xmm_xmm_xmmm128,
VEX_Vpcmpgtq_ymm_ymm_ymmm256,
EVEX_Vpcmpgtq_kr_k1_xmm_xmmm128b64,
EVEX_Vpcmpgtq_kr_k1_ymm_ymmm256b64,
EVEX_Vpcmpgtq_kr_k1_zmm_zmmm512b64,
Pminsb_xmm_xmmm128,
VEX_Vpminsb_xmm_xmm_xmmm128,
VEX_Vpminsb_ymm_ymm_ymmm256,
EVEX_Vpminsb_xmm_k1z_xmm_xmmm128,
EVEX_Vpminsb_ymm_k1z_ymm_ymmm256,
EVEX_Vpminsb_zmm_k1z_zmm_zmmm512,
EVEX_Vpmovm2d_xmm_kr,
EVEX_Vpmovm2d_ymm_kr,
EVEX_Vpmovm2d_zmm_kr,
EVEX_Vpmovm2q_xmm_kr,
EVEX_Vpmovm2q_ymm_kr,
EVEX_Vpmovm2q_zmm_kr,
Pminsd_xmm_xmmm128,
VEX_Vpminsd_xmm_xmm_xmmm128,
VEX_Vpminsd_ymm_ymm_ymmm256,
EVEX_Vpminsd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpminsd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpminsd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpminsq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpminsq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpminsq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpmovd2m_kr_xmm,
EVEX_Vpmovd2m_kr_ymm,
EVEX_Vpmovd2m_kr_zmm,
EVEX_Vpmovq2m_kr_xmm,
EVEX_Vpmovq2m_kr_ymm,
EVEX_Vpmovq2m_kr_zmm,
Pminuw_xmm_xmmm128,
VEX_Vpminuw_xmm_xmm_xmmm128,
VEX_Vpminuw_ymm_ymm_ymmm256,
EVEX_Vpminuw_xmm_k1z_xmm_xmmm128,
EVEX_Vpminuw_ymm_k1z_ymm_ymmm256,
EVEX_Vpminuw_zmm_k1z_zmm_zmmm512,
EVEX_Vpbroadcastmw2d_xmm_kr,
EVEX_Vpbroadcastmw2d_ymm_kr,
EVEX_Vpbroadcastmw2d_zmm_kr,
Pminud_xmm_xmmm128,
VEX_Vpminud_xmm_xmm_xmmm128,
VEX_Vpminud_ymm_ymm_ymmm256,
EVEX_Vpminud_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpminud_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpminud_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpminuq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpminuq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpminuq_zmm_k1z_zmm_zmmm512b64,
Pmaxsb_xmm_xmmm128,
VEX_Vpmaxsb_xmm_xmm_xmmm128,
VEX_Vpmaxsb_ymm_ymm_ymmm256,
EVEX_Vpmaxsb_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaxsb_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaxsb_zmm_k1z_zmm_zmmm512,
Pmaxsd_xmm_xmmm128,
VEX_Vpmaxsd_xmm_xmm_xmmm128,
VEX_Vpmaxsd_ymm_ymm_ymmm256,
EVEX_Vpmaxsd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpmaxsd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpmaxsd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpmaxsq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmaxsq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmaxsq_zmm_k1z_zmm_zmmm512b64,
Pmaxuw_xmm_xmmm128,
VEX_Vpmaxuw_xmm_xmm_xmmm128,
VEX_Vpmaxuw_ymm_ymm_ymmm256,
EVEX_Vpmaxuw_xmm_k1z_xmm_xmmm128,
EVEX_Vpmaxuw_ymm_k1z_ymm_ymmm256,
EVEX_Vpmaxuw_zmm_k1z_zmm_zmmm512,
Pmaxud_xmm_xmmm128,
VEX_Vpmaxud_xmm_xmm_xmmm128,
VEX_Vpmaxud_ymm_ymm_ymmm256,
EVEX_Vpmaxud_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpmaxud_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpmaxud_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpmaxuq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmaxuq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmaxuq_zmm_k1z_zmm_zmmm512b64,
Pmulld_xmm_xmmm128,
VEX_Vpmulld_xmm_xmm_xmmm128,
VEX_Vpmulld_ymm_ymm_ymmm256,
EVEX_Vpmulld_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpmulld_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpmulld_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpmullq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmullq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmullq_zmm_k1z_zmm_zmmm512b64,
Phminposuw_xmm_xmmm128,
VEX_Vphminposuw_xmm_xmmm128,
EVEX_Vgetexpps_xmm_k1z_xmmm128b32,
EVEX_Vgetexpps_ymm_k1z_ymmm256b32,
EVEX_Vgetexpps_zmm_k1z_zmmm512b32_sae,
EVEX_Vgetexppd_xmm_k1z_xmmm128b64,
EVEX_Vgetexppd_ymm_k1z_ymmm256b64,
EVEX_Vgetexppd_zmm_k1z_zmmm512b64_sae,
EVEX_Vgetexpss_xmm_k1z_xmm_xmmm32_sae,
EVEX_Vgetexpsd_xmm_k1z_xmm_xmmm64_sae,
EVEX_Vplzcntd_xmm_k1z_xmmm128b32,
EVEX_Vplzcntd_ymm_k1z_ymmm256b32,
EVEX_Vplzcntd_zmm_k1z_zmmm512b32,
EVEX_Vplzcntq_xmm_k1z_xmmm128b64,
EVEX_Vplzcntq_ymm_k1z_ymmm256b64,
EVEX_Vplzcntq_zmm_k1z_zmmm512b64,
VEX_Vpsrlvd_xmm_xmm_xmmm128,
VEX_Vpsrlvd_ymm_ymm_ymmm256,
VEX_Vpsrlvq_xmm_xmm_xmmm128,
VEX_Vpsrlvq_ymm_ymm_ymmm256,
EVEX_Vpsrlvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpsrlvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpsrlvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpsrlvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpsrlvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpsrlvq_zmm_k1z_zmm_zmmm512b64,
VEX_Vpsravd_xmm_xmm_xmmm128,
VEX_Vpsravd_ymm_ymm_ymmm256,
EVEX_Vpsravd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpsravd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpsravd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpsravq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpsravq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpsravq_zmm_k1z_zmm_zmmm512b64,
VEX_Vpsllvd_xmm_xmm_xmmm128,
VEX_Vpsllvd_ymm_ymm_ymmm256,
VEX_Vpsllvq_xmm_xmm_xmmm128,
VEX_Vpsllvq_ymm_ymm_ymmm256,
EVEX_Vpsllvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpsllvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpsllvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpsllvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpsllvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpsllvq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vrcp14ps_xmm_k1z_xmmm128b32,
EVEX_Vrcp14ps_ymm_k1z_ymmm256b32,
EVEX_Vrcp14ps_zmm_k1z_zmmm512b32,
EVEX_Vrcp14pd_xmm_k1z_xmmm128b64,
EVEX_Vrcp14pd_ymm_k1z_ymmm256b64,
EVEX_Vrcp14pd_zmm_k1z_zmmm512b64,
EVEX_Vrcp14ss_xmm_k1z_xmm_xmmm32,
EVEX_Vrcp14sd_xmm_k1z_xmm_xmmm64,
EVEX_Vrsqrt14ps_xmm_k1z_xmmm128b32,
EVEX_Vrsqrt14ps_ymm_k1z_ymmm256b32,
EVEX_Vrsqrt14ps_zmm_k1z_zmmm512b32,
EVEX_Vrsqrt14pd_xmm_k1z_xmmm128b64,
EVEX_Vrsqrt14pd_ymm_k1z_ymmm256b64,
EVEX_Vrsqrt14pd_zmm_k1z_zmmm512b64,
EVEX_Vrsqrt14ss_xmm_k1z_xmm_xmmm32,
EVEX_Vrsqrt14sd_xmm_k1z_xmm_xmmm64,
EVEX_Vpdpbusd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpdpbusd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpdpbusd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpdpbusds_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpdpbusds_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpdpbusds_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpdpwssd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpdpwssd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpdpwssd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vdpbf16ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vdpbf16ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vdpbf16ps_zmm_k1z_zmm_zmmm512b32,
EVEX_Vp4dpwssd_zmm_k1z_zmmp3_m128,
EVEX_Vpdpwssds_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpdpwssds_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpdpwssds_zmm_k1z_zmm_zmmm512b32,
EVEX_Vp4dpwssds_zmm_k1z_zmmp3_m128,
EVEX_Vpopcntb_xmm_k1z_xmmm128,
EVEX_Vpopcntb_ymm_k1z_ymmm256,
EVEX_Vpopcntb_zmm_k1z_zmmm512,
EVEX_Vpopcntw_xmm_k1z_xmmm128,
EVEX_Vpopcntw_ymm_k1z_ymmm256,
EVEX_Vpopcntw_zmm_k1z_zmmm512,
EVEX_Vpopcntd_xmm_k1z_xmmm128b32,
EVEX_Vpopcntd_ymm_k1z_ymmm256b32,
EVEX_Vpopcntd_zmm_k1z_zmmm512b32,
EVEX_Vpopcntq_xmm_k1z_xmmm128b64,
EVEX_Vpopcntq_ymm_k1z_ymmm256b64,
EVEX_Vpopcntq_zmm_k1z_zmmm512b64,
VEX_Vpbroadcastd_xmm_xmmm32,
VEX_Vpbroadcastd_ymm_xmmm32,
EVEX_Vpbroadcastd_xmm_k1z_xmmm32,
EVEX_Vpbroadcastd_ymm_k1z_xmmm32,
EVEX_Vpbroadcastd_zmm_k1z_xmmm32,
VEX_Vpbroadcastq_xmm_xmmm64,
VEX_Vpbroadcastq_ymm_xmmm64,
EVEX_Vbroadcasti32x2_xmm_k1z_xmmm64,
EVEX_Vbroadcasti32x2_ymm_k1z_xmmm64,
EVEX_Vbroadcasti32x2_zmm_k1z_xmmm64,
EVEX_Vpbroadcastq_xmm_k1z_xmmm64,
EVEX_Vpbroadcastq_ymm_k1z_xmmm64,
EVEX_Vpbroadcastq_zmm_k1z_xmmm64,
VEX_Vbroadcasti128_ymm_m128,
EVEX_Vbroadcasti32x4_ymm_k1z_m128,
EVEX_Vbroadcasti32x4_zmm_k1z_m128,
EVEX_Vbroadcasti64x2_ymm_k1z_m128,
EVEX_Vbroadcasti64x2_zmm_k1z_m128,
EVEX_Vbroadcasti32x8_zmm_k1z_m256,
EVEX_Vbroadcasti64x4_zmm_k1z_m256,
EVEX_Vpexpandb_xmm_k1z_xmmm128,
EVEX_Vpexpandb_ymm_k1z_ymmm256,
EVEX_Vpexpandb_zmm_k1z_zmmm512,
EVEX_Vpexpandw_xmm_k1z_xmmm128,
EVEX_Vpexpandw_ymm_k1z_ymmm256,
EVEX_Vpexpandw_zmm_k1z_zmmm512,
EVEX_Vpcompressb_xmmm128_k1z_xmm,
EVEX_Vpcompressb_ymmm256_k1z_ymm,
EVEX_Vpcompressb_zmmm512_k1z_zmm,
EVEX_Vpcompressw_xmmm128_k1z_xmm,
EVEX_Vpcompressw_ymmm256_k1z_ymm,
EVEX_Vpcompressw_zmmm512_k1z_zmm,
EVEX_Vpblendmd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpblendmd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpblendmd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpblendmq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpblendmq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpblendmq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vblendmps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vblendmps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vblendmps_zmm_k1z_zmm_zmmm512b32,
EVEX_Vblendmpd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vblendmpd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vblendmpd_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpblendmb_xmm_k1z_xmm_xmmm128,
EVEX_Vpblendmb_ymm_k1z_ymm_ymmm256,
EVEX_Vpblendmb_zmm_k1z_zmm_zmmm512,
EVEX_Vpblendmw_xmm_k1z_xmm_xmmm128,
EVEX_Vpblendmw_ymm_k1z_ymm_ymmm256,
EVEX_Vpblendmw_zmm_k1z_zmm_zmmm512,
EVEX_Vp2intersectd_kp1_xmm_xmmm128b32,
EVEX_Vp2intersectd_kp1_ymm_ymmm256b32,
EVEX_Vp2intersectd_kp1_zmm_zmmm512b32,
EVEX_Vp2intersectq_kp1_xmm_xmmm128b64,
EVEX_Vp2intersectq_kp1_ymm_ymmm256b64,
EVEX_Vp2intersectq_kp1_zmm_zmmm512b64,
EVEX_Vpshldvw_xmm_k1z_xmm_xmmm128,
EVEX_Vpshldvw_ymm_k1z_ymm_ymmm256,
EVEX_Vpshldvw_zmm_k1z_zmm_zmmm512,
EVEX_Vpshldvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpshldvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpshldvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpshldvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpshldvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpshldvq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpshrdvw_xmm_k1z_xmm_xmmm128,
EVEX_Vpshrdvw_ymm_k1z_ymm_ymmm256,
EVEX_Vpshrdvw_zmm_k1z_zmm_zmmm512,
EVEX_Vcvtneps2bf16_xmm_k1z_xmmm128b32,
EVEX_Vcvtneps2bf16_xmm_k1z_ymmm256b32,
EVEX_Vcvtneps2bf16_ymm_k1z_zmmm512b32,
EVEX_Vcvtne2ps2bf16_xmm_k1z_xmm_xmmm128b32,
EVEX_Vcvtne2ps2bf16_ymm_k1z_ymm_ymmm256b32,
EVEX_Vcvtne2ps2bf16_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpshrdvd_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpshrdvd_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpshrdvd_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpshrdvq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpshrdvq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpshrdvq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpermi2b_xmm_k1z_xmm_xmmm128,
EVEX_Vpermi2b_ymm_k1z_ymm_ymmm256,
EVEX_Vpermi2b_zmm_k1z_zmm_zmmm512,
EVEX_Vpermi2w_xmm_k1z_xmm_xmmm128,
EVEX_Vpermi2w_ymm_k1z_ymm_ymmm256,
EVEX_Vpermi2w_zmm_k1z_zmm_zmmm512,
EVEX_Vpermi2d_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpermi2d_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermi2d_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermi2q_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpermi2q_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermi2q_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpermi2ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpermi2ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermi2ps_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermi2pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpermi2pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermi2pd_zmm_k1z_zmm_zmmm512b64,
VEX_Vpbroadcastb_xmm_xmmm8,
VEX_Vpbroadcastb_ymm_xmmm8,
EVEX_Vpbroadcastb_xmm_k1z_xmmm8,
EVEX_Vpbroadcastb_ymm_k1z_xmmm8,
EVEX_Vpbroadcastb_zmm_k1z_xmmm8,
VEX_Vpbroadcastw_xmm_xmmm16,
VEX_Vpbroadcastw_ymm_xmmm16,
EVEX_Vpbroadcastw_xmm_k1z_xmmm16,
EVEX_Vpbroadcastw_ymm_k1z_xmmm16,
EVEX_Vpbroadcastw_zmm_k1z_xmmm16,
EVEX_Vpbroadcastb_xmm_k1z_r32,
EVEX_Vpbroadcastb_ymm_k1z_r32,
EVEX_Vpbroadcastb_zmm_k1z_r32,
EVEX_Vpbroadcastw_xmm_k1z_r32,
EVEX_Vpbroadcastw_ymm_k1z_r32,
EVEX_Vpbroadcastw_zmm_k1z_r32,
EVEX_Vpbroadcastd_xmm_k1z_r32,
EVEX_Vpbroadcastd_ymm_k1z_r32,
EVEX_Vpbroadcastd_zmm_k1z_r32,
EVEX_Vpbroadcastq_xmm_k1z_r64,
EVEX_Vpbroadcastq_ymm_k1z_r64,
EVEX_Vpbroadcastq_zmm_k1z_r64,
EVEX_Vpermt2b_xmm_k1z_xmm_xmmm128,
EVEX_Vpermt2b_ymm_k1z_ymm_ymmm256,
EVEX_Vpermt2b_zmm_k1z_zmm_zmmm512,
EVEX_Vpermt2w_xmm_k1z_xmm_xmmm128,
EVEX_Vpermt2w_ymm_k1z_ymm_ymmm256,
EVEX_Vpermt2w_zmm_k1z_zmm_zmmm512,
EVEX_Vpermt2d_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpermt2d_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermt2d_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermt2q_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpermt2q_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermt2q_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpermt2ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vpermt2ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vpermt2ps_zmm_k1z_zmm_zmmm512b32,
EVEX_Vpermt2pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpermt2pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpermt2pd_zmm_k1z_zmm_zmmm512b64,
Invept_r32_m128,
Invept_r64_m128,
Invvpid_r32_m128,
Invvpid_r64_m128,
Invpcid_r32_m128,
Invpcid_r64_m128,
EVEX_Vpmultishiftqb_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmultishiftqb_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmultishiftqb_zmm_k1z_zmm_zmmm512b64,
EVEX_Vexpandps_xmm_k1z_xmmm128,
EVEX_Vexpandps_ymm_k1z_ymmm256,
EVEX_Vexpandps_zmm_k1z_zmmm512,
EVEX_Vexpandpd_xmm_k1z_xmmm128,
EVEX_Vexpandpd_ymm_k1z_ymmm256,
EVEX_Vexpandpd_zmm_k1z_zmmm512,
EVEX_Vpexpandd_xmm_k1z_xmmm128,
EVEX_Vpexpandd_ymm_k1z_ymmm256,
EVEX_Vpexpandd_zmm_k1z_zmmm512,
EVEX_Vpexpandq_xmm_k1z_xmmm128,
EVEX_Vpexpandq_ymm_k1z_ymmm256,
EVEX_Vpexpandq_zmm_k1z_zmmm512,
EVEX_Vcompressps_xmmm128_k1z_xmm,
EVEX_Vcompressps_ymmm256_k1z_ymm,
EVEX_Vcompressps_zmmm512_k1z_zmm,
EVEX_Vcompresspd_xmmm128_k1z_xmm,
EVEX_Vcompresspd_ymmm256_k1z_ymm,
EVEX_Vcompresspd_zmmm512_k1z_zmm,
EVEX_Vpcompressd_xmmm128_k1z_xmm,
EVEX_Vpcompressd_ymmm256_k1z_ymm,
EVEX_Vpcompressd_zmmm512_k1z_zmm,
EVEX_Vpcompressq_xmmm128_k1z_xmm,
EVEX_Vpcompressq_ymmm256_k1z_ymm,
EVEX_Vpcompressq_zmmm512_k1z_zmm,
VEX_Vpmaskmovd_xmm_xmm_m128,
VEX_Vpmaskmovd_ymm_ymm_m256,
VEX_Vpmaskmovq_xmm_xmm_m128,
VEX_Vpmaskmovq_ymm_ymm_m256,
EVEX_Vpermb_xmm_k1z_xmm_xmmm128,
EVEX_Vpermb_ymm_k1z_ymm_ymmm256,
EVEX_Vpermb_zmm_k1z_zmm_zmmm512,
EVEX_Vpermw_xmm_k1z_xmm_xmmm128,
EVEX_Vpermw_ymm_k1z_ymm_ymmm256,
EVEX_Vpermw_zmm_k1z_zmm_zmmm512,
VEX_Vpmaskmovd_m128_xmm_xmm,
VEX_Vpmaskmovd_m256_ymm_ymm,
VEX_Vpmaskmovq_m128_xmm_xmm,
VEX_Vpmaskmovq_m256_ymm_ymm,
EVEX_Vpshufbitqmb_kr_k1_xmm_xmmm128,
EVEX_Vpshufbitqmb_kr_k1_ymm_ymmm256,
EVEX_Vpshufbitqmb_kr_k1_zmm_zmmm512,
VEX_Vpgatherdd_xmm_vm32x_xmm,
VEX_Vpgatherdd_ymm_vm32y_ymm,
VEX_Vpgatherdq_xmm_vm32x_xmm,
VEX_Vpgatherdq_ymm_vm32x_ymm,
EVEX_Vpgatherdd_xmm_k1_vm32x,
EVEX_Vpgatherdd_ymm_k1_vm32y,
EVEX_Vpgatherdd_zmm_k1_vm32z,
EVEX_Vpgatherdq_xmm_k1_vm32x,
EVEX_Vpgatherdq_ymm_k1_vm32x,
EVEX_Vpgatherdq_zmm_k1_vm32y,
VEX_Vpgatherqd_xmm_vm64x_xmm,
VEX_Vpgatherqd_xmm_vm64y_xmm,
VEX_Vpgatherqq_xmm_vm64x_xmm,
VEX_Vpgatherqq_ymm_vm64y_ymm,
EVEX_Vpgatherqd_xmm_k1_vm64x,
EVEX_Vpgatherqd_xmm_k1_vm64y,
EVEX_Vpgatherqd_ymm_k1_vm64z,
EVEX_Vpgatherqq_xmm_k1_vm64x,
EVEX_Vpgatherqq_ymm_k1_vm64y,
EVEX_Vpgatherqq_zmm_k1_vm64z,
VEX_Vgatherdps_xmm_vm32x_xmm,
VEX_Vgatherdps_ymm_vm32y_ymm,
VEX_Vgatherdpd_xmm_vm32x_xmm,
VEX_Vgatherdpd_ymm_vm32x_ymm,
EVEX_Vgatherdps_xmm_k1_vm32x,
EVEX_Vgatherdps_ymm_k1_vm32y,
EVEX_Vgatherdps_zmm_k1_vm32z,
EVEX_Vgatherdpd_xmm_k1_vm32x,
EVEX_Vgatherdpd_ymm_k1_vm32x,
EVEX_Vgatherdpd_zmm_k1_vm32y,
VEX_Vgatherqps_xmm_vm64x_xmm,
VEX_Vgatherqps_xmm_vm64y_xmm,
VEX_Vgatherqpd_xmm_vm64x_xmm,
VEX_Vgatherqpd_ymm_vm64y_ymm,
EVEX_Vgatherqps_xmm_k1_vm64x,
EVEX_Vgatherqps_xmm_k1_vm64y,
EVEX_Vgatherqps_ymm_k1_vm64z,
EVEX_Vgatherqpd_xmm_k1_vm64x,
EVEX_Vgatherqpd_ymm_k1_vm64y,
EVEX_Vgatherqpd_zmm_k1_vm64z,
VEX_Vfmaddsub132ps_xmm_xmm_xmmm128,
VEX_Vfmaddsub132ps_ymm_ymm_ymmm256,
VEX_Vfmaddsub132pd_xmm_xmm_xmmm128,
VEX_Vfmaddsub132pd_ymm_ymm_ymmm256,
EVEX_Vfmaddsub132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmaddsub132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmaddsub132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmaddsub132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmaddsub132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmaddsub132pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmsubadd132ps_xmm_xmm_xmmm128,
VEX_Vfmsubadd132ps_ymm_ymm_ymmm256,
VEX_Vfmsubadd132pd_xmm_xmm_xmmm128,
VEX_Vfmsubadd132pd_ymm_ymm_ymmm256,
EVEX_Vfmsubadd132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsubadd132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsubadd132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsubadd132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsubadd132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsubadd132pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd132ps_xmm_xmm_xmmm128,
VEX_Vfmadd132ps_ymm_ymm_ymmm256,
VEX_Vfmadd132pd_xmm_xmm_xmmm128,
VEX_Vfmadd132pd_ymm_ymm_ymmm256,
EVEX_Vfmadd132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmadd132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmadd132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmadd132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmadd132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmadd132pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd132ss_xmm_xmm_xmmm32,
VEX_Vfmadd132sd_xmm_xmm_xmmm64,
EVEX_Vfmadd132ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmadd132sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfmsub132ps_xmm_xmm_xmmm128,
VEX_Vfmsub132ps_ymm_ymm_ymmm256,
VEX_Vfmsub132pd_xmm_xmm_xmmm128,
VEX_Vfmsub132pd_ymm_ymm_ymmm256,
EVEX_Vfmsub132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsub132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsub132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsub132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsub132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsub132pd_zmm_k1z_zmm_zmmm512b64_er,
EVEX_V4fmaddps_zmm_k1z_zmmp3_m128,
VEX_Vfmsub132ss_xmm_xmm_xmmm32,
VEX_Vfmsub132sd_xmm_xmm_xmmm64,
EVEX_Vfmsub132ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmsub132sd_xmm_k1z_xmm_xmmm64_er,
EVEX_V4fmaddss_xmm_k1z_xmmp3_m128,
VEX_Vfnmadd132ps_xmm_xmm_xmmm128,
VEX_Vfnmadd132ps_ymm_ymm_ymmm256,
VEX_Vfnmadd132pd_xmm_xmm_xmmm128,
VEX_Vfnmadd132pd_ymm_ymm_ymmm256,
EVEX_Vfnmadd132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmadd132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmadd132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmadd132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmadd132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmadd132pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmadd132ss_xmm_xmm_xmmm32,
VEX_Vfnmadd132sd_xmm_xmm_xmmm64,
EVEX_Vfnmadd132ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmadd132sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfnmsub132ps_xmm_xmm_xmmm128,
VEX_Vfnmsub132ps_ymm_ymm_ymmm256,
VEX_Vfnmsub132pd_xmm_xmm_xmmm128,
VEX_Vfnmsub132pd_ymm_ymm_ymmm256,
EVEX_Vfnmsub132ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmsub132ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmsub132ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmsub132pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmsub132pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmsub132pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmsub132ss_xmm_xmm_xmmm32,
VEX_Vfnmsub132sd_xmm_xmm_xmmm64,
EVEX_Vfnmsub132ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmsub132sd_xmm_k1z_xmm_xmmm64_er,
EVEX_Vpscatterdd_vm32x_k1_xmm,
EVEX_Vpscatterdd_vm32y_k1_ymm,
EVEX_Vpscatterdd_vm32z_k1_zmm,
EVEX_Vpscatterdq_vm32x_k1_xmm,
EVEX_Vpscatterdq_vm32x_k1_ymm,
EVEX_Vpscatterdq_vm32y_k1_zmm,
EVEX_Vpscatterqd_vm64x_k1_xmm,
EVEX_Vpscatterqd_vm64y_k1_xmm,
EVEX_Vpscatterqd_vm64z_k1_ymm,
EVEX_Vpscatterqq_vm64x_k1_xmm,
EVEX_Vpscatterqq_vm64y_k1_ymm,
EVEX_Vpscatterqq_vm64z_k1_zmm,
EVEX_Vscatterdps_vm32x_k1_xmm,
EVEX_Vscatterdps_vm32y_k1_ymm,
EVEX_Vscatterdps_vm32z_k1_zmm,
EVEX_Vscatterdpd_vm32x_k1_xmm,
EVEX_Vscatterdpd_vm32x_k1_ymm,
EVEX_Vscatterdpd_vm32y_k1_zmm,
EVEX_Vscatterqps_vm64x_k1_xmm,
EVEX_Vscatterqps_vm64y_k1_xmm,
EVEX_Vscatterqps_vm64z_k1_ymm,
EVEX_Vscatterqpd_vm64x_k1_xmm,
EVEX_Vscatterqpd_vm64y_k1_ymm,
EVEX_Vscatterqpd_vm64z_k1_zmm,
VEX_Vfmaddsub213ps_xmm_xmm_xmmm128,
VEX_Vfmaddsub213ps_ymm_ymm_ymmm256,
VEX_Vfmaddsub213pd_xmm_xmm_xmmm128,
VEX_Vfmaddsub213pd_ymm_ymm_ymmm256,
EVEX_Vfmaddsub213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmaddsub213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmaddsub213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmaddsub213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmaddsub213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmaddsub213pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmsubadd213ps_xmm_xmm_xmmm128,
VEX_Vfmsubadd213ps_ymm_ymm_ymmm256,
VEX_Vfmsubadd213pd_xmm_xmm_xmmm128,
VEX_Vfmsubadd213pd_ymm_ymm_ymmm256,
EVEX_Vfmsubadd213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsubadd213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsubadd213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsubadd213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsubadd213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsubadd213pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd213ps_xmm_xmm_xmmm128,
VEX_Vfmadd213ps_ymm_ymm_ymmm256,
VEX_Vfmadd213pd_xmm_xmm_xmmm128,
VEX_Vfmadd213pd_ymm_ymm_ymmm256,
EVEX_Vfmadd213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmadd213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmadd213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmadd213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmadd213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmadd213pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd213ss_xmm_xmm_xmmm32,
VEX_Vfmadd213sd_xmm_xmm_xmmm64,
EVEX_Vfmadd213ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmadd213sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfmsub213ps_xmm_xmm_xmmm128,
VEX_Vfmsub213ps_ymm_ymm_ymmm256,
VEX_Vfmsub213pd_xmm_xmm_xmmm128,
VEX_Vfmsub213pd_ymm_ymm_ymmm256,
EVEX_Vfmsub213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsub213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsub213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsub213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsub213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsub213pd_zmm_k1z_zmm_zmmm512b64_er,
EVEX_V4fnmaddps_zmm_k1z_zmmp3_m128,
VEX_Vfmsub213ss_xmm_xmm_xmmm32,
VEX_Vfmsub213sd_xmm_xmm_xmmm64,
EVEX_Vfmsub213ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmsub213sd_xmm_k1z_xmm_xmmm64_er,
EVEX_V4fnmaddss_xmm_k1z_xmmp3_m128,
VEX_Vfnmadd213ps_xmm_xmm_xmmm128,
VEX_Vfnmadd213ps_ymm_ymm_ymmm256,
VEX_Vfnmadd213pd_xmm_xmm_xmmm128,
VEX_Vfnmadd213pd_ymm_ymm_ymmm256,
EVEX_Vfnmadd213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmadd213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmadd213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmadd213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmadd213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmadd213pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmadd213ss_xmm_xmm_xmmm32,
VEX_Vfnmadd213sd_xmm_xmm_xmmm64,
EVEX_Vfnmadd213ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmadd213sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfnmsub213ps_xmm_xmm_xmmm128,
VEX_Vfnmsub213ps_ymm_ymm_ymmm256,
VEX_Vfnmsub213pd_xmm_xmm_xmmm128,
VEX_Vfnmsub213pd_ymm_ymm_ymmm256,
EVEX_Vfnmsub213ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmsub213ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmsub213ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmsub213pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmsub213pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmsub213pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmsub213ss_xmm_xmm_xmmm32,
VEX_Vfnmsub213sd_xmm_xmm_xmmm64,
EVEX_Vfnmsub213ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmsub213sd_xmm_k1z_xmm_xmmm64_er,
EVEX_Vpmadd52luq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmadd52luq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmadd52luq_zmm_k1z_zmm_zmmm512b64,
EVEX_Vpmadd52huq_xmm_k1z_xmm_xmmm128b64,
EVEX_Vpmadd52huq_ymm_k1z_ymm_ymmm256b64,
EVEX_Vpmadd52huq_zmm_k1z_zmm_zmmm512b64,
VEX_Vfmaddsub231ps_xmm_xmm_xmmm128,
VEX_Vfmaddsub231ps_ymm_ymm_ymmm256,
VEX_Vfmaddsub231pd_xmm_xmm_xmmm128,
VEX_Vfmaddsub231pd_ymm_ymm_ymmm256,
EVEX_Vfmaddsub231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmaddsub231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmaddsub231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmaddsub231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmaddsub231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmaddsub231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmsubadd231ps_xmm_xmm_xmmm128,
VEX_Vfmsubadd231ps_ymm_ymm_ymmm256,
VEX_Vfmsubadd231pd_xmm_xmm_xmmm128,
VEX_Vfmsubadd231pd_ymm_ymm_ymmm256,
EVEX_Vfmsubadd231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsubadd231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsubadd231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsubadd231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsubadd231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsubadd231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd231ps_xmm_xmm_xmmm128,
VEX_Vfmadd231ps_ymm_ymm_ymmm256,
VEX_Vfmadd231pd_xmm_xmm_xmmm128,
VEX_Vfmadd231pd_ymm_ymm_ymmm256,
EVEX_Vfmadd231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmadd231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmadd231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmadd231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmadd231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmadd231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmadd231ss_xmm_xmm_xmmm32,
VEX_Vfmadd231sd_xmm_xmm_xmmm64,
EVEX_Vfmadd231ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmadd231sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfmsub231ps_xmm_xmm_xmmm128,
VEX_Vfmsub231ps_ymm_ymm_ymmm256,
VEX_Vfmsub231pd_xmm_xmm_xmmm128,
VEX_Vfmsub231pd_ymm_ymm_ymmm256,
EVEX_Vfmsub231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfmsub231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfmsub231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfmsub231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfmsub231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfmsub231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfmsub231ss_xmm_xmm_xmmm32,
VEX_Vfmsub231sd_xmm_xmm_xmmm64,
EVEX_Vfmsub231ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfmsub231sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfnmadd231ps_xmm_xmm_xmmm128,
VEX_Vfnmadd231ps_ymm_ymm_ymmm256,
VEX_Vfnmadd231pd_xmm_xmm_xmmm128,
VEX_Vfnmadd231pd_ymm_ymm_ymmm256,
EVEX_Vfnmadd231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmadd231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmadd231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmadd231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmadd231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmadd231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmadd231ss_xmm_xmm_xmmm32,
VEX_Vfnmadd231sd_xmm_xmm_xmmm64,
EVEX_Vfnmadd231ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmadd231sd_xmm_k1z_xmm_xmmm64_er,
VEX_Vfnmsub231ps_xmm_xmm_xmmm128,
VEX_Vfnmsub231ps_ymm_ymm_ymmm256,
VEX_Vfnmsub231pd_xmm_xmm_xmmm128,
VEX_Vfnmsub231pd_ymm_ymm_ymmm256,
EVEX_Vfnmsub231ps_xmm_k1z_xmm_xmmm128b32,
EVEX_Vfnmsub231ps_ymm_k1z_ymm_ymmm256b32,
EVEX_Vfnmsub231ps_zmm_k1z_zmm_zmmm512b32_er,
EVEX_Vfnmsub231pd_xmm_k1z_xmm_xmmm128b64,
EVEX_Vfnmsub231pd_ymm_k1z_ymm_ymmm256b64,
EVEX_Vfnmsub231pd_zmm_k1z_zmm_zmmm512b64_er,
VEX_Vfnmsub231ss_xmm_xmm_xmmm32,
VEX_Vfnmsub231sd_xmm_xmm_xmmm64,
EVEX_Vfnmsub231ss_xmm_k1z_xmm_xmmm32_er,
EVEX_Vfnmsub231sd_xmm_k1z_xmm_xmmm64_er,
EVEX_Vpconflictd_xmm_k1z_xmmm128b32,
EVEX_Vpconflictd_ymm_k1z_ymmm256b32,
EVEX_Vpconflictd_zmm_k1z_zmmm512b32,
EVEX_Vpconflictq_xmm_k1z_xmmm128b64,
EVEX_Vpconflictq_ymm_k1z_ymmm256b64,
EVEX_Vpconflictq_zmm_k1z_zmmm512b64,
EVEX_Vgatherpf0dps_vm32z_k1,
EVEX_Vgatherpf0dpd_vm32y_k1,
EVEX_Vgatherpf1dps_vm32z_k1,
EVEX_Vgatherpf1dpd_vm32y_k1,
EVEX_Vscatterpf0dps_vm32z_k1,
EVEX_Vscatterpf0dpd_vm32y_k1,
EVEX_Vscatterpf1dps_vm32z_k1,
EVEX_Vscatterpf1dpd_vm32y_k1,
EVEX_Vgatherpf0qps_vm64z_k1,
EVEX_Vgatherpf0qpd_vm64z_k1,
EVEX_Vgatherpf1qps_vm64z_k1,
EVEX_Vgatherpf1qpd_vm64z_k1,
EVEX_Vscatterpf0qps_vm64z_k1,
EVEX_Vscatterpf0qpd_vm64z_k1,
EVEX_Vscatterpf1qps_vm64z_k1,
EVEX_Vscatterpf1qpd_vm64z_k1,
Sha1nexte_xmm_xmmm128,
EVEX_Vexp2ps_zmm_k1z_zmmm512b32_sae,
EVEX_Vexp2pd_zmm_k1z_zmmm512b64_sae,
Sha1msg1_xmm_xmmm128,
Sha1msg2_xmm_xmmm128,
EVEX_Vrcp28ps_zmm_k1z_zmmm512b32_sae,
EVEX_Vrcp28pd_zmm_k1z_zmmm512b64_sae,
Sha256rnds2_xmm_xmmm128,
EVEX_Vrcp28ss_xmm_k1z_xmm_xmmm32_sae,
EVEX_Vrcp28sd_xmm_k1z_xmm_xmmm64_sae,
Sha256msg1_xmm_xmmm128,
EVEX_Vrsqrt28ps_zmm_k1z_zmmm512b32_sae,
EVEX_Vrsqrt28pd_zmm_k1z_zmmm512b64_sae,
Sha256msg2_xmm_xmmm128,
EVEX_Vrsqrt28ss_xmm_k1z_xmm_xmmm32_sae,
EVEX_Vrsqrt28sd_xmm_k1z_xmm_xmmm64_sae,
Gf2p8mulb_xmm_xmmm128,
VEX_Vgf2p8mulb_xmm_xmm_xmmm128,
VEX_Vgf2p8mulb_ymm_ymm_ymmm256,
EVEX_Vgf2p8mulb_xmm_k1z_xmm_xmmm128,
EVEX_Vgf2p8mulb_ymm_k1z_ymm_ymmm256,
EVEX_Vgf2p8mulb_zmm_k1z_zmm_zmmm512,
Aesimc_xmm_xmmm128,
VEX_Vaesimc_xmm_xmmm128,
Aesenc_xmm_xmmm128,
VEX_Vaesenc_xmm_xmm_xmmm128,
VEX_Vaesenc_ymm_ymm_ymmm256,
EVEX_Vaesenc_xmm_xmm_xmmm128,
EVEX_Vaesenc_ymm_ymm_ymmm256,
EVEX_Vaesenc_zmm_zmm_zmmm512,
Aesenclast_xmm_xmmm128,
VEX_Vaesenclast_xmm_xmm_xmmm128,
VEX_Vaesenclast_ymm_ymm_ymmm256,
EVEX_Vaesenclast_xmm_xmm_xmmm128,
EVEX_Vaesenclast_ymm_ymm_ymmm256,
EVEX_Vaesenclast_zmm_zmm_zmmm512,
Aesdec_xmm_xmmm128,
VEX_Vaesdec_xmm_xmm_xmmm128,
VEX_Vaesdec_ymm_ymm_ymmm256,
EVEX_Vaesdec_xmm_xmm_xmmm128,
EVEX_Vaesdec_ymm_ymm_ymmm256,
EVEX_Vaesdec_zmm_zmm_zmmm512,
Aesdeclast_xmm_xmmm128,
VEX_Vaesdeclast_xmm_xmm_xmmm128,
VEX_Vaesdeclast_ymm_ymm_ymmm256,
EVEX_Vaesdeclast_xmm_xmm_xmmm128,
EVEX_Vaesdeclast_ymm_ymm_ymmm256,
EVEX_Vaesdeclast_zmm_zmm_zmmm512,
Movbe_r16_m16,
Movbe_r32_m32,
Movbe_r64_m64,
Crc32_r32_rm8,
Crc32_r64_rm8,
Movbe_m16_r16,
Movbe_m32_r32,
Movbe_m64_r64,
Crc32_r32_rm16,
Crc32_r32_rm32,
Crc32_r64_rm64,
VEX_Andn_r32_r32_rm32,
VEX_Andn_r64_r64_rm64,
VEX_Blsr_r32_rm32,
VEX_Blsr_r64_rm64,
VEX_Blsmsk_r32_rm32,
VEX_Blsmsk_r64_rm64,
VEX_Blsi_r32_rm32,
VEX_Blsi_r64_rm64,
VEX_Bzhi_r32_rm32_r32,
VEX_Bzhi_r64_rm64_r64,
Wrussd_m32_r32,
Wrussq_m64_r64,
VEX_Pext_r32_r32_rm32,
VEX_Pext_r64_r64_rm64,
VEX_Pdep_r32_r32_rm32,
VEX_Pdep_r64_r64_rm64,
Wrssd_m32_r32,
Wrssq_m64_r64,
Adcx_r32_rm32,
Adcx_r64_rm64,
Adox_r32_rm32,
Adox_r64_rm64,
VEX_Mulx_r32_r32_rm32,
VEX_Mulx_r64_r64_rm64,
VEX_Bextr_r32_rm32_r32,
VEX_Bextr_r64_rm64_r64,
VEX_Shlx_r32_rm32_r32,
VEX_Shlx_r64_rm64_r64,
VEX_Sarx_r32_rm32_r32,
VEX_Sarx_r64_rm64_r64,
VEX_Shrx_r32_rm32_r32,
VEX_Shrx_r64_rm64_r64,
Movdir64b_r16_m512,
Movdir64b_r32_m512,
Movdir64b_r64_m512,
Enqcmds_r16_m512,
Enqcmds_r32_m512,
Enqcmds_r64_m512,
Enqcmd_r16_m512,
Enqcmd_r32_m512,
Enqcmd_r64_m512,
Movdiri_m32_r32,
Movdiri_m64_r64,
VEX_Vpermq_ymm_ymmm256_imm8,
EVEX_Vpermq_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpermq_zmm_k1z_zmmm512b64_imm8,
VEX_Vpermpd_ymm_ymmm256_imm8,
EVEX_Vpermpd_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpermpd_zmm_k1z_zmmm512b64_imm8,
VEX_Vpblendd_xmm_xmm_xmmm128_imm8,
VEX_Vpblendd_ymm_ymm_ymmm256_imm8,
EVEX_Valignd_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Valignd_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Valignd_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Valignq_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Valignq_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Valignq_zmm_k1z_zmm_zmmm512b64_imm8,
VEX_Vpermilps_xmm_xmmm128_imm8,
VEX_Vpermilps_ymm_ymmm256_imm8,
EVEX_Vpermilps_xmm_k1z_xmmm128b32_imm8,
EVEX_Vpermilps_ymm_k1z_ymmm256b32_imm8,
EVEX_Vpermilps_zmm_k1z_zmmm512b32_imm8,
VEX_Vpermilpd_xmm_xmmm128_imm8,
VEX_Vpermilpd_ymm_ymmm256_imm8,
EVEX_Vpermilpd_xmm_k1z_xmmm128b64_imm8,
EVEX_Vpermilpd_ymm_k1z_ymmm256b64_imm8,
EVEX_Vpermilpd_zmm_k1z_zmmm512b64_imm8,
VEX_Vperm2f128_ymm_ymm_ymmm256_imm8,
Roundps_xmm_xmmm128_imm8,
VEX_Vroundps_xmm_xmmm128_imm8,
VEX_Vroundps_ymm_ymmm256_imm8,
EVEX_Vrndscaleps_xmm_k1z_xmmm128b32_imm8,
EVEX_Vrndscaleps_ymm_k1z_ymmm256b32_imm8,
EVEX_Vrndscaleps_zmm_k1z_zmmm512b32_imm8_sae,
Roundpd_xmm_xmmm128_imm8,
VEX_Vroundpd_xmm_xmmm128_imm8,
VEX_Vroundpd_ymm_ymmm256_imm8,
EVEX_Vrndscalepd_xmm_k1z_xmmm128b64_imm8,
EVEX_Vrndscalepd_ymm_k1z_ymmm256b64_imm8,
EVEX_Vrndscalepd_zmm_k1z_zmmm512b64_imm8_sae,
Roundss_xmm_xmmm32_imm8,
VEX_Vroundss_xmm_xmm_xmmm32_imm8,
EVEX_Vrndscaless_xmm_k1z_xmm_xmmm32_imm8_sae,
Roundsd_xmm_xmmm64_imm8,
VEX_Vroundsd_xmm_xmm_xmmm64_imm8,
EVEX_Vrndscalesd_xmm_k1z_xmm_xmmm64_imm8_sae,
Blendps_xmm_xmmm128_imm8,
VEX_Vblendps_xmm_xmm_xmmm128_imm8,
VEX_Vblendps_ymm_ymm_ymmm256_imm8,
Blendpd_xmm_xmmm128_imm8,
VEX_Vblendpd_xmm_xmm_xmmm128_imm8,
VEX_Vblendpd_ymm_ymm_ymmm256_imm8,
Pblendw_xmm_xmmm128_imm8,
VEX_Vpblendw_xmm_xmm_xmmm128_imm8,
VEX_Vpblendw_ymm_ymm_ymmm256_imm8,
Palignr_mm_mmm64_imm8,
Palignr_xmm_xmmm128_imm8,
VEX_Vpalignr_xmm_xmm_xmmm128_imm8,
VEX_Vpalignr_ymm_ymm_ymmm256_imm8,
EVEX_Vpalignr_xmm_k1z_xmm_xmmm128_imm8,
EVEX_Vpalignr_ymm_k1z_ymm_ymmm256_imm8,
EVEX_Vpalignr_zmm_k1z_zmm_zmmm512_imm8,
Pextrb_r32m8_xmm_imm8,
Pextrb_r64m8_xmm_imm8,
VEX_Vpextrb_r32m8_xmm_imm8,
VEX_Vpextrb_r64m8_xmm_imm8,
EVEX_Vpextrb_r32m8_xmm_imm8,
EVEX_Vpextrb_r64m8_xmm_imm8,
Pextrw_r32m16_xmm_imm8,
Pextrw_r64m16_xmm_imm8,
VEX_Vpextrw_r32m16_xmm_imm8,
VEX_Vpextrw_r64m16_xmm_imm8,
EVEX_Vpextrw_r32m16_xmm_imm8,
EVEX_Vpextrw_r64m16_xmm_imm8,
Pextrd_rm32_xmm_imm8,
Pextrq_rm64_xmm_imm8,
VEX_Vpextrd_rm32_xmm_imm8,
VEX_Vpextrq_rm64_xmm_imm8,
EVEX_Vpextrd_rm32_xmm_imm8,
EVEX_Vpextrq_rm64_xmm_imm8,
Extractps_rm32_xmm_imm8,
Extractps_r64m32_xmm_imm8,
VEX_Vextractps_rm32_xmm_imm8,
VEX_Vextractps_r64m32_xmm_imm8,
EVEX_Vextractps_rm32_xmm_imm8,
EVEX_Vextractps_r64m32_xmm_imm8,
VEX_Vinsertf128_ymm_ymm_xmmm128_imm8,
EVEX_Vinsertf32x4_ymm_k1z_ymm_xmmm128_imm8,
EVEX_Vinsertf32x4_zmm_k1z_zmm_xmmm128_imm8,
EVEX_Vinsertf64x2_ymm_k1z_ymm_xmmm128_imm8,
EVEX_Vinsertf64x2_zmm_k1z_zmm_xmmm128_imm8,
VEX_Vextractf128_xmmm128_ymm_imm8,
EVEX_Vextractf32x4_xmmm128_k1z_ymm_imm8,
EVEX_Vextractf32x4_xmmm128_k1z_zmm_imm8,
EVEX_Vextractf64x2_xmmm128_k1z_ymm_imm8,
EVEX_Vextractf64x2_xmmm128_k1z_zmm_imm8,
EVEX_Vinsertf32x8_zmm_k1z_zmm_ymmm256_imm8,
EVEX_Vinsertf64x4_zmm_k1z_zmm_ymmm256_imm8,
EVEX_Vextractf32x8_ymmm256_k1z_zmm_imm8,
EVEX_Vextractf64x4_ymmm256_k1z_zmm_imm8,
VEX_Vcvtps2ph_xmmm64_xmm_imm8,
VEX_Vcvtps2ph_xmmm128_ymm_imm8,
EVEX_Vcvtps2ph_xmmm64_k1z_xmm_imm8,
EVEX_Vcvtps2ph_xmmm128_k1z_ymm_imm8,
EVEX_Vcvtps2ph_ymmm256_k1z_zmm_imm8_sae,
EVEX_Vpcmpud_kr_k1_xmm_xmmm128b32_imm8,
EVEX_Vpcmpud_kr_k1_ymm_ymmm256b32_imm8,
EVEX_Vpcmpud_kr_k1_zmm_zmmm512b32_imm8,
EVEX_Vpcmpuq_kr_k1_xmm_xmmm128b64_imm8,
EVEX_Vpcmpuq_kr_k1_ymm_ymmm256b64_imm8,
EVEX_Vpcmpuq_kr_k1_zmm_zmmm512b64_imm8,
EVEX_Vpcmpd_kr_k1_xmm_xmmm128b32_imm8,
EVEX_Vpcmpd_kr_k1_ymm_ymmm256b32_imm8,
EVEX_Vpcmpd_kr_k1_zmm_zmmm512b32_imm8,
EVEX_Vpcmpq_kr_k1_xmm_xmmm128b64_imm8,
EVEX_Vpcmpq_kr_k1_ymm_ymmm256b64_imm8,
EVEX_Vpcmpq_kr_k1_zmm_zmmm512b64_imm8,
Pinsrb_xmm_r32m8_imm8,
Pinsrb_xmm_r64m8_imm8,
VEX_Vpinsrb_xmm_xmm_r32m8_imm8,
VEX_Vpinsrb_xmm_xmm_r64m8_imm8,
EVEX_Vpinsrb_xmm_xmm_r32m8_imm8,
EVEX_Vpinsrb_xmm_xmm_r64m8_imm8,
Insertps_xmm_xmmm32_imm8,
VEX_Vinsertps_xmm_xmm_xmmm32_imm8,
EVEX_Vinsertps_xmm_xmm_xmmm32_imm8,
Pinsrd_xmm_rm32_imm8,
Pinsrq_xmm_rm64_imm8,
VEX_Vpinsrd_xmm_xmm_rm32_imm8,
VEX_Vpinsrq_xmm_xmm_rm64_imm8,
EVEX_Vpinsrd_xmm_xmm_rm32_imm8,
EVEX_Vpinsrq_xmm_xmm_rm64_imm8,
EVEX_Vshuff32x4_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vshuff32x4_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Vshuff64x2_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vshuff64x2_zmm_k1z_zmm_zmmm512b64_imm8,
EVEX_Vpternlogd_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vpternlogd_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vpternlogd_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Vpternlogq_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vpternlogq_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vpternlogq_zmm_k1z_zmm_zmmm512b64_imm8,
EVEX_Vgetmantps_xmm_k1z_xmmm128b32_imm8,
EVEX_Vgetmantps_ymm_k1z_ymmm256b32_imm8,
EVEX_Vgetmantps_zmm_k1z_zmmm512b32_imm8_sae,
EVEX_Vgetmantpd_xmm_k1z_xmmm128b64_imm8,
EVEX_Vgetmantpd_ymm_k1z_ymmm256b64_imm8,
EVEX_Vgetmantpd_zmm_k1z_zmmm512b64_imm8_sae,
EVEX_Vgetmantss_xmm_k1z_xmm_xmmm32_imm8_sae,
EVEX_Vgetmantsd_xmm_k1z_xmm_xmmm64_imm8_sae,
VEX_Kshiftrb_kr_kr_imm8,
VEX_Kshiftrw_kr_kr_imm8,
VEX_Kshiftrd_kr_kr_imm8,
VEX_Kshiftrq_kr_kr_imm8,
VEX_Kshiftlb_kr_kr_imm8,
VEX_Kshiftlw_kr_kr_imm8,
VEX_Kshiftld_kr_kr_imm8,
VEX_Kshiftlq_kr_kr_imm8,
VEX_Vinserti128_ymm_ymm_xmmm128_imm8,
EVEX_Vinserti32x4_ymm_k1z_ymm_xmmm128_imm8,
EVEX_Vinserti32x4_zmm_k1z_zmm_xmmm128_imm8,
EVEX_Vinserti64x2_ymm_k1z_ymm_xmmm128_imm8,
EVEX_Vinserti64x2_zmm_k1z_zmm_xmmm128_imm8,
VEX_Vextracti128_xmmm128_ymm_imm8,
EVEX_Vextracti32x4_xmmm128_k1z_ymm_imm8,
EVEX_Vextracti32x4_xmmm128_k1z_zmm_imm8,
EVEX_Vextracti64x2_xmmm128_k1z_ymm_imm8,
EVEX_Vextracti64x2_xmmm128_k1z_zmm_imm8,
EVEX_Vinserti32x8_zmm_k1z_zmm_ymmm256_imm8,
EVEX_Vinserti64x4_zmm_k1z_zmm_ymmm256_imm8,
EVEX_Vextracti32x8_ymmm256_k1z_zmm_imm8,
EVEX_Vextracti64x4_ymmm256_k1z_zmm_imm8,
EVEX_Vpcmpub_kr_k1_xmm_xmmm128_imm8,
EVEX_Vpcmpub_kr_k1_ymm_ymmm256_imm8,
EVEX_Vpcmpub_kr_k1_zmm_zmmm512_imm8,
EVEX_Vpcmpuw_kr_k1_xmm_xmmm128_imm8,
EVEX_Vpcmpuw_kr_k1_ymm_ymmm256_imm8,
EVEX_Vpcmpuw_kr_k1_zmm_zmmm512_imm8,
EVEX_Vpcmpb_kr_k1_xmm_xmmm128_imm8,
EVEX_Vpcmpb_kr_k1_ymm_ymmm256_imm8,
EVEX_Vpcmpb_kr_k1_zmm_zmmm512_imm8,
EVEX_Vpcmpw_kr_k1_xmm_xmmm128_imm8,
EVEX_Vpcmpw_kr_k1_ymm_ymmm256_imm8,
EVEX_Vpcmpw_kr_k1_zmm_zmmm512_imm8,
Dpps_xmm_xmmm128_imm8,
VEX_Vdpps_xmm_xmm_xmmm128_imm8,
VEX_Vdpps_ymm_ymm_ymmm256_imm8,
Dppd_xmm_xmmm128_imm8,
VEX_Vdppd_xmm_xmm_xmmm128_imm8,
Mpsadbw_xmm_xmmm128_imm8,
VEX_Vmpsadbw_xmm_xmm_xmmm128_imm8,
VEX_Vmpsadbw_ymm_ymm_ymmm256_imm8,
EVEX_Vdbpsadbw_xmm_k1z_xmm_xmmm128_imm8,
EVEX_Vdbpsadbw_ymm_k1z_ymm_ymmm256_imm8,
EVEX_Vdbpsadbw_zmm_k1z_zmm_zmmm512_imm8,
EVEX_Vshufi32x4_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vshufi32x4_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Vshufi64x2_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vshufi64x2_zmm_k1z_zmm_zmmm512b64_imm8,
Pclmulqdq_xmm_xmmm128_imm8,
VEX_Vpclmulqdq_xmm_xmm_xmmm128_imm8,
VEX_Vpclmulqdq_ymm_ymm_ymmm256_imm8,
EVEX_Vpclmulqdq_xmm_xmm_xmmm128_imm8,
EVEX_Vpclmulqdq_ymm_ymm_ymmm256_imm8,
EVEX_Vpclmulqdq_zmm_zmm_zmmm512_imm8,
VEX_Vperm2i128_ymm_ymm_ymmm256_imm8,
VEX_Vpermil2ps_xmm_xmm_xmmm128_xmm_imm4,
VEX_Vpermil2ps_ymm_ymm_ymmm256_ymm_imm4,
VEX_Vpermil2ps_xmm_xmm_xmm_xmmm128_imm4,
VEX_Vpermil2ps_ymm_ymm_ymm_ymmm256_imm4,
VEX_Vpermil2pd_xmm_xmm_xmmm128_xmm_imm4,
VEX_Vpermil2pd_ymm_ymm_ymmm256_ymm_imm4,
VEX_Vpermil2pd_xmm_xmm_xmm_xmmm128_imm4,
VEX_Vpermil2pd_ymm_ymm_ymm_ymmm256_imm4,
VEX_Vblendvps_xmm_xmm_xmmm128_xmm,
VEX_Vblendvps_ymm_ymm_ymmm256_ymm,
VEX_Vblendvpd_xmm_xmm_xmmm128_xmm,
VEX_Vblendvpd_ymm_ymm_ymmm256_ymm,
VEX_Vpblendvb_xmm_xmm_xmmm128_xmm,
VEX_Vpblendvb_ymm_ymm_ymmm256_ymm,
EVEX_Vrangeps_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vrangeps_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vrangeps_zmm_k1z_zmm_zmmm512b32_imm8_sae,
EVEX_Vrangepd_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vrangepd_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vrangepd_zmm_k1z_zmm_zmmm512b64_imm8_sae,
EVEX_Vrangess_xmm_k1z_xmm_xmmm32_imm8_sae,
EVEX_Vrangesd_xmm_k1z_xmm_xmmm64_imm8_sae,
EVEX_Vfixupimmps_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vfixupimmps_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vfixupimmps_zmm_k1z_zmm_zmmm512b32_imm8_sae,
EVEX_Vfixupimmpd_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vfixupimmpd_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vfixupimmpd_zmm_k1z_zmm_zmmm512b64_imm8_sae,
EVEX_Vfixupimmss_xmm_k1z_xmm_xmmm32_imm8_sae,
EVEX_Vfixupimmsd_xmm_k1z_xmm_xmmm64_imm8_sae,
EVEX_Vreduceps_xmm_k1z_xmmm128b32_imm8,
EVEX_Vreduceps_ymm_k1z_ymmm256b32_imm8,
EVEX_Vreduceps_zmm_k1z_zmmm512b32_imm8_sae,
EVEX_Vreducepd_xmm_k1z_xmmm128b64_imm8,
EVEX_Vreducepd_ymm_k1z_ymmm256b64_imm8,
EVEX_Vreducepd_zmm_k1z_zmmm512b64_imm8_sae,
EVEX_Vreducess_xmm_k1z_xmm_xmmm32_imm8_sae,
EVEX_Vreducesd_xmm_k1z_xmm_xmmm64_imm8_sae,
VEX_Vfmaddsubps_xmm_xmm_xmmm128_xmm,
VEX_Vfmaddsubps_ymm_ymm_ymmm256_ymm,
VEX_Vfmaddsubps_xmm_xmm_xmm_xmmm128,
VEX_Vfmaddsubps_ymm_ymm_ymm_ymmm256,
VEX_Vfmaddsubpd_xmm_xmm_xmmm128_xmm,
VEX_Vfmaddsubpd_ymm_ymm_ymmm256_ymm,
VEX_Vfmaddsubpd_xmm_xmm_xmm_xmmm128,
VEX_Vfmaddsubpd_ymm_ymm_ymm_ymmm256,
VEX_Vfmsubaddps_xmm_xmm_xmmm128_xmm,
VEX_Vfmsubaddps_ymm_ymm_ymmm256_ymm,
VEX_Vfmsubaddps_xmm_xmm_xmm_xmmm128,
VEX_Vfmsubaddps_ymm_ymm_ymm_ymmm256,
VEX_Vfmsubaddpd_xmm_xmm_xmmm128_xmm,
VEX_Vfmsubaddpd_ymm_ymm_ymmm256_ymm,
VEX_Vfmsubaddpd_xmm_xmm_xmm_xmmm128,
VEX_Vfmsubaddpd_ymm_ymm_ymm_ymmm256,
Pcmpestrm_xmm_xmmm128_imm8,
Pcmpestrm64_xmm_xmmm128_imm8,
VEX_Vpcmpestrm_xmm_xmmm128_imm8,
VEX_Vpcmpestrm64_xmm_xmmm128_imm8,
Pcmpestri_xmm_xmmm128_imm8,
Pcmpestri64_xmm_xmmm128_imm8,
VEX_Vpcmpestri_xmm_xmmm128_imm8,
VEX_Vpcmpestri64_xmm_xmmm128_imm8,
Pcmpistrm_xmm_xmmm128_imm8,
VEX_Vpcmpistrm_xmm_xmmm128_imm8,
Pcmpistri_xmm_xmmm128_imm8,
VEX_Vpcmpistri_xmm_xmmm128_imm8,
EVEX_Vfpclassps_kr_k1_xmmm128b32_imm8,
EVEX_Vfpclassps_kr_k1_ymmm256b32_imm8,
EVEX_Vfpclassps_kr_k1_zmmm512b32_imm8,
EVEX_Vfpclasspd_kr_k1_xmmm128b64_imm8,
EVEX_Vfpclasspd_kr_k1_ymmm256b64_imm8,
EVEX_Vfpclasspd_kr_k1_zmmm512b64_imm8,
EVEX_Vfpclassss_kr_k1_xmmm32_imm8,
EVEX_Vfpclasssd_kr_k1_xmmm64_imm8,
VEX_Vfmaddps_xmm_xmm_xmmm128_xmm,
VEX_Vfmaddps_ymm_ymm_ymmm256_ymm,
VEX_Vfmaddps_xmm_xmm_xmm_xmmm128,
VEX_Vfmaddps_ymm_ymm_ymm_ymmm256,
VEX_Vfmaddpd_xmm_xmm_xmmm128_xmm,
VEX_Vfmaddpd_ymm_ymm_ymmm256_ymm,
VEX_Vfmaddpd_xmm_xmm_xmm_xmmm128,
VEX_Vfmaddpd_ymm_ymm_ymm_ymmm256,
VEX_Vfmaddss_xmm_xmm_xmmm32_xmm,
VEX_Vfmaddss_xmm_xmm_xmm_xmmm32,
VEX_Vfmaddsd_xmm_xmm_xmmm64_xmm,
VEX_Vfmaddsd_xmm_xmm_xmm_xmmm64,
VEX_Vfmsubps_xmm_xmm_xmmm128_xmm,
VEX_Vfmsubps_ymm_ymm_ymmm256_ymm,
VEX_Vfmsubps_xmm_xmm_xmm_xmmm128,
VEX_Vfmsubps_ymm_ymm_ymm_ymmm256,
VEX_Vfmsubpd_xmm_xmm_xmmm128_xmm,
VEX_Vfmsubpd_ymm_ymm_ymmm256_ymm,
VEX_Vfmsubpd_xmm_xmm_xmm_xmmm128,
VEX_Vfmsubpd_ymm_ymm_ymm_ymmm256,
VEX_Vfmsubss_xmm_xmm_xmmm32_xmm,
VEX_Vfmsubss_xmm_xmm_xmm_xmmm32,
VEX_Vfmsubsd_xmm_xmm_xmmm64_xmm,
VEX_Vfmsubsd_xmm_xmm_xmm_xmmm64,
EVEX_Vpshldw_xmm_k1z_xmm_xmmm128_imm8,
EVEX_Vpshldw_ymm_k1z_ymm_ymmm256_imm8,
EVEX_Vpshldw_zmm_k1z_zmm_zmmm512_imm8,
EVEX_Vpshldd_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vpshldd_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vpshldd_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Vpshldq_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vpshldq_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vpshldq_zmm_k1z_zmm_zmmm512b64_imm8,
EVEX_Vpshrdw_xmm_k1z_xmm_xmmm128_imm8,
EVEX_Vpshrdw_ymm_k1z_ymm_ymmm256_imm8,
EVEX_Vpshrdw_zmm_k1z_zmm_zmmm512_imm8,
EVEX_Vpshrdd_xmm_k1z_xmm_xmmm128b32_imm8,
EVEX_Vpshrdd_ymm_k1z_ymm_ymmm256b32_imm8,
EVEX_Vpshrdd_zmm_k1z_zmm_zmmm512b32_imm8,
EVEX_Vpshrdq_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vpshrdq_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vpshrdq_zmm_k1z_zmm_zmmm512b64_imm8,
VEX_Vfnmaddps_xmm_xmm_xmmm128_xmm,
VEX_Vfnmaddps_ymm_ymm_ymmm256_ymm,
VEX_Vfnmaddps_xmm_xmm_xmm_xmmm128,
VEX_Vfnmaddps_ymm_ymm_ymm_ymmm256,
VEX_Vfnmaddpd_xmm_xmm_xmmm128_xmm,
VEX_Vfnmaddpd_ymm_ymm_ymmm256_ymm,
VEX_Vfnmaddpd_xmm_xmm_xmm_xmmm128,
VEX_Vfnmaddpd_ymm_ymm_ymm_ymmm256,
VEX_Vfnmaddss_xmm_xmm_xmmm32_xmm,
VEX_Vfnmaddss_xmm_xmm_xmm_xmmm32,
VEX_Vfnmaddsd_xmm_xmm_xmmm64_xmm,
VEX_Vfnmaddsd_xmm_xmm_xmm_xmmm64,
VEX_Vfnmsubps_xmm_xmm_xmmm128_xmm,
VEX_Vfnmsubps_ymm_ymm_ymmm256_ymm,
VEX_Vfnmsubps_xmm_xmm_xmm_xmmm128,
VEX_Vfnmsubps_ymm_ymm_ymm_ymmm256,
VEX_Vfnmsubpd_xmm_xmm_xmmm128_xmm,
VEX_Vfnmsubpd_ymm_ymm_ymmm256_ymm,
VEX_Vfnmsubpd_xmm_xmm_xmm_xmmm128,
VEX_Vfnmsubpd_ymm_ymm_ymm_ymmm256,
VEX_Vfnmsubss_xmm_xmm_xmmm32_xmm,
VEX_Vfnmsubss_xmm_xmm_xmm_xmmm32,
VEX_Vfnmsubsd_xmm_xmm_xmmm64_xmm,
VEX_Vfnmsubsd_xmm_xmm_xmm_xmmm64,
Sha1rnds4_xmm_xmmm128_imm8,
Gf2p8affineqb_xmm_xmmm128_imm8,
VEX_Vgf2p8affineqb_xmm_xmm_xmmm128_imm8,
VEX_Vgf2p8affineqb_ymm_ymm_ymmm256_imm8,
EVEX_Vgf2p8affineqb_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vgf2p8affineqb_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vgf2p8affineqb_zmm_k1z_zmm_zmmm512b64_imm8,
Gf2p8affineinvqb_xmm_xmmm128_imm8,
VEX_Vgf2p8affineinvqb_xmm_xmm_xmmm128_imm8,
VEX_Vgf2p8affineinvqb_ymm_ymm_ymmm256_imm8,
EVEX_Vgf2p8affineinvqb_xmm_k1z_xmm_xmmm128b64_imm8,
EVEX_Vgf2p8affineinvqb_ymm_k1z_ymm_ymmm256b64_imm8,
EVEX_Vgf2p8affineinvqb_zmm_k1z_zmm_zmmm512b64_imm8,
Aeskeygenassist_xmm_xmmm128_imm8,
VEX_Vaeskeygenassist_xmm_xmmm128_imm8,
VEX_Rorx_r32_rm32_imm8,
VEX_Rorx_r64_rm64_imm8,
XOP_Vpmacssww_xmm_xmm_xmmm128_xmm,
XOP_Vpmacsswd_xmm_xmm_xmmm128_xmm,
XOP_Vpmacssdql_xmm_xmm_xmmm128_xmm,
XOP_Vpmacssdd_xmm_xmm_xmmm128_xmm,
XOP_Vpmacssdqh_xmm_xmm_xmmm128_xmm,
XOP_Vpmacsww_xmm_xmm_xmmm128_xmm,
XOP_Vpmacswd_xmm_xmm_xmmm128_xmm,
XOP_Vpmacsdql_xmm_xmm_xmmm128_xmm,
XOP_Vpmacsdd_xmm_xmm_xmmm128_xmm,
XOP_Vpmacsdqh_xmm_xmm_xmmm128_xmm,
XOP_Vpcmov_xmm_xmm_xmmm128_xmm,
XOP_Vpcmov_ymm_ymm_ymmm256_ymm,
XOP_Vpcmov_xmm_xmm_xmm_xmmm128,
XOP_Vpcmov_ymm_ymm_ymm_ymmm256,
XOP_Vpperm_xmm_xmm_xmmm128_xmm,
XOP_Vpperm_xmm_xmm_xmm_xmmm128,
XOP_Vpmadcsswd_xmm_xmm_xmmm128_xmm,
XOP_Vpmadcswd_xmm_xmm_xmmm128_xmm,
XOP_Vprotb_xmm_xmmm128_imm8,
XOP_Vprotw_xmm_xmmm128_imm8,
XOP_Vprotd_xmm_xmmm128_imm8,
XOP_Vprotq_xmm_xmmm128_imm8,
XOP_Vpcomb_xmm_xmm_xmmm128_imm8,
XOP_Vpcomw_xmm_xmm_xmmm128_imm8,
XOP_Vpcomd_xmm_xmm_xmmm128_imm8,
XOP_Vpcomq_xmm_xmm_xmmm128_imm8,
XOP_Vpcomub_xmm_xmm_xmmm128_imm8,
XOP_Vpcomuw_xmm_xmm_xmmm128_imm8,
XOP_Vpcomud_xmm_xmm_xmmm128_imm8,
XOP_Vpcomuq_xmm_xmm_xmmm128_imm8,
XOP_Blcfill_r32_rm32,
XOP_Blcfill_r64_rm64,
XOP_Blsfill_r32_rm32,
XOP_Blsfill_r64_rm64,
XOP_Blcs_r32_rm32,
XOP_Blcs_r64_rm64,
XOP_Tzmsk_r32_rm32,
XOP_Tzmsk_r64_rm64,
XOP_Blcic_r32_rm32,
XOP_Blcic_r64_rm64,
XOP_Blsic_r32_rm32,
XOP_Blsic_r64_rm64,
XOP_T1mskc_r32_rm32,
XOP_T1mskc_r64_rm64,
XOP_Blcmsk_r32_rm32,
XOP_Blcmsk_r64_rm64,
XOP_Blci_r32_rm32,
XOP_Blci_r64_rm64,
XOP_Llwpcb_r32,
XOP_Llwpcb_r64,
XOP_Slwpcb_r32,
XOP_Slwpcb_r64,
XOP_Vfrczps_xmm_xmmm128,
XOP_Vfrczps_ymm_ymmm256,
XOP_Vfrczpd_xmm_xmmm128,
XOP_Vfrczpd_ymm_ymmm256,
XOP_Vfrczss_xmm_xmmm32,
XOP_Vfrczsd_xmm_xmmm64,
XOP_Vprotb_xmm_xmmm128_xmm,
XOP_Vprotb_xmm_xmm_xmmm128,
XOP_Vprotw_xmm_xmmm128_xmm,
XOP_Vprotw_xmm_xmm_xmmm128,
XOP_Vprotd_xmm_xmmm128_xmm,
XOP_Vprotd_xmm_xmm_xmmm128,
XOP_Vprotq_xmm_xmmm128_xmm,
XOP_Vprotq_xmm_xmm_xmmm128,
XOP_Vpshlb_xmm_xmmm128_xmm,
XOP_Vpshlb_xmm_xmm_xmmm128,
XOP_Vpshlw_xmm_xmmm128_xmm,
XOP_Vpshlw_xmm_xmm_xmmm128,
XOP_Vpshld_xmm_xmmm128_xmm,
XOP_Vpshld_xmm_xmm_xmmm128,
XOP_Vpshlq_xmm_xmmm128_xmm,
XOP_Vpshlq_xmm_xmm_xmmm128,
XOP_Vpshab_xmm_xmmm128_xmm,
XOP_Vpshab_xmm_xmm_xmmm128,
XOP_Vpshaw_xmm_xmmm128_xmm,
XOP_Vpshaw_xmm_xmm_xmmm128,
XOP_Vpshad_xmm_xmmm128_xmm,
XOP_Vpshad_xmm_xmm_xmmm128,
XOP_Vpshaq_xmm_xmmm128_xmm,
XOP_Vpshaq_xmm_xmm_xmmm128,
XOP_Vphaddbw_xmm_xmmm128,
XOP_Vphaddbd_xmm_xmmm128,
XOP_Vphaddbq_xmm_xmmm128,
XOP_Vphaddwd_xmm_xmmm128,
XOP_Vphaddwq_xmm_xmmm128,
XOP_Vphadddq_xmm_xmmm128,
XOP_Vphaddubw_xmm_xmmm128,
XOP_Vphaddubd_xmm_xmmm128,
XOP_Vphaddubq_xmm_xmmm128,
XOP_Vphadduwd_xmm_xmmm128,
XOP_Vphadduwq_xmm_xmmm128,
XOP_Vphaddudq_xmm_xmmm128,
XOP_Vphsubbw_xmm_xmmm128,
XOP_Vphsubwd_xmm_xmmm128,
XOP_Vphsubdq_xmm_xmmm128,
XOP_Bextr_r32_rm32_imm32,
XOP_Bextr_r64_rm64_imm32,
XOP_Lwpins_r32_rm32_imm32,
XOP_Lwpins_r64_rm32_imm32,
XOP_Lwpval_r32_rm32_imm32,
XOP_Lwpval_r64_rm32_imm32,
D3NOW_Pi2fw_mm_mmm64,
D3NOW_Pi2fd_mm_mmm64,
D3NOW_Pf2iw_mm_mmm64,
D3NOW_Pf2id_mm_mmm64,
D3NOW_Pfrcpv_mm_mmm64,
D3NOW_Pfrsqrtv_mm_mmm64,
D3NOW_Pfnacc_mm_mmm64,
D3NOW_Pfpnacc_mm_mmm64,
D3NOW_Pfcmpge_mm_mmm64,
D3NOW_Pfmin_mm_mmm64,
D3NOW_Pfrcp_mm_mmm64,
D3NOW_Pfrsqrt_mm_mmm64,
D3NOW_Pfsub_mm_mmm64,
D3NOW_Pfadd_mm_mmm64,
D3NOW_Pfcmpgt_mm_mmm64,
D3NOW_Pfmax_mm_mmm64,
D3NOW_Pfrcpit1_mm_mmm64,
D3NOW_Pfrsqit1_mm_mmm64,
D3NOW_Pfsubr_mm_mmm64,
D3NOW_Pfacc_mm_mmm64,
D3NOW_Pfcmpeq_mm_mmm64,
D3NOW_Pfmul_mm_mmm64,
D3NOW_Pfrcpit2_mm_mmm64,
D3NOW_Pmulhrw_mm_mmm64,
D3NOW_Pswapd_mm_mmm64,
D3NOW_Pavgusb_mm_mmm64,
Rmpadjust,
Rmpupdate,
Psmash,
Pvalidatew,
Pvalidated,
Pvalidateq,
Serialize,
Xsusldtrk,
Xresldtrk,
Invlpgbw,
Invlpgbd,
Invlpgbq,
Tlbsync,
Prefetchreserved3_m8,
Prefetchreserved4_m8,
Prefetchreserved5_m8,
Prefetchreserved6_m8,
Prefetchreserved7_m8,
Ud0,
Vmgexit,
Getsecq,
VEX_Ldtilecfg_m512,
VEX_Tilerelease,
VEX_Sttilecfg_m512,
VEX_Tilezero_tmm,
VEX_Tileloaddt1_tmm_sibmem,
VEX_Tilestored_sibmem_tmm,
VEX_Tileloadd_tmm_sibmem,
VEX_Tdpbf16ps_tmm_tmm_tmm,
VEX_Tdpbuud_tmm_tmm_tmm,
VEX_Tdpbusd_tmm_tmm_tmm,
VEX_Tdpbsud_tmm_tmm_tmm,
VEX_Tdpbssd_tmm_tmm_tmm,
Fnstdw_AX,
Fnstsg_AX,
Rdshr_rm32,
Wrshr_rm32,
Smint,
Dmint,
Rdm,
Svdc_m80_Sreg,
Rsdc_Sreg_m80,
Svldt_m80,
Rsldt_m80,
Svts_m80,
Rsts_m80,
Smint_0F7E,
Bb0_reset,
Bb1_reset,
Cpu_write,
Cpu_read,
Altinst,
Paveb_mm_mmm64,
Paddsiw_mm_mmm64,
Pmagw_mm_mmm64,
Pdistib_mm_m64,
Psubsiw_mm_mmm64,
Pmvzb_mm_m64,
Pmulhrw_mm_mmm64,
Pmvnzb_mm_m64,
Pmvlzb_mm_m64,
Pmvgezb_mm_m64,
Pmulhriw_mm_mmm64,
Pmachriw_mm_m64,
Cyrix_D9D7,
Cyrix_D9E2,
Ftstp,
Cyrix_D9E7,
Frint2,
Frichop,
Cyrix_DED8,
Cyrix_DEDA,
Cyrix_DEDC,
Cyrix_DEDD,
Cyrix_DEDE,
Frinear,
Tdcall,
Seamret,
Seamops,
Seamcall,
Aesencwide128kl_m384,
Aesdecwide128kl_m384,
Aesencwide256kl_m512,
Aesdecwide256kl_m512,
Loadiwkey_xmm_xmm,
Aesenc128kl_xmm_m384,
Aesdec128kl_xmm_m384,
Aesenc256kl_xmm_m512,
Aesdec256kl_xmm_m512,
Encodekey128_r32_r32,
Encodekey256_r32_r32,
VEX_Vbroadcastss_xmm_xmm,
VEX_Vbroadcastss_ymm_xmm,
VEX_Vbroadcastsd_ymm_xmm,
Vmgexit_F2,
Uiret,
Testui,
Clui,
Stui,
Senduipi_r64,
Hreset_imm8,
VEX_Vpdpbusd_xmm_xmm_xmmm128,
VEX_Vpdpbusd_ymm_ymm_ymmm256,
VEX_Vpdpbusds_xmm_xmm_xmmm128,
VEX_Vpdpbusds_ymm_ymm_ymmm256,
VEX_Vpdpwssd_xmm_xmm_xmmm128,
VEX_Vpdpwssd_ymm_ymm_ymmm256,
VEX_Vpdpwssds_xmm_xmm_xmmm128,
VEX_Vpdpwssds_ymm_ymm_ymmm256,
Ccs_hash_16,
Ccs_hash_32,
Ccs_hash_64,
Ccs_encrypt_16,
Ccs_encrypt_32,
Ccs_encrypt_64,
}
[TypeGen(TypeGenOrders.CreatedInstructions)]
sealed class CodeEnum {
CodeEnum(GenTypes genTypes) {
// It must have value 0
if (genTypes[TypeIds.Code][nameof(Code.INVALID)].Value != 0)
throw new InvalidOperationException();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using OpenMetaverse;
using log4net;
using Nini.Config;
using System.Reflection;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.InventoryService;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Server.Base;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// Hypergrid inventory service. It serves the IInventoryService interface,
/// but implements it in ways that are appropriate for inter-grid
/// inventory exchanges. Specifically, it does not performs deletions
/// and it responds to GetRootFolder requests with the ID of the
/// Suitcase folder, not the actual "My Inventory" folder.
/// </summary>
public class HGSuitcaseInventoryService : XInventoryService, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// private string m_HomeURL;
private IUserAccountService m_UserAccountService;
private IAvatarService m_AvatarService;
// private UserAccountCache m_Cache;
private ExpiringCache<UUID, List<XInventoryFolder>> m_SuitcaseTrees = new ExpiringCache<UUID, List<XInventoryFolder>>();
private ExpiringCache<UUID, AvatarAppearance> m_Appearances = new ExpiringCache<UUID, AvatarAppearance>();
public HGSuitcaseInventoryService(IConfigSource config, string configName)
: base(config, configName)
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Starting with config name {0}", configName);
if (configName != string.Empty)
m_ConfigName = configName;
if (m_Database == null)
m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: m_Database is null!");
//
// Try reading the [InventoryService] section, if it exists
//
IConfig invConfig = config.Configs[m_ConfigName];
if (invConfig != null)
{
string userAccountsDll = invConfig.GetString("UserAccountsService", string.Empty);
if (userAccountsDll == string.Empty)
throw new Exception("Please specify UserAccountsService in HGInventoryService configuration");
Object[] args = new Object[] { config };
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountsDll, args);
if (m_UserAccountService == null)
throw new Exception(String.Format("Unable to create UserAccountService from {0}", userAccountsDll));
string avatarDll = invConfig.GetString("AvatarService", string.Empty);
if (avatarDll == string.Empty)
throw new Exception("Please specify AvatarService in HGInventoryService configuration");
m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarDll, args);
if (m_AvatarService == null)
throw new Exception(String.Format("Unable to create m_AvatarService from {0}", avatarDll));
// m_HomeURL = Util.GetConfigVarFromSections<string>(config, "HomeURI",
// new string[] { "Startup", "Hypergrid", m_ConfigName }, String.Empty);
// m_Cache = UserAccountCache.CreateUserAccountCache(m_UserAccountService);
}
m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Starting...");
}
public override bool CreateUserInventory(UUID principalID)
{
// NOGO
return false;
}
public override List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
XInventoryFolder suitcase = GetSuitcaseXFolder(principalID);
if (suitcase == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no suitcase folder for user {0} when looking for inventory skeleton", principalID);
return null;
}
List<XInventoryFolder> tree = GetFolderTree(principalID, suitcase.folderID);
if (tree == null || (tree != null && tree.Count == 0))
return null;
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
foreach (XInventoryFolder x in tree)
{
folders.Add(ConvertToOpenSim(x));
}
SetAsNormalFolder(suitcase);
folders.Add(ConvertToOpenSim(suitcase));
return folders;
}
public override InventoryCollection GetUserInventory(UUID userID)
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Get Suitcase inventory for user {0}", userID);
InventoryCollection userInventory = new InventoryCollection();
userInventory.UserID = userID;
userInventory.Folders = new List<InventoryFolderBase>();
userInventory.Items = new List<InventoryItemBase>();
XInventoryFolder suitcase = GetSuitcaseXFolder(userID);
if (suitcase == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no suitcase folder for user {0} when looking for user inventory", userID);
return null;
}
List<XInventoryFolder> tree = GetFolderTree(userID, suitcase.folderID);
if (tree == null || (tree != null && tree.Count == 0))
{
SetAsNormalFolder(suitcase);
userInventory.Folders.Add(ConvertToOpenSim(suitcase));
return userInventory;
}
List<InventoryItemBase> items;
foreach (XInventoryFolder f in tree)
{
// Add the items of this subfolder
items = GetFolderItems(userID, f.folderID);
if (items != null && items.Count > 0)
{
userInventory.Items.AddRange(items);
}
// Add the folder itself
userInventory.Folders.Add(ConvertToOpenSim(f));
}
items = GetFolderItems(userID, suitcase.folderID);
if (items != null && items.Count > 0)
{
userInventory.Items.AddRange(items);
}
SetAsNormalFolder(suitcase);
userInventory.Folders.Add(ConvertToOpenSim(suitcase));
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: GetUserInventory for user {0} returning {1} folders and {2} items",
userID, userInventory.Folders.Count, userInventory.Items.Count);
return userInventory;
}
public override InventoryFolderBase GetRootFolder(UUID principalID)
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: GetRootFolder for {0}", principalID);
// Let's find out the local root folder
XInventoryFolder root = GetRootXFolder(principalID);
if (root == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve local root folder for user {0}", principalID);
return null;
}
// Warp! Root folder for travelers is the suitcase folder
XInventoryFolder suitcase = GetSuitcaseXFolder(principalID);
if (suitcase == null)
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder. Creating it...", principalID);
// make one, and let's add it to the user's inventory as a direct child of the root folder
// In the DB we tag it as type 100, but we use -1 (Unknown) outside
suitcase = CreateFolder(principalID, root.folderID, 100, "My Suitcase");
if (suitcase == null)
m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to create suitcase folder");
m_Database.StoreFolder(suitcase);
// Create System folders
CreateSystemFolders(principalID, suitcase.folderID);
}
SetAsNormalFolder(suitcase);
return ConvertToOpenSim(suitcase);
}
protected void CreateSystemFolders(UUID principalID, UUID rootID)
{
m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Creating System folders under Suitcase...");
XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootID);
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Animation, "Animations");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Bodypart, "Body Parts");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.CallingCard, "Calling Cards");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Clothing, "Clothing");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Gesture, "Gestures");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Landmark, "Landmarks");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.LostAndFoundFolder, "Lost And Found");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Notecard, "Notecards");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Object, "Objects");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.SnapshotFolder, "Photo Album");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.LSLText, "Scripts");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Sound, "Sounds");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.Texture, "Textures");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.TrashFolder, "Trash");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.FavoriteFolder) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.FavoriteFolder, "Favorites");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CurrentOutfitFolder) return true; return false; }))
CreateFolder(principalID, rootID, (int)AssetType.CurrentOutfitFolder, "Current Outfit");
}
public override InventoryFolderBase GetFolderForType(UUID principalID, AssetType type)
{
//m_log.DebugFormat("[HG INVENTORY SERVICE]: GetFolderForType for {0} {0}", principalID, type);
XInventoryFolder suitcase = GetSuitcaseXFolder(principalID);
if (suitcase == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no suitcase folder for user {0} when looking for child type folder {1}", principalID, type);
return null;
}
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "type", "parentFolderID" },
new string[] { principalID.ToString(), ((int)type).ToString(), suitcase.folderID.ToString() });
if (folders.Length == 0)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no folder for type {0} for user {1}", type, principalID);
return null;
}
m_log.DebugFormat(
"[HG SUITCASE INVENTORY SERVICE]: Found folder {0} {1} for type {2} for user {3}",
folders[0].folderName, folders[0].folderID, type, principalID);
return ConvertToOpenSim(folders[0]);
}
public override InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
InventoryCollection coll = null;
if (!IsWithinSuitcaseTree(principalID, folderID))
return new InventoryCollection();
coll = base.GetFolderContent(principalID, folderID);
if (coll == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Something wrong with user {0}'s suitcase folder", principalID);
coll = new InventoryCollection();
}
return coll;
}
public override List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
// Let's do a bit of sanity checking, more than the base service does
// make sure the given folder exists under the suitcase tree of this user
if (!IsWithinSuitcaseTree(principalID, folderID))
return new List<InventoryItemBase>();
return base.GetFolderItems(principalID, folderID);
}
public override bool AddFolder(InventoryFolderBase folder)
{
//m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: AddFolder {0} {1}", folder.Name, folder.ParentID);
// Let's do a bit of sanity checking, more than the base service does
// make sure the given folder's parent folder exists under the suitcase tree of this user
if (!IsWithinSuitcaseTree(folder.Owner, folder.ParentID))
return false;
// OK, it's legit
if (base.AddFolder(folder))
{
List<XInventoryFolder> tree;
if (m_SuitcaseTrees.TryGetValue(folder.Owner, out tree))
tree.Add(ConvertFromOpenSim(folder));
return true;
}
return false;
}
public override bool UpdateFolder(InventoryFolderBase folder)
{
//m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Update folder {0}, version {1}", folder.ID, folder.Version);
if (!IsWithinSuitcaseTree(folder.Owner, folder.ID))
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: folder {0} not within Suitcase tree", folder.Name);
return false;
}
// For all others
return base.UpdateFolder(folder);
}
public override bool MoveFolder(InventoryFolderBase folder)
{
if (!IsWithinSuitcaseTree(folder.Owner, folder.ID) ||
!IsWithinSuitcaseTree(folder.Owner, folder.ParentID))
return false;
return base.MoveFolder(folder);
}
public override bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
// NOGO
return false;
}
public override bool PurgeFolder(InventoryFolderBase folder)
{
// NOGO
return false;
}
public override bool AddItem(InventoryItemBase item)
{
// Let's do a bit of sanity checking, more than the base service does
// make sure the given folder's parent folder exists under the suitcase tree of this user
if (!IsWithinSuitcaseTree(item.Owner, item.Folder))
return false;
// OK, it's legit
return base.AddItem(item);
}
public override bool UpdateItem(InventoryItemBase item)
{
if (!IsWithinSuitcaseTree(item.Owner, item.Folder))
return false;
return base.UpdateItem(item);
}
public override bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
// Principal is b0rked. *sigh*
if (!IsWithinSuitcaseTree(items[0].Owner, items[0].Folder))
return false;
return base.MoveItems(principalID, items);
}
public override bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
return false;
}
public new InventoryItemBase GetItem(InventoryItemBase item)
{
InventoryItemBase it = base.GetItem(item);
if (it == null)
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve item {0} ({1}) in folder {2}",
item.Name, item.ID, item.Folder);
return null;
}
if (!IsWithinSuitcaseTree(it.Owner, it.Folder) && !IsPartOfAppearance(it.Owner, it.ID))
{
m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Item {0} (folder {1}) is not within Suitcase",
it.Name, it.Folder);
return null;
}
// UserAccount user = m_Cache.GetUser(it.CreatorId);
// // Adjust the creator data
// if (user != null && it != null && (it.CreatorData == null || it.CreatorData == string.Empty))
// it.CreatorData = m_HomeURL + ";" + user.FirstName + " " + user.LastName;
//}
return it;
}
public new InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
InventoryFolderBase f = base.GetFolder(folder);
if (f != null)
{
if (!IsWithinSuitcaseTree(f.Owner, f.ID))
return null;
}
return f;
}
//public List<InventoryItemBase> GetActiveGestures(UUID principalID)
//{
//}
//public int GetAssetPermissions(UUID principalID, UUID assetID)
//{
//}
#region Auxiliary functions
private XInventoryFolder GetXFolder(UUID userID, UUID folderID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "folderID" },
new string[] { userID.ToString(), folderID.ToString() });
if (folders.Length == 0)
return null;
return folders[0];
}
private XInventoryFolder GetRootXFolder(UUID principalID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "folderName", "type" },
new string[] { principalID.ToString(), "My Inventory", ((int)AssetType.RootFolder).ToString() });
if (folders != null && folders.Length > 0)
return folders[0];
// OK, so the RootFolder type didn't work. Let's look for any type with parent UUID.Zero.
folders = m_Database.GetFolders(
new string[] { "agentID", "folderName", "parentFolderID" },
new string[] { principalID.ToString(), "My Inventory", UUID.Zero.ToString() });
if (folders != null && folders.Length > 0)
return folders[0];
return null;
}
private XInventoryFolder GetCurrentOutfitXFolder(UUID userID)
{
XInventoryFolder root = GetRootXFolder(userID);
if (root == null)
return null;
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "type", "parentFolderID" },
new string[] { userID.ToString(), ((int)AssetType.CurrentOutfitFolder).ToString(), root.folderID.ToString() });
if (folders.Length == 0)
return null;
return folders[0];
}
private XInventoryFolder GetSuitcaseXFolder(UUID principalID)
{
// Warp! Root folder for travelers
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "type" },
new string[] { principalID.ToString(), "100" }); // This is a special folder type...
if (folders != null && folders.Length > 0)
return folders[0];
// check to see if we have the old Suitcase folder
folders = m_Database.GetFolders(
new string[] { "agentID", "folderName", "parentFolderID" },
new string[] { principalID.ToString(), "My Suitcase", UUID.Zero.ToString() });
if (folders != null && folders.Length > 0)
{
// Move it to under the root folder
XInventoryFolder root = GetRootXFolder(principalID);
folders[0].parentFolderID = root.folderID;
folders[0].type = 100;
m_Database.StoreFolder(folders[0]);
return folders[0];
}
return null;
}
private void SetAsNormalFolder(XInventoryFolder suitcase)
{
suitcase.type = (short)AssetType.Folder;
}
private List<XInventoryFolder> GetFolderTree(UUID principalID, UUID folder)
{
List<XInventoryFolder> t = null;
if (m_SuitcaseTrees.TryGetValue(principalID, out t))
return t;
// Get the tree of the suitcase folder
t = GetFolderTreeRecursive(folder);
m_SuitcaseTrees.AddOrUpdate(principalID, t, 5*60); // 5minutes
return t;
}
private List<XInventoryFolder> GetFolderTreeRecursive(UUID root)
{
List<XInventoryFolder> tree = new List<XInventoryFolder>();
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "parentFolderID" },
new string[] { root.ToString() });
if (folders == null || (folders != null && folders.Length == 0))
return tree; // empty tree
else
{
foreach (XInventoryFolder f in folders)
{
tree.Add(f);
tree.AddRange(GetFolderTreeRecursive(f.folderID));
}
return tree;
}
}
/// <summary>
/// Return true if the folderID is a subfolder of the Suitcase or the suitcase folder itself
/// </summary>
/// <param name="folderID"></param>
/// <param name="root"></param>
/// <param name="suitcase"></param>
/// <returns></returns>
private bool IsWithinSuitcaseTree(UUID principalID, UUID folderID)
{
XInventoryFolder suitcase = GetSuitcaseXFolder(principalID);
if (suitcase == null)
{
m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder", principalID);
return false;
}
List<XInventoryFolder> tree = new List<XInventoryFolder>();
tree.Add(suitcase); // Warp! the tree is the real root folder plus the children of the suitcase folder
tree.AddRange(GetFolderTree(principalID, suitcase.folderID));
// Also add the Current Outfit folder to the list of available folders
tree.Add(GetCurrentOutfitXFolder(principalID));
XInventoryFolder f = tree.Find(delegate(XInventoryFolder fl)
{
if (fl.folderID == folderID) return true;
else return false;
});
if (f == null) return false;
else return true;
}
#endregion
#region Avatar Appearance
private AvatarAppearance GetAppearance(UUID principalID)
{
AvatarAppearance a = null;
if (m_Appearances.TryGetValue(principalID, out a))
return a;
a = m_AvatarService.GetAppearance(principalID);
m_Appearances.AddOrUpdate(principalID, a, 5 * 60); // 5minutes
return a;
}
private bool IsPartOfAppearance(UUID principalID, UUID itemID)
{
AvatarAppearance a = GetAppearance(principalID);
if (a == null)
return false;
// Check wearables (body parts and clothes)
for (int i = 0; i < a.Wearables.Length; i++)
{
for (int j = 0; j < a.Wearables[i].Count; j++)
{
if (a.Wearables[i][j].ItemID == itemID)
{
//m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is a wearable", itemID);
return true;
}
}
}
// Check attachments
if (a.GetAttachmentForItem(itemID) != null)
{
//m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is an attachment", itemID);
return true;
}
return false;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class HttpWebResponseTest
{
public static IEnumerable<object[]> Dates_ReadValue_Data()
{
var zero_formats = new[]
{
// RFC1123
"R",
// RFC1123 - UTC
"ddd, dd MMM yyyy HH:mm:ss 'UTC'",
// RFC850
"dddd, dd-MMM-yy HH:mm:ss 'GMT'",
// RFC850 - UTC
"dddd, dd-MMM-yy HH:mm:ss 'UTC'",
// ANSI
"ddd MMM d HH:mm:ss yyyy",
};
var offset_formats = new[]
{
// RFC1123 - Offset
"ddd, dd MMM yyyy HH:mm:ss zzz",
// RFC850 - Offset
"dddd, dd-MMM-yy HH:mm:ss zzz",
};
var dates = new[]
{
new DateTimeOffset(2018, 1, 1, 12, 1, 14, TimeSpan.Zero),
new DateTimeOffset(2018, 1, 3, 15, 0, 0, TimeSpan.Zero),
new DateTimeOffset(2015, 5, 6, 20, 45, 38, TimeSpan.Zero),
};
foreach (var date in dates)
{
var expected = date.LocalDateTime;
foreach (var format in zero_formats.Concat(offset_formats))
{
var formatted = date.ToString(format, CultureInfo.InvariantCulture);
yield return new object[] { formatted, expected };
}
}
foreach (var format in offset_formats)
{
foreach (var date in dates.SelectMany(d => new[] { d.ToOffset(TimeSpan.FromHours(5)), d.ToOffset(TimeSpan.FromHours(-5)) }))
{
var formatted = date.ToString(format, CultureInfo.InvariantCulture);
var expected = date.LocalDateTime;
yield return new object[] { formatted, expected };
yield return new object[] { formatted.ToLowerInvariant(), expected };
}
}
}
public static IEnumerable<object[]> Dates_Always_Invalid_Data()
{
yield return new object[] { "not a valid date here" };
yield return new object[] { "Sun, 32 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25 Car 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Nov 1234567890 33:77:80 GMT" };
yield return new object[] { "Sun, 25 Nov 2018 55:33:01+05:00" };
yield return new object[] { "Sunday, 25-Nov-18 16:77:01 GMT" };
yield return new object[] { "Sunday, 25-Nov-18 16:33:65 UTC" };
yield return new object[] { "Broken, 25-Nov-18 21:33:01+05:00" };
yield return new object[] { "Always Nov 25 21:33:01 2018" };
}
public static IEnumerable<object[]> Dates_Now_Invalid_Data()
{
yield return new object[] { "not a valid date here" };
yield return new object[] { "Sun, 31 Nov 1234567890 33:77:80 GMT" };
// Sat/Saturday is invalid, because 2018/3/25 is Sun/Sunday...
yield return new object[] { "Sat, 25 Mar 2018 16:33:01 GMT" };
yield return new object[] { "Sat, 25 Mar 2018 16:33:01 UTC" };
yield return new object[] { "Sat, 25 Mar 2018 21:33:01+05:00" };
yield return new object[] { "Saturday, 25-Mar-18 16:33:01 GMT" };
yield return new object[] { "Saturday, 25-Mar-18 16:33:01 UTC" };
yield return new object[] { "Saturday, 25-Mar-18 21:33:01+05:00" };
yield return new object[] { "Sat Mar 25 21:33:01 2018" };
// Invalid day-of-week values
yield return new object[] { "Sue, 25 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sue, 25 Nov 2018 16:33:01 UTC" };
yield return new object[] { "Sue, 25 Nov 2018 21:33:01+05:00" };
yield return new object[] { "Surprise, 25-Nov-18 16:33:01 GMT" };
yield return new object[] { "Surprise, 25-Nov-18 16:33:01 UTC" };
yield return new object[] { "Surprise, 25-Nov-18 21:33:01+05:00" };
yield return new object[] { "Sue Nov 25 21:33:01 2018" };
// Invalid month values
yield return new object[] { "Sun, 25 Not 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25 Not 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Not 2018 21:33:01+05:00" };
yield return new object[] { "Sunday, 25-Not-18 16:33:01 GMT" };
yield return new object[] { "Sunday, 25-Not-18 16:33:01 UTC" };
yield return new object[] { "Sunday, 25-Not-18 21:33:01+05:00" };
yield return new object[] { "Sun Not 25 21:33:01 2018" };
// Strange separators
yield return new object[] { "Sun? 25 Nov 2018 16:33:01 GMT" };
yield return new object[] { "Sun, 25*Nov 2018 16:33:01 UTC" };
yield return new object[] { "Sun, 25 Nov{2018 21:33:01+05:00" };
yield return new object[] { "Sunday, 25-Nov-18]16:33:01 GMT" };
yield return new object[] { "Sunday, 25-Nov-18 16/33:01 UTC" };
yield return new object[] { "Sunday, 25-Nov-18 21:33|01+05:00" };
yield return new object[] { "Sun=Not 25 21:33:01 2018" };
}
[Theory]
[MemberData(nameof(Dates_ReadValue_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that retains some bugs (mostly related to offset)")]
public async Task LastModified_ReadValue(string raw, DateTime expected)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Get.Method;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK);
using (WebResponse response = await getResponse)
{
response.Headers.Set(HttpResponseHeader.LastModified, raw);
HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response);
Assert.Equal(expected, httpResponse.LastModified);
}
});
}
[Theory]
[MemberData(nameof(Dates_Always_Invalid_Data))]
public async Task Date_AlwaysInvalidValue(string invalid)
{
await LastModified_InvalidValue(invalid);
}
[Theory]
[MemberData(nameof(Dates_Now_Invalid_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,
"Net Framework currently retains the custom date parsing that accepts a wider range of values")]
public async Task LastModified_InvalidValue(string invalid)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Get.Method;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK);
using (WebResponse response = await getResponse)
{
response.Headers.Set(HttpResponseHeader.LastModified, invalid);
HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response);
Assert.Throws<ProtocolViolationException>(() => httpResponse.LastModified);
}
});
}
[Fact]
public async Task LastModified_NotPresent()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Get.Method;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK);
using (WebResponse response = await getResponse)
{
HttpWebResponse httpResponse = Assert.IsType<HttpWebResponse>(response);
DateTime lower = DateTime.Now;
DateTime firstCaptured = httpResponse.LastModified;
DateTime middle = DateTime.Now;
Assert.InRange(firstCaptured, lower, middle);
await Task.Delay(10);
DateTime secondCaptured = httpResponse.LastModified;
DateTime upper = DateTime.Now;
Assert.InRange(secondCaptured, middle, upper);
Assert.NotEqual(firstCaptured, secondCaptured);
}
});
}
[Theory]
[InlineData("text/html")]
[InlineData("text/html; charset=utf-8")]
[InlineData("TypeAndNoSubType")]
public async Task ContentType_ServerResponseHasContentTypeHeader_ContentTypeReceivedCorrectly(string expectedContentType)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Get.Method;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.OK, $"Content-Type: {expectedContentType}\r\n", "12345");
using (WebResponse response = await getResponse)
{
Assert.Equal(expectedContentType, response.ContentType);
}
});
}
[Fact]
public async Task ContentType_ServerResponseMissingContentTypeHeader_ContentTypeIsEmptyString()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = HttpMethod.Get.Method;
Task<WebResponse> getResponse = request.GetResponseAsync();
await server.AcceptConnectionSendResponseAndCloseAsync(content: "12345");
using (WebResponse response = await getResponse)
{
Assert.Equal(string.Empty, response.ContentType);
}
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Management.Automation.Internal;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Class definition of CommandProcessor - This class provides interface to create
/// and execute commands written in CLS compliant languages.
/// </summary>
internal class CommandProcessor : CommandProcessorBase
{
#region ctor
static CommandProcessor()
{
s_constructInstanceCache = new ConcurrentDictionary<Type, Func<Cmdlet>>();
// Avoid jitting constructors some of the more commonly used cmdlets in SMA.dll - not meant to be
// exhaustive b/c many cmdlets aren't called at all, so we'd never even need an entry in the cache.
s_constructInstanceCache.GetOrAdd(typeof(ForEachObjectCommand), () => new ForEachObjectCommand());
s_constructInstanceCache.GetOrAdd(typeof(WhereObjectCommand), () => new WhereObjectCommand());
s_constructInstanceCache.GetOrAdd(typeof(ImportModuleCommand), () => new ImportModuleCommand());
s_constructInstanceCache.GetOrAdd(typeof(GetModuleCommand), () => new GetModuleCommand());
s_constructInstanceCache.GetOrAdd(typeof(GetHelpCommand), () => new GetHelpCommand());
s_constructInstanceCache.GetOrAdd(typeof(InvokeCommandCommand), () => new InvokeCommandCommand());
s_constructInstanceCache.GetOrAdd(typeof(GetCommandCommand), () => new GetCommandCommand());
s_constructInstanceCache.GetOrAdd(typeof(OutDefaultCommand), () => new OutDefaultCommand());
s_constructInstanceCache.GetOrAdd(typeof(OutHostCommand), () => new OutHostCommand());
s_constructInstanceCache.GetOrAdd(typeof(OutNullCommand), () => new OutNullCommand());
s_constructInstanceCache.GetOrAdd(typeof(SetStrictModeCommand), () => new SetStrictModeCommand());
s_constructInstanceCache.GetOrAdd(typeof(FormatDefaultCommand), () => new FormatDefaultCommand());
s_constructInstanceCache.GetOrAdd(typeof(OutLineOutputCommand), () => new OutLineOutputCommand());
}
/// <summary>
/// Initializes the new instance of CommandProcessor class.
/// </summary>
/// <param name="cmdletInfo">
/// The information about the cmdlet.
/// </param>
/// <param name="context">
/// PowerShell engine execution context for this command.
/// </param>
/// <exception cref="CommandNotFoundException">
/// If there was a failure creating an instance of the cmdlet type.
/// </exception>
internal CommandProcessor(CmdletInfo cmdletInfo, ExecutionContext context) : base(cmdletInfo)
{
this._context = context;
Init(cmdletInfo);
}
/// <summary>
/// This is the constructor for script as cmdlet.
/// </summary>
/// <param name="scriptCommandInfo">
/// The information about the cmdlet.
/// </param>
/// <param name="context">
/// PowerShell engine execution context for this command.
/// </param>
/// <param name="useLocalScope"></param>
/// <param name="sessionState"></param>
/// <param name="fromScriptFile">True when the script to be executed came from a file (as opposed to a function, or interactive input).</param>
internal CommandProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext context, bool useLocalScope, bool fromScriptFile, SessionStateInternal sessionState)
: base(scriptCommandInfo as CommandInfo)
{
this._context = context;
this._useLocalScope = useLocalScope;
this._fromScriptFile = fromScriptFile;
this.CommandSessionState = sessionState;
Init(scriptCommandInfo);
}
#endregion ctor
#region internal members
/// <summary>
/// Returns a CmdletParameterBinderController for the specified command.
/// </summary>
/// <param name="command">
/// The cmdlet to bind parameters to.
/// </param>
/// <returns>
/// A new instance of a CmdletParameterBinderController.
/// </returns>
/// <exception cref="ArgumentException">
/// if <paramref name="command"/> is not a Cmdlet.
/// </exception>
internal ParameterBinderController NewParameterBinderController(InternalCommand command)
{
Cmdlet cmdlet = command as Cmdlet;
if (cmdlet == null)
{
throw PSTraceSource.NewArgumentException("command");
}
ParameterBinderBase parameterBinder;
IScriptCommandInfo scriptCommandInfo = CommandInfo as IScriptCommandInfo;
if (scriptCommandInfo != null)
{
parameterBinder = new ScriptParameterBinder(scriptCommandInfo.ScriptBlock, cmdlet.MyInvocation, this._context, cmdlet, CommandScope);
}
else
{
parameterBinder = new ReflectionParameterBinder(cmdlet, cmdlet);
}
_cmdletParameterBinderController = new CmdletParameterBinderController(cmdlet, CommandInfo.CommandMetadata, parameterBinder);
return _cmdletParameterBinderController;
}
internal CmdletParameterBinderController CmdletParameterBinderController
{
get
{
if (_cmdletParameterBinderController == null)
{
NewParameterBinderController(this.Command);
}
return _cmdletParameterBinderController;
}
}
private CmdletParameterBinderController _cmdletParameterBinderController;
/// <summary>
/// Get the ObsoleteAttribute of the current command.
/// </summary>
internal override ObsoleteAttribute ObsoleteAttribute
{
get { return _obsoleteAttribute; }
}
private ObsoleteAttribute _obsoleteAttribute;
/// <summary>
/// Binds the specified command-line parameters to the target.
/// </summary>
/// <returns>
/// true if encode succeeds otherwise false.
/// </returns>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
internal void BindCommandLineParameters()
{
using (commandRuntime.AllowThisCommandToWrite(false))
{
Diagnostics.Assert(
this.CmdletParameterBinderController != null,
"A parameter binder controller should always be available");
// Always set the hash table on MyInvocation so it's available for both interpreted cmdlets
// as well as compiled ones.
this.CmdletParameterBinderController.CommandLineParameters.UpdateInvocationInfo(this.Command.MyInvocation);
this.Command.MyInvocation.UnboundArguments = new Collections.Generic.List<object>();
this.CmdletParameterBinderController.BindCommandLineParameters(arguments);
}
}
/// <summary>
/// Prepares the command. Encodes the command-line parameters
/// JonN 2003-04-02 Split from Execute()
/// </summary>
/// <exception cref="ParameterBindingException">
/// If any parameters fail to bind,
/// or
/// If any mandatory parameters are missing.
/// </exception>
/// <exception cref="MetadataException">
/// If there is an error generating the metadata for dynamic parameters.
/// </exception>
internal override void Prepare(IDictionary psDefaultParameterValues)
{
// Note that Prepare() and DoBegin() should NOT be combined.
// Reason: Encoding of commandline parameters happen as part of
// Prepare(). If they are combined, the first command's
// DoBegin() will be called before the next command's Prepare().
// Since BeginProcessing() can write objects to the downstream
// commandlet, it will end up calling DoExecute() (from Pipe.Add())
// before Prepare.
// Steps involved:
// (1) Backup the default parameter values
// (2) Handle input objects - add them to the input pipe.
// (3) Bind the parameters to properties (encoding)
// (4) Execute the command method using DoExecute() (repeatedly)
this.CmdletParameterBinderController.DefaultParameterValues = psDefaultParameterValues;
Diagnostics.Assert(
this.Command != null,
"CommandProcessor did not initialize Command\n" + this.CommandInfo.Name);
PSLanguageMode? oldLanguageMode = null;
bool? oldLangModeTransitionStatus = null;
try
{
var scriptCmdletInfo = this.CommandInfo as IScriptCommandInfo;
if (scriptCmdletInfo != null &&
scriptCmdletInfo.ScriptBlock.LanguageMode.HasValue &&
scriptCmdletInfo.ScriptBlock.LanguageMode != Context.LanguageMode)
{
// Set the language mode before parameter binding if it's necessary for a script cmdlet, so that the language
// mode is appropriately applied for evaluating parameter defaults and argument type conversion.
oldLanguageMode = Context.LanguageMode;
Context.LanguageMode = scriptCmdletInfo.ScriptBlock.LanguageMode.Value;
// If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place.
if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && Context.LanguageMode == PSLanguageMode.FullLanguage)
{
oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding;
Context.LanguageModeTransitionInParameterBinding = true;
}
}
BindCommandLineParameters();
}
finally
{
if (oldLanguageMode.HasValue)
{
// Revert to the original language mode after doing the parameter binding
Context.LanguageMode = oldLanguageMode.Value;
}
if (oldLangModeTransitionStatus.HasValue)
{
// Revert the transition state to old value after doing the parameter binding
Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value;
}
}
}
protected override void OnSetCurrentScope()
{
// When dotting a script cmdlet, push the locals of automatic variables to
// the 'DottedScopes' of the current scope.
PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet;
if (scriptCmdlet != null && !UseLocalScope)
{
scriptCmdlet.PushDottedScope(CommandSessionState.CurrentScope);
}
}
protected override void OnRestorePreviousScope()
{
// When dotting a script cmdlet, pop the locals of automatic variables from
// the 'DottedScopes' of the current scope.
PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet;
if (scriptCmdlet != null && !UseLocalScope)
{
scriptCmdlet.PopDottedScope(CommandSessionState.CurrentScope);
}
}
/// <summary>
/// Execute BeginProcessing part of command.
/// </summary>
internal override void DoBegin()
{
if (!RanBeginAlready && CmdletParameterBinderController.ObsoleteParameterWarningList != null)
{
using (CommandRuntime.AllowThisCommandToWrite(false))
{
// Write out warning messages for the bound obsolete parameters.
// The warning message are generated during parameter binding, but we delay writing
// them out until now so that the -WarningAction will be respected as expected.
foreach (WarningRecord warningRecord in CmdletParameterBinderController.ObsoleteParameterWarningList)
{
CommandRuntime.WriteWarning(warningRecord);
}
}
// Clear up the warning message list
CmdletParameterBinderController.ObsoleteParameterWarningList.Clear();
}
base.DoBegin();
}
/// <summary>
/// This calls the command. It assumes that Prepare() has already been called.
/// JonN 2003-04-02 Split from Execute()
/// </summary>
/// <exception cref="PipelineStoppedException">
/// a terminating error occurred, or the pipeline was otherwise stopped
/// </exception>
internal override void ProcessRecord()
{
// Invoke the Command method with the request object
if (!this.RanBeginAlready)
{
RanBeginAlready = true;
try
{
// NOTICE-2004/06/08-JonN 959638
using (commandRuntime.AllowThisCommandToWrite(true))
{
if (Context._debuggingMode > 0 && !(Command is PSScriptCmdlet))
{
Context.Debugger.CheckCommand(this.Command.MyInvocation);
}
Command.DoBeginProcessing();
}
}
// 2004/03/18-JonN This is understood to be
// an FXCOP violation, cleared by KCwalina.
catch (Exception e) // Catch-all OK, 3rd party callout.
{
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(e);
}
}
Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipeline was started
while (Read())
{
Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe;
Exception exceptionToThrow = null;
try
{
//
// On V1 the output pipe was redirected to the command's output pipe only when it
// was already redirected. This is the original comment explaining this behaviour:
//
// NTRAID#Windows Out of Band Releases-926183-2005-12-15
// MonadTestHarness has a bad dependency on an artifact of the current implementation
// The following code only redirects the output pipe if it's already redirected
// to preserve the artifact. The test suites need to be fixed and then this
// the check can be removed and the assignment always done.
//
// However, this makes the hosting APIs behave differently than commands executed
// from the command-line host (for example, see bugs Win7:415915 and Win7:108670).
// The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the
// redirection.
//
if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null)
{
_context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe;
}
// NOTICE-2004/06/08-JonN 959638
using (commandRuntime.AllowThisCommandToWrite(true))
{
if (CmdletParameterBinderController.ObsoleteParameterWarningList != null &&
CmdletParameterBinderController.ObsoleteParameterWarningList.Count > 0)
{
// Write out warning messages for the pipeline-value-bound obsolete parameters.
// The warning message are generated during parameter binding, but we delay writing
// them out until now so that the -WarningAction will be respected as expected.
foreach (WarningRecord warningRecord in CmdletParameterBinderController.ObsoleteParameterWarningList)
{
CommandRuntime.WriteWarning(warningRecord);
}
// Clear up the warning message list
CmdletParameterBinderController.ObsoleteParameterWarningList.Clear();
}
this.Command.MyInvocation.PipelineIterationInfo[this.Command.MyInvocation.PipelinePosition]++;
Command.DoProcessRecord();
}
}
catch (RuntimeException rte)
{
// Most exceptions get wrapped here, but an exception that originated from
// a throw statement should not get wrapped, so it is just rethrown.
if (rte.WasThrownFromThrowStatement)
{
throw;
}
exceptionToThrow = rte;
}
catch (LoopFlowException)
{
// Win8:84066 - Don't wrap LoopFlowException, we incorrectly raise a PipelineStoppedException
// which gets caught by a script try/catch if we wrap here.
throw;
}
// 2004/03/18-JonN This is understood to be
// an FXCOP violation, cleared by KCwalina.
catch (Exception e) // Catch-all OK, 3rd party callout.
{
exceptionToThrow = e;
}
finally
{
_context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe;
}
if (exceptionToThrow != null)
{
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(exceptionToThrow);
}
}
}
#endregion public_methods
#region helper_methods
/// <summary>
/// Tells whether it is the first call to Read.
/// </summary>
private bool _firstCallToRead = true;
/// <summary>
/// Tells whether to bail out in the next call to Read.
/// </summary>
private bool _bailInNextCall;
/// <summary>
/// Populates the parameters specified from the pipeline.
/// </summary>
/// <returns>
/// A bool indicating whether read succeeded.
/// </returns>
/// <exception cref="ParameterBindingException">
/// If a parameter fails to bind.
/// or
/// If a mandatory parameter is missing.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// The pipeline was already stopped.
/// </exception>
// 2003/10/07-JonN was public, now internal
internal sealed override bool Read()
{
// (1) If Read() is called for the first time and with pipe closed and
// no object in the input pipe and
// (typically for the first cmdlet in the pipe & during programmatic
// execution of a command), Read() will succeed (return true) for
// only one time (so that the
// (2) If Read() is called with some input objects in the pipeline, it
// processes the input
// object one at a time and adds parameters from the input object
// to the list of parameters. If
// added to the error pipe and Read() will continue to read the
// next object in the pipe.
// (3) Read() will return false if there are no objects in the pipe
// for processing.
// (4) Read() will return true if the parameters are encoded in the
// request - signals ready for execution.
// (5) Read() will refresh the properties that are encoded via pipeline
// parameters in the next
// call to Read() [To their default values, so that the
// next execution of the command will
// not work on previously specified parameter].
// If the flag 'bail in next call' is true, then bail out returning false.
if (_bailInNextCall)
return false;
// ProcessRecord() will loop on Command.Read(), and continue calling
// ProcessRecord() until the incoming pipe is empty. We need to
// stop this loop if a downstream cmdlet broke guidelines and
// "swallowed" a PipelineStoppedException.
Command.ThrowIfStopping();
// Prepare the default value parameter list if this is the first call to Read
if (_firstCallToRead)
{
_firstCallToRead = false;
if (!IsPipelineInputExpected())
{
// Cmdlet should operate only with command-line parameters
// Let the command Execute with the specified command line parameters
// And Read should return false in the next call.
_bailInNextCall = true;
return true;
}
}
// If this cmdlet has any members that could be bound
// from the pipeline, do that now. In fact, we always try and
// do it once anyway because this BindPipelineParameters() does
// the final binding stage in before executing the cmdlet.
bool mandatoryParametersSpecified = false;
while (!mandatoryParametersSpecified)
{
// Retrieve the object from the input pipeline
object inputObject = this.commandRuntime.InputPipe.Retrieve();
if (inputObject == AutomationNull.Value)
{
// no object in the pipeline, stop reading
Command.CurrentPipelineObject = null;
return false;
}
// If we are reading input for the first command in the pipeline increment PipelineIterationInfo[0], which is the number of items read from the input
if (this.Command.MyInvocation.PipelinePosition == 1)
{
this.Command.MyInvocation.PipelineIterationInfo[0]++;
}
try
{
// Process the input pipeline object
if (false == ProcessInputPipelineObject(inputObject))
{
// The input object was not bound to any parameters of the cmdlet.
// Write a non-terminating error and continue with the next input
// object.
WriteInputObjectError(
inputObject,
ParameterBinderStrings.InputObjectNotBound,
"InputObjectNotBound");
continue;
}
}
catch (ParameterBindingException bindingError)
{
// Set the target and write the error
bindingError.ErrorRecord.SetTargetObject(inputObject);
ErrorRecord errorRecord =
new ErrorRecord(
bindingError.ErrorRecord,
bindingError);
this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
continue;
}
Collection<MergedCompiledCommandParameter> missingMandatoryParameters;
using (ParameterBinderBase.bindingTracer.TraceScope(
"MANDATORY PARAMETER CHECK on cmdlet [{0}]",
this.CommandInfo.Name))
{
// Check for unbound mandatory parameters but don't prompt
mandatoryParametersSpecified =
this.CmdletParameterBinderController.HandleUnboundMandatoryParameters(out missingMandatoryParameters);
}
if (!mandatoryParametersSpecified)
{
string missingParameters =
CmdletParameterBinderController.BuildMissingParamsString(missingMandatoryParameters);
// Since the input object did not satisfy all mandatory parameters
// for the command, write an ErrorRecord to the error pipe with
// the target as the input object.
WriteInputObjectError(
inputObject,
ParameterBinderStrings.InputObjectMissingMandatory,
"InputObjectMissingMandatory",
missingParameters);
}
}
return true;
}
/// <summary>
/// Writes an ErrorRecord to the commands error pipe because the specified
/// input object was not bound to the command.
/// </summary>
/// <param name="inputObject">
/// The pipeline input object that was not bound.
/// </param>
/// <param name="resourceString">
/// The error message.
/// </param>
/// <param name="errorId">
/// The resource ID of the error message is also used as error ID
/// of the ErrorRecord.
/// </param>
/// <param name="args">
/// Additional arguments to be formatted into the error message that represented in <paramref name="resourceString"/>.
/// </param>
private void WriteInputObjectError(
object inputObject,
string resourceString,
string errorId,
params object[] args)
{
Type inputObjectType = (inputObject == null) ? null : inputObject.GetType();
ParameterBindingException bindingException = new ParameterBindingException(
ErrorCategory.InvalidArgument,
this.Command.MyInvocation,
null,
null,
null,
inputObjectType,
resourceString,
errorId,
args);
ErrorRecord errorRecord =
new ErrorRecord(
bindingException,
errorId,
ErrorCategory.InvalidArgument,
inputObject);
errorRecord.SetInvocationInfo(this.Command.MyInvocation);
this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord);
}
/// <summary>
/// Reads an object from an input pipeline and attempts to bind the parameters.
/// </summary>
/// <param name="inputObject">
/// The pipeline input object to be processed.
/// </param>
/// <returns>
/// False the pipeline input object was not bound in any way to the command.
/// </returns>
/// <exception cref="ParameterBindingException">
/// If a ShouldProcess parameter is specified but the cmdlet does not support
/// ShouldProcess.
/// or
/// If an error occurred trying to bind a parameter from the pipeline object.
/// </exception>
private bool ProcessInputPipelineObject(object inputObject)
{
PSObject inputToOperateOn = null;
// Use ETS to retrieve properties from the input object
// turn it into a shell object if it isn't one already...
// we depend on PSObject.AsPSObject() being idempotent - if
// it's already a shell object, don't encapsulate it again.
if (inputObject != null)
{
inputToOperateOn = PSObject.AsPSObject(inputObject);
}
Command.CurrentPipelineObject = inputToOperateOn;
return this.CmdletParameterBinderController.BindPipelineParameters(inputToOperateOn);
}
private static readonly ConcurrentDictionary<Type, Func<Cmdlet>> s_constructInstanceCache;
private static Cmdlet ConstructInstance(Type type)
{
// Call the default constructor if type derives from Cmdlet.
// Return null (and the caller will generate an appropriate error) if
// type does not derive from Cmdlet. We do it this way so the expensive type check
// is performed just once per type.
return s_constructInstanceCache.GetOrAdd(type,
t => Expression.Lambda<Func<Cmdlet>>(
typeof(Cmdlet).IsAssignableFrom(t)
? (Expression)Expression.New(t)
: Expression.Constant(null, typeof(Cmdlet))).Compile())();
}
/// <summary>
/// Initializes the command's request object.
/// </summary>
/// <param name="cmdletInformation">
/// The information about the cmdlet.
/// </param>
/// <exception cref="CmdletInvocationException">
/// If the constructor for the cmdlet threw an exception.
/// </exception>
/// <exception cref="MemberAccessException">
/// The type referenced by <paramref name="cmdletInformation"/> refered to an
/// abstract type or them member was invoked via a late-binding mechanism.
/// </exception>
/// <exception cref="TypeLoadException">
/// If <paramref name="cmdletInformation"/> refers to a type that is invalid.
/// </exception>
private void Init(CmdletInfo cmdletInformation)
{
Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null.");
Cmdlet newCmdlet = null;
Exception initError = null;
string errorIdAndResourceId = null;
string resourceStr = null;
try
{
// Create the request object
newCmdlet = ConstructInstance(cmdletInformation.ImplementingType);
if (newCmdlet == null)
{
// We could test the inheritance before constructing, but that's
// expensive. Much cheaper to just check for null.
initError = new InvalidCastException();
errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType";
resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType;
}
}
catch (MemberAccessException memberAccessException)
{
initError = memberAccessException;
}
catch (TypeLoadException typeLoadException)
{
initError = typeLoadException;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
// We don't have a Command or InvocationInfo at this point,
// since the command failed to initialize.
var commandException = new CmdletInvocationException(e, null);
// Log a command health event
MshLog.LogCommandHealthEvent(
this._context,
commandException,
Severity.Warning);
throw commandException;
}
if (initError != null)
{
// Log a command health event
MshLog.LogCommandHealthEvent(
this._context,
initError,
Severity.Warning);
CommandNotFoundException exception =
new CommandNotFoundException(
cmdletInformation.Name,
initError,
errorIdAndResourceId ?? "CmdletNotFoundException",
resourceStr ?? DiscoveryExceptions.CmdletNotFoundException,
initError.Message);
throw exception;
}
this.Command = newCmdlet;
this.CommandScope = Context.EngineSessionState.CurrentScope;
InitCommon();
}
private void Init(IScriptCommandInfo scriptCommandInfo)
{
var scriptCmdlet = new PSScriptCmdlet(scriptCommandInfo.ScriptBlock, UseLocalScope, FromScriptFile, _context);
this.Command = scriptCmdlet;
this.CommandScope = UseLocalScope
? this.CommandSessionState.NewScope(_fromScriptFile)
: this.CommandSessionState.CurrentScope;
if (UseLocalScope)
{
// Set the 'LocalsTuple' of the new scope to that of the scriptCmdlet
scriptCmdlet.SetLocalsTupleForNewScope(CommandScope);
}
InitCommon();
// If the script has been dotted, throw an error if it's from a different language mode.
if (!this.UseLocalScope)
{
ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context.LanguageMode, Command.MyInvocation);
}
}
private void InitCommon()
{
// set the metadata
this.Command.CommandInfo = this.CommandInfo;
// set the ObsoleteAttribute of the current command
_obsoleteAttribute = this.CommandInfo.CommandMetadata.Obsolete;
// set the execution context
this.Command.Context = this._context;
// Now set up the command runtime for this command.
try
{
this.commandRuntime = new MshCommandRuntime(_context, this.CommandInfo, this.Command);
this.Command.commandRuntime = this.commandRuntime;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
// Log a command health event
MshLog.LogCommandHealthEvent(
this._context,
e,
Severity.Warning);
throw;
}
}
/// <summary>
/// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
/// and if yes, then returns the help target to display.
/// </summary>
/// <param name="helpTarget">Help target to request.</param>
/// <param name="helpCategory">Help category to request.</param>
/// <returns><c>true</c> if user requested help; <c>false</c> otherwise.</returns>
internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
{
if (this.arguments != null)
{
foreach (CommandParameterInternal parameter in this.arguments)
{
Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
if (parameter.IsDashQuestion())
{
helpCategory = HelpCategory.All;
// using InvocationName mainly to avoid bogus this.CommandInfo.Name
// (when CmdletInfo.Name is initialized from "cmdlet" declaration
// of a scriptblock and when "cmdlet" declaration doesn't specify any name)
if ((this.Command != null) && (this.Command.MyInvocation != null) &&
(!string.IsNullOrEmpty(this.Command.MyInvocation.InvocationName)))
{
helpTarget = this.Command.MyInvocation.InvocationName;
// Win8: 391035 get-help does not work properly for aliased cmdlets
// For aliased cmdlets/functions,example Initialize-Volume -> Format-Volume,
// MyInvocation.InvocationName is different from CommandInfo.Name
// - CommandInfo.Name points to Format-Volume
// - MyInvocation.InvocationName points to Initialize-Volume
if (string.Equals(this.Command.MyInvocation.InvocationName, this.CommandInfo.Name, StringComparison.OrdinalIgnoreCase))
{
helpCategory = this.CommandInfo.HelpCategory;
}
}
else
{
helpTarget = this.CommandInfo.Name;
helpCategory = this.CommandInfo.HelpCategory;
}
return true;
}
}
}
return base.IsHelpRequested(out helpTarget, out helpCategory);
}
#endregion helper_methods
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
#if FEATURE_CORESYSTEM
using System.Core;
#endif
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Flag to indicate if we're doing encryption or decryption
/// </summary>
internal enum EncryptionMode {
Encrypt,
Decrypt
}
/// <summary>
/// Implementation of a generic CAPI symmetric encryption algorithm. Concrete SymmetricAlgorithm classes
/// which wrap CAPI implementations can use this class to perform the actual encryption work.
/// </summary>
internal sealed class CapiSymmetricAlgorithm : ICryptoTransform {
private int m_blockSize;
private byte[] m_depadBuffer;
private EncryptionMode m_encryptionMode;
[SecurityCritical]
private SafeCapiKeyHandle m_key;
private PaddingMode m_paddingMode;
[SecurityCritical]
private SafeCspHandle m_provider;
[System.Security.SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
public CapiSymmetricAlgorithm(int blockSize,
int feedbackSize,
SafeCspHandle provider,
SafeCapiKeyHandle key,
byte[] iv,
CipherMode cipherMode,
PaddingMode paddingMode,
EncryptionMode encryptionMode) {
Contract.Requires(0 < blockSize && blockSize % 8 == 0);
Contract.Requires(0 <= feedbackSize);
Contract.Requires(provider != null && !provider.IsInvalid && !provider.IsClosed);
Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed);
Contract.Ensures(m_provider != null && !m_provider.IsInvalid && !m_provider.IsClosed);
m_blockSize = blockSize;
m_encryptionMode = encryptionMode;
m_paddingMode = paddingMode;
m_provider = provider.Duplicate();
m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
}
public bool CanReuseTransform {
get { return true; }
}
public bool CanTransformMultipleBlocks {
get { return true; }
}
//
// Note: both input and output block size are in bytes rather than bits
//
public int InputBlockSize {
[Pure]
get { return m_blockSize / 8; }
}
public int OutputBlockSize {
get { return m_blockSize / 8; }
}
[SecuritySafeCritical]
public void Dispose() {
Contract.Ensures(m_key == null || m_key.IsClosed);
Contract.Ensures(m_provider == null || m_provider.IsClosed);
Contract.Ensures(m_depadBuffer == null);
if (m_key != null) {
m_key.Dispose();
}
if (m_provider != null) {
m_provider.Dispose();
}
if (m_depadBuffer != null) {
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
}
return;
}
[SecuritySafeCritical]
private int DecryptBlocks(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
Contract.Requires(m_key != null);
Contract.Requires(inputBuffer != null && inputCount <= inputBuffer.Length - inputOffset);
Contract.Requires(inputOffset >= 0);
Contract.Requires(inputCount > 0 && inputCount % InputBlockSize == 0);
Contract.Requires(outputBuffer != null && inputCount <= outputBuffer.Length - outputOffset);
Contract.Requires(inputOffset >= 0);
Contract.Requires(m_depadBuffer == null || (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros));
Contract.Ensures(Contract.Result<int>() >= 0);
//
// If we're decrypting, it's possible to be called with the last blocks of the data, and then
// have TransformFinalBlock called with an empty array. Since we don't know if this is the case,
// we won't decrypt the last block of the input until either TransformBlock or
// TransformFinalBlock is next called.
//
// We don't need to do this for PaddingMode.None because there is no padding to strip, and
// we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the
// zeros at the end of a block are part of the plaintext or the padding.
//
int decryptedBytes = 0;
if (m_paddingMode != PaddingMode.None && m_paddingMode != PaddingMode.Zeros) {
// If we have data saved from a previous call, decrypt that into the output first
if (m_depadBuffer != null) {
int depadDecryptLength = RawDecryptBlocks(m_depadBuffer, 0, m_depadBuffer.Length);
Buffer.BlockCopy(m_depadBuffer, 0, outputBuffer, outputOffset, depadDecryptLength);
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
outputOffset += depadDecryptLength;
decryptedBytes += depadDecryptLength;
}
else {
m_depadBuffer = new byte[InputBlockSize];
}
// Copy the last block of the input buffer into the depad buffer
Debug.Assert(inputCount >= m_depadBuffer.Length, "inputCount >= m_depadBuffer.Length");
Buffer.BlockCopy(inputBuffer,
inputOffset + inputCount - m_depadBuffer.Length,
m_depadBuffer,
0,
m_depadBuffer.Length);
inputCount -= m_depadBuffer.Length;
Debug.Assert(inputCount % InputBlockSize == 0, "Did not remove whole blocks for depadding");
}
// CryptDecrypt operates in place, so if after reserving the depad buffer there's still data to decrypt,
// make a copy of that in the output buffer to work on.
if (inputCount > 0) {
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
decryptedBytes += RawDecryptBlocks(outputBuffer, outputOffset, inputCount);
}
return decryptedBytes;
}
/// <summary>
/// Remove the padding from the last blocks being decrypted
/// </summary>
private byte[] DepadBlock(byte[] block, int offset, int count) {
Contract.Requires(block != null && count >= block.Length - offset);
Contract.Requires(0 <= offset);
Contract.Requires(0 <= count);
Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length <= block.Length);
int padBytes = 0;
// See code:System.Security.Cryptography.CapiSymmetricAlgorithm.PadBlock for a description of the
// padding modes.
switch (m_paddingMode) {
case PaddingMode.ANSIX923:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Verify that all the padding bytes are 0s
for (int i = offset + count - padBytes; i < offset + count - 1; i++) {
if (block[i] != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
}
break;
case PaddingMode.ISO10126:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Since the padding consists of random bytes, we cannot verify the actual pad bytes themselves
break;
case PaddingMode.PKCS7:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
// Verify all the padding bytes match the amount of padding
for (int i = offset + count - padBytes; i < offset + count; i++) {
if (block[i] != padBytes) {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidPadding));
}
}
break;
// We cannot remove Zeros padding because we don't know if the zeros at the end of the block
// belong to the padding or the plaintext itself.
case PaddingMode.Zeros:
case PaddingMode.None:
padBytes = 0;
break;
default:
throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode));
}
// Copy everything but the padding to the output
byte[] depadded = new byte[count - padBytes];
Buffer.BlockCopy(block, offset, depadded, 0, depadded.Length);
return depadded;
}
/// <summary>
/// Encrypt blocks of plaintext
/// </summary>
[SecurityCritical]
private int EncryptBlocks(byte[] buffer, int offset, int count) {
Contract.Requires(m_key != null);
Contract.Requires(buffer != null && count <= buffer.Length - offset);
Contract.Requires(offset >= 0);
Contract.Requires(count > 0 && count % InputBlockSize == 0);
Contract.Ensures(Contract.Result<int>() >= 0);
//
// Do the encryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR
// supports padding modes that CAPI does not, so we will always tell CAPI that we are not working
// with the final block.
//
int dataLength = count;
unsafe {
fixed (byte* pData = &buffer[offset]) {
if (!CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
false,
0,
new IntPtr(pData),
ref dataLength,
buffer.Length - offset)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
return dataLength;
}
/// <summary>
/// Calculate the padding for a block of data
/// </summary>
[SecuritySafeCritical]
private byte[] PadBlock(byte[] block, int offset, int count) {
Contract.Requires(m_provider != null);
Contract.Requires(block != null && count <= block.Length - offset);
Contract.Requires(0 <= offset);
Contract.Requires(0 <= count);
Contract.Ensures(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length % InputBlockSize == 0);
byte[] result = null;
int padBytes = InputBlockSize - (count % InputBlockSize);
switch (m_paddingMode) {
// ANSI padding fills the blocks with zeros and adds the total number of padding bytes as
// the last pad byte, adding an extra block if the last block is complete.
//
// x 00 00 00 00 00 00 07
case PaddingMode.ANSIX923:
result = new byte[count + padBytes];
Buffer.BlockCopy(block, 0, result, 0, count);
result[result.Length - 1] = (byte)padBytes;
break;
// ISO padding fills the blocks up with random bytes and adds the total number of padding
// bytes as the last pad byte, adding an extra block if the last block is complete.
//
// xx rr rr rr rr rr rr 07
case PaddingMode.ISO10126:
result = new byte[count + padBytes];
CapiNative.UnsafeNativeMethods.CryptGenRandom(m_provider, result.Length - 1, result);
Buffer.BlockCopy(block, 0, result, 0, count);
result[result.Length - 1] = (byte)padBytes;
break;
// No padding requires that the input already be a multiple of the block size
case PaddingMode.None:
if (count % InputBlockSize != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock));
}
result = new byte[count];
Buffer.BlockCopy(block, offset, result, 0, result.Length);
break;
// PKCS padding fills the blocks up with bytes containing the total number of padding bytes
// used, adding an extra block if the last block is complete.
//
// xx xx 06 06 06 06 06 06
case PaddingMode.PKCS7:
result = new byte[count + padBytes];
Buffer.BlockCopy(block, offset, result, 0, count);
for (int i = count; i < result.Length; i++) {
result[i] = (byte)padBytes;
}
break;
// Zeros padding fills the last partial block with zeros, and does not add a new block to
// the end if the last block is already complete.
//
// xx 00 00 00 00 00 00 00
case PaddingMode.Zeros:
if (padBytes == InputBlockSize) {
padBytes = 0;
}
result = new byte[count + padBytes];
Buffer.BlockCopy(block, offset, result, 0, count);
break;
default:
throw new CryptographicException(SR.GetString(SR.Cryptography_UnknownPaddingMode));
}
return result;
}
/// <summary>
/// Validate and transform the user's IV into one that we will pass on to CAPI
///
/// If we have an IV, make a copy of it so that it doesn't get modified while we're using it. If
/// not, and we're not in ECB mode then throw an error, since we cannot decrypt without the IV, and
/// generating a random IV to encrypt with would lead to data which is not decryptable.
///
/// For compatibility with v1.x, we accept IVs which are longer than the block size, and truncate
/// them back. We will reject an IV which is smaller than the block size however.
/// </summary>
private static byte[] ProcessIV(byte[] iv, int blockSize, CipherMode cipherMode) {
Contract.Requires(blockSize % 8 == 0);
Contract.Ensures(cipherMode == CipherMode.ECB ||
(Contract.Result<byte[]>() != null && Contract.Result<byte[]>().Length == blockSize / 8));
byte[] realIV = null;
if (iv != null) {
if (blockSize / 8 <= iv.Length) {
realIV = new byte[blockSize / 8];
Buffer.BlockCopy(iv, 0, realIV, 0, realIV.Length);
}
else {
throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidIVSize));
}
}
else if (cipherMode != CipherMode.ECB) {
throw new CryptographicException(SR.GetString(SR.Cryptography_MissingIV));
}
return realIV;
}
/// <summary>
/// Do a direct decryption of the ciphertext blocks. This method should not be called from anywhere
/// but DecryptBlocks or TransformFinalBlock since it does not account for the depadding buffer and
/// direct use could lead to incorrect decryption values.
/// </summary>
[SecurityCritical]
private int RawDecryptBlocks(byte[] buffer, int offset, int count) {
Contract.Requires(m_key != null);
Contract.Requires(buffer != null && count <= buffer.Length - offset);
Contract.Requires(offset >= 0);
Contract.Requires(count > 0 && count % InputBlockSize == 0);
Contract.Ensures(Contract.Result<int>() >= 0);
//
// Do the decryption. Note that CapiSymmetricAlgorithm will do all padding itself since the CLR
// supports padding modes that CAPI does not, so we will always tell CAPI that we are not working
// with the final block.
//
int dataLength = count;
unsafe {
fixed (byte* pData = &buffer[offset]) {
if (!CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
false,
0,
new IntPtr(pData),
ref dataLength)) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
}
}
return dataLength;
}
/// <summary>
/// Reset the state of the algorithm so that it can begin processing a new message
/// </summary>
[SecuritySafeCritical]
private void Reset() {
Contract.Requires(m_key != null);
Contract.Ensures(m_depadBuffer == null);
//
// CryptEncrypt / CryptDecrypt must be called with the Final parameter set to true so that
// their internal state is reset. Since we do all padding by hand, this isn't done by
// TransformFinalBlock so is done on an empty buffer here.
//
byte[] buffer = new byte[OutputBlockSize];
int resetSize = 0;
unsafe {
fixed (byte* pBuffer = buffer) {
if (m_encryptionMode == EncryptionMode.Encrypt) {
CapiNative.UnsafeNativeMethods.CryptEncrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
true,
0,
new IntPtr(pBuffer),
ref resetSize,
buffer.Length);
}
else {
CapiNative.UnsafeNativeMethods.CryptDecrypt(m_key,
SafeCapiHashHandle.InvalidHandle,
true,
0,
new IntPtr(pBuffer),
ref resetSize);
}
}
}
// Also erase the depadding buffer so we don't cross data from the previous message into this one
if (m_depadBuffer != null) {
Array.Clear(m_depadBuffer, 0, m_depadBuffer.Length);
m_depadBuffer = null;
}
}
/// <summary>
/// Encrypt or decrypt a single block of data
/// </summary>
[SecuritySafeCritical]
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
Contract.Ensures(Contract.Result<int>() >= 0);
if (inputBuffer == null) {
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException("inputOffset");
}
if (inputCount <= 0) {
throw new ArgumentOutOfRangeException("inputCount");
}
if (inputCount % InputBlockSize != 0) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_MustTransformWholeBlock));
}
if (inputCount > inputBuffer.Length - inputOffset) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
if (outputBuffer == null) {
throw new ArgumentNullException("outputBuffer");
}
if (inputCount > outputBuffer.Length - outputOffset) {
throw new ArgumentOutOfRangeException("outputOffset", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
if (m_encryptionMode == EncryptionMode.Encrypt) {
// CryptEncrypt operates in place, so make a copy of the original data in the output buffer for
// it to work on.
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
return EncryptBlocks(outputBuffer, outputOffset, inputCount);
}
else {
return DecryptBlocks(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
}
/// <summary>
/// Encrypt or decrypt the last block of data in the current message
/// </summary>
[SecuritySafeCritical]
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (inputBuffer == null) {
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0) {
throw new ArgumentOutOfRangeException("inputOffset");
}
if (inputCount < 0) {
throw new ArgumentOutOfRangeException("inputCount");
}
if (inputCount > inputBuffer.Length - inputOffset) {
throw new ArgumentOutOfRangeException("inputCount", SR.GetString(SR.Cryptography_TransformBeyondEndOfBuffer));
}
byte[] outputData = null;
if (m_encryptionMode == EncryptionMode.Encrypt) {
// If we're encrypting, we need to pad the last block before encrypting it
outputData = PadBlock(inputBuffer, inputOffset, inputCount);
if (outputData.Length > 0) {
EncryptBlocks(outputData, 0, outputData.Length);
}
}
else {
// We can't complete decryption on a partial block
if (inputCount % InputBlockSize != 0) {
throw new CryptographicException(SR.GetString(SR.Cryptography_PartialBlock));
}
//
// If we have a depad buffer, copy that into the decryption buffer followed by the input data.
// Otherwise the decryption buffer is just the input data.
//
byte[] ciphertext = null;
if (m_depadBuffer == null) {
ciphertext = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, 0, inputCount);
}
else {
ciphertext = new byte[m_depadBuffer.Length + inputCount];
Buffer.BlockCopy(m_depadBuffer, 0, ciphertext, 0, m_depadBuffer.Length);
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, m_depadBuffer.Length, inputCount);
}
// Decrypt the data, then strip the padding to get the final decrypted data.
if (ciphertext.Length > 0) {
int decryptedBytes = RawDecryptBlocks(ciphertext, 0, ciphertext.Length);
outputData = DepadBlock(ciphertext, 0, decryptedBytes);
}
else {
outputData = new byte[0];
}
}
Reset();
return outputData;
}
/// <summary>
/// Prepare the cryptographic key for use in the encryption / decryption operation
/// </summary>
[System.Security.SecurityCritical]
private static SafeCapiKeyHandle SetupKey(SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, int feedbackSize) {
Contract.Requires(key != null);
Contract.Requires(cipherMode == CipherMode.ECB || iv != null);
Contract.Requires(0 <= feedbackSize);
Contract.Ensures(Contract.Result<SafeCapiKeyHandle>() != null &&
!Contract.Result<SafeCapiKeyHandle>().IsInvalid &&
!Contract.Result<SafeCapiKeyHandle>().IsClosed);
// Make a copy of the key so that we don't modify the properties of the caller's copy
SafeCapiKeyHandle encryptionKey = key.Duplicate();
// Setup the cipher mode first
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.Mode, (int)cipherMode);
// If we're not in ECB mode then setup the IV
if (cipherMode != CipherMode.ECB) {
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.IV, iv);
}
// OFB and CFB require a feedback loop size
if (cipherMode == CipherMode.CFB || cipherMode == CipherMode.OFB) {
CapiNative.SetKeyParameter(encryptionKey, CapiNative.KeyParameter.ModeBits, feedbackSize);
}
return encryptionKey;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Composition.Runtime.Util;
using System.Linq;
namespace System.Composition.Hosting.Core
{
/// <summary>
/// The link between exports and imports.
/// </summary>
public sealed class CompositionContract
{
private readonly Type _contractType;
private readonly string _contractName;
private readonly IDictionary<string, object> _metadataConstraints;
/// <summary>
/// Construct a <see cref="CompositionContract"/>.
/// </summary>
/// <param name="contractType">The type shared between the exporter and importer.</param>
public CompositionContract(Type contractType)
: this(contractType, null)
{
}
/// <summary>
/// Construct a <see cref="CompositionContract"/>.
/// </summary>
/// <param name="contractType">The type shared between the exporter and importer.</param>
/// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param>
public CompositionContract(Type contractType, string contractName)
: this(contractType, contractName, null)
{
}
/// <summary>
/// Construct a <see cref="CompositionContract"/>.
/// </summary>
/// <param name="contractType">The type shared between the exporter and importer.</param>
/// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param>
/// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param>
public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints)
{
if (contractType == null) throw new ArgumentNullException(nameof(contractType));
if (metadataConstraints?.Count == 0) throw new ArgumentOutOfRangeException(nameof(metadataConstraints));
_contractType = contractType;
_contractName = contractName;
_metadataConstraints = metadataConstraints;
}
/// <summary>
/// The type shared between the exporter and importer.
/// </summary>
public Type ContractType => _contractType;
/// <summary>
/// A name that discriminates this contract from others with the same type.
/// </summary>
public string ContractName => _contractName;
/// <summary>
/// Constraints applied to the contract. Instead of using this collection
/// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method.
/// </summary>
public IEnumerable<KeyValuePair<string, object>> MetadataConstraints => _metadataConstraints;
/// <summary>
/// Determines equality between two contracts.
/// </summary>
/// <param name="obj">The contract to test.</param>
/// <returns>True if the contracts are equivalent; otherwise, false.</returns>
public override bool Equals(object obj)
{
var contract = obj as CompositionContract;
return contract != null &&
contract._contractType.Equals(_contractType) &&
(_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) &&
ConstraintEqual(_metadataConstraints, contract._metadataConstraints);
}
/// <summary>
/// Gets a hash code for the contract.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
var hc = _contractType.GetHashCode();
if (_contractName != null)
hc = hc ^ _contractName.GetHashCode();
if (_metadataConstraints != null)
hc = hc ^ ConstraintHashCode(_metadataConstraints);
return hc;
}
/// <summary>
/// Creates a string representation of the contract.
/// </summary>
/// <returns>A string representation of the contract.</returns>
public override string ToString()
{
var result = Formatters.Format(_contractType);
if (_contractName != null)
result += " " + Formatters.Format(_contractName);
if (_metadataConstraints != null)
result += string.Format(" {{ {0} }}",
string.Join(SR.Formatter_ListSeparatorWithSpace,
_metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value)))));
return result;
}
/// <summary>
/// Transform the contract into a matching contract with a
/// new contract type (with the same contract name and constraints).
/// </summary>
/// <param name="newContractType">The contract type for the new contract.</param>
/// <returns>A matching contract with a
/// new contract type.</returns>
public CompositionContract ChangeType(Type newContractType)
{
if (newContractType == null) throw new ArgumentNullException(nameof(newContractType));
return new CompositionContract(newContractType, _contractName, _metadataConstraints);
}
/// <summary>
/// Check the contract for a constraint with a particular name and value, and, if it exists,
/// retrieve both the value and the remainder of the contract with the constraint
/// removed.
/// </summary>
/// <typeparam name="T">The type of the constraint value.</typeparam>
/// <param name="constraintName">The name of the constraint.</param>
/// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param>
/// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param>
/// <returns>True if the constraint is present and of the correct type, otherwise false.</returns>
public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract)
{
if (constraintName == null) throw new ArgumentNullException(nameof(constraintName));
constraintValue = default(T);
remainingContract = null;
if (_metadataConstraints == null)
return false;
if (!_metadataConstraints.TryGetValue(constraintName, out object value))
return false;
if (!(value is T))
return false;
constraintValue = (T)value;
if (_metadataConstraints.Count == 1)
{
remainingContract = new CompositionContract(_contractType, _contractName);
}
else
{
var remainingConstraints = new Dictionary<string, object>(_metadataConstraints);
remainingConstraints.Remove(constraintName);
remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints);
}
return true;
}
internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second)
{
if (first == second)
return true;
if (first == null || second == null)
return false;
if (first.Count != second.Count)
return false;
foreach (KeyValuePair<string, object> firstItem in first)
{
if (!second.TryGetValue(firstItem.Key, out object secondValue))
return false;
if (firstItem.Value == null && secondValue != null ||
secondValue == null && firstItem.Value != null)
{
return false;
}
else
{
if (firstItem.Value is IEnumerable firstEnumerable && !(firstEnumerable is string))
{
var secondEnumerable = secondValue as IEnumerable;
if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>()))
return false;
}
else if (!firstItem.Value.Equals(secondValue))
{
return false;
}
}
}
return true;
}
private static int ConstraintHashCode(IDictionary<string, object> metadata)
{
var result = -1;
foreach (KeyValuePair<string, object> kv in metadata)
{
result ^= kv.Key.GetHashCode();
if (kv.Value != null)
{
if (kv.Value is string sval)
{
result ^= sval.GetHashCode();
}
else
{
if (kv.Value is IEnumerable enumerableValue)
{
foreach (var ev in enumerableValue)
if (ev != null)
result ^= ev.GetHashCode();
}
else
{
result ^= kv.Value.GetHashCode();
}
}
}
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security;
using System;
using System.Runtime.InteropServices; // For SafeHandle
[SecurityCritical]
public class MySafeValidHandle : SafeHandle
{
[SecurityCritical]
public MySafeValidHandle()
: base(IntPtr.Zero, true)
{
}
public MySafeValidHandle(IntPtr handleValue)
: base(IntPtr.Zero, true)
{
handle = handleValue;
}
public override bool IsInvalid
{
[SecurityCritical]
get { return false; }
}
public void DisposeWrap(bool dispose)
{
Dispose(dispose);
}
[SecurityCritical]
protected override bool ReleaseHandle()
{
return true;
}
}
[SecurityCritical]
public class MySafeInValidHandle : SafeHandle
{
[SecurityCritical]
public MySafeInValidHandle()
: base(IntPtr.Zero, true)
{
}
public MySafeInValidHandle(IntPtr handleValue)
: base(IntPtr.Zero, true)
{
handle = handleValue;
}
public override bool IsInvalid
{
[SecurityCritical]
get { return true; }
}
public void DisposeWrap(bool dispose)
{
Dispose(dispose);
}
[SecurityCritical]
protected override bool ReleaseHandle()
{
return true;
}
}
/// <summary>
/// Dispose(System.Boolean)
/// </summary>
public class SafeHandleDispose2
{
#region Public Methods
[SecuritySafeCritical]
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region Positive Test Cases
[SecuritySafeCritical]
public bool PosTest1()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("PosTest1: call Dispose on valid SafeHandle instance");
try
{
MySafeValidHandle handle = new MySafeValidHandle();
handle.DisposeWrap(true);
randValue = TestLibrary.Generator.GetInt32(-55);
handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool PosTest2()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("PosTest2: call Dispose on an invalid SafeHandle instance");
try
{
MySafeInValidHandle handle = new MySafeInValidHandle();
handle.DisposeWrap(true);
randValue = TestLibrary.Generator.GetInt32(-55);
handle = new MySafeInValidHandle(new IntPtr(randValue));
handle.DisposeWrap(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool PosTest3()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("PosTest3: call Dispose on valid SafeHandle instance with false");
try
{
MySafeValidHandle handle = new MySafeValidHandle();
handle.DisposeWrap(false);
randValue = TestLibrary.Generator.GetInt32(-55);
handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool PosTest4()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("PosTest4: call Dispose on an invalid SafeHandle instance with false");
try
{
MySafeInValidHandle handle = new MySafeInValidHandle();
handle.DisposeWrap(false);
randValue = TestLibrary.Generator.GetInt32(-55);
handle = new MySafeInValidHandle(new IntPtr(randValue));
handle.DisposeWrap(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Negative Test Cases
[SecuritySafeCritical]
public bool NegTest1()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("NegTest1: Call Dispose twice");
try
{
randValue = TestLibrary.Generator.GetInt32(-55);
MySafeValidHandle handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(true);
handle.DisposeWrap(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool NegTest2()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("NegTest2: Call Dispose twice");
try
{
randValue = TestLibrary.Generator.GetInt32(-55);
MySafeValidHandle handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(false);
handle.DisposeWrap(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool NegTest3()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("NegTest3: Call Dispose twice");
try
{
randValue = TestLibrary.Generator.GetInt32(-55);
MySafeValidHandle handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(true);
handle.DisposeWrap(true);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
[SecuritySafeCritical]
public bool NegTest4()
{
bool retVal = true;
int randValue = 0;
TestLibrary.TestFramework.BeginScenario("NegTest3: Call Dispose twice");
try
{
randValue = TestLibrary.Generator.GetInt32(-55);
MySafeValidHandle handle = new MySafeValidHandle(new IntPtr(randValue));
handle.DisposeWrap(false);
handle.DisposeWrap(false);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
[SecuritySafeCritical]
public static int Main()
{
SafeHandleDispose2 test = new SafeHandleDispose2();
TestLibrary.TestFramework.BeginTestCase("SafeHandleDispose2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToUInt64Vector128UInt64()
{
var test = new SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64
{
private struct TestStruct
{
public Vector128<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64 testClass)
{
var result = Sse2.X64.ConvertToUInt64(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimdScalarUnaryOpTest__DataTable<UInt64> _dataTable;
static SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimdScalarUnaryOpTest__DataTable<UInt64>(_data, LargestVectorSize);
}
public bool IsSupported => Sse2.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.X64.ConvertToUInt64(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.X64.ConvertToUInt64(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.X64.ConvertToUInt64(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToUInt64), new Type[] { typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
});
ValidateResult(_dataTable.inArrayPtr, (UInt64)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToUInt64), new Type[] { typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (UInt64)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToUInt64), new Type[] { typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (UInt64)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.X64.ConvertToUInt64(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Sse2.X64.ConvertToUInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.X64.ConvertToUInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Sse2.X64.ConvertToUInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimdScalarUnaryOpConvertTest__ConvertToUInt64Vector128UInt64();
var result = Sse2.X64.ConvertToUInt64(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.X64.ConvertToUInt64(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.X64.ConvertToUInt64(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, UInt64 result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
ValidateResult(inArray, result, method);
}
private void ValidateResult(void* firstOp, UInt64 result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray, result, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64 result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[0] != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2.X64)}.{nameof(Sse2.X64.ConvertToUInt64)}<UInt64>(Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: result");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Deploy;
using Umbraco.Cms.Infrastructure.Serialization;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.CoreThings
{
[TestFixture]
public class UdiTests
{
[SetUp]
public void SetUp() => UdiParser.ResetUdiTypes();
[Test]
public void StringUdiCtorTest()
{
var udi = new StringUdi(Constants.UdiEntityType.AnyString, "test-id");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
Assert.AreEqual("test-id", udi.Id);
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/test-id", udi.ToString());
}
[Test]
public void StringUdiParseTest()
{
Udi udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/test-id");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
Assert.IsInstanceOf<StringUdi>(udi);
var stringEntityId = udi as StringUdi;
Assert.IsNotNull(stringEntityId);
Assert.AreEqual("test-id", stringEntityId.Id);
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/test-id", udi.ToString());
udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/DA845952BE474EE9BD6F6194272AC750");
Assert.IsInstanceOf<StringUdi>(udi);
}
[Test]
public void StringEncodingTest()
{
// absolute path is unescaped
var uri = new Uri("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this is a test", uri.ToString());
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test", uri.AbsoluteUri);
Assert.AreEqual("/this%20is%20a%20test", uri.AbsolutePath);
Assert.AreEqual("/this is a test", Uri.UnescapeDataString(uri.AbsolutePath));
Assert.AreEqual("%2Fthis%20is%20a%20test", Uri.EscapeDataString("/this is a test"));
Assert.AreEqual("/this%20is%20a%20test", Uri.EscapeUriString("/this is a test"));
Udi udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
Assert.IsInstanceOf<StringUdi>(udi);
var stringEntityId = udi as StringUdi;
Assert.IsNotNull(stringEntityId);
Assert.AreEqual("this is a test", stringEntityId.Id);
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test", udi.ToString());
var udi2 = new StringUdi(Constants.UdiEntityType.AnyString, "this is a test");
Assert.AreEqual(udi, udi2);
var udi3 = new StringUdi(Constants.UdiEntityType.AnyString, "path to/this is a test.xyz");
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/path%20to/this%20is%20a%20test.xyz", udi3.ToString());
}
[Test]
public void StringEncodingTest2()
{
// reserved = : / ? # [ ] @ ! $ & ' ( ) * + , ; =
// unreserved = alpha digit - . _ ~
Assert.AreEqual("%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2B%2C%3B%3D.-_~%25", Uri.EscapeDataString(":/?#[]@!$&'()+,;=.-_~%"));
Assert.AreEqual(":/?#[]@!$&'()+,;=.-_~%25", Uri.EscapeUriString(":/?#[]@!$&'()+,;=.-_~%"));
// we cannot have reserved chars at random places
// we want to keep the / in string udis
var r = string.Join("/", "path/to/View[1].cshtml".Split('/').Select(Uri.EscapeDataString));
Assert.AreEqual("path/to/View%5B1%5D.cshtml", r);
Assert.IsTrue(Uri.IsWellFormedUriString("umb://partial-view-macro/" + r, UriKind.Absolute));
// with the proper fix in StringUdi this should work:
var udi1 = new StringUdi("partial-view-macro", "path/to/View[1].cshtml");
Assert.AreEqual("umb://partial-view-macro/path/to/View%5B1%5D.cshtml", udi1.ToString());
Udi udi2 = UdiParser.Parse("umb://partial-view-macro/path/to/View%5B1%5D.cshtml");
Assert.AreEqual("path/to/View[1].cshtml", ((StringUdi)udi2).Id);
}
[Test]
public void GuidUdiCtorTest()
{
var guid = Guid.NewGuid();
var udi = new GuidUdi(Constants.UdiEntityType.AnyGuid, guid);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.AreEqual(guid, udi.Guid);
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N"), udi.ToString());
}
[Test]
public void GuidUdiParseTest()
{
var guid = Guid.NewGuid();
var s = "umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N");
Udi udi = UdiParser.Parse(s);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.IsInstanceOf<GuidUdi>(udi);
var gudi = udi as GuidUdi;
Assert.IsNotNull(gudi);
Assert.AreEqual(guid, gudi.Guid);
Assert.AreEqual(s, udi.ToString());
}
[Test]
public void EqualityTest()
{
var guid1 = Guid.NewGuid();
var guid2 = Guid.NewGuid();
Assert.IsTrue(new GuidUdi("type", guid1).Equals(new GuidUdi("type", guid1)));
Assert.IsTrue(new GuidUdi("type", guid1) == new GuidUdi("type", guid1));
Assert.IsTrue(new GuidUdi("type", guid1).Equals(new GuidUdi("type", guid1)));
Assert.IsTrue(new GuidUdi("type", guid1) == new GuidUdi("type", guid1));
Assert.IsFalse(new GuidUdi("type", guid1).Equals(new GuidUdi("typex", guid1)));
Assert.IsFalse(new GuidUdi("type", guid1) == new GuidUdi("typex", guid1));
Assert.IsFalse(new GuidUdi("type", guid1).Equals(new GuidUdi("type", guid2)));
Assert.IsFalse(new GuidUdi("type", guid1) == new GuidUdi("type", guid2));
Assert.IsTrue(new GuidUdi("type", guid1).ToString() == new StringUdi("type", guid1.ToString("N")).ToString());
Assert.IsFalse(new GuidUdi("type", guid1) == new StringUdi("type", guid1.ToString("N")));
}
[Test]
public void DistinctTest()
{
var guid1 = Guid.NewGuid();
GuidUdi[] entities = new[]
{
new GuidUdi(Constants.UdiEntityType.AnyGuid, guid1),
new GuidUdi(Constants.UdiEntityType.AnyGuid, guid1),
new GuidUdi(Constants.UdiEntityType.AnyGuid, guid1),
};
Assert.AreEqual(1, entities.Distinct().Count());
}
[Test]
public void CreateTest()
{
var guid = Guid.NewGuid();
var udi = Udi.Create(Constants.UdiEntityType.AnyGuid, guid);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.AreEqual(guid, ((GuidUdi)udi).Guid);
// *not* testing whether Udi.Create(type, invalidValue) throws
// because we don't throw anymore - see U4-10409
}
[Test]
public void RootUdiTest()
{
var stringUdi = new StringUdi(Constants.UdiEntityType.AnyString, string.Empty);
Assert.IsTrue(stringUdi.IsRoot);
Assert.AreEqual("umb://any-string/", stringUdi.ToString());
var guidUdi = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.Empty);
Assert.IsTrue(guidUdi.IsRoot);
Assert.AreEqual("umb://any-guid/00000000000000000000000000000000", guidUdi.ToString());
Udi udi = UdiParser.Parse("umb://any-string/");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<StringUdi>(udi);
udi = UdiParser.Parse("umb://any-guid/00000000000000000000000000000000");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<GuidUdi>(udi);
udi = UdiParser.Parse("umb://any-guid/");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<GuidUdi>(udi);
}
[Test]
public void RangeTest()
{
// can parse open string udi
var stringUdiString = "umb://" + Constants.UdiEntityType.AnyString;
Assert.IsTrue(UdiParser.TryParse(stringUdiString, out Udi stringUdi));
Assert.AreEqual(string.Empty, ((StringUdi)stringUdi).Id);
// can parse open guid udi
var guidUdiString = "umb://" + Constants.UdiEntityType.AnyGuid;
Assert.IsTrue(UdiParser.TryParse(guidUdiString, out Udi guidUdi));
Assert.AreEqual(Guid.Empty, ((GuidUdi)guidUdi).Guid);
// can create a range
var range = new UdiRange(stringUdi, Constants.DeploySelector.ChildrenOfThis);
// cannot create invalid ranges
Assert.Throws<ArgumentException>(() => new UdiRange(guidUdi, "x"));
}
[Test]
public void SerializationTest()
{
var settings = new JsonSerializerSettings
{
Converters = new JsonConverter[] { new UdiJsonConverter(), new UdiRangeJsonConverter() }
};
var guid = Guid.NewGuid();
var udi = new GuidUdi(Constants.UdiEntityType.AnyGuid, guid);
var json = JsonConvert.SerializeObject(udi, settings);
Assert.AreEqual(string.Format("\"umb://any-guid/{0:N}\"", guid), json);
Udi dudi = JsonConvert.DeserializeObject<Udi>(json, settings);
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, dudi.EntityType);
Assert.AreEqual(guid, ((GuidUdi)dudi).Guid);
var range = new UdiRange(udi, Constants.DeploySelector.ChildrenOfThis);
json = JsonConvert.SerializeObject(range, settings);
Assert.AreEqual(string.Format("\"umb://any-guid/{0:N}?children\"", guid), json);
UdiRange drange = JsonConvert.DeserializeObject<UdiRange>(json, settings);
Assert.AreEqual(udi, drange.Udi);
Assert.AreEqual(string.Format("umb://any-guid/{0:N}", guid), drange.Udi.UriValue.ToString());
Assert.AreEqual(Constants.DeploySelector.ChildrenOfThis, drange.Selector);
}
[Test]
public void ValidateUdiEntityType()
{
Dictionary<string, UdiType> types = UdiParser.GetKnownUdiTypes();
foreach (FieldInfo fi in typeof(Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
{
// IsLiteral determines if its value is written at
// compile time and not changeable
// IsInitOnly determine if the field can be set
// in the body of the constructor
// for C# a field which is readonly keyword would have both true
// but a const field would have only IsLiteral equal to true
if (fi.IsLiteral && fi.IsInitOnly == false)
{
var value = fi.GetValue(null).ToString();
if (types.ContainsKey(value) == false)
{
Assert.Fail("Error in class Constants.UdiEntityType, type \"{0}\" is not declared by GetTypes.", value);
}
types.Remove(value);
}
}
Assert.AreEqual(0, types.Count, "Error in class Constants.UdiEntityType, GetTypes declares types that don't exist ({0}).", string.Join(",", types.Keys.Select(x => "\"" + x + "\"")));
}
[Test]
public void KnownTypes()
{
// cannot parse an unknown type, udi is null
// this will scan
Assert.IsFalse(UdiParser.TryParse("umb://whatever/1234", out Udi udi));
Assert.IsNull(udi);
UdiParser.ResetUdiTypes();
// unless we want to know
Assert.IsFalse(UdiParser.TryParse("umb://whatever/1234", true, out udi));
Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
Assert.AreEqual("Umbraco.Cms.Core.UnknownTypeUdi", udi.GetType().FullName);
UdiParser.ResetUdiTypes();
// not known
Assert.IsFalse(UdiParser.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
Assert.AreEqual("Umbraco.Cms.Core.UnknownTypeUdi", udi.GetType().FullName);
// scanned
UdiParserServiceConnectors.RegisterServiceConnector<FooConnector>(); // this is the equivalent of scanning but we'll just manually register this one
Assert.IsTrue(UdiParser.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", out udi));
Assert.IsInstanceOf<GuidUdi>(udi);
// known
Assert.IsTrue(UdiParser.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
Assert.IsInstanceOf<GuidUdi>(udi);
// can get method for Deploy compatibility
MethodInfo method = typeof(UdiParser).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(bool) }, null);
Assert.IsNotNull(method);
}
[UdiDefinition("foo", UdiType.GuidUdi)]
public class FooConnector : IServiceConnector
{
public IArtifact GetArtifact(Udi udi) => throw new NotImplementedException();
public IArtifact GetArtifact(object entity) => throw new NotImplementedException();
public ArtifactDeployState ProcessInit(IArtifact art, IDeployContext context) => throw new NotImplementedException();
public void Process(ArtifactDeployState dart, IDeployContext context, int pass) => throw new NotImplementedException();
public void Explode(UdiRange range, List<Udi> udis) => throw new NotImplementedException();
public NamedUdiRange GetRange(Udi udi, string selector) => throw new NotImplementedException();
public NamedUdiRange GetRange(string entityType, string sid, string selector) => throw new NotImplementedException();
public bool Compare(IArtifact art1, IArtifact art2, ICollection<Difference> differences = null) => throw new NotImplementedException();
}
}
}
| |
using UnityEngine;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class RoundScript : MonoBehaviour {
// Public
public string[] allowedLevels = { "pi_rah", "pi_jst", "pi_mar", "pi_ven", "pi_gho", "pi_set" };
private static int lastLevelPrefix = 0;
// Private
private const int roundDuration = 60 * 3;
private const int preRoundDuration = 5;
private const int postRoundDuration = 15;
private const int roundPerLevel = 2;
private const int readyDuration = 5;
float roundTime;
public bool roundStopped { get; private set; }
public string currentLevel;
int roundsRemaining;
// Time events
private delegate void roundTimeCB(float time);
private static Dictionary<float, roundTimeCB> roundTimeEvents = null;
public static RoundScript Instance { get; private set; }
// Unity Functions
//!? CLIENT & SERVER
void Awake() {
Instance = this;
roundsRemaining = roundPerLevel;
networkView.group = 1;
}
//!? CLIENT & SERVER
void Update() {
if (Network.isServer) {
//Increment round time
roundTime += Time.deltaTime;
//Trigger round events
handleTimeEvents(roundTime);
}
}
IEnumerator OnPlayerConnected(NetworkPlayer player) {
// If the first player connects, notify and wait a couple second then restart
if (Network.connections.Length == 1) {
yield return 0;
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Another player has joined", true, true);
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Starting round in 5 seconds", true, true);
yield return new WaitForSeconds(readyDuration);
//NetworkSync.afterSync("OnLevelWasLoaded", () => {
RestartRound();
//});
}
}
// Time Events
//? SERVER ONLY
void handleTimeEvents(float time) {
if (roundTimeEvents == null) {
return;
}
Dictionary<float, roundTimeCB> triggeredEvents = new Dictionary<float, roundTimeCB>();
foreach (KeyValuePair<float, roundTimeCB> pair in roundTimeEvents) {
// Time for the event is now or has passed
if (time >= pair.Key) {
// Since we cannot alter a list we are currently iterating on, copy it over
triggeredEvents.Add(pair.Key, pair.Value);
}
}
foreach (KeyValuePair<float, roundTimeCB> pair in triggeredEvents) {
// Even has triggered, remove from list
roundTimeEvents.Remove(pair.Key);
// Run event
pair.Value(time);
}
}
//? SERVER ONLY
void setTimeEvents_DeathMatch() {
roundTimeEvents = new Dictionary<float, roundTimeCB>();
roundTimeEvents.Add(roundDuration - 60, (time) => announceTimeLeft(60));
roundTimeEvents.Add(roundDuration - 30, (time) => announceTimeLeft(30));
roundTimeEvents.Add(roundDuration - 10, (time) => announceTimeLeft(10));
roundTimeEvents.Add(roundDuration, (time) => postRound());
roundTimeEvents.Add(roundDuration + postRoundDuration, (time) => endRound(preRoundDuration));
roundTimeEvents.Add(roundDuration + postRoundDuration + preRoundDuration, (time) => changeRound());
}
//? SERVER ONLY
void announceTimeLeft(int time) {
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, time.ToString() + " seconds remaining...", true, true);
}
//? SERVER ONLY
void postRound() {
// Stop the round
networkView.RPC("setRoundStopped", RPCMode.All, true);
roundsRemaining--;
// Pause all players that have a player object
foreach (KeyValuePair<NetworkPlayer, PlayerRegistry.PlayerInfo> pair in PlayerRegistry.All()) {
PlayerScript player = pair.Value.Player;
if (player != null) {
player.networkView.RPC("setPaused", RPCMode.All, true);
}
}
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Round over!", true, true);
// Was this the last round on this map? announce change
if (roundsRemaining <= 0) {
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Level will change on the next round", true, true);
}
}
//? SERVER ONLY
void endRound(int timeout) {
if (roundsRemaining <= 0) {
// Have the players change level
ChangeLevelAndRestart(getRandomMap());
}
// Announce new round
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Starting game in " + timeout + " seconds!", true, true);
}
//? SERVER ONLY
void changeRound() {
RestartRound();
ChatScript.Instance.networkView.RPC("LogChat", RPCMode.All, Network.player, "Game start!", true, true);
}
//? SERVER ONLY
public void RestartRound() {
// Sync on players registered
NetworkSync.createSync("RegisterPlayer");
// Make sure every user has a player
SpawnScript.Instance.networkView.RPC("CreatePlayer", RPCMode.All);
// Wait until all players have synced their registry
NetworkSync.afterSync("RegisterPlayer", () => {
foreach (KeyValuePair<NetworkPlayer, PlayerRegistry.PlayerInfo> pair in PlayerRegistry.All()) {
PlayerScript player = pair.Value.Player;
// Respawn own player and unpause
// TODO setting a player to spectator mode should resolve check itself on spawn
if (!pair.Value.Spectating) {
player.networkView.RPC("ImmediateRespawn", RPCMode.All);
}
player.networkView.RPC("setPaused", RPCMode.All, false);
}
// Clean leaderboard
NetworkLeaderboard.instance.networkView.RPC("resetLeaderboard", RPCMode.All);
// Start round
networkView.RPC("setRoundStopped", RPCMode.All, false);
// Reset time events
roundTime = 0;
setTimeEvents_DeathMatch();
});
}
// Remote Protocol Calls
//!? CLIENT & SERVER
[RPC]
public void setRoundStopped(bool stopped) {
roundStopped = stopped;
}
//!? CLIENT & SERVER
[RPC]
private void ChangeLevelAndRestartRPC(string toLevelName, int levelPrefix) {
roundsRemaining = roundPerLevel;
ChangeLevel(toLevelName, levelPrefix);
}
// Map loading
//? SERVER ONLY
public void ChangeLevelAndRestart(string toLevelName) {
// Destroy all old calls
Network.RemoveRPCsInGroup(1);
Network.RemoveRPCsInGroup(0);
// Create a sync to ensure a sync when all levels are loaded
NetworkSync.createSync("OnLevelWasLoaded");
networkView.RPC("ChangeLevelAndRestartRPC", RPCMode.AllBuffered, toLevelName, lastLevelPrefix + 1);
}
// Server picks new map and loads
//? SERVER ONLY
public string getRandomMap() {
return RandomHelper.InEnumerable(allowedLevels.Except(new[] { RoundScript.Instance.currentLevel }));
}
// Load new map
//!? CLIENT & SERVER
public void ChangeLevel(string newLevel, int levelPrefix) {
// Use a new prefix for the next level
lastLevelPrefix = levelPrefix;
// Clean the player register, it will be rebuild when the level is loaded
PlayerRegistry.Clear();
// Disable sending
// Stop recieving
// Move to new level prefix
Network.SetSendingEnabled(0, false);
Network.isMessageQueueRunning = false;
Network.SetLevelPrefix(levelPrefix);
// Load the actual level
Application.LoadLevel(newLevel);
}
//!? CLIENT & SERVER
void OnLevelWasLoaded(int id) {
// Turn networking back on
Network.isMessageQueueRunning = true;
Network.SetSendingEnabled(0, true);
// Notify and change
ChatScript.Instance.LogChat(Network.player, "Changed level to " + Application.loadedLevelName, true, true);
RoundScript.Instance.currentLevel = Application.loadedLevelName;
ServerScript.Instance.SetMap(RoundScript.Instance.currentLevel);
// If we are playing, build the player again, register and restart
if (Network.peerType != NetworkPeerType.Disconnected) {
if (Network.isServer) {
NetworkSync.afterSync("OnLevelWasLoaded", () => {
RestartRound();
});
} else {
NetworkSync.sync("OnLevelWasLoaded");
}
}
}
}
| |
//
// 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.Net.Http;
using Microsoft.Azure.Management.Authorization;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
namespace Microsoft.Azure.Management.Authorization
{
public partial class AuthorizationManagementClient : ServiceClient<AuthorizationManagementClient>, IAuthorizationManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IPermissionOperations _permissions;
/// <summary>
/// Get resource or resource group permissions (see http://TBD for
/// more information)
/// </summary>
public virtual IPermissionOperations Permissions
{
get { return this._permissions; }
}
private IRoleAssignmentOperations _roleAssignments;
/// <summary>
/// TBD (see http://TBD for more information)
/// </summary>
public virtual IRoleAssignmentOperations RoleAssignments
{
get { return this._roleAssignments; }
}
private IRoleDefinitionOperations _roleDefinitions;
/// <summary>
/// TBD (see http://TBD for more information)
/// </summary>
public virtual IRoleDefinitionOperations RoleDefinitions
{
get { return this._roleDefinitions; }
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
private AuthorizationManagementClient()
: base()
{
this._permissions = new PermissionOperations(this);
this._roleAssignments = new RoleAssignmentOperations(this);
this._roleDefinitions = new RoleDefinitionOperations(this);
this._apiVersion = "2014-07-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private AuthorizationManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._permissions = new PermissionOperations(this);
this._roleAssignments = new RoleAssignmentOperations(this);
this._roleDefinitions = new RoleDefinitionOperations(this);
this._apiVersion = "2014-07-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AuthorizationManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of AuthorizationManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<AuthorizationManagementClient> client)
{
base.Clone(client);
if (client is AuthorizationManagementClient)
{
AuthorizationManagementClient clonedClient = ((AuthorizationManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
/// <summary> <p>Abstract class representing the result of decoding a barcode, as more than
/// a String -- as some type of structured data. This might be a subclass which represents
/// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
/// decoded string into the most appropriate type of structured representation.</p>
///
/// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
/// on exception-based mechanisms during parsing.</p>
/// </summary>
/// <author>Sean Owen</author>
public abstract class ResultParser
{
private static readonly ResultParser[] PARSERS =
{
new BookmarkDoCoMoResultParser(),
new AddressBookDoCoMoResultParser(),
new EmailDoCoMoResultParser(),
new AddressBookAUResultParser(),
new VCardResultParser(),
new BizcardResultParser(),
new VEventResultParser(),
new EmailAddressResultParser(),
new SMTPResultParser(),
new TelResultParser(),
new SMSMMSResultParser(),
new SMSTOMMSTOResultParser(),
new GeoResultParser(),
new WifiResultParser(),
new URLTOResultParser(),
new URIResultParser(),
new ISBNResultParser(),
new ProductResultParser(),
new ExpandedProductResultParser(),
new VINResultParser(),
};
#if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z");
private static readonly Regex AMPERSAND = new Regex("&");
private static readonly Regex EQUALS = new Regex("=");
#else
private static readonly Regex DIGITS = new Regex(@"\A(?:" + "\\d+" + @")\z", RegexOptions.Compiled);
private static readonly Regex AMPERSAND = new Regex("&", RegexOptions.Compiled);
private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled);
#endif
/// <summary>
/// Attempts to parse the raw {@link Result}'s contents as a particular type
/// of information (email, URL, etc.) and return a {@link ParsedResult} encapsulating
/// the result of parsing.
/// </summary>
/// <param name="theResult">the raw <see cref="Result"/> to parse</param>
/// <returns><see cref="ParsedResult" /> encapsulating the parsing result</returns>
public abstract ParsedResult parse(ZXing.Result theResult);
/// <summary>
/// Parses the result.
/// </summary>
/// <param name="theResult">The result.</param>
/// <returns></returns>
public static ParsedResult parseResult(ZXing.Result theResult)
{
foreach (var parser in PARSERS)
{
var result = parser.parse(theResult);
if (result != null)
{
return result;
}
}
return new TextParsedResult(theResult.Text, null);
}
protected static void maybeAppend(String value, System.Text.StringBuilder result)
{
if (value != null)
{
result.Append('\n');
result.Append(value);
}
}
protected static void maybeAppend(String[] value, System.Text.StringBuilder result)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
result.Append('\n');
result.Append(value[i]);
}
}
}
protected static String[] maybeWrap(String value)
{
return value == null ? null : new[] { value };
}
protected static String unescapeBackslash(String escaped)
{
if (escaped != null)
{
int backslash = escaped.IndexOf('\\');
if (backslash >= 0)
{
int max = escaped.Length;
var unescaped = new System.Text.StringBuilder(max - 1);
unescaped.Append(escaped.ToCharArray(), 0, backslash);
bool nextIsEscaped = false;
for (int i = backslash; i < max; i++)
{
char c = escaped[i];
if (nextIsEscaped || c != '\\')
{
unescaped.Append(c);
nextIsEscaped = false;
}
else
{
nextIsEscaped = true;
}
}
return unescaped.ToString();
}
}
return escaped;
}
protected static int parseHexDigit(char c)
{
if (c >= 'a')
{
if (c <= 'f')
{
return 10 + (c - 'a');
}
}
else if (c >= 'A')
{
if (c <= 'F')
{
return 10 + (c - 'A');
}
}
else if (c >= '0')
{
if (c <= '9')
{
return c - '0';
}
}
return -1;
}
internal static bool isStringOfDigits(String value, int length)
{
return value != null && length > 0 && length == value.Length && DIGITS.Match(value).Success;
}
internal static bool isSubstringOfDigits(String value, int offset, int length)
{
if (value == null || length <= 0)
{
return false;
}
int max = offset + length;
return value.Length >= max && DIGITS.Match(value, offset, length).Success;
}
internal static IDictionary<string, string> parseNameValuePairs(String uri)
{
int paramStart = uri.IndexOf('?');
if (paramStart < 0)
{
return null;
}
var result = new Dictionary<String, String>(3);
foreach (var keyValue in AMPERSAND.Split(uri.Substring(paramStart + 1)))
{
appendKeyValue(keyValue, result);
}
return result;
}
private static void appendKeyValue(String keyValue, IDictionary<String, String> result)
{
String[] keyValueTokens = EQUALS.Split(keyValue, 2);
if (keyValueTokens.Length == 2)
{
String key = keyValueTokens[0];
String value = keyValueTokens[1];
try
{
//value = URLDecoder.decode(value, "UTF-8");
value = urlDecode(value);
result[key] = value;
}
catch (Exception uee)
{
throw new InvalidOperationException("url decoding failed", uee); // can't happen
}
result[key] = value;
}
}
internal static String[] matchPrefixedField(String prefix, String rawText, char endChar, bool trim)
{
IList<string> matches = null;
int i = 0;
int max = rawText.Length;
while (i < max)
{
i = rawText.IndexOf(prefix, i);
if (i < 0)
{
break;
}
i += prefix.Length; // Skip past this prefix we found to start
int start = i; // Found the start of a match here
bool done = false;
while (!done)
{
i = rawText.IndexOf(endChar, i);
if (i < 0)
{
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.Length;
done = true;
}
else if (countPrecedingBackslashes(rawText, i)%2 != 0)
{
// semicolon was escaped (odd count of preceding backslashes) so continue
i++;
}
else
{
// found a match
if (matches == null)
{
matches = new List<string>();
}
String element = unescapeBackslash(rawText.Substring(start, (i) - (start)));
if (trim)
{
element = element.Trim();
}
if (!String.IsNullOrEmpty(element))
{
matches.Add(element);
}
i++;
done = true;
}
}
}
if (matches == null || (matches.Count == 0))
{
return null;
}
return SupportClass.toStringArray(matches);
}
private static int countPrecedingBackslashes(String s, int pos)
{
int count = 0;
for (int i = pos - 1; i >= 0; i--)
{
if (s[i] == '\\')
{
count++;
}
else
{
break;
}
}
return count;
}
internal static String matchSinglePrefixedField(String prefix, String rawText, char endChar, bool trim)
{
String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
return matches == null ? null : matches[0];
}
protected static String urlDecode(String escaped)
{
// Should we better use HttpUtility.UrlDecode?
// Is HttpUtility.UrlDecode available for all platforms?
// What about encoding like UTF8?
if (escaped == null)
{
return null;
}
char[] escapedArray = escaped.ToCharArray();
int first = findFirstEscape(escapedArray);
if (first < 0)
{
return escaped;
}
int max = escapedArray.Length;
// final length is at most 2 less than original due to at least 1 unescaping
var unescaped = new System.Text.StringBuilder(max - 2);
// Can append everything up to first escape character
unescaped.Append(escapedArray, 0, first);
for (int i = first; i < max; i++)
{
char c = escapedArray[i];
if (c == '+')
{
// + is translated directly into a space
unescaped.Append(' ');
}
else if (c == '%')
{
// Are there even two more chars? if not we will just copy the escaped sequence and be done
if (i >= max - 2)
{
unescaped.Append('%'); // append that % and move on
}
else
{
int firstDigitValue = parseHexDigit(escapedArray[++i]);
int secondDigitValue = parseHexDigit(escapedArray[++i]);
if (firstDigitValue < 0 || secondDigitValue < 0)
{
// bad digit, just move on
unescaped.Append('%');
unescaped.Append(escapedArray[i - 1]);
unescaped.Append(escapedArray[i]);
}
unescaped.Append((char) ((firstDigitValue << 4) + secondDigitValue));
}
}
else
{
unescaped.Append(c);
}
}
return unescaped.ToString();
}
private static int findFirstEscape(char[] escapedArray)
{
int max = escapedArray.Length;
for (int i = 0; i < max; i++)
{
char c = escapedArray[i];
if (c == '+' || c == '%')
{
return i;
}
}
return -1;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.DotNet.CodeFormatting
{
[Export(typeof(IFormattingEngine))]
internal sealed class FormattingEngineImplementation : IFormattingEngine
{
/// <summary>
/// Developers who want to opt out of the code formatter for items like unicode
/// tables can surround them with #if !DOTNET_FORMATTER.
/// </summary>
internal const string TablePreprocessorSymbolName = "DOTNET_FORMATTER";
private readonly Options _options;
private readonly IEnumerable<IFormattingFilter> _filters;
private readonly IEnumerable<Lazy<ISyntaxFormattingRule, IRuleMetadata>> _syntaxRules;
private readonly IEnumerable<Lazy<ILocalSemanticFormattingRule, IRuleMetadata>> _localSemanticRules;
private readonly IEnumerable<Lazy<IGlobalSemanticFormattingRule, IRuleMetadata>> _globalSemanticRules;
private readonly Stopwatch _watch = new Stopwatch();
private readonly Dictionary<string, bool> _ruleMap = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private bool _allowTables;
private bool _verbose;
public ImmutableArray<string> CopyrightHeader
{
get { return _options.CopyrightHeader; }
set { _options.CopyrightHeader = value; }
}
public ImmutableArray<string[]> PreprocessorConfigurations
{
get { return _options.PreprocessorConfigurations; }
set { _options.PreprocessorConfigurations = value; }
}
public ImmutableArray<string> FileNames
{
get { return _options.FileNames; }
set { _options.FileNames = value; }
}
public IFormatLogger FormatLogger
{
get { return _options.FormatLogger; }
set { _options.FormatLogger = value; }
}
public bool AllowTables
{
get { return _allowTables; }
set { _allowTables = value; }
}
public bool Verbose
{
get { return _verbose; }
set { _verbose = value; }
}
public ImmutableArray<IRuleMetadata> AllRules
{
get
{
var list = new List<IRuleMetadata>();
list.AddRange(_syntaxRules.Select(x => x.Metadata));
list.AddRange(_localSemanticRules.Select(x => x.Metadata));
list.AddRange(_globalSemanticRules.Select(x => x.Metadata));
return list.ToImmutableArray();
}
}
[ImportingConstructor]
internal FormattingEngineImplementation(
Options options,
[ImportMany] IEnumerable<IFormattingFilter> filters,
[ImportMany] IEnumerable<Lazy<ISyntaxFormattingRule, IRuleMetadata>> syntaxRules,
[ImportMany] IEnumerable<Lazy<ILocalSemanticFormattingRule, IRuleMetadata>> localSemanticRules,
[ImportMany] IEnumerable<Lazy<IGlobalSemanticFormattingRule, IRuleMetadata>> globalSemanticRules)
{
_options = options;
_filters = filters;
_syntaxRules = syntaxRules;
_localSemanticRules = localSemanticRules;
_globalSemanticRules = globalSemanticRules;
foreach (var rule in AllRules)
{
_ruleMap[rule.Name] = rule.DefaultRule;
}
}
private IEnumerable<TRule> GetOrderedRules<TRule>(IEnumerable<Lazy<TRule, IRuleMetadata>> rules)
where TRule : IFormattingRule
{
return rules
.OrderBy(r => r.Metadata.Order)
.Where(r => _ruleMap[r.Metadata.Name])
.Select(r => r.Value)
.ToList();
}
public Task FormatSolutionAsync(Solution solution, CancellationToken cancellationToken)
{
var documentIds = solution.Projects.SelectMany(x => x.DocumentIds).ToList();
return FormatAsync(solution.Workspace, documentIds, cancellationToken);
}
public Task FormatProjectAsync(Project project, CancellationToken cancellationToken)
{
return FormatAsync(project.Solution.Workspace, project.DocumentIds, cancellationToken);
}
public void ToggleRuleEnabled(IRuleMetadata ruleMetaData, bool enabled)
{
_ruleMap[ruleMetaData.Name] = enabled;
}
private async Task FormatAsync(Workspace workspace, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var watch = new Stopwatch();
watch.Start();
var originalSolution = workspace.CurrentSolution;
var solution = await FormatCoreAsync(originalSolution, documentIds, cancellationToken);
watch.Stop();
if (!workspace.TryApplyChanges(solution))
{
FormatLogger.WriteErrorLine("Unable to save changes to disk");
}
FormatLogger.WriteLine("Total time {0}", watch.Elapsed);
}
private Solution AddTablePreprocessorSymbol(Solution solution)
{
var projectIds = solution.ProjectIds;
foreach (var projectId in projectIds)
{
var project = solution.GetProject(projectId);
var parseOptions = project.ParseOptions as CSharpParseOptions;
if (parseOptions != null)
{
var list = new List<string>();
list.AddRange(parseOptions.PreprocessorSymbolNames);
list.Add(TablePreprocessorSymbolName);
parseOptions = parseOptions.WithPreprocessorSymbols(list);
solution = project.WithParseOptions(parseOptions).Solution;
}
}
return solution;
}
/// <summary>
/// Remove the added table preprocessor symbol. Don't want that saved into the project
/// file as a change.
/// </summary>
private Solution RemoveTablePreprocessorSymbol(Solution newSolution, Solution oldSolution)
{
var projectIds = newSolution.ProjectIds;
foreach (var projectId in projectIds)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
newSolution = newProject.WithParseOptions(oldProject.ParseOptions).Solution;
}
return newSolution;
}
internal async Task<Solution> FormatCoreAsync(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var solution = originalSolution;
if (_allowTables)
{
solution = AddTablePreprocessorSymbol(originalSolution);
}
solution = await RunSyntaxPass(solution, documentIds, cancellationToken);
solution = await RunLocalSemanticPass(solution, documentIds, cancellationToken);
solution = await RunGlobalSemanticPass(solution, documentIds, cancellationToken);
if (_allowTables)
{
solution = RemoveTablePreprocessorSymbol(solution, originalSolution);
}
return solution;
}
private bool ShouldBeProcessed(Document document)
{
foreach (var filter in _filters)
{
var shouldBeProcessed = filter.ShouldBeProcessed(document);
if (!shouldBeProcessed)
return false;
}
return true;
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(Document document, CancellationToken cancellationToken)
{
if (!ShouldBeProcessed(document))
{
return Task.FromResult<SyntaxNode>(null);
}
return document.GetSyntaxRootAsync(cancellationToken);
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken)
{
if (!formattingRule.SupportsLanguage(document.Project.Language))
{
return Task.FromResult<SyntaxNode>(null);
}
return GetSyntaxRootAndFilter(document, cancellationToken);
}
private void StartDocument()
{
_watch.Restart();
}
private void EndDocument(Document document)
{
_watch.Stop();
if (_verbose)
{
FormatLogger.WriteLine(" {0} {1} seconds", document.Name, _watch.Elapsed.TotalSeconds);
}
}
/// <summary>
/// Semantics is not involved in this pass at all. It is just a straight modification of the
/// parse tree so there are no issues about ensuring the version of <see cref="SemanticModel"/> and
/// the <see cref="SyntaxNode"/> line up. Hence we do this by iteraning every <see cref="Document"/>
/// and processing all rules against them at once
/// </summary>
private async Task<Solution> RunSyntaxPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tSyntax Pass");
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = RunSyntaxPass(syntaxRoot, document.Project.Language);
EndDocument(document);
if (newRoot != syntaxRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot);
}
}
return currentSolution;
}
private SyntaxNode RunSyntaxPass(SyntaxNode root, string languageName)
{
foreach (var rule in GetOrderedRules(_syntaxRules))
{
if (rule.SupportsLanguage(languageName))
{
root = rule.Process(root, languageName);
}
}
return root;
}
private async Task<Solution> RunLocalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tLocal Semantic Pass");
foreach (var localSemanticRule in GetOrderedRules(_localSemanticRules))
{
solution = await RunLocalSemanticPass(solution, documentIds, localSemanticRule, cancellationToken);
}
return solution;
}
private async Task<Solution> RunLocalSemanticPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, ILocalSemanticFormattingRule localSemanticRule, CancellationToken cancellationToken)
{
if (_verbose)
{
FormatLogger.WriteLine(" {0}", localSemanticRule.GetType().Name);
}
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(localSemanticRule, document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = await localSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken);
EndDocument(document);
if (syntaxRoot != newRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(documentId, newRoot);
}
}
return currentSolution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tGlobal Semantic Pass");
foreach (var globalSemanticRule in GetOrderedRules(_globalSemanticRules))
{
solution = await RunGlobalSemanticPass(solution, documentIds, globalSemanticRule, cancellationToken);
}
return solution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, IGlobalSemanticFormattingRule globalSemanticRule, CancellationToken cancellationToken)
{
if (_verbose)
{
FormatLogger.WriteLine(" {0}", globalSemanticRule.GetType().Name);
}
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(globalSemanticRule, document, cancellationToken);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
solution = await globalSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken);
EndDocument(document);
}
return solution;
}
}
}
| |
using UnityEngine;
using Pathfinding;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/GraphUpdateScene")]
/** Helper class for easily updating graphs.
The GraphUpdateScene component is really easy to use. Create a new empty GameObject and add the component to it, it can be found in Components-->Pathfinding-->GraphUpdateScene.\n
When you have added the component, you should see something like the image below.
\shadowimage{graphUpdateScene.png}
The area which the component will affect is defined by creating a polygon in the scene.
If you make sure you have the Position tool enabled (top-left corner of the Unity window) you can shift-click in the scene view to add more points to the polygon.
You can remove points using shift-alt-click. By clicking on the points you can bring up a positioning tool. You can also open the "points" array in the inspector to set each point's coordinates.
\shadowimage{graphUpdateScenePoly.png}
In the inspector there are a number of variables. The first one is named "Convex", it sets if the convex hull of the points should be calculated or if the polygon should be used as-is.
Using the convex hull is faster when applying the changes to the graph, but with a non-convex polygon you can specify more complicated areas.\n
The next two variables, called "Apply On Start" and "Apply On Scan" determine when to apply the changes. If the object is in the scene from the beginning, both can be left on, it doesn't
matter since the graph is also scanned at start. However if you instantiate it later in the game, you can make it apply it's setting directly, or wait until the next scan (if any).
If the graph is rescanned, all GraphUpdateScene components which have the Apply On Scan variable toggled will apply their settings again to the graph since rescanning clears all previous changes.\n
You can also make it apply it's changes using scripting.
\code GetComponent<GraphUpdateScene>().Apply (); \endcode
The above code will make it apply it's changes to the graph (assuming a GraphUpdateScene component is attached to the same GameObject).
Next there is "Modify Walkability" and "Set Walkability" (which appears when "Modify Walkability" is toggled).
If Modify Walkability is set, then all nodes inside the area will either be set to walkable or unwalkable depending on the value of the "Set Walkability" variable.
Penalty can also be applied to the nodes. A higher penalty (aka weight) makes the nodes harder to traverse so it will try to avoid those areas.
The tagging variables can be read more about on this page: \ref tags "Working with tags".
*/
public class GraphUpdateScene : GraphModifier {
/** Points which define the region to update */
public Vector3[] points;
/** Private cached convex hull of the #points */
private Vector3[] convexPoints;
[HideInInspector]
/** Use the convex hull (XZ space) of the points. */
public bool convex = true;
[HideInInspector]
/** Minumum height of the bounds of the resulting Graph Update Object.
* Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a
* zero height graph update object would usually result in no nodes being updated.
*/
public float minBoundsHeight = 1;
[HideInInspector]
/** Penalty to add to nodes.
* Be careful when setting negative values since if a node get's a negative penalty it will underflow and instead get
* really large. In most cases a warning will be logged if that happens.
*/
public int penaltyDelta;
[HideInInspector]
/** Set to true to set all targeted nodese walkability to #setWalkability */
public bool modifyWalkability;
[HideInInspector]
/** See #modifyWalkability */
public bool setWalkability;
[HideInInspector]
/** Apply this graph update object on start */
public bool applyOnStart = true;
[HideInInspector]
/** Apply this graph update object whenever a graph is rescanned */
public bool applyOnScan = true;
/** Use world space for coordinates.
* If true, the shape will not follow when moving around the transform.
*
* \see #ToggleUseWorldSpace
*/
[HideInInspector]
public bool useWorldSpace;
/** Update node's walkability and connectivity using physics functions.
* For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph.
* If enabled for grid graphs, #modifyWalkability will be ignored.
*
* For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object
* using raycasts (if enabled).
*
*/
[HideInInspector]
public bool updatePhysics;
/** \copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics */
[HideInInspector]
public bool resetPenaltyOnPhysics = true;
/** \copydoc Pathfinding::GraphUpdateObject::updateErosion */
[HideInInspector]
public bool updateErosion = true;
[HideInInspector]
/** Lock all points to Y = #lockToYValue */
public bool lockToY;
[HideInInspector]
/** if #lockToY is enabled lock all points to this value */
public float lockToYValue;
[HideInInspector]
/** If enabled, set all nodes' tags to #setTag */
public bool modifyTag;
[HideInInspector]
/** If #modifyTag is enabled, set all nodes' tags to this value */
public int setTag;
/** Private cached inversion of #setTag.
* Used for InvertSettings() */
private int setTagInvert;
/** Has apply been called yet.
* Used to prevent applying twice when both applyOnScan and applyOnStart are enabled */
private bool firstApplied;
/** Do some stuff at start */
public void Start () {
//If firstApplied is true, that means the graph was scanned during Awake.
//So we shouldn't apply it again because then we would end up applying it two times
if (!firstApplied && applyOnStart) {
Apply ();
}
}
public override void OnPostScan () {
if (applyOnScan) Apply ();
}
/** Inverts all invertable settings for this GUS.
* Namely: penalty delta, walkability, tags.
*
* Penalty delta will be changed to negative penalty delta.\n
* #setWalkability will be inverted.\n
* #setTag will be stored in a private variable, and the new value will be 0. When calling this function again, the saved
* value will be the new value.
*
* Calling this function an even number of times without changing any settings in between will be identical to no change in settings.
*/
public virtual void InvertSettings () {
setWalkability = !setWalkability;
penaltyDelta = -penaltyDelta;
if (setTagInvert == 0) {
setTagInvert = setTag;
setTag = 0;
} else {
setTag = setTagInvert;
setTagInvert = 0;
}
}
/** Recalculate convex points.
* Will not do anything if not #convex is enabled
*/
public void RecalcConvex () {
convexPoints = convex ? Polygon.ConvexHull (points) : null;
}
/** Switches between using world space and using local space.
* Changes point coordinates to stay the same in world space after the change.
*
* \see #useWorldSpace
*/
public void ToggleUseWorldSpace () {
useWorldSpace = !useWorldSpace;
if (points == null) return;
convexPoints = null;
Matrix4x4 matrix = useWorldSpace ? transform.localToWorldMatrix : transform.worldToLocalMatrix;
for (int i=0;i<points.Length;i++) {
points[i] = matrix.MultiplyPoint3x4 (points[i]);
}
}
/** Lock all points to a specific Y value.
*
* \see lockToYValue
*/
public void LockToY () {
if (points == null) return;
for (int i=0;i<points.Length;i++)
points[i].y = lockToYValue;
}
/** Apply the update.
* Will only do anything if #applyOnScan is enabled */
public void Apply (AstarPath active) {
if (applyOnScan) {
Apply ();
}
}
/** Calculates the bounds for this component.
* This is a relatively expensive operation, it needs to go through all points and
* sometimes do matrix multiplications.
*/
public Bounds GetBounds () {
Bounds b;
if (points == null || points.Length == 0) {
var coll = GetComponent<Collider>();
var rend = GetComponent<Renderer>();
if (coll != null) b = coll.bounds;
else if (rend != null) b = rend.bounds;
else {
//Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached");
return new Bounds(Vector3.zero, Vector3.zero);
}
} else {
Matrix4x4 matrix = Matrix4x4.identity;
if (!useWorldSpace) {
matrix = transform.localToWorldMatrix;
}
Vector3 min = matrix.MultiplyPoint3x4(points[0]);
Vector3 max = matrix.MultiplyPoint3x4(points[0]);
for (int i=0;i<points.Length;i++) {
Vector3 p = matrix.MultiplyPoint3x4(points[i]);
min = Vector3.Min (min,p);
max = Vector3.Max (max,p);
}
b = new Bounds ((min+max)*0.5F,max-min);
}
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
return b;
}
/** Updates graphs with a created GUO.
* Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
* representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
* This will not update graphs directly. See AstarPath.UpdateGraph for more info.
*/
public void Apply () {
if (AstarPath.active == null) {
Debug.LogError ("There is no AstarPath object in the scene");
return;
}
GraphUpdateObject guo;
if (points == null || points.Length == 0) {
var coll = GetComponent<Collider>();
var rend = GetComponent<Renderer>();
Bounds b;
if (coll != null) b = coll.bounds;
else if (rend != null) b = rend.bounds;
else {
Debug.LogWarning ("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached");
return;
}
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
guo = new GraphUpdateObject (b);
} else {
var shape = new GraphUpdateShape ();
shape.convex = convex;
Vector3[] worldPoints = points;
if (!useWorldSpace) {
worldPoints = new Vector3[points.Length];
Matrix4x4 matrix = transform.localToWorldMatrix;
for (int i=0;i<worldPoints.Length;i++) worldPoints[i] = matrix.MultiplyPoint3x4 (points[i]);
}
shape.points = worldPoints;
Bounds b = shape.GetBounds ();
if (b.size.y < minBoundsHeight) b.size = new Vector3(b.size.x,minBoundsHeight,b.size.z);
guo = new GraphUpdateObject (b);
guo.shape = shape;
}
firstApplied = true;
guo.modifyWalkability = modifyWalkability;
guo.setWalkability = setWalkability;
guo.addPenalty = penaltyDelta;
guo.updatePhysics = updatePhysics;
guo.updateErosion = updateErosion;
guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;
guo.modifyTag = modifyTag;
guo.setTag = setTag;
AstarPath.active.UpdateGraphs (guo);
}
/** Draws some gizmos */
public void OnDrawGizmos () {
OnDrawGizmos (false);
}
/** Draws some gizmos */
public void OnDrawGizmosSelected () {
OnDrawGizmos (true);
}
/** Draws some gizmos */
public void OnDrawGizmos (bool selected) {
Color c = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f);
if (selected) {
Gizmos.color = Color.Lerp (c, new Color (1,1,1,0.2f), 0.9f);
Bounds b = GetBounds ();
Gizmos.DrawCube (b.center, b.size);
Gizmos.DrawWireCube (b.center, b.size);
}
if (points == null) return;
if (convex) {
c.a *= 0.5f;
}
Gizmos.color = c;
Matrix4x4 matrix = useWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix;
if (convex) {
c.r -= 0.1f;
c.g -= 0.2f;
c.b -= 0.1f;
Gizmos.color = c;
}
if (selected || !convex) {
for (int i=0;i<points.Length;i++) {
Gizmos.DrawLine (matrix.MultiplyPoint3x4(points[i]),matrix.MultiplyPoint3x4(points[(i+1)%points.Length]));
}
}
if (convex) {
if (convexPoints == null) RecalcConvex ();
Gizmos.color = selected ? new Color (227/255f,61/255f,22/255f,1.0f) : new Color (227/255f,61/255f,22/255f,0.9f);
for (int i=0;i<convexPoints.Length;i++) {
Gizmos.DrawLine (matrix.MultiplyPoint3x4(convexPoints[i]),matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length]));
}
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Securities
{
/// <summary>
/// Represents the market hours under normal conditions for an exchange and a specific day of the week in terms of local time
/// </summary>
public class LocalMarketHours
{
private readonly bool _hasPreMarket;
private readonly bool _hasPostMarket;
private readonly MarketHoursSegment[] _segments;
/// <summary>
/// Gets whether or not this exchange is closed all day
/// </summary>
public bool IsClosedAllDay { get; }
/// <summary>
/// Gets whether or not this exchange is closed all day
/// </summary>
public bool IsOpenAllDay { get; }
/// <summary>
/// Gets the day of week these hours apply to
/// </summary>
public DayOfWeek DayOfWeek { get; }
/// <summary>
/// Gets the tradable time during the market day.
/// For a normal US equity trading day this is 6.5 hours.
/// This does NOT account for extended market hours and only
/// considers <see cref="MarketHoursState.Market"/>
/// </summary>
public TimeSpan MarketDuration { get; }
/// <summary>
/// Gets the individual market hours segments that define the hours of operation for this day
/// </summary>
public IEnumerable<MarketHoursSegment> Segments => _segments;
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class
/// </summary>
/// <param name="day">The day of the week these hours are applicable</param>
/// <param name="segments">The open/close segments defining the market hours for one day</param>
public LocalMarketHours(DayOfWeek day, params MarketHoursSegment[] segments)
: this(day, (IEnumerable<MarketHoursSegment>) segments)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class
/// </summary>
/// <param name="day">The day of the week these hours are applicable</param>
/// <param name="segments">The open/close segments defining the market hours for one day</param>
public LocalMarketHours(DayOfWeek day, IEnumerable<MarketHoursSegment> segments)
{
DayOfWeek = day;
// filter out the closed states, we'll assume closed if no segment exists
_segments = (segments ?? Enumerable.Empty<MarketHoursSegment>()).Where(x => x.State != MarketHoursState.Closed).ToArray();
IsClosedAllDay = _segments.Length == 0;
IsOpenAllDay = _segments.Length == 1
&& _segments[0].Start == TimeSpan.Zero
&& _segments[0].End == Time.OneDay
&& _segments[0].State == MarketHoursState.Market;
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.PreMarket)
{
_hasPreMarket = true;
}
if (segment.State == MarketHoursState.PostMarket)
{
_hasPostMarket = true;
}
if (segment.State == MarketHoursState.Market)
{
MarketDuration += segment.End - segment.Start;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class from the specified open/close times
/// </summary>
/// <param name="day">The day of week these hours apply to</param>
/// <param name="extendedMarketOpen">The extended market open time</param>
/// <param name="marketOpen">The regular market open time, must be greater than or equal to the extended market open time</param>
/// <param name="marketClose">The regular market close time, must be greater than the regular market open time</param>
/// <param name="extendedMarketClose">The extended market close time, must be greater than or equal to the regular market close time</param>
public LocalMarketHours(DayOfWeek day, TimeSpan extendedMarketOpen, TimeSpan marketOpen, TimeSpan marketClose, TimeSpan extendedMarketClose)
: this(day, MarketHoursSegment.GetMarketHoursSegments(extendedMarketOpen, marketOpen, marketClose, extendedMarketClose))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalMarketHours"/> class from the specified open/close times
/// using the market open as the extended market open and the market close as the extended market close, effectively
/// removing any 'extended' session from these exchange hours
/// </summary>
/// <param name="day">The day of week these hours apply to</param>
/// <param name="marketOpen">The regular market open time</param>
/// <param name="marketClose">The regular market close time, must be greater than the regular market open time</param>
public LocalMarketHours(DayOfWeek day, TimeSpan marketOpen, TimeSpan marketClose)
: this(day, marketOpen, marketOpen, marketClose, marketClose)
{
}
/// <summary>
/// Gets the market opening time of day
/// </summary>
/// <param name="time">The reference time, the open returned will be the first open after the specified time if there are multiple market open segments</param>
/// <param name="extendedMarket">True to include extended market hours, false for regular market hours</param>
/// <returns>The market's opening time of day</returns>
public TimeSpan? GetMarketOpen(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed || segment.End <= time)
{
continue;
}
if (extendedMarket && _hasPreMarket)
{
if (segment.State == MarketHoursState.PreMarket)
{
return segment.Start;
}
}
else if (segment.State == MarketHoursState.Market)
{
return segment.Start;
}
}
// we couldn't locate an open segment after the specified time
return null;
}
/// <summary>
/// Gets the market closing time of day
/// </summary>
/// <param name="time">The reference time, the close returned will be the first close after the specified time if there are multiple market open segments</param>
/// <param name="extendedMarket">True to include extended market hours, false for regular market hours</param>
/// <returns>The market's closing time of day</returns>
public TimeSpan? GetMarketClose(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed || segment.End <= time)
{
continue;
}
if (extendedMarket && _hasPostMarket)
{
if (segment.State == MarketHoursState.PostMarket)
{
return segment.End;
}
}
else if (segment.State == MarketHoursState.Market)
{
return segment.End;
}
}
// we couldn't locate an open segment after the specified time
return null;
}
/// <summary>
/// Determines if the exchange is open at the specified time
/// </summary>
/// <param name="time">The time of day to check</param>
/// <param name="extendedMarket">True to check exended market hours, false to check regular market hours</param>
/// <returns>True if the exchange is considered open, false otherwise</returns>
public bool IsOpen(TimeSpan time, bool extendedMarket)
{
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed)
{
continue;
}
if (segment.Contains(time))
{
return extendedMarket || segment.State == MarketHoursState.Market;
}
}
// if we didn't find a segment then we're closed
return false;
}
/// <summary>
/// Determines if the exchange is open during the specified interval
/// </summary>
/// <param name="start">The start time of the interval</param>
/// <param name="end">The end time of the interval</param>
/// <param name="extendedMarket">True to check exended market hours, false to check regular market hours</param>
/// <returns>True if the exchange is considered open, false otherwise</returns>
public bool IsOpen(TimeSpan start, TimeSpan end, bool extendedMarket)
{
if (start == end)
{
return IsOpen(start, extendedMarket);
}
foreach (var segment in _segments)
{
if (segment.State == MarketHoursState.Closed)
{
continue;
}
if (extendedMarket || segment.State == MarketHoursState.Market)
{
if (segment.Overlaps(start, end))
{
return true;
}
}
}
// if we didn't find a segment then we're closed
return false;
}
/// <summary>
/// Gets a <see cref="LocalMarketHours"/> instance that is always closed
/// </summary>
/// <param name="dayOfWeek">The day of week</param>
/// <returns>A <see cref="LocalMarketHours"/> instance that is always closed</returns>
public static LocalMarketHours ClosedAllDay(DayOfWeek dayOfWeek)
{
return new LocalMarketHours(dayOfWeek);
}
/// <summary>
/// Gets a <see cref="LocalMarketHours"/> instance that is always open
/// </summary>
/// <param name="dayOfWeek">The day of week</param>
/// <returns>A <see cref="LocalMarketHours"/> instance that is always open</returns>
public static LocalMarketHours OpenAllDay(DayOfWeek dayOfWeek)
{
return new LocalMarketHours(dayOfWeek, new MarketHoursSegment(MarketHoursState.Market, TimeSpan.Zero, Time.OneDay));
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
if (IsClosedAllDay)
{
return "Closed All Day";
}
if (IsOpenAllDay)
{
return "Open All Day";
}
return Invariant($"{DayOfWeek}: {string.Join(" | ", (IEnumerable<MarketHoursSegment>) _segments)}");
}
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class InvoiceEstimate : Resource
{
public InvoiceEstimate() { }
public InvoiceEstimate(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public InvoiceEstimate(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public InvoiceEstimate(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
#endregion
#region Properties
public bool Recurring
{
get { return GetValue<bool>("recurring", true); }
}
public PriceTypeEnum PriceType
{
get { return GetEnum<PriceTypeEnum>("price_type", true); }
}
public string CurrencyCode
{
get { return GetValue<string>("currency_code", true); }
}
public int SubTotal
{
get { return GetValue<int>("sub_total", true); }
}
public int? Total
{
get { return GetValue<int?>("total", false); }
}
public int? CreditsApplied
{
get { return GetValue<int?>("credits_applied", false); }
}
public int? AmountPaid
{
get { return GetValue<int?>("amount_paid", false); }
}
public int? AmountDue
{
get { return GetValue<int?>("amount_due", false); }
}
public List<InvoiceEstimateLineItem> LineItems
{
get { return GetResourceList<InvoiceEstimateLineItem>("line_items"); }
}
public List<InvoiceEstimateDiscount> Discounts
{
get { return GetResourceList<InvoiceEstimateDiscount>("discounts"); }
}
public List<InvoiceEstimateTax> Taxes
{
get { return GetResourceList<InvoiceEstimateTax>("taxes"); }
}
public List<InvoiceEstimateLineItemTax> LineItemTaxes
{
get { return GetResourceList<InvoiceEstimateLineItemTax>("line_item_taxes"); }
}
public List<InvoiceEstimateLineItemTier> LineItemTiers
{
get { return GetResourceList<InvoiceEstimateLineItemTier>("line_item_tiers"); }
}
public List<InvoiceEstimateLineItemDiscount> LineItemDiscounts
{
get { return GetResourceList<InvoiceEstimateLineItemDiscount>("line_item_discounts"); }
}
public int? RoundOffAmount
{
get { return GetValue<int?>("round_off_amount", false); }
}
public string CustomerId
{
get { return GetValue<string>("customer_id", false); }
}
#endregion
#region Subclasses
public class InvoiceEstimateLineItem : Resource
{
public enum EntityTypeEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "plan_setup")]
PlanSetup,
[EnumMember(Value = "plan")]
Plan,
[EnumMember(Value = "addon")]
Addon,
[EnumMember(Value = "adhoc")]
Adhoc,
[EnumMember(Value = "plan_item_price")]
PlanItemPrice,
[EnumMember(Value = "addon_item_price")]
AddonItemPrice,
[EnumMember(Value = "charge_item_price")]
ChargeItemPrice,
}
public string Id {
get { return GetValue<string>("id", false); }
}
public string SubscriptionId {
get { return GetValue<string>("subscription_id", false); }
}
public DateTime DateFrom {
get { return (DateTime)GetDateTime("date_from", true); }
}
public DateTime DateTo {
get { return (DateTime)GetDateTime("date_to", true); }
}
public int UnitAmount {
get { return GetValue<int>("unit_amount", true); }
}
public int? Quantity {
get { return GetValue<int?>("quantity", false); }
}
public int? Amount {
get { return GetValue<int?>("amount", false); }
}
public PricingModelEnum? PricingModel {
get { return GetEnum<PricingModelEnum>("pricing_model", false); }
}
public bool IsTaxed {
get { return GetValue<bool>("is_taxed", true); }
}
public int? TaxAmount {
get { return GetValue<int?>("tax_amount", false); }
}
public double? TaxRate {
get { return GetValue<double?>("tax_rate", false); }
}
public string UnitAmountInDecimal {
get { return GetValue<string>("unit_amount_in_decimal", false); }
}
public string QuantityInDecimal {
get { return GetValue<string>("quantity_in_decimal", false); }
}
public string AmountInDecimal {
get { return GetValue<string>("amount_in_decimal", false); }
}
public int? DiscountAmount {
get { return GetValue<int?>("discount_amount", false); }
}
public int? ItemLevelDiscountAmount {
get { return GetValue<int?>("item_level_discount_amount", false); }
}
public string Description {
get { return GetValue<string>("description", true); }
}
public string EntityDescription {
get { return GetValue<string>("entity_description", true); }
}
public EntityTypeEnum EntityType {
get { return GetEnum<EntityTypeEnum>("entity_type", true); }
}
public TaxExemptReasonEnum? TaxExemptReason {
get { return GetEnum<TaxExemptReasonEnum>("tax_exempt_reason", false); }
}
public string EntityId {
get { return GetValue<string>("entity_id", false); }
}
public string CustomerId {
get { return GetValue<string>("customer_id", false); }
}
}
public class InvoiceEstimateDiscount : Resource
{
public enum EntityTypeEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "item_level_coupon")]
ItemLevelCoupon,
[EnumMember(Value = "document_level_coupon")]
DocumentLevelCoupon,
[EnumMember(Value = "promotional_credits")]
PromotionalCredits,
[EnumMember(Value = "prorated_credits")]
ProratedCredits,
[EnumMember(Value = "item_level_discount")]
ItemLevelDiscount,
[EnumMember(Value = "document_level_discount")]
DocumentLevelDiscount,
}
public int Amount {
get { return GetValue<int>("amount", true); }
}
public string Description {
get { return GetValue<string>("description", false); }
}
public EntityTypeEnum EntityType {
get { return GetEnum<EntityTypeEnum>("entity_type", true); }
}
public string EntityId {
get { return GetValue<string>("entity_id", false); }
}
}
public class InvoiceEstimateTax : Resource
{
public string Name {
get { return GetValue<string>("name", true); }
}
public int Amount {
get { return GetValue<int>("amount", true); }
}
public string Description {
get { return GetValue<string>("description", false); }
}
}
public class InvoiceEstimateLineItemTax : Resource
{
public string LineItemId {
get { return GetValue<string>("line_item_id", false); }
}
public string TaxName {
get { return GetValue<string>("tax_name", true); }
}
public double TaxRate {
get { return GetValue<double>("tax_rate", true); }
}
public bool? IsPartialTaxApplied {
get { return GetValue<bool?>("is_partial_tax_applied", false); }
}
public bool? IsNonComplianceTax {
get { return GetValue<bool?>("is_non_compliance_tax", false); }
}
public int TaxableAmount {
get { return GetValue<int>("taxable_amount", true); }
}
public int TaxAmount {
get { return GetValue<int>("tax_amount", true); }
}
public TaxJurisTypeEnum? TaxJurisType {
get { return GetEnum<TaxJurisTypeEnum>("tax_juris_type", false); }
}
public string TaxJurisName {
get { return GetValue<string>("tax_juris_name", false); }
}
public string TaxJurisCode {
get { return GetValue<string>("tax_juris_code", false); }
}
public int? TaxAmountInLocalCurrency {
get { return GetValue<int?>("tax_amount_in_local_currency", false); }
}
public string LocalCurrencyCode {
get { return GetValue<string>("local_currency_code", false); }
}
}
public class InvoiceEstimateLineItemTier : Resource
{
public string LineItemId {
get { return GetValue<string>("line_item_id", false); }
}
public int StartingUnit {
get { return GetValue<int>("starting_unit", true); }
}
public int? EndingUnit {
get { return GetValue<int?>("ending_unit", false); }
}
public int QuantityUsed {
get { return GetValue<int>("quantity_used", true); }
}
public int UnitAmount {
get { return GetValue<int>("unit_amount", true); }
}
public string StartingUnitInDecimal {
get { return GetValue<string>("starting_unit_in_decimal", false); }
}
public string EndingUnitInDecimal {
get { return GetValue<string>("ending_unit_in_decimal", false); }
}
public string QuantityUsedInDecimal {
get { return GetValue<string>("quantity_used_in_decimal", false); }
}
public string UnitAmountInDecimal {
get { return GetValue<string>("unit_amount_in_decimal", false); }
}
}
public class InvoiceEstimateLineItemDiscount : Resource
{
public enum DiscountTypeEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "item_level_coupon")]
ItemLevelCoupon,
[EnumMember(Value = "document_level_coupon")]
DocumentLevelCoupon,
[EnumMember(Value = "promotional_credits")]
PromotionalCredits,
[EnumMember(Value = "prorated_credits")]
ProratedCredits,
[EnumMember(Value = "item_level_discount")]
ItemLevelDiscount,
[EnumMember(Value = "document_level_discount")]
DocumentLevelDiscount,
}
public string LineItemId {
get { return GetValue<string>("line_item_id", true); }
}
public DiscountTypeEnum DiscountType {
get { return GetEnum<DiscountTypeEnum>("discount_type", true); }
}
public string CouponId {
get { return GetValue<string>("coupon_id", false); }
}
public string EntityId {
get { return GetValue<string>("entity_id", false); }
}
public int DiscountAmount {
get { return GetValue<int>("discount_amount", true); }
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Tao.DevIl;
using Axiom.Core;
namespace Axiom.Media {
public class ILFormat {
public ILFormat(int channels, int format, int type) {
this.channels = channels;
this.format = format;
this.type = type;
}
public ILFormat(int channels, int format) {
this.channels = channels;
this.format = format;
this.type = Il.IL_TYPE_UNKNOWN;
}
public ILFormat() {
this.channels = 0;
this.format = Il.IL_FORMAT_NOT_SUPPORTED;
this.type = Il.IL_TYPE_UNKNOWN;
}
public int channels = 0;
public int format = Il.IL_FORMAT_NOT_SUPPORTED;
public int type = Il.IL_TYPE_UNKNOWN;
}
public class ILUtil {
#if NOT
//-----------------------------------------------------------------------
/// Helper functions for DevIL to Ogre conversion
inline void packI(uint8 r, uint8 g, uint8 b, uint8 a, PixelFormat pf, void* dest)
{
PixelUtil::packColour(r, g, b, a, pf, dest);
}
inline void packI(uint16 r, uint16 g, uint16 b, uint16 a, PixelFormat pf, void* dest)
{
PixelUtil::packColour((float)r/65535.0f, (float)g/65535.0f,
(float)b/65535.0f, (float)a/65535.0f, pf, dest);
}
inline void packI(float r, float g, float b, float a, PixelFormat pf, void* dest)
{
PixelUtil::packColour(r, g, b, a, pf, dest);
}
template <typename T> void ilToOgreInternal(uint8 *tar, PixelFormat ogrefmt,
T r, T g, T b, T a)
{
const int ilfmt = ilGetInteger( IL_IMAGE_FORMAT );
T *src = (T*)ilGetData();
T *srcend = (T*)((uint8*)ilGetData() + ilGetInteger( IL_IMAGE_SIZE_OF_DATA ));
const size_t elemSize = PixelUtil::getNumElemBytes(ogrefmt);
while(src < srcend) {
switch(ilfmt) {
case IL_RGB:
r = src[0]; g = src[1]; b = src[2];
src += 3;
break;
case IL_BGR:
b = src[0]; g = src[1]; r = src[2];
src += 3;
break;
case IL_LUMINANCE:
r = src[0]; g = src[0]; b = src[0];
src += 1;
break;
case IL_LUMINANCE_ALPHA:
r = src[0]; g = src[0]; b = src[0]; a = src[1];
src += 2;
break;
case IL_RGBA:
r = src[0]; g = src[1]; b = src[2]; a = src[3];
src += 4;
break;
case IL_BGRA:
b = src[0]; g = src[1]; r = src[2]; a = src[3];
src += 4;
break;
default:
return;
}
packI(r, g, b, a, ogrefmt, tar);
tar += elemSize;
}
}
#endif
/// <summary>
/// Converts a PixelFormat enum to a pair with DevIL format enum and bytesPerPixel.
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
public static ILFormat ConvertToILFormat(PixelFormat format) {
switch (format) {
case PixelFormat.BYTE_L:
return new ILFormat(1, Il.IL_LUMINANCE, Il.IL_UNSIGNED_BYTE);
case PixelFormat.BYTE_A:
return new ILFormat(1, Il.IL_LUMINANCE, Il.IL_UNSIGNED_BYTE);
case PixelFormat.SHORT_L:
return new ILFormat(1, Il.IL_LUMINANCE, Il.IL_UNSIGNED_SHORT);
case PixelFormat.BYTE_LA:
return new ILFormat(2, Il.IL_LUMINANCE_ALPHA, Il.IL_UNSIGNED_BYTE);
case PixelFormat.BYTE_RGB:
return new ILFormat(3, Il.IL_RGB, Il.IL_UNSIGNED_BYTE);
case PixelFormat.BYTE_RGBA:
return new ILFormat(4, Il.IL_RGBA, Il.IL_UNSIGNED_BYTE);
case PixelFormat.BYTE_BGR:
return new ILFormat(3, Il.IL_BGR, Il.IL_UNSIGNED_BYTE);
case PixelFormat.BYTE_BGRA:
return new ILFormat(4, Il.IL_BGRA, Il.IL_UNSIGNED_BYTE);
case PixelFormat.SHORT_RGBA:
return new ILFormat(4, Il.IL_RGBA, Il.IL_UNSIGNED_SHORT);
case PixelFormat.FLOAT32_RGB:
return new ILFormat(3, Il.IL_RGB, Il.IL_FLOAT);
case PixelFormat.FLOAT32_RGBA:
return new ILFormat(4, Il.IL_RGBA, Il.IL_FLOAT);
case PixelFormat.DXT1:
return new ILFormat(0, Il.IL_DXT1);
case PixelFormat.DXT2:
return new ILFormat(0, Il.IL_DXT2);
case PixelFormat.DXT3:
return new ILFormat(0, Il.IL_DXT3);
case PixelFormat.DXT4:
return new ILFormat(0, Il.IL_DXT4);
case PixelFormat.DXT5:
return new ILFormat(0, Il.IL_DXT5);
}
return new ILFormat();
}
/// <summary>
/// Converts a DevIL format enum to a PixelFormat enum.
/// </summary>
/// <param name="imageFormat"></param>
/// <param name="imageType"></param>
/// <returns></returns>
public static PixelFormat ConvertFromILFormat(int imageFormat, int imageType) {
PixelFormat fmt = PixelFormat.Unknown;
switch (imageFormat) {
/* Compressed formats -- ignore type */
case Il.IL_DXT1: fmt = PixelFormat.DXT1; break;
case Il.IL_DXT2: fmt = PixelFormat.DXT2; break;
case Il.IL_DXT3: fmt = PixelFormat.DXT3; break;
case Il.IL_DXT4: fmt = PixelFormat.DXT4; break;
case Il.IL_DXT5: fmt = PixelFormat.DXT5; break;
/* Normal formats */
case Il.IL_RGB:
switch (imageType) {
case Il.IL_FLOAT: fmt = PixelFormat.FLOAT32_RGB; break;
case Il.IL_UNSIGNED_SHORT:
case Il.IL_SHORT: fmt = PixelFormat.SHORT_RGBA; break;
default: fmt = PixelFormat.BYTE_RGB; break;
}
break;
case Il.IL_BGR:
switch (imageType) {
case Il.IL_FLOAT: fmt = PixelFormat.FLOAT32_RGB; break;
case Il.IL_UNSIGNED_SHORT:
case Il.IL_SHORT: fmt = PixelFormat.SHORT_RGBA; break;
default: fmt = PixelFormat.BYTE_BGR; break;
}
break;
case Il.IL_RGBA:
switch (imageType) {
case Il.IL_FLOAT: fmt = PixelFormat.FLOAT32_RGBA; break;
case Il.IL_UNSIGNED_SHORT:
case Il.IL_SHORT: fmt = PixelFormat.SHORT_RGBA; break;
default: fmt = PixelFormat.BYTE_RGBA; break;
}
break;
case Il.IL_BGRA:
switch (imageType) {
case Il.IL_FLOAT: fmt = PixelFormat.FLOAT32_RGBA; break;
case Il.IL_UNSIGNED_SHORT:
case Il.IL_SHORT: fmt = PixelFormat.SHORT_RGBA; break;
default: fmt = PixelFormat.BYTE_BGRA; break;
}
break;
case Il.IL_LUMINANCE:
switch (imageType) {
case Il.IL_BYTE:
case Il.IL_UNSIGNED_BYTE:
fmt = PixelFormat.L8;
break;
default:
fmt = PixelFormat.L16;
break;
}
break;
case Il.IL_LUMINANCE_ALPHA:
fmt = PixelFormat.BYTE_LA;
break;
}
return fmt;
}
//-----------------------------------------------------------------------
/// Utility function to convert IL data types to UNSIGNED_
public static int ILabs(int type) {
switch (type) {
case Il.IL_INT: return Il.IL_UNSIGNED_INT;
case Il.IL_BYTE: return Il.IL_UNSIGNED_BYTE;
case Il.IL_SHORT: return Il.IL_UNSIGNED_SHORT;
default: return type;
}
}
//-----------------------------------------------------------------------
public static void ToAxiom(PixelBox dst)
{
if (!dst.Consecutive)
throw new NotImplementedException("Destination must currently be consecutive");
if (dst.Width != Il.ilGetInteger(Il.IL_IMAGE_WIDTH) ||
dst.Height != Il.ilGetInteger(Il.IL_IMAGE_HEIGHT) ||
dst.Depth != Il.ilGetInteger(Il.IL_IMAGE_DEPTH))
throw new AxiomException("Destination dimensions must equal IL dimension");
int ilfmt = Il.ilGetInteger(Il.IL_IMAGE_FORMAT);
int iltp = Il.ilGetInteger(Il.IL_IMAGE_TYPE);
// Check if in-memory format just matches
// If yes, we can just copy it and save conversion
ILFormat ifmt = ILUtil.ConvertToILFormat(dst.Format);
if (ifmt.format == ilfmt && ILabs(ifmt.type) == ILabs(iltp)) {
int size = Il.ilGetInteger(Il.IL_IMAGE_SIZE_OF_DATA);
// Copy from the IL structure to our buffer
PixelUtil.CopyBytes(dst.Data, dst.Offset, Il.ilGetData(), 0, size);
return;
}
// Try if buffer is in a known OGRE format so we can use OGRE its
// conversion routines
PixelFormat bufFmt = ILUtil.ConvertFromILFormat(ilfmt, iltp);
ifmt = ILUtil.ConvertToILFormat(bufFmt);
if (ifmt.format == ilfmt && ILabs(ifmt.type) == ILabs(iltp))
{
// IL format matches another OGRE format
PixelBox src = new PixelBox(dst.Width, dst.Height, dst.Depth, bufFmt, Il.ilGetData());
PixelUtil.BulkPixelConversion(src, dst);
return;
}
#if NOT
// The extremely slow method
if (iltp == Il.IL_UNSIGNED_BYTE || iltp == Il.IL_BYTE)
{
ilToOgreInternal(static_cast<uint8*>(dst.data), dst.format, (uint8)0x00,(uint8)0x00,(uint8)0x00,(uint8)0xFF);
}
else if(iltp == IL_FLOAT)
{
ilToOgreInternal(static_cast<uint8*>(dst.data), dst.format, 0.0f,0.0f,0.0f,1.0f);
}
else if(iltp == IL_SHORT || iltp == IL_UNSIGNED_SHORT)
{
ilToOgreInternal(static_cast<uint8*>(dst.data), dst.format,
(uint16)0x0000,(uint16)0x0000,(uint16)0x0000,(uint16)0xFFFF);
}
else
{
OGRE_EXCEPT( Exception::UNIMPLEMENTED_FEATURE,
"Cannot convert this DevIL type",
"ILUtil::ilToOgre" ) ;
}
#else
throw new NotImplementedException("Cannot convert this DevIL type");
#endif
}
#if NOT
//-----------------------------------------------------------------------
public void ILUtil.FromAxiom(PixelBox src)
{
// ilTexImage http://openil.sourceforge.net/docs/il/f00059.htm
ILFormat ifmt = OgreFormat2ilFormat( src.format );
if(src.isConsecutive() && ifmt.isValid())
{
// The easy case, the buffer is laid out in memory just like
// we want it to be and is in a format DevIL can understand directly
// We could even save the copy if DevIL would let us
Il.ilTexImage(src.Width, src.Height, src.Depth, ifmt.numberOfChannels,
ifmt.format, ifmt.type, src.data);
}
else if(ifmt.isValid())
{
// The format can be understood directly by DevIL. The only
// problem is that ilTexImage expects our image data consecutively
// so we cannot use that directly.
// Let DevIL allocate the memory for us, and copy the data consecutively
// to its memory
ilTexImage(static_cast<ILuint>(src.getWidth()),
static_cast<ILuint>(src.getHeight()),
static_cast<ILuint>(src.getDepth()), ifmt.numberOfChannels,
ifmt.format, ifmt.type, 0);
PixelBox dst(src.getWidth(), src.getHeight(), src.getDepth(), src.format, ilGetData());
PixelUtil::bulkPixelConversion(src, dst);
}
else
{
// Here it gets ugly. We're stuck with a pixel format that DevIL
// can't do anything with. We will do a bulk pixel conversion and
// then feed it to DevIL anyway. The problem is finding the best
// format to convert to.
// most general format supported by OGRE and DevIL
PixelFormat fmt = PixelUtil::hasAlpha(src.format)?PF_FLOAT32_RGBA:PF_FLOAT32_RGB;
// Make up a pixel format
// We don't have to consider luminance formats as they have
// straight conversions to DevIL, just weird permutations of RGBA an LA
int depths[4];
PixelUtil::getBitDepths(src.format, depths);
// Native endian format with all bit depths<8 can safely and quickly be
// converted to 24/32 bit
if(PixelUtil::isNativeEndian(src.format) &&
depths[0]<=8 && depths[1]<=8 && depths[2]<=8 && depths[3]<=8) {
if(PixelUtil::hasAlpha(src.format)) {
fmt = PF_A8R8G8B8;
} else {
fmt = PF_R8G8B8;
}
}
// Let DevIL allocate the memory for us, then do the conversion ourselves
ifmt = OgreFormat2ilFormat( fmt );
ilTexImage(static_cast<ILuint>(src.getWidth()),
static_cast<ILuint>(src.getHeight()),
static_cast<ILuint>(src.getDepth()), ifmt.numberOfChannels,
ifmt.format, ifmt.type, 0);
PixelBox dst(src.getWidth(), src.getHeight(), src.getDepth(), fmt, ilGetData());
PixelUtil::bulkPixelConversion(src, dst);
}
}
#endif
}
}
| |
/********************************************************************
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.
*********************************************************************/
#region BSD License
/*
Copyright (c) 2004 Matthew Holmes ([email protected]), Dan Moorehead ([email protected])
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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
#region CVS Information
/*
* $Source$
* $Author: mccollum $
* $Date: 2006-09-08 17:12:07 -0700 (Fri, 08 Sep 2006) $
* $Revision: 6434 $
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using DNPreBuild.Core.Attributes;
using DNPreBuild.Core.Interfaces;
using DNPreBuild.Core.Nodes;
using DNPreBuild.Core.Util;
namespace DNPreBuild.Core.Targets
{
[Target("sharpdev")]
public class SharpDevelopTarget : ITarget
{
#region Fields
private Kernel m_Kernel = null;
#endregion
#region Private Methods
private string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
tmpPath = Helper.NormalizePath(tmpPath);
else
tmpPath = Helper.NormalizePath("./" + tmpPath);
return tmpPath;
}
private string BuildReference(SolutionNode solution, ReferenceNode refr)
{
string ret = "\t\t<Reference type=\"";
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ret += "Project\" refto=\"" + refr.Name;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if(refr.Path != null || fileRef != null)
{
ret += "Assembly\" refto=\"";
string finalPath = (refr.Path != null) ? Helper.MakeFilePath(refr.Path, refr.Name, "dll") : fileRef;
ret += finalPath;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
return ret;
}
ret += "Gac\" refto=\"";
ret += refr.Name;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
}
return ret;
}
private string FindFileReference(string refName, ProjectNode project)
{
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if(File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string csComp = "Csc";
string netRuntime = "MsNet";
if(project.Runtime == Runtime.Mono)
{
csComp = "Mcs";
netRuntime = "Mono";
}
string projFile = Helper.MakeFilePath(project.FullPath, project.Name, "prjx");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CWDStack.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
using(ss)
{
ss.WriteLine(
"<Project name=\"{0}\" description=\"\" standardNamespace=\"{1}\" newfilesearch=\"None\" enableviewstate=\"True\" version=\"1.1\" projecttype=\"C#\">",
project.Name,
project.RootNamespace
);
ss.WriteLine("\t<Contents>");
foreach(string file in project.Files)
{
string buildAction = "Compile";
switch(project.Files.GetBuildAction(file))
{
case BuildAction.None:
buildAction = "Nothing";
break;
case BuildAction.Content:
buildAction = "Exclude";
break;
case BuildAction.EmbeddedResource:
buildAction = "EmbedAsResource";
break;
default:
buildAction = "Compile";
break;
}
// Sort of a hack, we try and resolve the path and make it relative, if we can.
string filePath = PrependPath(file);
ss.WriteLine("\t\t<File name=\"{0}\" subtype=\"Code\" buildaction=\"{1}\" dependson=\"\" data=\"\" />", filePath, buildAction);
}
ss.WriteLine("\t</Contents>");
ss.WriteLine("\t<References>");
foreach(ReferenceNode refr in project.References)
ss.WriteLine("\t\t{0}", BuildReference(solution, refr));
ss.WriteLine("\t</References>");
int count = 0;
foreach(ConfigurationNode conf in solution.Configurations)
{
if(count == 0)
ss.WriteLine("\t<Configurations active=\"{0}\">", conf.Name);
ss.WriteLine("\t\t<Configuration name=\"{0}\">", conf.Name);
ss.WriteLine("\t\t\t<CodeGeneration");
ss.WriteLine("\t\t\t\truntime=\"{0}\"", netRuntime);
ss.WriteLine("\t\t\t\tcompiler=\"{0}\"", csComp);
ss.WriteLine("\t\t\t\twarninglevel=\"{0}\"", conf.Options["WarningLevel"]);
ss.WriteLine("\t\t\t\tincludedebuginformation=\"{0}\"", conf.Options["DebugInformation"]);
ss.WriteLine("\t\t\t\toptimize=\"{0}\"", conf.Options["OptimizeCode"]);
ss.WriteLine("\t\t\t\tunsafecodeallowed=\"{0}\"", conf.Options["AllowUnsafe"]);
ss.WriteLine("\t\t\t\tgenerateoverflowchecks=\"{0}\"", conf.Options["CheckUnderflowOverflow"]);
ss.WriteLine("\t\t\t\tmainclass=\"{0}\"", project.StartupObject);
ss.WriteLine("\t\t\t\ttarget=\"{0}\"", project.Type);
ss.WriteLine("\t\t\t\tdefinesymbols=\"{0}\"", conf.Options["CompilerDefines"]);
ss.WriteLine("\t\t\t\tgeneratexmldocumentation=\"{0}\"", (((string)conf.Options["XmlDocFile"]).Length > 0));
ss.WriteLine("\t\t\t/>");
ss.WriteLine("\t\t\t<Output");
ss.WriteLine("\t\t\t\tdirectory=\".\\{0}\"", conf.Options["OutputPath"]);
ss.WriteLine("\t\t\t\tassembly=\"{0}\"", project.AssemblyName);
ss.WriteLine("\t\t\t\texecuteScript=\"\"");
ss.WriteLine("\t\t\t\texecuteBeforeBuild=\"\"");
ss.WriteLine("\t\t\t\texecuteAfterBuild=\"\"");
ss.WriteLine("\t\t\t/>");
ss.WriteLine("\t\t</Configuration>");
count++;
}
ss.WriteLine("\t</Configurations>");
ss.WriteLine("</Project>");
}
m_Kernel.CWDStack.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating SharpDevelop combine and project files");
foreach(ProjectNode project in solution.Projects)
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "cmbx");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CWDStack.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using(ss)
{
ss.WriteLine("<Combine fileversion=\"1.0\" name=\"{0}\" description=\"\">", solution.Name);
int count = 0;
foreach(ProjectNode project in solution.Projects)
{
if(count == 0)
ss.WriteLine("\t<StartMode startupentry=\"{0}\" single=\"True\">", project.Name);
ss.WriteLine("\t\t<Execute entry=\"{0}\" type=\"None\" />", project.Name);
count++;
}
ss.WriteLine("\t</StartMode>");
ss.WriteLine("\t<Entries>");
foreach(ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine("\t\t<Entry filename=\"{0}\" />",
Helper.MakeFilePath(path, project.Name, "prjx"));
}
ss.WriteLine("\t</Entries>");
count = 0;
foreach(ConfigurationNode conf in solution.Configurations)
{
if(count == 0)
ss.WriteLine("\t<Configurations active=\"{0}\">", conf.Name);
ss.WriteLine("\t\t<Configuration name=\"{0}\">", conf.Name);
foreach(ProjectNode project in solution.Projects)
ss.WriteLine("\t\t\t<Entry name=\"{0}\" configurationname=\"{1}\" build=\"True\"/>", project.Name, conf.Name);
ss.WriteLine("\t\t</Configuration>");
count++;
}
ss.WriteLine("\t</Configurations>");
ss.WriteLine("</Combine>");
}
m_Kernel.CWDStack.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "prjx");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning SharpDevelop combine and project files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "cmbx");
Helper.DeleteIfExists(slnFile);
foreach(ProjectNode project in solution.Projects)
CleanProject(project);
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
public void Write(Kernel kern)
{
m_Kernel = kern;
foreach(SolutionNode solution in kern.Solutions)
WriteCombine(solution);
m_Kernel = null;
}
public virtual void Clean(Kernel kern)
{
m_Kernel = kern;
foreach(SolutionNode sol in kern.Solutions)
CleanSolution(sol);
m_Kernel = null;
}
public string Name
{
get
{
return "sharpdev";
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using NUnit.Framework;
using osu.Framework.Threading;
using osu.Framework.Timing;
namespace osu.Framework.Tests.Threading
{
[TestFixture]
public class SchedulerTest
{
private Scheduler scheduler;
private bool fromMainThread;
[SetUp]
public void Setup()
{
scheduler = new Scheduler(() => fromMainThread, new StopwatchClock(true));
}
[Test]
public void TestScheduleOnce([Values(false, true)] bool fromMainThread, [Values(false, true)] bool forceScheduled)
{
this.fromMainThread = fromMainThread;
int invocations = 0;
var del = scheduler.Add(() => invocations++, forceScheduled);
if (fromMainThread && !forceScheduled)
{
Assert.AreEqual(1, invocations);
Assert.That(del, Is.Null);
}
else
{
Assert.AreEqual(0, invocations);
Assert.That(del, Is.Not.Null);
}
scheduler.Update();
Assert.AreEqual(1, invocations);
// Ensures that the delegate runs only once in the scheduled/not on main thread branch
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestCancelScheduledDelegate()
{
int invocations = 0;
ScheduledDelegate del;
scheduler.Add(del = new ScheduledDelegate(() => invocations++));
del.Cancel();
scheduler.Update();
Assert.AreEqual(0, invocations);
}
[Test]
public void TestAddCancelledDelegate()
{
int invocations = 0;
ScheduledDelegate del = new ScheduledDelegate(() => invocations++);
del.Cancel();
scheduler.Add(del);
scheduler.Update();
Assert.AreEqual(0, invocations);
}
[Test]
public void TestCustomScheduledDelegateRunsOnce()
{
int invocations = 0;
scheduler.Add(new ScheduledDelegate(() => invocations++));
scheduler.Update();
Assert.AreEqual(1, invocations);
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestDelayedDelegatesAreScheduledWithCorrectTime()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
ScheduledDelegate del = scheduler.AddDelayed(() => { }, 1000);
Assert.AreEqual(1000, del.ExecutionTime);
clock.Seek(500);
del = scheduler.AddDelayed(() => { }, 1000);
Assert.AreEqual(1500, del.ExecutionTime);
}
[Test]
public void TestDelayedDelegateDoesNotRunUntilExpectedTime()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
scheduler.AddDelayed(() => invocations++, 1000);
clock.Seek(1000);
scheduler.AddDelayed(() => invocations++, 1000);
for (double d = 0; d <= 2500; d += 100)
{
clock.Seek(d);
scheduler.Update();
int expectedInvocations = 0;
if (d >= 1000)
expectedInvocations++;
if (d >= 2000)
expectedInvocations++;
Assert.AreEqual(expectedInvocations, invocations);
}
}
[Test]
public void TestCancelDelayedDelegate()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
ScheduledDelegate del;
scheduler.Add(del = new ScheduledDelegate(() => invocations++, 1000));
del.Cancel();
clock.Seek(1500);
scheduler.Update();
Assert.AreEqual(0, invocations);
}
[Test]
public void TestCancelDelayedDelegateDuringRun()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
ScheduledDelegate del = null;
scheduler.Add(del = new ScheduledDelegate(() =>
{
invocations++;
// ReSharper disable once AccessToModifiedClosure
del?.Cancel();
}, 1000));
Assert.AreEqual(ScheduledDelegate.RunState.Waiting, del.State);
clock.Seek(1500);
scheduler.Update();
Assert.AreEqual(1, invocations);
Assert.AreEqual(ScheduledDelegate.RunState.Cancelled, del.State);
clock.Seek(2500);
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestRepeatingDelayedDelegate()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
scheduler.Add(new ScheduledDelegate(() => invocations++, 500, 500));
scheduler.Add(new ScheduledDelegate(() => invocations++, 1000, 500));
for (double d = 0; d <= 2500; d += 100)
{
clock.Seek(d);
scheduler.Update();
int expectedInvocations = 0;
if (d >= 500)
expectedInvocations += 1 + (int)((d - 500) / 500);
if (d >= 1000)
expectedInvocations += 1 + (int)((d - 1000) / 500);
Assert.AreEqual(expectedInvocations, invocations);
}
}
[Test]
public void TestZeroDelayRepeatingDelegate()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
Assert.Zero(scheduler.TotalPendingTasks);
scheduler.Add(new ScheduledDelegate(() => invocations++, 500, 0));
Assert.AreEqual(1, scheduler.TotalPendingTasks);
int expectedInvocations = 0;
for (double d = 0; d <= 2500; d += 100)
{
clock.Seek(d);
scheduler.Update();
if (d >= 500)
expectedInvocations++;
Assert.AreEqual(expectedInvocations, invocations);
Assert.AreEqual(1, scheduler.TotalPendingTasks);
}
}
[TestCase(false)]
[TestCase(true)]
public void TestRepeatingDelayedDelegateCatchUp(bool performCatchUp)
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
scheduler.Add(new ScheduledDelegate(() => invocations++, 500, 500)
{
PerformRepeatCatchUpExecutions = performCatchUp
});
for (double d = 0; d <= 10000; d += 2000)
{
clock.Seek(d);
for (int i = 0; i < 10; i++)
// allow catch-up to potentially occur.
scheduler.Update();
int expectedInovations;
if (performCatchUp)
expectedInovations = (int)(d / 500);
else
expectedInovations = (int)(d / 2000);
Assert.AreEqual(expectedInovations, invocations);
}
}
[Test]
public void TestCancelAfterRepeatReschedule()
{
var clock = new StopwatchClock();
scheduler.UpdateClock(clock);
int invocations = 0;
ScheduledDelegate del;
scheduler.Add(del = new ScheduledDelegate(() => invocations++, 500, 500));
Assert.AreEqual(ScheduledDelegate.RunState.Waiting, del.State);
clock.Seek(750);
scheduler.Update();
Assert.AreEqual(1, invocations);
Assert.AreEqual(ScheduledDelegate.RunState.Complete, del.State);
del.Cancel();
Assert.AreEqual(ScheduledDelegate.RunState.Cancelled, del.State);
clock.Seek(1250);
scheduler.Update();
Assert.AreEqual(1, invocations);
Assert.AreEqual(ScheduledDelegate.RunState.Cancelled, del.State);
}
[Test]
public void TestAddOnce()
{
int invocations = 0;
void action() => invocations++;
scheduler.AddOnce(action);
scheduler.AddOnce(action);
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestPerUpdateTask()
{
int invocations = 0;
scheduler.AddDelayed(() => invocations++, 0, true);
Assert.AreEqual(0, invocations);
scheduler.Update();
Assert.AreEqual(1, invocations);
scheduler.Update();
Assert.AreEqual(2, invocations);
}
[Test]
public void TestScheduleFromInsideDelegate([Values(false, true)] bool forceScheduled)
{
const int max_reschedules = 3;
fromMainThread = !forceScheduled;
int reschedules = 0;
scheduleTask();
if (forceScheduled)
{
for (int i = 0; i <= max_reschedules; i++)
{
scheduler.Update();
Assert.AreEqual(Math.Min(max_reschedules, i + 1), reschedules);
}
}
else
Assert.AreEqual(max_reschedules, reschedules);
void scheduleTask() => scheduler.Add(() =>
{
if (reschedules == max_reschedules)
return;
reschedules++;
scheduleTask();
}, forceScheduled);
}
[Test]
public void TestInvokeBeforeSchedulerRun()
{
int invocations = 0;
ScheduledDelegate del = new ScheduledDelegate(() => invocations++);
scheduler.Add(del);
Assert.AreEqual(0, invocations);
del.RunTask();
Assert.AreEqual(1, invocations);
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestInvokeAfterSchedulerRun()
{
int invocations = 0;
ScheduledDelegate del = new ScheduledDelegate(() => invocations++);
scheduler.Add(del);
Assert.AreEqual(0, invocations);
scheduler.Update();
Assert.AreEqual(1, invocations);
Assert.Throws<InvalidOperationException>(del.RunTask);
Assert.AreEqual(1, invocations);
}
[Test]
public void TestInvokeBeforeScheduleUpdate()
{
int invocations = 0;
ScheduledDelegate del;
scheduler.Add(del = new ScheduledDelegate(() => invocations++));
Assert.AreEqual(0, invocations);
del.RunTask();
Assert.AreEqual(1, invocations);
scheduler.Update();
Assert.AreEqual(1, invocations);
}
[Test]
public void TestRepeatAlreadyCompletedSchedule()
{
int invocations = 0;
var del = new ScheduledDelegate(() => invocations++);
del.RunTask();
Assert.AreEqual(1, invocations);
Assert.Throws<InvalidOperationException>(() => scheduler.Add(del));
scheduler.Update();
Assert.AreEqual(1, invocations);
}
/// <summary>
/// Tests that delegates added from inside a scheduled callback don't get executed when the scheduled callback cancels a prior intermediate task.
///
/// Delegate 1 - Added at the start.
/// Delegate 2 - Added at the start, cancelled by Delegate 1.
/// Delegate 3 - Added during Delegate 1 callback, should not get executed.
/// </summary>
[Test]
public void TestDelegateAddedInCallbackNotExecutedAfterIntermediateCancelledDelegate()
{
int invocations = 0;
// Delegate 2
var cancelled = new ScheduledDelegate(() => { });
// Delegate 1
scheduler.Add(() =>
{
invocations++;
cancelled.Cancel();
// Delegate 3
scheduler.Add(() => invocations++);
});
scheduler.Add(cancelled);
scheduler.Update();
Assert.That(invocations, Is.EqualTo(1));
}
}
}
| |
namespace NativeCode.Mobile.AppCompat.FormsAppCompat.Adapters
{
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Media;
using Android.Net;
using Android.OS;
using Android.Support.V7.App;
using Android.Views;
using Java.Lang;
/// <summary>
/// Adapts an existing <see cref="Window"/> to override required methods to implement <see cref="AppCompatDelegate"/>.
/// </summary>
internal class WindowAdapter : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="WindowAdapter"/> class.
/// </summary>
/// <param name="window">The window.</param>
/// <param name="appCompatDelegateProvider">The application delegate provider.</param>
internal WindowAdapter(Window window, IAppCompatDelegateProvider appCompatDelegateProvider) : base(window.Context)
{
this.AppCompatDelegateProvider = appCompatDelegateProvider;
this.Callback = window.Callback;
this.Window = window;
}
public override bool IsFloating
{
get { return this.Window.IsFloating; }
}
public override LayoutInflater LayoutInflater
{
get { return this.Window.LayoutInflater; }
}
public override int NavigationBarColor
{
get { return this.Window.NavigationBarColor; }
}
public override int StatusBarColor
{
get { return this.Window.StatusBarColor; }
}
public override Stream VolumeControlStream
{
get { return this.Window.VolumeControlStream; }
set { this.Window.VolumeControlStream = value; }
}
public override View CurrentFocus
{
get { return this.Window.CurrentFocus; }
}
public override View DecorView
{
get { return this.Window.DecorView; }
}
protected IAppCompatDelegateProvider AppCompatDelegateProvider { get; private set; }
protected AppCompatDelegate AppCompatDelegate
{
get { return this.AppCompatDelegateProvider.AppCompatDelegate; }
}
protected Window Window { get; private set; }
public override void AddContentView(View view, ViewGroup.LayoutParams @params)
{
this.Window.AddContentView(view, @params);
}
public override void CloseAllPanels()
{
this.Window.CloseAllPanels();
}
public override void ClosePanel(int featureId)
{
this.Window.ClosePanel(featureId);
}
public override void InvalidatePanelMenu(WindowFeatures featureId)
{
this.Window.InvalidatePanelMenu(featureId);
}
public override bool IsShortcutKey(Keycode keyCode, KeyEvent e)
{
return this.Window.IsShortcutKey(keyCode, e);
}
public override void OnConfigurationChanged(Configuration newConfig)
{
this.Window.OnConfigurationChanged(newConfig);
}
public override void OpenPanel(int featureId, KeyEvent e)
{
this.Window.OpenPanel(featureId, e);
}
public override View PeekDecorView()
{
return this.Window.PeekDecorView();
}
public override bool PerformContextMenuIdentifierAction(int id, MenuPerformFlags flags)
{
return this.Window.PerformContextMenuIdentifierAction(id, flags);
}
public override bool PerformPanelIdentifierAction(int featureId, int id, MenuPerformFlags flags)
{
return this.Window.PerformPanelIdentifierAction(featureId, id, flags);
}
public override bool PerformPanelShortcut(int featureId, Keycode keyCode, KeyEvent e, MenuPerformFlags flags)
{
return this.Window.PerformPanelShortcut(featureId, keyCode, e, flags);
}
public override bool RequestFeature(WindowFeatures featureId)
{
return this.AppCompatDelegate.RequestWindowFeature((int)featureId);
}
public override void RestoreHierarchyState(Bundle savedInstanceState)
{
this.Window.RestoreHierarchyState(savedInstanceState);
}
public override Bundle SaveHierarchyState()
{
return this.Window.SaveHierarchyState();
}
public override void SetBackgroundDrawable(Drawable drawable)
{
this.Window.SetBackgroundDrawable(drawable);
}
public override void SetChildDrawable(int featureId, Drawable drawable)
{
this.Window.SetChildDrawable(featureId, drawable);
}
public override void SetChildInt(int featureId, int value)
{
this.Window.SetChildInt(featureId, value);
}
public override void SetContentView(View view)
{
this.Window.SetContentView(view);
}
public override void SetContentView(View view, ViewGroup.LayoutParams @params)
{
this.Window.SetContentView(view, @params);
}
public override void SetContentView(int layoutResId)
{
this.Window.SetContentView(layoutResId);
}
public override void SetFeatureDrawable(WindowFeatures featureId, Drawable drawable)
{
this.Window.SetFeatureDrawable(featureId, drawable);
}
public override void SetFeatureDrawableAlpha(WindowFeatures featureId, int alpha)
{
this.Window.SetFeatureDrawableAlpha(featureId, alpha);
}
public override void SetFeatureDrawableResource(WindowFeatures featureId, int resId)
{
this.Window.SetFeatureDrawableResource(featureId, resId);
}
public override void SetFeatureDrawableUri(WindowFeatures featureId, Uri uri)
{
this.Window.SetFeatureDrawableUri(featureId, uri);
}
public override void SetFeatureInt(WindowFeatures featureId, int value)
{
this.Window.SetFeatureInt(featureId, value);
}
public override void SetNavigationBarColor(Color color)
{
this.Window.SetNavigationBarColor(color);
}
public override void SetStatusBarColor(Color color)
{
this.Window.SetStatusBarColor(color);
}
public override void SetTitle(ICharSequence title)
{
this.Window.SetTitle(title);
}
public override void SetTitleColor(Color textColor)
{
this.Window.SetTitleColor(textColor);
}
public override bool SuperDispatchGenericMotionEvent(MotionEvent e)
{
return this.Window.SuperDispatchGenericMotionEvent(e);
}
public override bool SuperDispatchKeyEvent(KeyEvent e)
{
return this.Window.SuperDispatchKeyEvent(e);
}
public override bool SuperDispatchKeyShortcutEvent(KeyEvent e)
{
return this.Window.SuperDispatchKeyShortcutEvent(e);
}
public override bool SuperDispatchTouchEvent(MotionEvent e)
{
return this.Window.SuperDispatchTouchEvent(e);
}
public override bool SuperDispatchTrackballEvent(MotionEvent e)
{
return this.Window.SuperDispatchTrackballEvent(e);
}
public override void TakeInputQueue(InputQueue.ICallback callback)
{
this.Window.TakeInputQueue(callback);
}
public override void TakeKeyEvents(bool get)
{
this.Window.TakeKeyEvents(get);
}
public override void TakeSurface(ISurfaceHolderCallback2 callback)
{
this.Window.TakeSurface(callback);
}
public override void TogglePanel(int featureId, KeyEvent e)
{
this.Window.TogglePanel(featureId, e);
}
protected override void OnActive()
{
this.Window.MakeActive();
}
}
}
| |
namespace android.telephony
{
[global::MonoJavaBridge.JavaClass()]
public partial class SmsMessage : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected SmsMessage(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class MessageClass : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal MessageClass(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::android.telephony.SmsMessage.MessageClass[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage.MessageClass._m0.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage.MessageClass._m0 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "values", "()[Landroid/telephony/SmsMessage/MessageClass;");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.telephony.SmsMessage.MessageClass>(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.MessageClass.staticClass, global::android.telephony.SmsMessage.MessageClass._m0)) as android.telephony.SmsMessage.MessageClass[];
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::android.telephony.SmsMessage.MessageClass valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage.MessageClass._m1.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage.MessageClass._m1 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/telephony/SmsMessage$MessageClass;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.MessageClass.staticClass, global::android.telephony.SmsMessage.MessageClass._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.telephony.SmsMessage.MessageClass;
}
internal static global::MonoJavaBridge.FieldId _CLASS_05105;
public static global::android.telephony.SmsMessage.MessageClass CLASS_0
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.SmsMessage.MessageClass.staticClass, _CLASS_05105)) as android.telephony.SmsMessage.MessageClass;
}
}
internal static global::MonoJavaBridge.FieldId _CLASS_15106;
public static global::android.telephony.SmsMessage.MessageClass CLASS_1
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.SmsMessage.MessageClass.staticClass, _CLASS_15106)) as android.telephony.SmsMessage.MessageClass;
}
}
internal static global::MonoJavaBridge.FieldId _CLASS_25107;
public static global::android.telephony.SmsMessage.MessageClass CLASS_2
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.SmsMessage.MessageClass.staticClass, _CLASS_25107)) as android.telephony.SmsMessage.MessageClass;
}
}
internal static global::MonoJavaBridge.FieldId _CLASS_35108;
public static global::android.telephony.SmsMessage.MessageClass CLASS_3
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.SmsMessage.MessageClass.staticClass, _CLASS_35108)) as android.telephony.SmsMessage.MessageClass;
}
}
internal static global::MonoJavaBridge.FieldId _UNKNOWN5109;
public static global::android.telephony.SmsMessage.MessageClass UNKNOWN
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.SmsMessage.MessageClass.staticClass, _UNKNOWN5109)) as android.telephony.SmsMessage.MessageClass;
}
}
static MessageClass()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.telephony.SmsMessage.MessageClass.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/SmsMessage$MessageClass"));
global::android.telephony.SmsMessage.MessageClass._CLASS_05105 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "CLASS_0", "Landroid/telephony/SmsMessage$MessageClass;");
global::android.telephony.SmsMessage.MessageClass._CLASS_15106 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "CLASS_1", "Landroid/telephony/SmsMessage$MessageClass;");
global::android.telephony.SmsMessage.MessageClass._CLASS_25107 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "CLASS_2", "Landroid/telephony/SmsMessage$MessageClass;");
global::android.telephony.SmsMessage.MessageClass._CLASS_35108 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "CLASS_3", "Landroid/telephony/SmsMessage$MessageClass;");
global::android.telephony.SmsMessage.MessageClass._UNKNOWN5109 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.SmsMessage.MessageClass.staticClass, "UNKNOWN", "Landroid/telephony/SmsMessage$MessageClass;");
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class SubmitPdu : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected SubmitPdu(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.SubmitPdu.staticClass, "toString", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage.SubmitPdu._m0) as java.lang.String;
}
internal static global::MonoJavaBridge.FieldId _encodedScAddress5110;
public byte[] encodedScAddress
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.GetObjectField(this.JvmHandle, _encodedScAddress5110)) as byte[];
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _encodedMessage5111;
public byte[] encodedMessage
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.GetObjectField(this.JvmHandle, _encodedMessage5111)) as byte[];
}
set
{
}
}
static SubmitPdu()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.telephony.SmsMessage.SubmitPdu.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/SmsMessage$SubmitPdu"));
global::android.telephony.SmsMessage.SubmitPdu._encodedScAddress5110 = @__env.GetFieldIDNoThrow(global::android.telephony.SmsMessage.SubmitPdu.staticClass, "encodedScAddress", "[B");
global::android.telephony.SmsMessage.SubmitPdu._encodedMessage5111 = @__env.GetFieldIDNoThrow(global::android.telephony.SmsMessage.SubmitPdu.staticClass, "encodedMessage", "[B");
}
}
public new byte[] UserData
{
get
{
return getUserData();
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual byte[] getUserData()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.telephony.SmsMessage.staticClass, "getUserData", "()[B", ref global::android.telephony.SmsMessage._m0) as byte[];
}
public new int Status
{
get
{
return getStatus();
}
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual int getStatus()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getStatus", "()I", ref global::android.telephony.SmsMessage._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public static global::android.telephony.SmsMessage createFromPdu(byte[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m2.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m2 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "createFromPdu", "([B)Landroid/telephony/SmsMessage;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.telephony.SmsMessage;
}
private static global::MonoJavaBridge.MethodId _m3;
public static int getTPLayerLengthForPDU(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m3.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m3 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "getTPLayerLengthForPDU", "(Ljava/lang/String;)I");
return @__env.CallStaticIntMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public static int[] calculateLength(java.lang.CharSequence arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m4.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m4 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "calculateLength", "(Ljava/lang/CharSequence;Z)[I");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as int[];
}
public static int[] calculateLength(string arg0, bool arg1)
{
return calculateLength((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m5;
public static int[] calculateLength(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m5.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m5 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "calculateLength", "(Ljava/lang/String;Z)[I");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as int[];
}
private static global::MonoJavaBridge.MethodId _m6;
public static global::android.telephony.SmsMessage.SubmitPdu getSubmitPdu(java.lang.String arg0, java.lang.String arg1, short arg2, byte[] arg3, bool arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m6.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m6 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/SmsMessage$SubmitPdu;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.telephony.SmsMessage.SubmitPdu;
}
private static global::MonoJavaBridge.MethodId _m7;
public static global::android.telephony.SmsMessage.SubmitPdu getSubmitPdu(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.telephony.SmsMessage._m7.native == global::System.IntPtr.Zero)
global::android.telephony.SmsMessage._m7 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.SmsMessage.staticClass, "getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/SmsMessage$SubmitPdu;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.SmsMessage.staticClass, global::android.telephony.SmsMessage._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.telephony.SmsMessage.SubmitPdu;
}
public new global::java.lang.String ServiceCenterAddress
{
get
{
return getServiceCenterAddress();
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual global::java.lang.String getServiceCenterAddress()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getServiceCenterAddress", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m8) as java.lang.String;
}
public new global::java.lang.String OriginatingAddress
{
get
{
return getOriginatingAddress();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::java.lang.String getOriginatingAddress()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getOriginatingAddress", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m9) as java.lang.String;
}
public new global::java.lang.String DisplayOriginatingAddress
{
get
{
return getDisplayOriginatingAddress();
}
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual global::java.lang.String getDisplayOriginatingAddress()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getDisplayOriginatingAddress", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m10) as java.lang.String;
}
public new global::java.lang.String MessageBody
{
get
{
return getMessageBody();
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::java.lang.String getMessageBody()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getMessageBody", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m11) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::android.telephony.SmsMessage.MessageClass getMessageClass()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.telephony.SmsMessage.MessageClass>(this, global::android.telephony.SmsMessage.staticClass, "getMessageClass", "()Landroid/telephony/SmsMessage$MessageClass;", ref global::android.telephony.SmsMessage._m12) as android.telephony.SmsMessage.MessageClass;
}
public new global::java.lang.String DisplayMessageBody
{
get
{
return getDisplayMessageBody();
}
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::java.lang.String getDisplayMessageBody()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getDisplayMessageBody", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m13) as java.lang.String;
}
public new global::java.lang.String PseudoSubject
{
get
{
return getPseudoSubject();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual global::java.lang.String getPseudoSubject()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getPseudoSubject", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m14) as java.lang.String;
}
public new long TimestampMillis
{
get
{
return getTimestampMillis();
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual long getTimestampMillis()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.telephony.SmsMessage.staticClass, "getTimestampMillis", "()J", ref global::android.telephony.SmsMessage._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual bool isEmail()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isEmail", "()Z", ref global::android.telephony.SmsMessage._m16);
}
public new global::java.lang.String EmailBody
{
get
{
return getEmailBody();
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual global::java.lang.String getEmailBody()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getEmailBody", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m17) as java.lang.String;
}
public new global::java.lang.String EmailFrom
{
get
{
return getEmailFrom();
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::java.lang.String getEmailFrom()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.SmsMessage.staticClass, "getEmailFrom", "()Ljava/lang/String;", ref global::android.telephony.SmsMessage._m18) as java.lang.String;
}
public new int ProtocolIdentifier
{
get
{
return getProtocolIdentifier();
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual int getProtocolIdentifier()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getProtocolIdentifier", "()I", ref global::android.telephony.SmsMessage._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual bool isReplace()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isReplace", "()Z", ref global::android.telephony.SmsMessage._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual bool isCphsMwiMessage()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isCphsMwiMessage", "()Z", ref global::android.telephony.SmsMessage._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual bool isMWIClearMessage()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isMWIClearMessage", "()Z", ref global::android.telephony.SmsMessage._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual bool isMWISetMessage()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isMWISetMessage", "()Z", ref global::android.telephony.SmsMessage._m23);
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual bool isMwiDontStore()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isMwiDontStore", "()Z", ref global::android.telephony.SmsMessage._m24);
}
public new byte[] Pdu
{
get
{
return getPdu();
}
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual byte[] getPdu()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.telephony.SmsMessage.staticClass, "getPdu", "()[B", ref global::android.telephony.SmsMessage._m25) as byte[];
}
public new int StatusOnSim
{
get
{
return getStatusOnSim();
}
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual int getStatusOnSim()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getStatusOnSim", "()I", ref global::android.telephony.SmsMessage._m26);
}
public new int StatusOnIcc
{
get
{
return getStatusOnIcc();
}
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual int getStatusOnIcc()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getStatusOnIcc", "()I", ref global::android.telephony.SmsMessage._m27);
}
public new int IndexOnSim
{
get
{
return getIndexOnSim();
}
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual int getIndexOnSim()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getIndexOnSim", "()I", ref global::android.telephony.SmsMessage._m28);
}
public new int IndexOnIcc
{
get
{
return getIndexOnIcc();
}
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual int getIndexOnIcc()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.SmsMessage.staticClass, "getIndexOnIcc", "()I", ref global::android.telephony.SmsMessage._m29);
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual bool isStatusReportMessage()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isStatusReportMessage", "()Z", ref global::android.telephony.SmsMessage._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual bool isReplyPathPresent()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.SmsMessage.staticClass, "isReplyPathPresent", "()Z", ref global::android.telephony.SmsMessage._m31);
}
public static int ENCODING_UNKNOWN
{
get
{
return 0;
}
}
public static int ENCODING_7BIT
{
get
{
return 1;
}
}
public static int ENCODING_8BIT
{
get
{
return 2;
}
}
public static int ENCODING_16BIT
{
get
{
return 3;
}
}
public static int MAX_USER_DATA_BYTES
{
get
{
return 140;
}
}
public static int MAX_USER_DATA_BYTES_WITH_HEADER
{
get
{
return 134;
}
}
public static int MAX_USER_DATA_SEPTETS
{
get
{
return 160;
}
}
public static int MAX_USER_DATA_SEPTETS_WITH_HEADER
{
get
{
return 153;
}
}
static SmsMessage()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.telephony.SmsMessage.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/SmsMessage"));
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Sce.Sled.Lua.Resources;
namespace Sce.Sled.Lua
{
public partial class SledLuaVariableFilterForm : Form
{
/// <summary>
/// Constructor
/// </summary>
public SledLuaVariableFilterForm()
{
InitializeComponent();
}
/// <summary>
/// Indicates whether the local filter state changed during
/// the course of the dialog being shown
/// </summary>
public bool LocalFilterStateChanged
{
get
{
if (m_bLocalChanged)
return true;
for (var i = 0; i < 9; i++)
{
if ((m_iLocalFilterTypes[i] % 2) != 0)
return true;
}
return false;
}
}
/// <summary>
/// Indicates whether the target filter state changed during
/// the course of the dialog being shown
/// </summary>
public bool TargetFilterStateChanged
{
get
{
if (m_bTargetChanged)
return true;
for (var i = 0; i < 9; i++)
{
if ((m_iTargetFilterTypes[i] % 2) != 0)
return true;
}
return false;
}
}
/// <summary>
/// Gets/sets the local filter types
/// </summary>
public bool[] LocalFilterTypes
{
get { return m_bLocalFilterTypes; }
set
{
m_bLocalFilterTypes = value;
m_bLocalModifyingCheckstate = true;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TNIL])
m_chkLocalLuaTNil.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TBOOLEAN])
m_chkLocalLuaTBoolean.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA])
m_chkLocalLuaTLightUserData.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TNUMBER])
m_chkLocalLuaTNumber.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TSTRING])
m_chkLocalLuaTString.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TTABLE])
m_chkLocalLuaTTable.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TFUNCTION])
m_chkLocalLuaTFunction.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TUSERDATA])
m_chkLocalLuaTUserData.CheckState = CheckState.Checked;
if (m_bLocalFilterTypes[(int)LuaType.LUA_TTHREAD])
m_chkLocalLuaTThread.CheckState = CheckState.Checked;
m_bLocalModifyingCheckstate = false;
}
}
/// <summary>
/// Gets/sets the target filter types
/// </summary>
public bool[] TargetFilterTypes
{
get { return m_bTargetFilterTypes; }
set
{
m_bTargetFilterTypes = value;
m_bTargetModifyingCheckstate = true;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TNIL])
m_chkTargetLuaTNil.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TBOOLEAN])
m_chkTargetLuaTBoolean.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA])
m_chkTargetLuaTLightUserData.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TNUMBER])
m_chkTargetLuaTNumber.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TSTRING])
m_chkTargetLuaTString.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TTABLE])
m_chkTargetLuaTTable.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TFUNCTION])
m_chkTargetLuaTFunction.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TUSERDATA])
m_chkTargetLuaTUserData.CheckState = CheckState.Checked;
if (m_bTargetFilterTypes[(int)LuaType.LUA_TTHREAD])
m_chkTargetLuaTThread.CheckState = CheckState.Checked;
m_bTargetModifyingCheckstate = false;
}
}
/// <summary>
/// Gets/sets local filtered names
/// </summary>
public List<string> LocalFilterNames
{
get { return m_lstLocalFilterNames; }
set
{
m_lstLocalFilterNames = value;
foreach (var s in m_lstLocalFilterNames)
m_lstLocalNames.Items.Add(s);
}
}
/// <summary>
/// Gets/sets target filtered names
/// </summary>
public List<string> TargetFilterNames
{
get { return m_lstTargetFilterNames; }
set
{
m_lstTargetFilterNames = value;
foreach (var s in m_lstTargetFilterNames)
m_lstTargetNames.Items.Add(s);
}
}
private bool[] m_bLocalFilterTypes;
private bool[] m_bTargetFilterTypes;
private readonly int[] m_iLocalFilterTypes = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private readonly int[] m_iTargetFilterTypes = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private List<string> m_lstLocalFilterNames;
private List<string> m_lstTargetFilterNames;
private void ChkLocalLuaTNilCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TNIL] = m_chkLocalLuaTNil.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TNIL]++;
}
private void ChkLocalLuaTBooleanCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TBOOLEAN] = m_chkLocalLuaTBoolean.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TBOOLEAN]++;
}
private void ChkLocalLuaTLightUserDataCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA] = m_chkLocalLuaTLightUserData.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA]++;
}
private void ChkLocalLuaTNumberCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TNUMBER] = m_chkLocalLuaTNumber.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TNUMBER]++;
}
private void ChkLocalLuaTStringCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TSTRING] = m_chkLocalLuaTString.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TSTRING]++;
}
private void ChkLocalLuaTTableCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TTABLE] = m_chkLocalLuaTTable.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TTABLE]++;
}
private void ChkLocalLuaTFunctionCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TFUNCTION] = m_chkLocalLuaTFunction.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TFUNCTION]++;
}
private void ChkLocalLuaTUserDataCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TUSERDATA] = m_chkLocalLuaTUserData.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TUSERDATA]++;
}
private void ChkLocalLuaTThreadCheckedChanged(object sender, EventArgs e)
{
if (m_bLocalModifyingCheckstate)
return;
m_bLocalFilterTypes[(int)LuaType.LUA_TTHREAD] = m_chkLocalLuaTThread.CheckState == CheckState.Checked;
m_iLocalFilterTypes[(int)LuaType.LUA_TTHREAD]++;
}
private void ChkTargetLuaTNilCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TNIL] = m_chkTargetLuaTNil.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TNIL]++;
}
private void ChkTargetLuaTBooleanCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TBOOLEAN] = m_chkTargetLuaTBoolean.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TBOOLEAN]++;
}
private void ChkTargetLuaTLightUserDataCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA] = m_chkTargetLuaTLightUserData.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TLIGHTUSERDATA]++;
}
private void ChkTargetLuaTNumberCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TNUMBER] = m_chkTargetLuaTNumber.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TNUMBER]++;
}
private void ChkTargetLuaTStringCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TSTRING] = m_chkTargetLuaTString.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TSTRING]++;
}
private void ChkTargetLuaTTableCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TTABLE] = m_chkTargetLuaTTable.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TTABLE]++;
}
private void ChkTargetLuaTFunctionCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TFUNCTION] = m_chkTargetLuaTFunction.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TFUNCTION]++;
}
private void ChkTargetLuaTUserDataCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TUSERDATA] = m_chkTargetLuaTUserData.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TUSERDATA]++;
}
private void ChkTargetLuaTThreadCheckedChanged(object sender, EventArgs e)
{
if (m_bTargetModifyingCheckstate)
return;
m_bTargetFilterTypes[(int)LuaType.LUA_TTHREAD] = m_chkTargetLuaTThread.CheckState == CheckState.Checked;
m_iTargetFilterTypes[(int)LuaType.LUA_TTHREAD]++;
}
private bool m_bLocalModifyingCheckstate;
private bool m_bTargetModifyingCheckstate;
private bool m_bLocalChanged;
private bool m_bTargetChanged;
/// <summary>
/// Event for clicking the local add button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnLocalListNamesAddClick(object sender, EventArgs e)
{
var form = new SledLuaVariableFilterVarNameForm();
form.Text += Localization.SledLuaTTYFilterAdd;
// Show form
if (form.ShowDialog(this) == DialogResult.OK)
{
var bDuplicate = false;
foreach (var o in m_lstLocalNames.Items)
{
if (o.ToString() == form.VarName)
{
bDuplicate = true;
break;
}
}
if (!bDuplicate)
{
// Add item
m_lstLocalNames.Items.Add(form.VarName);
m_lstLocalFilterNames.Add(form.VarName);
m_bLocalChanged = true;
}
}
}
/// <summary>
/// Event for clicking the local edit button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnLocalListNamesEditClick(object sender, EventArgs e)
{
if (m_lstLocalNames.SelectedItem == null)
return;
var selection = m_lstLocalNames.SelectedItem.ToString();
var form = new SledLuaVariableFilterVarNameForm();
form.Text += Localization.SledLuaTTYFilterEdit;
form.VarName = selection;
// Show form
if (form.ShowDialog(this) == DialogResult.OK)
{
if (selection != form.VarName)
{
var bDuplicate = false;
foreach (var o in m_lstLocalNames.Items)
{
if (o.ToString() == form.VarName)
{
bDuplicate = true;
break;
}
}
if (!bDuplicate)
{
// Remove old item
m_lstLocalNames.Items.Remove(selection);
m_lstLocalFilterNames.Remove(selection);
// Add new item
m_lstLocalNames.Items.Add(form.VarName);
m_lstLocalFilterNames.Add(form.VarName);
// Adjust selection to point to new item
m_lstLocalNames.SelectedItem = form.VarName;
m_bLocalChanged = true;
}
}
}
}
/// <summary>
/// Event for clicking the local delete button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnLocalListNamesDeleteClick(object sender, EventArgs e)
{
if (m_lstLocalNames.SelectedItem == null)
return;
var iIndex = m_lstLocalNames.SelectedIndex;
var selection = m_lstLocalNames.SelectedItem.ToString();
// Remove the selected item
m_lstLocalFilterNames.Remove(selection);
m_lstLocalNames.Items.Remove(selection);
m_bLocalChanged = true;
// Update selection
if (m_lstLocalNames.Items.Count > 0)
{
if (iIndex >= m_lstLocalNames.Items.Count)
iIndex--;
m_lstLocalNames.SelectedIndex = iIndex;
}
}
/// <summary>
/// Event for double clicking the local list box
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void LstLocalNamesMouseDoubleClick(object sender, MouseEventArgs e)
{
// Double clicking edits so piggy back existing method
BtnLocalListNamesEditClick(sender, e);
}
/// <summary>
/// Event for clicking the target add button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnTargetListNamesAddClick(object sender, EventArgs e)
{
var form = new SledLuaVariableFilterVarNameForm();
form.Text += Localization.SledLuaTTYFilterAdd;
// Show form
if (form.ShowDialog(this) == DialogResult.OK)
{
var bDuplicate = false;
foreach (var o in m_lstTargetNames.Items)
{
if (o.ToString() == form.VarName)
{
bDuplicate = true;
break;
}
}
if (!bDuplicate)
{
// Add item
m_lstTargetNames.Items.Add(form.VarName);
m_lstTargetFilterNames.Add(form.VarName);
m_bTargetChanged = true;
}
}
}
/// <summary>
/// Event for clicking the target edit button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnTargetListNamesEditClick(object sender, EventArgs e)
{
if (m_lstTargetNames.SelectedItem == null)
return;
var selection = m_lstTargetNames.SelectedItem.ToString();
var form = new SledLuaVariableFilterVarNameForm();
form.Text += Localization.SledLuaTTYFilterEdit;
form.VarName = selection;
// Show form
if (form.ShowDialog(this) == DialogResult.OK)
{
if (selection != form.VarName)
{
var bDuplicate = false;
foreach (var o in m_lstTargetNames.Items)
{
if (o.ToString() == form.VarName)
{
bDuplicate = true;
break;
}
}
if (!bDuplicate)
{
// Remove old item
m_lstTargetNames.Items.Remove(selection);
m_lstTargetFilterNames.Remove(selection);
// Add new item
m_lstTargetNames.Items.Add(form.VarName);
m_lstTargetFilterNames.Add(form.VarName);
// Adjust selection to point to new item
m_lstTargetNames.SelectedItem = form.VarName;
m_bTargetChanged = true;
}
}
}
}
/// <summary>
/// Event for clicking the target delete button
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void BtnTargetListNamesDeleteClick(object sender, EventArgs e)
{
if (m_lstTargetNames.SelectedItem == null)
return;
var iIndex = m_lstTargetNames.SelectedIndex;
var selection = m_lstTargetNames.SelectedItem.ToString();
// Remove the selected item
m_lstTargetFilterNames.Remove(selection);
m_lstTargetNames.Items.Remove(selection);
m_bTargetChanged = true;
// Update selection
if (m_lstTargetNames.Items.Count > 0)
{
if (iIndex >= m_lstTargetNames.Items.Count)
iIndex--;
m_lstTargetNames.SelectedIndex = iIndex;
}
}
/// <summary>
/// Event for double clicking the target list box
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void LstTargetNamesMouseDoubleClick(object sender, MouseEventArgs e)
{
// Double clicking edits so piggy back existing method
BtnTargetListNamesEditClick(sender, e);
}
/// <summary>
/// Enable/disable edit & delete buttons based on if item is selected or not
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void LstLocalNamesSelectedIndexChanged(object sender, EventArgs e)
{
var lstBox = (ListBox)sender;
if (lstBox.SelectedItem == null)
{
m_btnLocalListNamesEdit.Enabled = false;
m_btnLocalListNamesDelete.Enabled = false;
}
else
{
m_btnLocalListNamesEdit.Enabled = true;
m_btnLocalListNamesDelete.Enabled = true;
}
}
/// <summary>
/// Enable/disable edit & delete buttons based on if item is selected or not
/// </summary>
/// <param name="sender">object that fired the event</param>
/// <param name="e">event arguments</param>
private void LstTargetNamesSelectedIndexChanged(object sender, EventArgs e)
{
var lstBox = (ListBox)sender;
if (lstBox.SelectedItem == null)
{
m_btnTargetListNamesEdit.Enabled = false;
m_btnTargetListNamesDelete.Enabled = false;
}
else
{
m_btnTargetListNamesEdit.Enabled = true;
m_btnTargetListNamesDelete.Enabled = true;
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using Unity.IL2CPP.CompilerServices;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Pixeye.Actors
{
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks | Option.DivideByZeroChecks, false)]
public class PoolContainer
{
List<GameObject> activeObjs = new List<GameObject>(500);
Dictionary<int, Stack<GameObject>> cachedObjects =
new Dictionary<int, Stack<GameObject>>(500, new FastComparable());
Dictionary<int, int> cachedIds = new Dictionary<int, int>(500, new FastComparable());
internal void RegisterAndAdd(GameObject prefab, GameObject obj)
{
var key = prefab.GetInstanceID();
Stack<GameObject> stack;
var hasValue = cachedObjects.TryGetValue(key, out stack);
if (!hasValue) cachedObjects.Add(key, new Stack<GameObject>());
cachedIds.Add(obj.GetInstanceID(), key);
}
public void RegisterObject(GameObject prefab)
{
var key = prefab.GetInstanceID();
Stack<GameObject> stack;
var hasValue = cachedObjects.TryGetValue(key, out stack);
if (!hasValue) cachedObjects.Add(key, new Stack<GameObject>());
}
public void Prepopulate(GameObject prefab, GameObject obj)
{
var key = prefab.GetInstanceID();
Stack<GameObject> stack;
var hasValue = cachedObjects.TryGetValue(key, out stack);
if (!hasValue) cachedObjects.Add(key, new Stack<GameObject>());
else
{
cachedIds.Add(obj.GetInstanceID(), key);
}
}
public void AddToPool(GameObject go, GameObject prefab)
{
cachedIds.Add(go.GetInstanceID(), prefab.GetInstanceID());
}
public PoolContainer PopulateWith(GameObject prefab, int amount, int amountPerTick = 10, int timeRate = 1)
{
var key = prefab.GetInstanceID();
Stack<GameObject> stack;
var hasValue = cachedObjects.TryGetValue(key, out stack);
if (!hasValue) cachedObjects.Add(key, new Stack<GameObject>(amount));
LayerKernel.Run(CoPop());
IEnumerator CoPop()
{
var delay = LayerKernel.Time.deltaTime;
yield return LayerKernel.Wait(delay);
for (var i = 0; i < amountPerTick; i++)
{
if (amount == 0) break;
Populate(prefab, key);
amount--;
}
if (amount > 0)
{
PopulateWith(prefab, amount, amountPerTick, timeRate);
}
}
return this;
}
public bool Spawn(GameObject prefab, out GameObject obj, Transform parent = null)
{
var key = prefab.GetInstanceID();
Stack<GameObject> objs;
var stacked = cachedObjects.TryGetValue(key, out objs);
if (stacked && objs.Count > 0)
{
obj = objs.Pop();
var transform = obj.transform;
if (transform.parent != parent)
transform.SetParent(parent);
transform.gameObject.SetActive(true);
return true;
}
if (!stacked)
{
cachedObjects.Add(key, new Stack<GameObject>(500));
}
var createdPrefab = Object.Instantiate(prefab, parent);
var k = createdPrefab.GetInstanceID();
cachedIds.Add(k, key);
obj = createdPrefab;
return false;
}
public GameObject Spawn(GameObject prefab, Transform parent = null)
{
var key = prefab.GetInstanceID();
Stack<GameObject> objs;
var stacked = cachedObjects.TryGetValue(key, out objs);
if (stacked && objs.Count > 0)
{
var obj = objs.Pop();
var transform = obj.transform;
if (transform.parent != parent)
transform.SetParent(parent);
transform.gameObject.SetActive(true);
return obj;
}
if (!stacked)
{
cachedObjects.Add(key, new Stack<GameObject>(600));
}
var createdPrefab = Object.Instantiate(prefab, parent);
var k = createdPrefab.GetInstanceID();
cachedIds.Add(k, key);
return createdPrefab;
}
public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent = null)
{
var key = prefab.GetInstanceID();
Stack<GameObject> objs;
var stacked = cachedObjects.TryGetValue(key, out objs);
if (stacked && objs.Count > 0)
{
var obj = objs.Pop();
var transform = obj.transform;
if (transform.parent != parent)
transform.SetParent(parent);
transform.position = position;
transform.rotation = rotation;
transform.gameObject.SetActive(true);
return obj;
}
if (!stacked)
{
cachedObjects.Add(key, new Stack<GameObject>(600));
}
if (parent != null)
{
position = parent.TransformPoint(position);
rotation *= parent.rotation;
}
var createdPrefab = Object.Instantiate(prefab, position, rotation, parent);
var k = createdPrefab.GetInstanceID();
cachedIds.Add(k, key);
return createdPrefab;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public void Despawn(GameObject go)
{
go.SetActive(false);
cachedObjects[cachedIds[go.GetInstanceID()]].Push(go);
}
public void DespawnAll()
{
for (var i = 0; i < activeObjs.Count; i++)
{
Despawn(activeObjs[i]);
}
activeObjs.Clear();
}
public void Dispose()
{
cachedObjects.Clear();
cachedIds.Clear();
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
void Populate(GameObject prefab, int key)
{
var go = Object.Instantiate(prefab);
go.SetActive(false);
cachedIds.Add(go.GetInstanceID(), key);
cachedObjects[key].Push(go);
}
}
}
| |
// 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="AdGroupFeedServiceClient"/> instances.</summary>
public sealed partial class AdGroupFeedServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupFeedServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupFeedServiceSettings"/>.</returns>
public static AdGroupFeedServiceSettings GetDefault() => new AdGroupFeedServiceSettings();
/// <summary>Constructs a new <see cref="AdGroupFeedServiceSettings"/> object with default settings.</summary>
public AdGroupFeedServiceSettings()
{
}
private AdGroupFeedServiceSettings(AdGroupFeedServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupFeedSettings = existing.GetAdGroupFeedSettings;
MutateAdGroupFeedsSettings = existing.MutateAdGroupFeedsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupFeedServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupFeedServiceClient.GetAdGroupFeed</c> and <c>AdGroupFeedServiceClient.GetAdGroupFeedAsync</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 GetAdGroupFeedSettings { 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>AdGroupFeedServiceClient.MutateAdGroupFeeds</c> and <c>AdGroupFeedServiceClient.MutateAdGroupFeedsAsync</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 MutateAdGroupFeedsSettings { 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="AdGroupFeedServiceSettings"/> object.</returns>
public AdGroupFeedServiceSettings Clone() => new AdGroupFeedServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupFeedServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupFeedServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupFeedServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupFeedServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupFeedServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupFeedServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupFeedServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupFeedServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupFeedServiceClient Build()
{
AdGroupFeedServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupFeedServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupFeedServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupFeedServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupFeedServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupFeedServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupFeedServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupFeedServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupFeedServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupFeedServiceClient.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>AdGroupFeedService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group feeds.
/// </remarks>
public abstract partial class AdGroupFeedServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupFeedService 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 AdGroupFeedService scopes.</summary>
/// <remarks>
/// The default AdGroupFeedService 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="AdGroupFeedServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AdGroupFeedServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupFeedServiceClient"/>.</returns>
public static stt::Task<AdGroupFeedServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupFeedServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupFeedServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AdGroupFeedServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="AdGroupFeedServiceClient"/>.</returns>
public static AdGroupFeedServiceClient Create() => new AdGroupFeedServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupFeedServiceClient"/> 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="AdGroupFeedServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupFeedServiceClient"/>.</returns>
internal static AdGroupFeedServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupFeedServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupFeedService.AdGroupFeedServiceClient grpcClient = new AdGroupFeedService.AdGroupFeedServiceClient(callInvoker);
return new AdGroupFeedServiceClientImpl(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 AdGroupFeedService client</summary>
public virtual AdGroupFeedService.AdGroupFeedServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group feed 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::AdGroupFeed GetAdGroupFeed(GetAdGroupFeedRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(GetAdGroupFeedRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(GetAdGroupFeedRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupFeed GetAdGroupFeed(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupFeed(new GetAdGroupFeedRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupFeedAsync(new GetAdGroupFeedRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupFeed GetAdGroupFeed(gagvr::AdGroupFeedName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupFeed(new GetAdGroupFeedRequest
{
ResourceNameAsAdGroupFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(gagvr::AdGroupFeedName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupFeedAsync(new GetAdGroupFeedRequest
{
ResourceNameAsAdGroupFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(gagvr::AdGroupFeedName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateAdGroupFeedsResponse MutateAdGroupFeeds(MutateAdGroupFeedsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateAdGroupFeedsResponse> MutateAdGroupFeedsAsync(MutateAdGroupFeedsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateAdGroupFeedsResponse> MutateAdGroupFeedsAsync(MutateAdGroupFeedsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group feeds.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupFeedsResponse MutateAdGroupFeeds(string customerId, scg::IEnumerable<AdGroupFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupFeeds(new MutateAdGroupFeedsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group feeds.
/// </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<MutateAdGroupFeedsResponse> MutateAdGroupFeedsAsync(string customerId, scg::IEnumerable<AdGroupFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupFeedsAsync(new MutateAdGroupFeedsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group feeds.
/// </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<MutateAdGroupFeedsResponse> MutateAdGroupFeedsAsync(string customerId, scg::IEnumerable<AdGroupFeedOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupFeedsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupFeedService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group feeds.
/// </remarks>
public sealed partial class AdGroupFeedServiceClientImpl : AdGroupFeedServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupFeedRequest, gagvr::AdGroupFeed> _callGetAdGroupFeed;
private readonly gaxgrpc::ApiCall<MutateAdGroupFeedsRequest, MutateAdGroupFeedsResponse> _callMutateAdGroupFeeds;
/// <summary>
/// Constructs a client wrapper for the AdGroupFeedService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AdGroupFeedServiceSettings"/> used within this client.</param>
public AdGroupFeedServiceClientImpl(AdGroupFeedService.AdGroupFeedServiceClient grpcClient, AdGroupFeedServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupFeedServiceSettings effectiveSettings = settings ?? AdGroupFeedServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupFeed = clientHelper.BuildApiCall<GetAdGroupFeedRequest, gagvr::AdGroupFeed>(grpcClient.GetAdGroupFeedAsync, grpcClient.GetAdGroupFeed, effectiveSettings.GetAdGroupFeedSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupFeed);
Modify_GetAdGroupFeedApiCall(ref _callGetAdGroupFeed);
_callMutateAdGroupFeeds = clientHelper.BuildApiCall<MutateAdGroupFeedsRequest, MutateAdGroupFeedsResponse>(grpcClient.MutateAdGroupFeedsAsync, grpcClient.MutateAdGroupFeeds, effectiveSettings.MutateAdGroupFeedsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupFeeds);
Modify_MutateAdGroupFeedsApiCall(ref _callMutateAdGroupFeeds);
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_GetAdGroupFeedApiCall(ref gaxgrpc::ApiCall<GetAdGroupFeedRequest, gagvr::AdGroupFeed> call);
partial void Modify_MutateAdGroupFeedsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupFeedsRequest, MutateAdGroupFeedsResponse> call);
partial void OnConstruction(AdGroupFeedService.AdGroupFeedServiceClient grpcClient, AdGroupFeedServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupFeedService client</summary>
public override AdGroupFeedService.AdGroupFeedServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupFeedRequest(ref GetAdGroupFeedRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupFeedsRequest(ref MutateAdGroupFeedsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group feed 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::AdGroupFeed GetAdGroupFeed(GetAdGroupFeedRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupFeedRequest(ref request, ref callSettings);
return _callGetAdGroupFeed.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group feed 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::AdGroupFeed> GetAdGroupFeedAsync(GetAdGroupFeedRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupFeedRequest(ref request, ref callSettings);
return _callGetAdGroupFeed.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateAdGroupFeedsResponse MutateAdGroupFeeds(MutateAdGroupFeedsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupFeedsRequest(ref request, ref callSettings);
return _callMutateAdGroupFeeds.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes ad group feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AdGroupFeedError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateAdGroupFeedsResponse> MutateAdGroupFeedsAsync(MutateAdGroupFeedsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupFeedsRequest(ref request, ref callSettings);
return _callMutateAdGroupFeeds.Async(request, callSettings);
}
}
}
| |
// $begin{copyright}
//
// This file is part of WebSharper
//
// Copyright (c) 2008-2018 IntelliFactory
//
// 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.
//
// $end{copyright}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.FSharp.Core;
using WebSharper;
using WebSharper.JavaScript;
using WebSharper.Sitelets;
using WebSharper.UI;
using WebSharper.UI.Client;
using static WebSharper.UI.Client.Html;
using static WebSharper.UI.V;
namespace WebSharper.UI.CSharp.Tests
{
[JavaScript]
public class App
{
[EndPoint("/{First}/{Last}")]
public class Name
{
public string First;
public string Last;
private Name() { }
public Name(string first, string last)
{
First = first;
Last = last;
}
}
[EndPoint("/")]
public class Home {
[EndPoint("/person/{Name}/{Age}")]
public class Person : Home
{
public Name Name;
[Query]
public int? Age;
private Person() { }
public Person(Name name, int? age)
{
Name = name;
Age = age;
}
}
[EndPoint("/people/{people}")]
public class People : Home
{
public Name[] people;
}
}
public class LoginData
{
public string Username { get; set; }
public string Password { get; set; }
}
public class Rpc
{
[Remote]
public static Task<bool> Login(LoginData data) => Task.FromResult(true);
}
void Animating()
{
// define animations that can be parametrized by start and end times
Func<double, double, Anim<double>> linearAnim =
(start, end) => Anim.Simple(Interpolation.Double, new Easing(x => x), 300, start, end);
Func<double, double, Anim<double>> cubicAnim =
(start, end) => Anim.Simple(Interpolation.Double, Easing.CubicInOut, 300, start, end);
// define the transition with a cubic in and out and linear in between
var swipeTransition =
new Trans<double>(linearAnim, x => cubicAnim(x - 100, x), x => cubicAnim(x, x + 100));
var rvLeftPos = Var.Create<double>(0);
var animatedDoc =
div(
style("position", "relative"),
// TODO + with object and string
style("left", swipeTransition, rvLeftPos.View, pos => pos + "%"),
"content"
);
}
void DocConstruction()
{
//var rvUsername = Var.Create("");
//var rvPassword = Var.Create("");
//var vLoginData =
// rvUsername.View.Map2(rvPassword.View, (username, password) =>
// new LoginData { Username = username, Password = password });
//var sLoginData = Submitter.Create(vLoginData, null);
//var vLoginResult = sLoginData.View.MapAsync(async login => await Rpc.Login(login));
//div(
// input(rvUsername),
// passwordBox(rvPassword),
// button("Log in", sLoginData.Trigger),
// vLoginResult.Map(res => Doc.Empty)
//);
//{
// Doc myDoc = Doc.TextNode("WebSharper");
// //WebSharper.UI.Client.Doc
// // myDoc HTML equivalent is now: WebSharper
//}
//{
// var myDoc = Doc.SvgElement("rect",
// new[] {
// Attr.Create("width", "150"),
// Attr.Create("height", "120")
// }, Enumerable.Empty<Doc>());
//}
//{
// var myDoc =
// Doc.Append(
// text("Visit "),
// a(attr.href("http://websharper.com"), "WebSharper"));
//}
//WebSharper.UI.CSharp.Client.Html.textarea
//inputArea();
}
static async Task<string> LoginUser(string u, string p)
{
await Task.Delay(500);
return "Done";
}
void LoginForm()
{
//type LoginData = { Username: string; Password: string }
//var rvSubmit = Var.Create<object>(null);
//var rvUsername = Var.Create("");
//var rvPassword = Var.Create("");
//var vLoginResult =
// rvUsername.View.Bind(u =>
// rvPassword.View.Map(p =>
// new { Username = u, Password = p }
// )
// ).SnapshotOn(null, rvSubmit.View).MapAsync(async res => LoginUser)
}
public class TestRecord
{
public string X;
public string P { get; set; }
}
[SPAEntryPoint]
public static void ClientMain()
{
// Don't run the entry point in Routing.Tests
if (JS.Document.GetElementById("main") == null) return;
var people = ListModel.FromSeq(new[] { "John", "Paul" });
var newName = Var.Create("");
var router = InferRouter.Router.Infer<Home>();
var endpoint = router.InstallHash(new Home());
var routed =
endpoint.View.Map((Home act) =>
{
switch (act) {
case Home.Person p:
return div(p.Name.First, " ", p.Name.Last,
p.Age == null ? " won't tell their age!" : $" is {p.Age} years old!",
button("Back", () => endpoint.Value = new Home())
);
case Home.People p:
return ul(p.people.Select(x => li(x.First, " ", x.Last)).ToArray());
default:
var first = Var.Create("John");
var last = Var.Create("Doe");
var age = Var.Create(20);
return div(
input(first),
input(last),
input(age),
button("Go", () =>
endpoint.Value = new Home.Person(new Name(first.Value, last.Value),
age.Value == 0 ? null : (int?)age.Value))
);
}
});
var testRecordVar = Var.Create(new TestRecord { X = "Hello from a field", P = "Hello from a property" });
div(
h1("My list of unique people"),
ul(people.View.DocSeqCached((string x) => li(x))),
div(
input(newName, attr.placeholder("Name")),
button("Add", () =>
{
people.Add(newName.Value);
newName.Value = "";
}),
div(newName.View)
),
h1("Routed element:"),
routed,
h1("V test:"),
ul(
li(testRecordVar.V.X),
li(testRecordVar.V.P)
)
).RunById("main");
TodoApp();
}
public class TaskItem
{
public string Name { get; private set; }
public int Priority { get; private set; }
public Var<bool> Done { get; private set; }
public TaskItem(string name, int priority, bool done)
{
Name = name;
Priority = priority;
Done = Var.Create(done);
}
}
public static void TodoApp()
{
var Tasks =
new ListModel<string, TaskItem>(task => task.Name) {
new TaskItem("Have breakfast", 8, true),
new TaskItem("Have lunch", 6, false)
};
var newTaskPriority = Var.Create(5);
new Template.Template.Main()
.ListContainer(
Tasks.View
.Map(l => (IEnumerable<TaskItem>)l.OrderByDescending(t => t.Priority))
.DocSeqCached((TaskItem task) => new Template.Template.ListItem()
.Task(task.Name)
.Priority(task.Priority.ToString())
.Clear((el, ev) => Tasks.RemoveByKey(task.Name))
.Done(task.Done)
.ShowDone(attr.@class("checked", task.Done.View, x => x))
.Elt()
))
.Add((m) =>
{
Tasks.Add(new TaskItem(m.Vars.NewTaskName.Value, newTaskPriority.Value, false));
m.Vars.NewTaskName.Value = "";
})
.ClearCompleted((el, ev) => Tasks.RemoveBy(task => task.Done.Value))
.NewTaskPriority(newTaskPriority)
.Doc()
.RunById("tasks");
new Template.Index.tasksTitle()
.Elt()
.OnAfterRender(FSharpConvert.Fun<JavaScript.Dom.Element>((el) => JavaScript.Console.Log("test")))
.RunById("tasksTitle");
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
#endif
using System.Security;
using System.Text;
using Moq.Language;
using Moq.Properties;
namespace Moq
{
/// <summary>
/// Exception thrown by mocks when they are not properly set up,
/// when setups are not matched, when verification fails, etc.
/// </summary>
/// <remarks>
/// A distinct exception type is provided so that exceptions
/// thrown by a mock can be distinguished from other exceptions
/// that might be thrown in tests.
/// <para>
/// Moq does not provide a richer hierarchy of exception types, as
/// tests typically should <em>not</em> catch or expect exceptions
/// from mocks. These are typically the result of changes
/// in the tested class or its collaborators' implementation, and
/// result in fixes in the mock setup so that they disappear and
/// allow the test to pass.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "It's only initialized internally.")]
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public class MockException : Exception
{
/// <summary>
/// Returns the exception to be thrown when a setup limited by <see cref="IOccurrence.AtMostOnce()"/> is invoked more often than once.
/// </summary>
internal static MockException MoreThanOneCall(MethodCall setup, int invocationCount)
{
var message = new StringBuilder();
message.AppendLine(setup.FailMessage ?? "")
.Append(Times.AtMostOnce().GetExceptionMessage(invocationCount))
.AppendLine(setup.Expression.ToStringFixed());
return new MockException(MockExceptionReasons.MoreThanOneCall, message.ToString());
}
/// <summary>
/// Returns the exception to be thrown when a setup limited by <see cref="IOccurrence.AtMost(int)"/> is invoked more often than the specified maximum number of times.
/// </summary>
internal static MockException MoreThanNCalls(MethodCall setup, int maxInvocationCount, int invocationCount)
{
var message = new StringBuilder();
message.AppendLine(setup.FailMessage ?? "")
.Append(Times.AtMost(maxInvocationCount).GetExceptionMessage(invocationCount))
.AppendLine(setup.Expression.ToStringFixed());
return new MockException(MockExceptionReasons.MoreThanNCalls, message.ToString());
}
/// <summary>
/// Returns the exception to be thrown when <see cref="Mock.Verify"/> finds no invocations (or the wrong number of invocations) that match the specified expectation.
/// </summary>
internal static MockException NoMatchingCalls(
Mock rootMock,
LambdaExpression expression,
string failMessage,
Times times,
int callCount)
{
var message = new StringBuilder();
message.AppendLine(failMessage ?? "")
.Append(times.GetExceptionMessage(callCount))
.AppendLine(expression.PartialMatcherAwareEval().ToStringFixed())
.AppendLine()
.AppendLine(Resources.PerformedInvocations)
.AppendLine();
var visitedMocks = new HashSet<Mock>();
var mocks = new Queue<Mock>();
mocks.Enqueue(rootMock);
while (mocks.Any())
{
var mock = mocks.Dequeue();
if (visitedMocks.Contains(mock)) continue;
visitedMocks.Add(mock);
message.AppendLine(mock == rootMock ? $" {mock} ({expression.Parameters[0].Name}):"
: $" {mock}:");
var invocations = mock.MutableInvocations.ToArray();
if (invocations.Any())
{
message.AppendLine();
foreach (var invocation in invocations)
{
message.Append($" {invocation}");
if (invocation.Method.ReturnType != typeof(void) && Unwrap.ResultIfCompletedTask(invocation.ReturnValue) is IMocked mocked)
{
var innerMock = mocked.Mock;
mocks.Enqueue(innerMock);
message.Append($" => {innerMock}");
}
message.AppendLine();
}
}
else
{
message.AppendLine($" {Resources.NoInvocationsPerformed}");
}
message.AppendLine();
}
return new MockException(MockExceptionReasons.NoMatchingCalls, message.TrimEnd().AppendLine().ToString());
}
/// <summary>
/// Returns the exception to be thrown when a strict mock has no setup corresponding to the specified invocation.
/// </summary>
internal static MockException NoSetup(Invocation invocation)
{
return new MockException(
MockExceptionReasons.NoSetup,
string.Format(
CultureInfo.CurrentCulture,
Resources.MockExceptionMessage,
invocation.ToString(),
MockBehavior.Strict,
Resources.NoSetup));
}
/// <summary>
/// Returns the exception to be thrown when a strict mock has no setup that provides a return value for the specified invocation.
/// </summary>
internal static MockException ReturnValueRequired(Invocation invocation)
{
return new MockException(
MockExceptionReasons.ReturnValueRequired,
string.Format(
CultureInfo.CurrentCulture,
Resources.MockExceptionMessage,
invocation.ToString(),
MockBehavior.Strict,
Resources.ReturnValueRequired));
}
/// <summary>
/// Returns the exception to be thrown when a setup has not been invoked.
/// </summary>
internal static MockException UnmatchedSetup(Setup setup)
{
return new MockException(
MockExceptionReasons.UnmatchedSetup,
string.Format(
CultureInfo.CurrentCulture,
Resources.UnmatchedSetup,
setup));
}
internal static MockException FromInnerMockOf(Setup setup, MockException error)
{
var message = new StringBuilder();
message.AppendLine(string.Format(CultureInfo.CurrentCulture, Resources.VerificationErrorsOfInnerMock, setup)).TrimEnd().AppendLine()
.AppendLine();
message.AppendIndented(error.Message, count: 3);
return new MockException(error.Reasons, message.ToString());
}
/// <summary>
/// Returns an exception whose message is the concatenation of the given <paramref name="errors"/>' messages
/// and whose reason(s) is the combination of the given <paramref name="errors"/>' reason(s).
/// Used by <see cref="MockFactory.VerifyMocks(Action{Mock})"/> when it finds one or more mocks with verification errors.
/// </summary>
internal static MockException Combined(IEnumerable<MockException> errors, string preamble)
{
Debug.Assert(errors != null);
Debug.Assert(errors.Any());
var reasons = default(MockExceptionReasons);
var message = new StringBuilder();
if (preamble != null)
{
message.Append(preamble).TrimEnd().AppendLine()
.AppendLine();
}
foreach (var error in errors)
{
reasons |= error.Reasons;
message.AppendIndented(error.Message, count: 3).TrimEnd().AppendLine()
.AppendLine();
}
return new MockException(reasons, message.TrimEnd().ToString());
}
/// <summary>
/// Returns the exception to be thrown when <see cref="Mock.VerifyNoOtherCalls(Mock)"/> finds invocations that have not been verified.
/// </summary>
internal static MockException UnverifiedInvocations(Mock mock, IEnumerable<Invocation> invocations)
{
var message = new StringBuilder();
message.AppendLine(string.Format(CultureInfo.CurrentCulture, Resources.UnverifiedInvocations, mock)).TrimEnd().AppendLine()
.AppendLine();
foreach (var invocation in invocations)
{
message.AppendIndented(invocation.ToString(), count: 3).TrimEnd().AppendLine();
}
return new MockException(MockExceptionReasons.UnverifiedInvocations, message.TrimEnd().ToString());
}
private readonly MockExceptionReasons reasons;
private MockException(MockExceptionReasons reasons, string message)
: base(message)
{
this.reasons = reasons;
}
internal MockExceptionReasons Reasons => this.reasons;
/// <summary>
/// Indicates whether this exception is a verification fault raised by Verify()
/// </summary>
public bool IsVerificationError
{
get
{
const MockExceptionReasons verificationErrorMask = MockExceptionReasons.NoMatchingCalls
| MockExceptionReasons.UnmatchedSetup
| MockExceptionReasons.UnverifiedInvocations;
return (this.reasons & verificationErrorMask) != 0;
}
}
#if FEATURE_SERIALIZATION
/// <summary>
/// Supports the serialization infrastructure.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected MockException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.reasons = (MockExceptionReasons)info.GetValue(nameof(this.reasons), typeof(MockExceptionReasons));
}
/// <summary>
/// Supports the serialization infrastructure.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(this.reasons), this.reasons);
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt641()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt641();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt641
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt64 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
Vector256<UInt64> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt64)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<UInt64>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
UInt64[] resultElements = new UInt64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using System.Linq;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord;
using NLog;
using System;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Concurrent;
namespace NadekoBot.Modules.Pokemon
{
[NadekoModule("Pokemon", ">")]
public partial class Pokemon : DiscordModule
{
private static List<PokemonType> PokemonTypes = new List<PokemonType>();
private static ConcurrentDictionary<ulong, PokeStats> Stats = new ConcurrentDictionary<ulong, PokeStats>();
public const string PokemonTypesFile = "data/pokemon_types.json";
private static new Logger _log { get; }
static Pokemon()
{
_log = LogManager.GetCurrentClassLogger();
if (File.Exists(PokemonTypesFile))
{
PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText(PokemonTypesFile));
}
else
{
_log.Warn(PokemonTypesFile + " is missing. Pokemon types not loaded.");
}
}
private int GetDamage(PokemonType usertype, PokemonType targetType)
{
var rng = new Random();
int damage = rng.Next(40, 60);
foreach (PokemonMultiplier Multiplier in usertype.Multipliers)
{
if (Multiplier.Type == targetType.Name)
{
var multiplier = Multiplier.Multiplication;
damage = (int)(damage * multiplier);
}
}
return damage;
}
private PokemonType GetPokeType(ulong id)
{
Dictionary<ulong, string> setTypes;
using (var uow = DbHandler.UnitOfWork())
{
setTypes = uow.PokeGame.GetAll().ToDictionary(x => x.UserId, y => y.type);
}
if (setTypes.ContainsKey(id))
{
return StringToPokemonType(setTypes[id]);
}
int count = PokemonTypes.Count;
int remainder = Math.Abs((int)(id % (ulong)count));
return PokemonTypes[remainder];
}
private PokemonType StringToPokemonType(string v)
{
var str = v?.ToUpperInvariant();
var list = PokemonTypes;
foreach (PokemonType p in list)
{
if (str == p.Name)
{
return p;
}
}
return null;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Attack(string move, IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (string.IsNullOrWhiteSpace(move)) {
return;
}
if (targetUser == null)
{
await Context.Channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return;
}
else if (targetUser == user)
{
await Context.Channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false);
return;
}
// Checking stats first, then move
//Set up the userstats
PokeStats userStats;
userStats = Stats.GetOrAdd(user.Id, new PokeStats());
//Check if able to move
//User not able if HP < 0, has made more than 4 attacks
if (userStats.Hp < 0)
{
await Context.Channel.SendMessageAsync($"{user.Mention} has fainted and was not able to move!").ConfigureAwait(false);
return;
}
if (userStats.MovesMade >= 5)
{
await Context.Channel.SendMessageAsync($"{user.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false);
return;
}
if (userStats.LastAttacked.Contains(targetUser.Id))
{
await Context.Channel.SendMessageAsync($"{user.Mention} can't attack again without retaliation!").ConfigureAwait(false);
return;
}
//get target stats
PokeStats targetStats;
targetStats = Stats.GetOrAdd(targetUser.Id, new PokeStats());
//If target's HP is below 0, no use attacking
if (targetStats.Hp <= 0)
{
await Context.Channel.SendMessageAsync($"{targetUser.Mention} has already fainted!").ConfigureAwait(false);
return;
}
//Check whether move can be used
PokemonType userType = GetPokeType(user.Id);
var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
{
await Context.Channel.SendMessageAsync($"{user.Mention} is not able to use **{move}**. Type {NadekoBot.ModulePrefixes[typeof(Pokemon).Name]}ml to see moves").ConfigureAwait(false);
return;
}
//get target type
PokemonType targetType = GetPokeType(targetUser.Id);
//generate damage
int damage = GetDamage(userType, targetType);
//apply damage to target
targetStats.Hp -= damage;
var response = $"{user.Mention} used **{move}**{userType.Icon} on {targetUser.Mention}{targetType.Icon} for **{damage}** damage";
//Damage type
if (damage < 40)
{
response += "\nIt's not effective..";
}
else if (damage > 60)
{
response += "\nIt's super effective!";
}
else
{
response += "\nIt's somewhat effective";
}
//check fainted
if (targetStats.Hp <= 0)
{
response += $"\n**{targetUser.Mention}** has fainted!";
}
else
{
response += $"\n**{targetUser.Mention}** has {targetStats.Hp} HP remaining";
}
//update other stats
userStats.LastAttacked.Add(targetUser.Id);
userStats.MovesMade++;
targetStats.MovesMade = 0;
if (targetStats.LastAttacked.Contains(user.Id))
{
targetStats.LastAttacked.Remove(user.Id);
}
//update dictionary
//This can stay the same right?
Stats[user.Id] = userStats;
Stats[targetUser.Id] = targetStats;
await Context.Channel.SendMessageAsync(response).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Movelist()
{
IGuildUser user = (IGuildUser)Context.User;
var userType = GetPokeType(user.Id);
var movesList = userType.Moves;
var str = $"**Moves for `{userType.Name}` type.**";
foreach (string m in movesList)
{
str += $"\n{userType.Icon}{m}";
}
await Context.Channel.SendMessageAsync(str).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Heal(IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (targetUser == null) {
await Context.Channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return;
}
if (Stats.ContainsKey(targetUser.Id))
{
var targetStats = Stats[targetUser.Id];
if (targetStats.Hp == targetStats.MaxHp)
{
await Context.Channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
var target = (targetUser.Id == user.Id) ? "yourself" : targetUser.Mention;
if (amount > 0)
{
if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"Poke-Heal {target}", amount, true).ConfigureAwait(false))
{
try { await Context.Channel.SendMessageAsync($"{user.Mention} You don't have enough {NadekoBot.BotConfig.CurrencyName}s.").ConfigureAwait(false); } catch { }
return;
}
}
//healing
targetStats.Hp = targetStats.MaxHp;
if (targetStats.Hp < 0)
{
//Could heal only for half HP?
Stats[targetUser.Id].Hp = (targetStats.MaxHp / 2);
if (target == "yourself")
{
await Context.Channel.SendMessageAsync($"You revived yourself with one {NadekoBot.BotConfig.CurrencySign}").ConfigureAwait(false);
}
else
{
await Context.Channel.SendMessageAsync($"{user.Mention} revived {targetUser.Mention} with one {NadekoBot.BotConfig.CurrencySign}").ConfigureAwait(false);
}
return;
}
await Context.Channel.SendMessageAsync($"{user.Mention} healed {targetUser.Mention} with one {NadekoBot.BotConfig.CurrencySign}").ConfigureAwait(false);
return;
}
else
{
await Context.Channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false);
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Type(IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (targetUser == null)
{
return;
}
var pType = GetPokeType(targetUser.Id);
await Context.Channel.SendMessageAsync($"Type of {targetUser.Mention} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Settype([Remainder] string typeTargeted = null)
{
IGuildUser user = (IGuildUser)Context.User;
var targetType = StringToPokemonType(typeTargeted);
if (targetType == null)
{
await Context.Channel.EmbedAsync(PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"),
(eb, pt) => eb.AddField(efb => efb.WithName(pt.Name)
.WithValue(pt.Icon)
.WithIsInline(true)))
.WithColor(NadekoBot.OkColor)).ConfigureAwait(false);
return;
}
if (targetType == GetPokeType(user.Id))
{
await Context.Channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
if (amount > 0)
{
if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"{user.Mention} change type to {typeTargeted}", amount, true).ConfigureAwait(false))
{
try { await Context.Channel.SendMessageAsync($"{user.Mention} You don't have enough {NadekoBot.BotConfig.CurrencyName}s.").ConfigureAwait(false); } catch { }
return;
}
}
//Actually changing the type here
Dictionary<ulong, string> setTypes;
using (var uow = DbHandler.UnitOfWork())
{
var pokeUsers = uow.PokeGame.GetAll();
setTypes = pokeUsers.ToDictionary(x => x.UserId, y => y.type);
var pt = new UserPokeTypes
{
UserId = user.Id,
type = targetType.Name,
};
if (!setTypes.ContainsKey(user.Id))
{
//create user in db
uow.PokeGame.Add(pt);
}
else
{
//update user in db
var pokeUserCmd = pokeUsers.Where(p => p.UserId == user.Id).FirstOrDefault();
pokeUserCmd.type = targetType.Name;
uow.PokeGame.Update(pokeUserCmd);
}
await uow.CompleteAsync();
}
//Now for the response
await Context.Channel.SendMessageAsync($"Set type of {user.Mention} to {typeTargeted}{targetType.Icon} for a {NadekoBot.BotConfig.CurrencySign}").ConfigureAwait(false);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.Debugging;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Debugging;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
using IVsDebugName = Microsoft.VisualStudio.TextManager.Interop.IVsDebugName;
using IVsEnumBSTR = Microsoft.VisualStudio.TextManager.Interop.IVsEnumBSTR;
using IVsTextBuffer = Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer;
using IVsTextLines = Microsoft.VisualStudio.TextManager.Interop.IVsTextLines;
using RESOLVENAMEFLAGS = Microsoft.VisualStudio.TextManager.Interop.RESOLVENAMEFLAGS;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
internal abstract partial class AbstractLanguageService<TPackage, TLanguageService>
{
internal class VsLanguageDebugInfo : IVsLanguageDebugInfo
{
private readonly Guid _languageId;
private readonly TLanguageService _languageService;
private readonly ILanguageDebugInfoService _languageDebugInfo;
private readonly IBreakpointResolutionService _breakpointService;
private readonly IProximityExpressionsService _proximityExpressionsService;
private readonly IWaitIndicator _waitIndicator;
private readonly CachedProximityExpressionsGetter _cachedProximityExpressionsGetter;
public VsLanguageDebugInfo(
Guid languageId,
TLanguageService languageService,
HostLanguageServices languageServiceProvider,
IWaitIndicator waitIndicator)
{
Contract.ThrowIfNull(languageService);
Contract.ThrowIfNull(languageServiceProvider);
_languageId = languageId;
_languageService = languageService;
_languageDebugInfo = languageServiceProvider.GetService<ILanguageDebugInfoService>();
_breakpointService = languageServiceProvider.GetService<IBreakpointResolutionService>();
_proximityExpressionsService = languageServiceProvider.GetService<IProximityExpressionsService>();
_cachedProximityExpressionsGetter = new CachedProximityExpressionsGetter(_proximityExpressionsService);
_waitIndicator = waitIndicator;
}
internal void OnDebugModeChanged(DebugMode debugMode)
{
_cachedProximityExpressionsGetter.OnDebugModeChanged(debugMode);
}
public int GetLanguageID(IVsTextBuffer pBuffer, int iLine, int iCol, out Guid pguidLanguageID)
{
pguidLanguageID = _languageId;
return VSConstants.S_OK;
}
public int GetLocationOfName(string pszName, out string pbstrMkDoc, out VsTextSpan pspanLocation)
{
pbstrMkDoc = null;
pspanLocation = default(VsTextSpan);
return VSConstants.E_NOTIMPL;
}
public int GetNameOfLocation(IVsTextBuffer pBuffer, int iLine, int iCol, out string pbstrName, out int piLineOffset)
{
using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetNameOfLocation, CancellationToken.None))
{
string name = null;
int lineOffset = 0;
var succeeded = false;
if (_languageDebugInfo != null)
{
_waitIndicator.Wait(
title: ServicesVSResources.Debugger,
message: ServicesVSResources.Determining_breakpoint_location,
allowCancel: true,
action: waitContext =>
{
var cancellationToken = waitContext.CancellationToken;
var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);
if (textBuffer != null)
{
var point = textBuffer.CurrentSnapshot.GetPoint(iLine, iCol);
var document = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
// NOTE(cyrusn): We have to wait here because the debuggers'
// GetNameOfLocation is a blocking call. In the future, it
// would be nice if they could make it async.
var debugLocationInfo = _languageDebugInfo.GetLocationInfoAsync(document, point, cancellationToken).WaitAndGetResult(cancellationToken);
if (!debugLocationInfo.IsDefault)
{
succeeded = true;
name = debugLocationInfo.Name;
lineOffset = debugLocationInfo.LineOffset;
}
}
}
});
if (succeeded)
{
pbstrName = name;
piLineOffset = lineOffset;
return VSConstants.S_OK;
}
}
// Note(DustinCa): Docs say that GetNameOfLocation should return S_FALSE if a name could not be found.
// Also, that's what the old native code does, so we should do it here.
pbstrName = null;
piLineOffset = 0;
return VSConstants.S_FALSE;
}
}
public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR ppEnum)
{
// NOTE(cyrusn): cLines is ignored. This is to match existing dev10 behavior.
using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetProximityExpressions, CancellationToken.None))
{
VsEnumBSTR enumBSTR = null;
var succeeded = false;
_waitIndicator.Wait(
title: ServicesVSResources.Debugger,
message: ServicesVSResources.Determining_autos,
allowCancel: true,
action: waitContext =>
{
var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);
if (textBuffer != null)
{
var snapshot = textBuffer.CurrentSnapshot;
Document document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var point = snapshot.GetPoint(iLine, iCol);
var proximityExpressions = _proximityExpressionsService.GetProximityExpressionsAsync(document, point.Position, waitContext.CancellationToken).WaitAndGetResult(waitContext.CancellationToken);
if (proximityExpressions != null)
{
enumBSTR = new VsEnumBSTR(proximityExpressions);
succeeded = true;
}
}
}
});
if (succeeded)
{
ppEnum = enumBSTR;
return VSConstants.S_OK;
}
ppEnum = null;
return VSConstants.E_FAIL;
}
}
public int IsMappedLocation(IVsTextBuffer pBuffer, int iLine, int iCol)
{
return VSConstants.E_NOTIMPL;
}
public int ResolveName(string pszName, uint dwFlags, out IVsEnumDebugName ppNames)
{
using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ResolveName, CancellationToken.None))
{
// In VS, this method frequently get's called with an empty string to test if the language service
// supports this method (some language services, like F#, implement IVsLanguageDebugInfo but don't
// implement this method). In that scenario, there's no sense doing work, so we'll just return
// S_FALSE (as the old VB language service did).
if (string.IsNullOrEmpty(pszName))
{
ppNames = null;
return VSConstants.S_FALSE;
}
VsEnumDebugName enumName = null;
var succeeded = false;
_waitIndicator.Wait(
title: ServicesVSResources.Debugger,
message: ServicesVSResources.Resolving_breakpoint_location,
allowCancel: true,
action: waitContext =>
{
var cancellationToken = waitContext.CancellationToken;
if (dwFlags == (uint)RESOLVENAMEFLAGS.RNF_BREAKPOINT)
{
var solution = _languageService.Workspace.CurrentSolution;
// NOTE(cyrusn): We have to wait here because the debuggers' ResolveName
// call is synchronous. In the future it would be nice to make it async.
if (_breakpointService != null)
{
var breakpoints = _breakpointService.ResolveBreakpointsAsync(solution, pszName, cancellationToken).WaitAndGetResult(cancellationToken);
var debugNames = breakpoints.Select(bp => CreateDebugName(bp, solution, cancellationToken)).WhereNotNull().ToList();
enumName = new VsEnumDebugName(debugNames);
succeeded = true;
}
}
});
if (succeeded)
{
ppNames = enumName;
return VSConstants.S_OK;
}
ppNames = null;
return VSConstants.E_NOTIMPL;
}
}
private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken)
{
var document = breakpoint.Document;
var filePath = _languageService.Workspace.GetFilePath(document.Id);
var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var span = text.GetVsTextSpanForSpan(breakpoint.TextSpan);
// If we're inside an Venus code nugget, we need to map the span to the surface buffer.
// Otherwise, we'll just use the original span.
if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out var mappedSpan))
{
mappedSpan = span;
}
return new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan);
}
public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan)
{
using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation, CancellationToken.None))
{
int result = VSConstants.E_NOTIMPL;
_waitIndicator.Wait(
title: ServicesVSResources.Debugger,
message: ServicesVSResources.Validating_breakpoint_location,
allowCancel: true,
action: waitContext =>
{
result = ValidateBreakpointLocationWorker(pBuffer, iLine, iCol, pCodeSpan, waitContext.CancellationToken);
});
return result;
}
}
private int ValidateBreakpointLocationWorker(
IVsTextBuffer pBuffer,
int iLine,
int iCol,
VsTextSpan[] pCodeSpan,
CancellationToken cancellationToken)
{
if (_breakpointService == null)
{
return VSConstants.E_FAIL;
}
var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer);
if (textBuffer != null)
{
var snapshot = textBuffer.CurrentSnapshot;
Document document = snapshot.AsText().GetDocumentWithFrozenPartialSemanticsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
if (document != null)
{
var point = snapshot.GetPoint(iLine, iCol);
var length = 0;
if (pCodeSpan != null && pCodeSpan.Length > 0)
{
// If we have a non-empty span then it means that the debugger is asking us to adjust an
// existing span. In Everett we didn't do this so we had some good and some bad
// behavior. For example if you had a breakpoint on: "int i;" and you changed it to "int
// i = 4;", then the breakpoint wouldn't adjust. That was bad. However, if you had the
// breakpoint on an open or close curly brace then it would always "stick" to that brace
// which was good.
//
// So we want to keep the best parts of both systems. We want to appropriately "stick"
// to tokens and we also want to adjust spans intelligently.
//
// However, it turns out the latter is hard to do when there are parse errors in the
// code. Things like missing name nodes cause a lot of havoc and make it difficult to
// track a closing curly brace.
//
// So the way we do this is that we default to not intelligently adjusting the spans
// while there are parse errors. But when there are no parse errors then the span is
// adjusted.
var initialBreakpointSpan = snapshot.GetSpan(pCodeSpan[0]);
if (initialBreakpointSpan.Length > 0 && document.SupportsSyntaxTree)
{
var tree = document.GetSyntaxTreeSynchronously(cancellationToken);
if (tree.GetDiagnostics(cancellationToken).Any(d => d.Severity == DiagnosticSeverity.Error))
{
return VSConstants.E_FAIL;
}
}
// If a span is provided, and the requested position falls in that span, then just
// move the requested position to the start of the span.
// Length will be used to determine if we need further analysis, which is only required when text spans multiple lines.
if (initialBreakpointSpan.Contains(point))
{
point = initialBreakpointSpan.Start;
length = pCodeSpan[0].iEndLine > pCodeSpan[0].iStartLine ? initialBreakpointSpan.Length : 0;
}
}
// NOTE(cyrusn): we need to wait here because ValidateBreakpointLocation is
// synchronous. In the future, it would be nice for the debugger to provide
// an async entry point for this.
var breakpoint = _breakpointService.ResolveBreakpointAsync(document, new CodeAnalysis.Text.TextSpan(point.Position, length), cancellationToken).WaitAndGetResult(cancellationToken);
if (breakpoint == null)
{
// There should *not* be a breakpoint here. E_FAIL to let the debugger know
// that.
return VSConstants.E_FAIL;
}
if (breakpoint.IsLineBreakpoint)
{
// Let the debugger take care of this. They'll put a line breakpoint
// here. This is useful for when the user does something like put a
// breakpoint in inactive code. We want to allow this as they might
// just have different defines during editing versus debugging.
// TODO(cyrusn): Do we need to set the pCodeSpan in this case?
return VSConstants.E_NOTIMPL;
}
// There should be a breakpoint at the location passed back.
if (pCodeSpan != null && pCodeSpan.Length > 0)
{
pCodeSpan[0] = breakpoint.TextSpan.ToSnapshotSpan(snapshot).ToVsTextSpan();
}
return VSConstants.S_OK;
}
}
return VSConstants.E_NOTIMPL;
}
public int GetDataTipText(IVsTextBuffer pBuffer, VsTextSpan[] pSpan, string pbstrText)
{
using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetDataTipText, CancellationToken.None))
{
pbstrText = null;
if (pSpan == null || pSpan.Length != 1)
{
return VSConstants.E_INVALIDARG;
}
int result = VSConstants.E_FAIL;
_waitIndicator.Wait(
title: ServicesVSResources.Debugger,
message: ServicesVSResources.Getting_DataTip_text,
allowCancel: true,
action: waitContext =>
{
var debugger = _languageService.Debugger;
DBGMODE[] debugMode = new DBGMODE[1];
var cancellationToken = waitContext.CancellationToken;
if (ErrorHandler.Succeeded(debugger.GetMode(debugMode)) && debugMode[0] != DBGMODE.DBGMODE_Design)
{
var editorAdapters = _languageService.EditorAdaptersFactoryService;
var textSpan = pSpan[0];
var subjectBuffer = editorAdapters.GetDataBuffer(pBuffer);
var textSnapshot = subjectBuffer.CurrentSnapshot;
var document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var spanOpt = textSnapshot.TryGetSpan(textSpan);
if (spanOpt.HasValue)
{
var dataTipInfo = _languageDebugInfo.GetDataTipInfoAsync(document, spanOpt.Value.Start, cancellationToken).WaitAndGetResult(cancellationToken);
if (!dataTipInfo.IsDefault)
{
var resultSpan = dataTipInfo.Span.ToSnapshotSpan(textSnapshot);
string textOpt = dataTipInfo.Text;
pSpan[0] = resultSpan.ToVsTextSpan();
result = debugger.GetDataTipValue((IVsTextLines)pBuffer, pSpan, textOpt, out pbstrText);
}
}
}
}
});
return result;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetItemStrStrStringDictionaryTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
StringDictionary sd;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
string itm; // returned Item
// initialize IntStrings
intl = new IntlStrings();
// [] StringDictionary is constructed as expected
//-----------------------------------------------------------------
sd = new StringDictionary();
// [] set Item on empty dictionary
//
// item with given key should be added
for (int i = 0; i < keys.Length; i++)
{
if (sd.Count > 0)
sd.Clear();
sd[keys[i]] = values[i];
if (sd.Count != 1)
{
Assert.False(true, string.Format("Error, didn't add item with {0} key", i));
}
if (String.Compare(sd[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, added wrong value", i));
}
}
//
// [] set Item on filled dictionary
//
int len = values.Length;
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
for (int i = 0; i < len; i++)
{
itm = "item" + i;
sd[keys[i]] = itm;
if (String.Compare(sd[keys[i]], itm) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[keys[i]], itm));
}
}
//
// [] set Item on dictionary with identical values
//
sd.Clear();
string intlStr = intl.GetRandomString(MAX_LEN);
string intlStr1 = intl.GetRandomString(MAX_LEN);
sd.Add("keykey1", intlStr); // 1st duplicate
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
sd.Add("keykey2", intlStr); // 2nd duplicate
if (sd.Count != len + 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2));
}
// set/get Item
//
sd["keykey1"] = intlStr1;
if (String.Compare(sd["keykey1"], intlStr1) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey1"], intlStr1));
}
sd["keykey2"] = intlStr1;
if (String.Compare(sd["keykey2"], intlStr1) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", sd["keykey2"], intlStr1));
}
//
// Intl strings
// [] set Item on dictionary filled with Intl strings
//
string[] intlValues = new string[len * 2];
string[] intlSets = new string[len];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
for (int i = 0; i < len; i++)
{
intlSets[i] = intl.GetRandomString(MAX_LEN);
}
//
// will use first half of array as values and second half as keys
//
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(intlValues[i + len], intlValues[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
// get item
for (int i = 0; i < len; i++)
{
sd[intlValues[i + len]] = intlSets[i];
if (String.Compare(sd[intlValues[i + len]], intlSets[i]) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValues[i + len]], intlSets[i]));
}
}
//
// [] Case sensitivity: keys are always lowercased
//
sd.Clear();
string[] intlValuesUpper = new string[len];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToLowerInvariant();
}
// array of uppercase keys
for (int i = 0; i < len; i++)
{
intlValuesUpper[i] = intlValues[i].ToUpperInvariant();
}
sd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
sd.Add(intlValues[i + len], intlValues[i]); // adding lowercase strings
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
// set/get Item
for (int i = 0; i < len; i++)
{
sd[intlValues[i + len]] = intlValuesUpper[i];
if (String.Compare(sd[intlValues[i + len]], intlValuesUpper[i]) != 0)
{
Assert.False(true, string.Format("Error, returned {1} instead of {2}", i, sd[intlValues[i + len]], intlValuesUpper[i]));
}
}
//
// [] Invalid parameter - set Item(null)
//
Assert.Throws<ArgumentNullException>(() => { sd[null] = intlStr; });
//
// [] set to null
//
if (!sd.ContainsKey(keys[0]))
{
sd.Add(keys[0], values[0]);
}
sd[keys[0]] = null;
if (sd[keys[0]] != null)
{
Assert.False(true, string.Format("Error, returned non-null"));
}
}
}
}
| |
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
[Cmdlet(
VerbsCommon.Set,
ProfileNouns.VirtualMachineDscExtension,
SupportsShouldProcess = true,
DefaultParameterSetName = AzureBlobDscExtensionParamSet)]
[OutputType(typeof(PSComputeLongRunningOperation))]
public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension";
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the virtual machine.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// The name of the configuration archive that was previously uploaded by
/// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name
/// of the file, without any path.
/// A null value or empty string indicate that the VM extension should install DSC,
/// but not start any configuration
/// </summary>
[Alias("ConfigurationArchiveBlob")]
[Parameter(
Mandatory = true,
Position = 5,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")]
[AllowEmptyString]
[AllowNull]
public string ArchiveBlobName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName.
/// </summary>
[Alias("StorageAccountName")]
[Parameter(
Mandatory = true,
Position = 4,
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")]
[ValidateNotNullOrEmpty]
public String ArchiveStorageAccountName { get; set; }
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " +
"This param is optional if storage account and virtual machine both exists in the same resource group name, " +
"specified by ResourceGroupName param.")]
[ValidateNotNullOrEmpty]
public string ArchiveResourceGroupName { get; set; }
/// <summary>
/// The DNS endpoint suffix for all storage services, e.g. "core.windows.net".
/// </summary>
[Alias("StorageEndpointSuffix")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "The Storage Endpoint Suffix.")]
[ValidateNotNullOrEmpty]
public string ArchiveStorageEndpointSuffix { get; set; }
/// <summary>
/// Name of the Azure Storage Container where the configuration script is located.
/// </summary>
[Alias("ContainerName")]
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = AzureBlobDscExtensionParamSet,
HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")]
[ValidateNotNullOrEmpty]
public string ArchiveContainerName { get; set; }
/// <summary>
/// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations
/// contained within the file specified by ArchiveBlobName.
///
/// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if
/// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite".
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")]
[ValidateNotNullOrEmpty]
public string ConfigurationName { get; set; }
/// <summary>
/// A hashtable specifying the arguments to the ConfigurationFunction. The keys
/// correspond to the parameter names and the values to the parameter values.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")]
[ValidateNotNullOrEmpty]
public Hashtable ConfigurationArgument { get; set; }
/// <summary>
/// Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")]
[ValidateNotNullOrEmpty]
public string ConfigurationData { get; set; }
/// <summary>
/// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will
/// apply the settings to.
/// </summary>
[Alias("HandlerVersion")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " +
"Allowed format N.N")]
[ValidateNotNullOrEmpty]
public string Version { get; set; }
/// <summary>
/// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them.
/// </summary>
[Parameter(
HelpMessage = "Use this parameter to overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Location of the resource.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
/// <summary>
/// We install the extension handler version specified by the version param. By default extension handler is not autoupdated.
/// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available.
/// </summary>
[Parameter(
HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")]
public SwitchParameter AutoUpdate { get; set; }
//Private Variables
private const string VersionRegexExpr = @"^(([0-9])\.)\d+$";
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
protected override void ProcessRecord()
{
base.ProcessRecord();
ValidateParameters();
CreateConfiguration();
}
//Private Methods
private void ValidateParameters()
{
if (string.IsNullOrEmpty(ArchiveBlobName))
{
if (ConfigurationName != null || ConfigurationArgument != null
|| ConfigurationData != null)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters);
}
if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters);
}
}
else
{
if (string.Compare(
Path.GetFileName(ArchiveBlobName),
ArchiveBlobName,
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath);
}
if (ConfigurationData != null)
{
ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData);
if (!File.Exists(ConfigurationData))
{
this.ThrowInvalidArgumentError(
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile,
ConfigurationData);
}
if (string.Compare(
Path.GetExtension(ConfigurationData),
".psd1",
StringComparison.InvariantCultureIgnoreCase) != 0)
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile);
}
}
if (ArchiveResourceGroupName == null)
{
ArchiveResourceGroupName = ResourceGroupName;
}
_storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName);
if (ConfigurationName == null)
{
ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName);
}
if (ArchiveContainerName == null)
{
ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (ArchiveStorageEndpointSuffix == null)
{
ArchiveStorageEndpointSuffix =
DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
if (!(Regex.Match(Version, VersionRegexExpr).Success))
{
this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion);
}
}
}
private void CreateConfiguration()
{
var publicSettings = new DscExtensionPublicSettings();
var privateSettings = new DscExtensionPrivateSettings();
if (!string.IsNullOrEmpty(ArchiveBlobName))
{
ConfigurationUris configurationUris = UploadConfigurationDataToBlob();
publicSettings.SasToken = configurationUris.SasToken;
publicSettings.ModulesUrl = configurationUris.ModulesUrl;
publicSettings.ConfigurationFunction = string.Format(
CultureInfo.InvariantCulture,
"{0}\\{1}",
Path.GetFileNameWithoutExtension(ArchiveBlobName),
ConfigurationName);
Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings =
DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument);
publicSettings.Properties = settings.Item1;
privateSettings.Items = settings.Item2;
privateSettings.DataBlobUri = configurationUris.DataBlobUri;
}
var parameters = new VirtualMachineExtension
{
Location = Location,
Name = Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName,
Type = VirtualMachineExtensionType,
Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace,
ExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName,
TypeHandlerVersion = Version,
// Define the public and private property bags that will be passed to the extension.
Settings = DscExtensionSettingsSerializer.SerializePublicSettings(publicSettings),
//PrivateConfuguration contains sensitive data in a plain text
ProtectedSettings = DscExtensionSettingsSerializer.SerializePrivateSettings(privateSettings),
AutoUpgradeMinorVersion = AutoUpdate.IsPresent
};
//Add retry logic due to CRP service restart known issue CRP bug: 3564713
var count = 1;
ComputeLongRunningOperationResponse op = null;
while (count <= 2)
{
op = VirtualMachineExtensionClient.CreateOrUpdate(
ResourceGroupName,
VMName,
parameters);
if (ComputeOperationStatus.Failed.Equals(op.Status) && op.Error != null && "InternalExecutionError".Equals(op.Error.Code))
{
count++;
}
else
{
break;
}
}
var result = Mapper.Map<PSComputeLongRunningOperation>(op);
WriteObject(result);
}
/// <summary>
/// Uploading configuration data to blob storage.
/// </summary>
/// <returns>ConfigurationUris collection that represent artifacts of uploading</returns>
private ConfigurationUris UploadConfigurationDataToBlob()
{
//
// Get a reference to the container in blob storage
//
var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true);
var blobClient = storageAccount.CreateCloudBlobClient();
var containerReference = blobClient.GetContainerReference(ArchiveContainerName);
//
// Get a reference to the configuration blob and create a SAS token to access it
//
var blobAccessPolicy = new SharedAccessBlobPolicy
{
SharedAccessExpiryTime =
DateTime.UtcNow.AddHours(1),
Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete
};
var configurationBlobName = ArchiveBlobName;
var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName);
var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy);
//
// Upload the configuration data to blob storage and get a SAS token
//
string configurationDataBlobUri = null;
if (ConfigurationData != null)
{
var guid = Guid.NewGuid();
// there may be multiple VMs using the same configuration
var configurationDataBlobName = string.Format(
CultureInfo.InvariantCulture,
"{0}-{1}.psd1",
ConfigurationName,
guid);
var configurationDataBlobReference =
containerReference.GetBlockBlobReference(configurationDataBlobName);
ConfirmAction(
true,
string.Empty,
string.Format(
CultureInfo.CurrentUICulture,
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction,
ConfigurationData),
configurationDataBlobReference.Uri.AbsoluteUri,
() =>
{
if (!Force && configurationDataBlobReference.Exists())
{
ThrowTerminatingError(
new ErrorRecord(
new UnauthorizedAccessException(
string.Format(
CultureInfo.CurrentUICulture,
Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists,
configurationDataBlobName)),
"StorageBlobAlreadyExists",
ErrorCategory.PermissionDenied,
null));
}
configurationDataBlobReference.UploadFromFile(ConfigurationData, FileMode.Open);
var configurationDataBlobSasToken =
configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy);
configurationDataBlobUri =
configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri
+ configurationDataBlobSasToken;
});
}
return new ConfigurationUris
{
ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri,
SasToken = configurationBlobSasToken,
DataBlobUri = configurationDataBlobUri
};
}
/// <summary>
/// Class represent info about uploaded Configuration.
/// </summary>
private class ConfigurationUris
{
public string SasToken { get; set; }
public string DataBlobUri { get; set; }
public string ModulesUrl { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Orders;
namespace Nop.Core.Domain.Customers
{
/// <summary>
/// Represents a customer
/// </summary>
public partial class Customer : BaseEntity
{
private ICollection<ExternalAuthenticationRecord> _externalAuthenticationRecords;
private ICollection<CustomerRole> _customerRoles;
private ICollection<ShoppingCartItem> _shoppingCartItems;
private ICollection<RewardPointsHistory> _rewardPointsHistory;
private ICollection<ReturnRequest> _returnRequests;
private ICollection<Address> _addresses;
/// <summary>
/// Ctor
/// </summary>
public Customer()
{
this.CustomerGuid = Guid.NewGuid();
this.PasswordFormat = PasswordFormat.Clear;
}
/// <summary>
/// Gets or sets the customer Guid
/// </summary>
public Guid CustomerGuid { get; set; }
/// <summary>
/// Gets or sets the username
/// </summary>
public string Username { get; set; }
/// <summary>
/// Gets or sets the email
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets or sets the password
/// </summary>
public string Password { get; set; }
/// <summary>
/// Gets or sets the password format
/// </summary>
public int PasswordFormatId { get; set; }
/// <summary>
/// Gets or sets the password format
/// </summary>
public PasswordFormat PasswordFormat
{
get { return (PasswordFormat)PasswordFormatId; }
set { this.PasswordFormatId = (int)value; }
}
/// <summary>
/// Gets or sets the password salt
/// </summary>
public string PasswordSalt { get; set; }
/// <summary>
/// Gets or sets the admin comment
/// </summary>
public string AdminComment { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer is tax exempt
/// </summary>
public bool IsTaxExempt { get; set; }
/// <summary>
/// Gets or sets the affiliate identifier
/// </summary>
public int AffiliateId { get; set; }
/// <summary>
/// Gets or sets the vendor identifier with which this customer is associated (maganer)
/// </summary>
public int VendorId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this customer has some products in the shopping cart
/// <remarks>The same as if we run this.ShoppingCartItems.Count > 0
/// We use this property for performance optimization:
/// if this property is set to false, then we do not need to load "ShoppingCartItems" navifation property for each page load
/// It's used only in a couple of places in the presenation layer
/// </remarks>
/// </summary>
public bool HasShoppingCartItems { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer is active
/// </summary>
public bool Active { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer has been deleted
/// </summary>
public bool Deleted { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the customer account is system
/// </summary>
public bool IsSystemAccount { get; set; }
/// <summary>
/// Gets or sets the customer system name
/// </summary>
public string SystemName { get; set; }
/// <summary>
/// Gets or sets the last IP address
/// </summary>
public string LastIpAddress { get; set; }
/// <summary>
/// Gets or sets the date and time of entity creation
/// </summary>
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of last login
/// </summary>
public DateTime? LastLoginDateUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of last activity
/// </summary>
public DateTime LastActivityDateUtc { get; set; }
#region Navigation properties
/// <summary>
/// Gets or sets customer generated content
/// </summary>
public virtual ICollection<ExternalAuthenticationRecord> ExternalAuthenticationRecords
{
get { return _externalAuthenticationRecords ?? (_externalAuthenticationRecords = new List<ExternalAuthenticationRecord>()); }
protected set { _externalAuthenticationRecords = value; }
}
/// <summary>
/// Gets or sets the customer roles
/// </summary>
public virtual ICollection<CustomerRole> CustomerRoles
{
get { return _customerRoles ?? (_customerRoles = new List<CustomerRole>()); }
protected set { _customerRoles = value; }
}
/// <summary>
/// Gets or sets shopping cart items
/// </summary>
public virtual ICollection<ShoppingCartItem> ShoppingCartItems
{
get { return _shoppingCartItems ?? (_shoppingCartItems = new List<ShoppingCartItem>()); }
protected set { _shoppingCartItems = value; }
}
/// <summary>
/// Gets or sets reward points history
/// </summary>
public virtual ICollection<RewardPointsHistory> RewardPointsHistory
{
get { return _rewardPointsHistory ?? (_rewardPointsHistory = new List<RewardPointsHistory>()); }
protected set { _rewardPointsHistory = value; }
}
/// <summary>
/// Gets or sets return request of this customer
/// </summary>
public virtual ICollection<ReturnRequest> ReturnRequests
{
get { return _returnRequests ?? (_returnRequests = new List<ReturnRequest>()); }
protected set { _returnRequests = value; }
}
/// <summary>
/// Default billing address
/// </summary>
public virtual Address BillingAddress { get; set; }
/// <summary>
/// Default shipping address
/// </summary>
public virtual Address ShippingAddress { get; set; }
/// <summary>
/// Gets or sets customer addresses
/// </summary>
public virtual ICollection<Address> Addresses
{
get { return _addresses ?? (_addresses = new List<Address>()); }
protected set { _addresses = value; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using SortedDictionaryTests.SortedDictionary_SortedDictionary_ValueCollection;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionaryTests
{
public class SortedDictionary_ValueCollectionTests
{
public class IntGenerator
{
private int _index;
public IntGenerator()
{
_index = 0;
}
public int NextValue()
{
return _index++;
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
public class StringGenerator
{
private int _index;
public StringGenerator()
{
_index = 0;
}
public String NextValue()
{
return (_index++).ToString();
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
[Fact]
public static void ValueCollectionTest1()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 100;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla(ints, ints);
simpleRef.TestVanilla(simpleStrings, simpleStrings);
simpleVal.TestVanilla(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla(new int[0], new int[0]);
simpleRef.TestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
IntDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
IntDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
[Fact]
public static void SortedDictionary_ValueCollectionTest_Negative()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 100;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla_Negative(ints, ints);
simpleRef.TestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.TestVanilla_Negative(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla_Negative(new int[0], new int[0]);
simpleRef.TestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
}
[Fact]
public static void SortedDictionary_ValueCollectionTest2()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
Driver<int, int> intDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int count = 100;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
for (int i = 0; i < count; i++)
ints[i] = i;
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
intDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
intDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
}
namespace SortedDictionary_SortedDictionary_ValueCollection
{
public class Driver<KeyType, ValueType>
{
public void TestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_1! Count not equal"
IEnumerator<ValueType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_2! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_3! Count not equal"
ValueType[] _values = new ValueType[_dic.Count];
_col.CopyTo(_values, 0);
for (int i = 0; i < values.Length - 1; i++)
Assert.True(_dic.ContainsValue(_values[i])); //"Err_4! Expected key to be present"
count = 0;
foreach (ValueType currValue in _dic.Values)
{
Assert.True(_dic.ContainsValue(currValue)); //"Err_5! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_! Count not equal"
try
{
//The behavior here is undefined as long as we don't AV we're fine
ValueType item = _enum.Current;
}
catch (Exception) { }
}
// verify we get InvalidOperationException when we call MoveNext() after adding a key
public void TestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
IEnumerator<ValueType> _enum = _col.GetEnumerator();
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_6! Expected InvalidOperationException."
}
}
public void TestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
{
_dic.Add(keys[i], values[i]);
}
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_7! Count not equal"
IEnumerator<ValueType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_8! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_9! Count not equal"
for (int i = 0; i < keys.Length; i++)
_dic[keys[i]] = newValues[i];
Assert.Equal(_col.Count, _dic.Count); //"Err_10! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue(_enum.Current)); //"Err_11! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_12! Count not equal"
ValueType[] _values = new ValueType[_dic.Count];
_col.CopyTo(_values, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsValue(_values[i])); //"Err_13! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_14! Count not equal"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_15! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_16! Count not equal"
ValueType[] _values = new ValueType[_dic.Count];
_col.CopyTo(_values, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsValue(_values[i])); //"Err_17! Expected key to be present"
_enum.Reset();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_18! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_19! Count not equal"
_values = new ValueType[_dic.Count];
_col.CopyTo(_values, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsValue(_values[i])); //"Err_20! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
IEnumerator _enum = _col.GetEnumerator();
// get to the end
while (_enum.MoveNext()) { }
Assert.Throws<InvalidOperationException>((() => _dic.ContainsValue((ValueType)_enum.Current))); //"Err_21! Expected InvalidOperationException."
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_22! Expected InvalidOperationException."
Assert.Throws<InvalidOperationException>((() => _enum.Reset())); //"Err_23! Expected InvalidOperationException."
}
}
public void NonGenericIDictionaryTestModify(KeyType[] keys, ValueType[] values, ValueType[] newValues)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.ValueCollection _col = new SortedDictionary<KeyType, ValueType>.ValueCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_24! Expected count to be zero"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_25! Expected count to be zero"
for (int i = 0; i < keys.Length; i++)
_dic[keys[i]] = newValues[i];
Assert.Equal(_col.Count, _dic.Count); //"Err_26! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsValue((ValueType)_enum.Current)); //"Err_27! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_28! Count not equal"
ValueType[] _values = new ValueType[_dic.Count];
_col.CopyTo(_values, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsValue(_values[i])); //"Err_29! Expected key to be present"
}
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D02_Continent (editable child object).<br/>
/// This is a generated base class of <see cref="D02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="D03_SubContinentObjects"/> of type <see cref="D03_SubContinentColl"/> (1:M relation to <see cref="D04_SubContinent"/>)<br/>
/// This class is an item of <see cref="D01_ContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class D02_Continent : BusinessBase<D02_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="D03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03_Continent_Child> D03_Continent_SingleObjectProperty = RegisterProperty<D03_Continent_Child>(p => p.D03_Continent_SingleObject, "D03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The D03 Continent Single Object.</value>
public D03_Continent_Child D03_Continent_SingleObject
{
get { return GetProperty(D03_Continent_SingleObjectProperty); }
private set { LoadProperty(D03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<D03_Continent_ReChild> D03_Continent_ASingleObjectProperty = RegisterProperty<D03_Continent_ReChild>(p => p.D03_Continent_ASingleObject, "D03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The D03 Continent ASingle Object.</value>
public D03_Continent_ReChild D03_Continent_ASingleObject
{
get { return GetProperty(D03_Continent_ASingleObjectProperty); }
private set { LoadProperty(D03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="D03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<D03_SubContinentColl> D03_SubContinentObjectsProperty = RegisterProperty<D03_SubContinentColl>(p => p.D03_SubContinentObjects, "D03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the D03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The D03 Sub Continent Objects.</value>
public D03_SubContinentColl D03_SubContinentObjects
{
get { return GetProperty(D03_SubContinentObjectsProperty); }
private set { LoadProperty(D03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D02_Continent"/> object.</returns>
internal static D02_Continent NewD02_Continent()
{
return DataPortal.CreateChild<D02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="D02_Continent"/> object from the given D02_ContinentDto.
/// </summary>
/// <param name="data">The <see cref="D02_ContinentDto"/>.</param>
/// <returns>A reference to the fetched <see cref="D02_Continent"/> object.</returns>
internal static D02_Continent GetD02_Continent(D02_ContinentDto data)
{
D02_Continent obj = new D02_Continent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D02_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 D02_Continent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(D03_Continent_SingleObjectProperty, DataPortal.CreateChild<D03_Continent_Child>());
LoadProperty(D03_Continent_ASingleObjectProperty, DataPortal.CreateChild<D03_Continent_ReChild>());
LoadProperty(D03_SubContinentObjectsProperty, DataPortal.CreateChild<D03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D02_Continent"/> object from the given <see cref="D02_ContinentDto"/>.
/// </summary>
/// <param name="data">The D02_ContinentDto to use.</param>
private void Fetch(D02_ContinentDto data)
{
// Value properties
LoadProperty(Continent_IDProperty, data.Continent_ID);
LoadProperty(Continent_NameProperty, data.Continent_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(D03_Continent_SingleObjectProperty, D03_Continent_Child.GetD03_Continent_Child(Continent_ID));
LoadProperty(D03_Continent_ASingleObjectProperty, D03_Continent_ReChild.GetD03_Continent_ReChild(Continent_ID));
LoadProperty(D03_SubContinentObjectsProperty, D03_SubContinentColl.GetD03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="D02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
var dto = new D02_ContinentDto();
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<ID02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Continent_IDProperty, resultDto.Continent_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new D02_ContinentDto();
dto.Continent_ID = Continent_ID;
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="D02_Continent"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<ID02_ContinentDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Continent_IDProperty));
}
OnDeletePost(args);
}
}
#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
}
}
| |
// 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.Security.Cryptography;
using System.Security.Cryptography.Apple;
namespace Internal.Cryptography
{
internal static partial class HashProviderDispenser
{
public static HashProvider CreateHashProvider(string hashAlgorithmId)
{
switch (hashAlgorithmId)
{
case HashAlgorithmNames.MD5:
return new AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Md5);
case HashAlgorithmNames.SHA1:
return new AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha1);
case HashAlgorithmNames.SHA256:
return new AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha256);
case HashAlgorithmNames.SHA384:
return new AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha384);
case HashAlgorithmNames.SHA512:
return new AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha512);
}
throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmId));
}
public static HashProvider CreateMacProvider(string hashAlgorithmId, byte[] key)
{
switch (hashAlgorithmId)
{
case HashAlgorithmNames.MD5:
return new AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Md5, key);
case HashAlgorithmNames.SHA1:
return new AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha1, key);
case HashAlgorithmNames.SHA256:
return new AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha256, key);
case HashAlgorithmNames.SHA384:
return new AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha384, key);
case HashAlgorithmNames.SHA512:
return new AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm.Sha512, key);
}
throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmId));
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private sealed class AppleHmacProvider : HashProvider
{
private readonly byte[] _key;
private readonly SafeHmacHandle _ctx;
private bool _running;
public override int HashSizeInBytes { get; }
internal AppleHmacProvider(Interop.AppleCrypto.PAL_HashAlgorithm algorithm, byte[] key)
{
_key = key.CloneByteArray();
int hashSizeInBytes = 0;
_ctx = Interop.AppleCrypto.HmacCreate(algorithm, ref hashSizeInBytes);
if (hashSizeInBytes < 0)
{
_ctx.Dispose();
throw new PlatformNotSupportedException(
SR.Format(
SR.Cryptography_UnknownHashAlgorithm,
Enum.GetName(typeof(Interop.AppleCrypto.PAL_HashAlgorithm), algorithm)));
}
if (_ctx.IsInvalid)
{
_ctx.Dispose();
throw new CryptographicException();
}
HashSizeInBytes = hashSizeInBytes;
}
public override void AppendHashData(ReadOnlySpan<byte> data)
{
if (!_running)
{
SetKey();
}
if (Interop.AppleCrypto.HmacUpdate(_ctx, data, data.Length) != 1)
{
throw new CryptographicException();
}
}
private void SetKey()
{
if (Interop.AppleCrypto.HmacInit(_ctx, _key, _key.Length) != 1)
{
throw new CryptographicException();
}
_running = true;
}
public override unsafe byte[] FinalizeHashAndReset()
{
var output = new byte[HashSizeInBytes];
bool success = TryFinalizeHashAndReset(output, out int bytesWritten);
Debug.Assert(success);
Debug.Assert(bytesWritten == output.Length);
return output;
}
public override bool TryFinalizeHashAndReset(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashSizeInBytes)
{
bytesWritten = 0;
return false;
}
if (!_running)
{
SetKey();
}
if (Interop.AppleCrypto.HmacFinal(_ctx, destination, destination.Length) != 1)
{
throw new CryptographicException();
}
bytesWritten = HashSizeInBytes;
_running = false;
return true;
}
public override void Dispose(bool disposing)
{
if (disposing)
{
_ctx?.Dispose();
Array.Clear(_key, 0, _key.Length);
}
}
}
private sealed class AppleDigestProvider : HashProvider
{
private readonly SafeDigestCtxHandle _ctx;
public override int HashSizeInBytes { get; }
internal AppleDigestProvider(Interop.AppleCrypto.PAL_HashAlgorithm algorithm)
{
int hashSizeInBytes;
_ctx = Interop.AppleCrypto.DigestCreate(algorithm, out hashSizeInBytes);
if (hashSizeInBytes < 0)
{
_ctx.Dispose();
throw new PlatformNotSupportedException(
SR.Format(
SR.Cryptography_UnknownHashAlgorithm,
Enum.GetName(typeof(Interop.AppleCrypto.PAL_HashAlgorithm), algorithm)));
}
if (_ctx.IsInvalid)
{
_ctx.Dispose();
throw new CryptographicException();
}
HashSizeInBytes = hashSizeInBytes;
}
public override void AppendHashData(ReadOnlySpan<byte> data)
{
int ret = Interop.AppleCrypto.DigestUpdate(_ctx, data, data.Length);
if (ret != 1)
{
Debug.Assert(ret == 0, $"DigestUpdate return value {ret} was not 0 or 1");
throw new CryptographicException();
}
}
public override byte[] FinalizeHashAndReset()
{
var hash = new byte[HashSizeInBytes];
bool success = TryFinalizeHashAndReset(hash, out int bytesWritten);
Debug.Assert(success);
Debug.Assert(bytesWritten == hash.Length);
return hash;
}
public override bool TryFinalizeHashAndReset(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashSizeInBytes)
{
bytesWritten = 0;
return false;
}
int ret = Interop.AppleCrypto.DigestFinal(_ctx, destination, destination.Length);
if (ret != 1)
{
Debug.Assert(ret == 0, $"DigestFinal return value {ret} was not 0 or 1");
throw new CryptographicException();
}
bytesWritten = HashSizeInBytes;
return true;
}
public override void Dispose(bool disposing)
{
if (disposing)
{
_ctx?.Dispose();
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activities
{
using System.Activities;
using System.Activities.Hosting;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.DurableInstancing;
using System.ServiceModel.Activation;
using System.ServiceModel.Activities.Configuration;
using System.ServiceModel.Activities.Description;
using System.ServiceModel.Activities.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Activities.Diagnostics;
using System.Xml;
using System.Xml.Linq;
[Fx.Tag.XamlVisible(false)]
public class WorkflowServiceHost : ServiceHostBase
{
static readonly XName mexContractXName = XName.Get(ServiceMetadataBehavior.MexContractName, ServiceMetadataBehavior.MexContractNamespace);
static readonly Type mexBehaviorType = typeof(ServiceMetadataBehavior);
static readonly TimeSpan defaultPersistTimeout = TimeSpan.FromSeconds(30);
static readonly TimeSpan defaultTrackTimeout = TimeSpan.FromSeconds(30);
static readonly Type baseActivityType = typeof(Activity);
static readonly Type correlationQueryBehaviorType = typeof(CorrelationQueryBehavior);
static readonly Type bufferedReceiveServiceBehaviorType = typeof(BufferedReceiveServiceBehavior);
WorkflowServiceHostExtensions workflowExtensions;
DurableInstanceManager durableInstanceManager;
WorkflowDefinitionProvider workflowDefinitionProvider;
Activity activity;
WorkflowService serviceDefinition;
IDictionary<XName, ContractDescription> inferredContracts;
IDictionary<XName, Collection<CorrelationQuery>> correlationQueries;
WorkflowUnhandledExceptionAction unhandledExceptionAction;
TimeSpan idleTimeToPersist;
TimeSpan idleTimeToUnload;
WorkflowServiceHostPerformanceCounters workflowServiceHostPerformanceCounters;
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(object serviceImplementation, params Uri[] baseAddresses)
: base()
{
if (serviceImplementation == null)
{
throw FxTrace.Exception.ArgumentNull("serviceImplementation");
}
if (serviceImplementation is WorkflowService)
{
InitializeFromConstructor((WorkflowService)serviceImplementation, baseAddresses);
}
else
{
Activity activity = serviceImplementation as Activity;
if (activity == null)
{
throw FxTrace.Exception.Argument("serviceImplementation", SR.InvalidServiceImplementation);
}
InitializeFromConstructor(activity, baseAddresses);
}
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(Activity activity, params Uri[] baseAddresses)
: base()
{
if (activity == null)
{
throw FxTrace.Exception.ArgumentNull("activity");
}
InitializeFromConstructor(activity, baseAddresses);
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(WorkflowService serviceDefinition, params Uri[] baseAddresses)
: base()
{
if (serviceDefinition == null)
{
throw FxTrace.Exception.ArgumentNull("serviceDefinition");
}
InitializeFromConstructor(serviceDefinition, baseAddresses);
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
protected WorkflowServiceHost()
{
InitializeFromConstructor((WorkflowService)null);
}
public Activity Activity
{
get
{
return this.activity;
}
}
public WorkflowInstanceExtensionManager WorkflowExtensions
{
get
{
return this.workflowExtensions;
}
}
public DurableInstancingOptions DurableInstancingOptions
{
get
{
return this.durableInstanceManager.DurableInstancingOptions;
}
}
public ICollection<WorkflowService> SupportedVersions
{
get
{
return this.workflowDefinitionProvider.SupportedVersions;
}
}
internal XName ServiceName
{
get;
set;
}
internal TimeSpan PersistTimeout
{
get;
set;
}
internal TimeSpan TrackTimeout
{
get;
set;
}
//
internal TimeSpan FilterResumeTimeout
{
get;
set;
}
internal DurableInstanceManager DurableInstanceManager
{
get
{
return this.durableInstanceManager;
}
}
internal bool IsLoadTransactionRequired
{
get;
private set;
}
// set by WorkflowUnhandledExceptionBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnhandledExceptionPolicy
internal WorkflowUnhandledExceptionAction UnhandledExceptionAction
{
get { return this.unhandledExceptionAction; }
set
{
Fx.Assert(WorkflowUnhandledExceptionActionHelper.IsDefined(value), "Undefined WorkflowUnhandledExceptionAction");
this.unhandledExceptionAction = value;
}
}
// set by WorkflowIdleBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnloadInstancePolicy
internal TimeSpan IdleTimeToPersist
{
get { return this.idleTimeToPersist; }
set
{
Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToPersist cannot be less than zero");
this.idleTimeToPersist = value;
}
}
internal TimeSpan IdleTimeToUnload
{
get { return this.idleTimeToUnload; }
set
{
Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToUnload cannot be less than zero");
this.idleTimeToUnload = value;
}
}
internal bool IsConfigurable
{
get
{
lock (this.ThisLock)
{
return this.State == CommunicationState.Created || this.State == CommunicationState.Opening;
}
}
}
internal WorkflowServiceHostPerformanceCounters WorkflowServiceHostPerformanceCounters
{
get
{
return this.workflowServiceHostPerformanceCounters;
}
}
internal bool OverrideSiteName
{
get;
set;
}
void InitializeFromConstructor(Activity activity, params Uri[] baseAddresses)
{
WorkflowService serviceDefinition = new WorkflowService
{
Body = activity
};
InitializeFromConstructor(serviceDefinition, baseAddresses);
}
void InitializeFromConstructor(WorkflowService serviceDefinition, params Uri[] baseAddresses)
{
// first initialize some values to their defaults
this.idleTimeToPersist = WorkflowIdleBehavior.defaultTimeToPersist;
this.idleTimeToUnload = WorkflowIdleBehavior.defaultTimeToUnload;
this.unhandledExceptionAction = WorkflowUnhandledExceptionBehavior.defaultAction;
this.workflowExtensions = new WorkflowServiceHostExtensions();
// If the AppSettings.DefaultAutomaticInstanceKeyDisassociation is specified and is true, create a DisassociateInstanceKeysExtension, set its
// AutomaticDisassociationEnabled property to true, and add it to the extensions collection so that System.Activities.BookmarkScopeHandle will
// unregister its BookmarkScope, which will cause key disassociation. KB2669774.
if (AppSettings.DefaultAutomaticInstanceKeyDisassociation)
{
DisassociateInstanceKeysExtension extension = new DisassociateInstanceKeysExtension();
extension.AutomaticDisassociationEnabled = true;
this.workflowExtensions.Add(extension);
}
if (TD.CreateWorkflowServiceHostStartIsEnabled())
{
TD.CreateWorkflowServiceHostStart();
}
if (serviceDefinition != null)
{
this.workflowDefinitionProvider = new WorkflowDefinitionProvider(serviceDefinition, this);
InitializeDescription(serviceDefinition, new UriSchemeKeyedCollection(baseAddresses));
}
this.durableInstanceManager = new DurableInstanceManager(this);
if (TD.CreateWorkflowServiceHostStopIsEnabled())
{
TD.CreateWorkflowServiceHostStop();
}
this.workflowServiceHostPerformanceCounters = new WorkflowServiceHostPerformanceCounters(this);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, string address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
return AddServiceEndpoint(serviceContractName, binding, new Uri(address, UriKind.RelativeOrAbsolute), listenUri, behaviorConfigurationName);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, Uri address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
if (binding == null)
{
throw FxTrace.Exception.ArgumentNull("binding");
}
if (address == null)
{
throw FxTrace.Exception.ArgumentNull("address");
}
Uri via = this.MakeAbsoluteUri(address, binding);
return AddServiceEndpointCore(serviceContractName, binding, new EndpointAddress(via), listenUri, behaviorConfigurationName);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
ServiceEndpoint AddServiceEndpointCore(XName serviceContractName, Binding binding, EndpointAddress address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
if (serviceContractName == null)
{
throw FxTrace.Exception.ArgumentNull("serviceContractName");
}
if (this.inferredContracts == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
}
ServiceEndpoint serviceEndpoint;
ContractDescription description;
ContractInferenceHelper.ProvideDefaultNamespace(ref serviceContractName);
if (this.inferredContracts.TryGetValue(serviceContractName, out description))
{
serviceEndpoint = new ServiceEndpoint(description, binding, address);
if (!string.IsNullOrEmpty(behaviorConfigurationName))
{
ConfigLoader.LoadChannelBehaviors(behaviorConfigurationName, null, serviceEndpoint.Behaviors);
}
}
else if (serviceContractName == mexContractXName) // Special case for mex endpoint
{
if (!this.Description.Behaviors.Contains(mexBehaviorType))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ServiceMetadataBehaviorNotFoundForServiceMetadataEndpoint(this.Description.Name)));
}
serviceEndpoint = new ServiceMetadataEndpoint(binding, address);
}
else
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
}
if (listenUri != null)
{
listenUri = base.MakeAbsoluteUri(listenUri, binding);
serviceEndpoint.ListenUri = listenUri;
}
base.Description.Endpoints.Add(serviceEndpoint);
if (TD.ServiceEndpointAddedIsEnabled())
{
TD.ServiceEndpointAdded(address.Uri.ToString(), binding.GetType().ToString(), serviceEndpoint.Contract.Name);
}
return serviceEndpoint;
}
// Duplicate public AddServiceEndpoint methods from the base class
// This is to ensure that base class methods with string are not hidden by derived class methods with XName
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address)
{
return base.AddServiceEndpoint(implementedContract, binding, address);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address)
{
return base.AddServiceEndpoint(implementedContract, binding, address);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri)
{
return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri)
{
return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
}
public override void AddServiceEndpoint(ServiceEndpoint endpoint)
{
if (!endpoint.IsSystemEndpoint)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotUseAddServiceEndpointOverloadForWorkflowServices));
}
base.AddServiceEndpoint(endpoint);
}
internal override void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints)
{
if (this.inferredContracts != null)
{
foreach (XName contractName in this.inferredContracts.Keys)
{
ServiceEndpoint endpoint = AddServiceEndpoint(contractName, defaultBinding, String.Empty);
ConfigLoader.LoadDefaultEndpointBehaviors(endpoint);
AddCorrelationQueryBehaviorToServiceEndpoint(endpoint);
defaultEndpoints.Add(endpoint);
}
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, MessageId = "0#", Justification = "This is defined by the ServiceHost base class")]
protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
{
Fx.AssertAndThrow(this.serviceDefinition != null, "serviceDefinition is null");
this.activity = this.serviceDefinition.Body;
Dictionary<string, ContractDescription> result = new Dictionary<string, ContractDescription>();
// Note: We do not check whether this.inferredContracts == null || this.inferredContracts.Count == 0,
// because we need to support hosting workflow with zero contract.
this.inferredContracts = this.serviceDefinition.GetContractDescriptions();
if (this.inferredContracts != null)
{
foreach (ContractDescription contract in this.inferredContracts.Values)
{
if (!string.IsNullOrEmpty(contract.ConfigurationName))
{
if (result.ContainsKey(contract.ConfigurationName))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.DifferentContractsSameConfigName));
}
result.Add(contract.ConfigurationName, contract);
}
}
}
implementedContracts = result;
// Currently, only WorkflowService has CorrelationQueries property
this.correlationQueries = this.serviceDefinition.CorrelationQueries;
ServiceDescription serviceDescription = this.serviceDefinition.GetEmptyServiceDescription();
serviceDescription.Behaviors.Add(new WorkflowServiceBehavior(this.workflowDefinitionProvider));
return serviceDescription;
}
void InitializeDescription(WorkflowService serviceDefinition, UriSchemeKeyedCollection baseAddresses)
{
Fx.Assert(serviceDefinition != null, "caller must verify");
this.serviceDefinition = serviceDefinition;
base.InitializeDescription(baseAddresses);
foreach (Endpoint endpoint in serviceDefinition.Endpoints)
{
if (endpoint.Binding == null)
{
string endpointName = ContractValidationHelper.GetErrorMessageEndpointName(endpoint.Name);
string contractName = ContractValidationHelper.GetErrorMessageEndpointServiceContractName(endpoint.ServiceContractName);
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MissingBindingInEndpoint(endpointName, contractName)));
}
ServiceEndpoint serviceEndpoint = AddServiceEndpointCore(endpoint.ServiceContractName, endpoint.Binding,
endpoint.GetAddress(this), endpoint.ListenUri, endpoint.BehaviorConfigurationName);
if (!string.IsNullOrEmpty(endpoint.Name))
{
serviceEndpoint.Name = endpoint.Name;
}
serviceEndpoint.UnresolvedAddress = endpoint.AddressUri;
serviceEndpoint.UnresolvedListenUri = endpoint.ListenUri;
}
this.PersistTimeout = defaultPersistTimeout;
this.TrackTimeout = defaultTrackTimeout;
this.FilterResumeTimeout = TimeSpan.FromSeconds(AppSettings.FilterResumeTimeoutInSeconds);
}
protected override void InitializeRuntime()
{
if (base.Description != null)
{
FixupEndpoints();
this.SetScopeName();
if (this.DurableInstancingOptions.ScopeName == null)
{
this.DurableInstancingOptions.ScopeName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);
}
}
base.InitializeRuntime();
this.WorkflowServiceHostPerformanceCounters.InitializePerformanceCounters();
this.ServiceName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);
// add a host-wide SendChannelCache (with default settings) if one doesn't exist
this.workflowExtensions.EnsureChannelCache();
// add a host-wide (free-threaded) CorrelationExtension based on our ServiceName
this.WorkflowExtensions.Add(new CorrelationExtension(this.DurableInstancingOptions.ScopeName));
this.WorkflowExtensions.MakeReadOnly();
// now calculate if IsLoadTransactionRequired
this.IsLoadTransactionRequired = WorkflowServiceInstance.IsLoadTransactionRequired(this);
if (this.serviceDefinition != null)
{
ValidateBufferedReceiveProperty();
this.serviceDefinition.ResetServiceDescription();
}
}
internal override void AfterInitializeRuntime(TimeSpan timeout)
{
this.durableInstanceManager.Open(timeout);
}
internal override IAsyncResult BeginAfterInitializeRuntime(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.durableInstanceManager.BeginOpen(timeout, callback, state);
}
internal override void EndAfterInitializeRuntime(IAsyncResult result)
{
this.durableInstanceManager.EndOpen(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
this.durableInstanceManager.Close(timeoutHelper.RemainingTime());
this.workflowServiceHostPerformanceCounters.Dispose();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CloseAsyncResult(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override void OnAbort()
{
base.OnAbort();
this.durableInstanceManager.Abort();
this.workflowServiceHostPerformanceCounters.Dispose();
}
internal void FaultServiceHostIfNecessary(Exception exception)
{
if (exception is InstancePersistenceException && !(exception is InstancePersistenceCommandException))
{
this.Fault(exception);
}
}
IAsyncResult BeginHostClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return base.OnBeginClose(timeout, callback, state);
}
void EndHostClose(IAsyncResult result)
{
base.OnEndClose(result);
}
void AddCorrelationQueryBehaviorToServiceEndpoint(ServiceEndpoint serviceEndpoint)
{
Fx.Assert(serviceEndpoint != null, "Argument cannot be null!");
Fx.Assert(serviceEndpoint.Contract != null, "ServiceEndpoint must have a contract!");
Fx.Assert(this.serviceDefinition != null, "Missing WorkflowService!");
Fx.Assert(!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType),
"ServiceEndpoint should not have CorrelationQueryBehavior before this point!");
XName endpointContractName = XName.Get(serviceEndpoint.Contract.Name, serviceEndpoint.Contract.Namespace);
Collection<CorrelationQuery> queries;
if (this.correlationQueries != null && this.correlationQueries.TryGetValue(endpointContractName, out queries))
{
// Filter out duplicate CorrelationQueries in the collection.
// Currently, we only do reference comparison and Where message filter comparison.
Collection<CorrelationQuery> uniqueQueries = new Collection<CorrelationQuery>();
foreach (CorrelationQuery correlationQuery in queries)
{
if (!uniqueQueries.Contains(correlationQuery))
{
uniqueQueries.Add(correlationQuery);
}
else
{
if (TD.DuplicateCorrelationQueryIsEnabled())
{
TD.DuplicateCorrelationQuery(correlationQuery.Where.ToString());
}
}
}
serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(uniqueQueries) { ServiceContractName = endpointContractName });
}
else if (CorrelationQueryBehavior.BindingHasDefaultQueries(serviceEndpoint.Binding))
{
if (!serviceEndpoint.Behaviors.Contains(typeof(CorrelationQueryBehavior)))
{
serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(new Collection<CorrelationQuery>()) { ServiceContractName = endpointContractName });
}
}
}
void FixupEndpoints()
{
Fx.Assert(this.Description != null, "ServiceDescription cannot be null");
Dictionary<Type, ContractDescription> contractDescriptionDictionary = new Dictionary<Type, ContractDescription>();
foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints)
{
if (this.serviceDefinition.AllowBufferedReceive)
{
// All application-level endpoints need to support ReceiveContext
SetupReceiveContextEnabledAttribute(serviceEndpoint);
}
// Need to add CorrelationQueryBehavior here so that endpoints added from config are included.
// It is possible that some endpoints already have CorrelationQueryBehavior from
// the AddDefaultEndpoints code path. We should skip them.
if (!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType))
{
AddCorrelationQueryBehaviorToServiceEndpoint(serviceEndpoint);
}
// Need to ensure that any WorkflowHostingEndpoints using the same contract type actually use the
// same contractDescription instance since this is required by WCF.
if (serviceEndpoint is WorkflowHostingEndpoint)
{
ContractDescription contract;
if (contractDescriptionDictionary.TryGetValue(serviceEndpoint.Contract.ContractType, out contract))
{
serviceEndpoint.Contract = contract;
}
else
{
contractDescriptionDictionary[serviceEndpoint.Contract.ContractType] = serviceEndpoint.Contract;
}
}
}
if (this.serviceDefinition.AllowBufferedReceive && !this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType))
{
this.Description.Behaviors.Add(new BufferedReceiveServiceBehavior());
}
}
void SetScopeName()
{
VirtualPathExtension virtualPathExtension = this.Extensions.Find<VirtualPathExtension>();
if (virtualPathExtension != null)
{
// Web Hosted scenario
WorkflowHostingOptionsSection hostingOptions = (WorkflowHostingOptionsSection)ConfigurationManager.GetSection(ConfigurationStrings.WorkflowHostingOptionsSectionPath);
if (hostingOptions != null && hostingOptions.OverrideSiteName)
{
this.OverrideSiteName = hostingOptions.OverrideSiteName;
string fullVirtualPath = virtualPathExtension.VirtualPath.Substring(1);
fullVirtualPath = ("/" == virtualPathExtension.ApplicationVirtualPath) ? fullVirtualPath : virtualPathExtension.ApplicationVirtualPath + fullVirtualPath;
int index = fullVirtualPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
string virtualDirectoryPath = fullVirtualPath.Substring(0, index + 1);
this.DurableInstancingOptions.ScopeName = XName.Get(XmlConvert.EncodeLocalName(Path.GetFileName(virtualPathExtension.VirtualPath)),
string.Format(CultureInfo.InvariantCulture, "/{0}{1}", this.Description.Name, virtualDirectoryPath));
}
}
}
void SetupReceiveContextEnabledAttribute(ServiceEndpoint serviceEndpoint)
{
if (BufferedReceiveServiceBehavior.IsWorkflowEndpoint(serviceEndpoint))
{
foreach (OperationDescription operation in serviceEndpoint.Contract.Operations)
{
ReceiveContextEnabledAttribute behavior = operation.Behaviors.Find<ReceiveContextEnabledAttribute>();
if (behavior == null)
{
operation.Behaviors.Add(new ReceiveContextEnabledAttribute() { ManualControl = true });
}
else
{
behavior.ManualControl = true;
}
}
}
}
void ValidateBufferedReceiveProperty()
{
// Validate that the AttachedProperty is indeed being used when the behavior is also used
bool hasBehavior = this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType);
if (hasBehavior && !this.serviceDefinition.AllowBufferedReceive)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BufferedReceiveBehaviorUsedWithoutProperty));
}
}
// specialized WorkflowInstanceExtensionManager that can default in a SendMessageChannelCache
class WorkflowServiceHostExtensions : WorkflowInstanceExtensionManager
{
static Type SendReceiveExtensionType = typeof(SendReceiveExtension);
bool hasChannelCache;
public WorkflowServiceHostExtensions()
: base()
{
}
public override void Add<T>(Func<T> extensionCreationFunction)
{
ThrowIfNotSupported(typeof(T));
if (TypeHelper.AreTypesCompatible(typeof(T), typeof(SendMessageChannelCache)))
{
this.hasChannelCache = true;
}
base.Add<T>(extensionCreationFunction);
}
public override void Add(object singletonExtension)
{
ThrowIfNotSupported(singletonExtension.GetType());
if (singletonExtension is SendMessageChannelCache)
{
this.hasChannelCache = true;
}
base.Add(singletonExtension);
}
public void EnsureChannelCache()
{
if (!this.hasChannelCache)
{
Add(new SendMessageChannelCache());
this.hasChannelCache = true;
}
}
void ThrowIfNotSupported(Type type)
{
if (TypeHelper.AreTypesCompatible(type, SendReceiveExtensionType))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ExtensionTypeNotSupported(SendReceiveExtensionType.FullName)));
}
}
}
class CloseAsyncResult : AsyncResult
{
static AsyncCompletion handleDurableInstanceManagerEndClose = new AsyncCompletion(HandleDurableInstanceManagerEndClose);
static AsyncCompletion handleEndHostClose = new AsyncCompletion(HandleEndHostClose);
TimeoutHelper timeoutHelper;
WorkflowServiceHost host;
public CloseAsyncResult(WorkflowServiceHost host, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.timeoutHelper = new TimeoutHelper(timeout);
this.host = host;
if (CloseHost())
{
Complete(true);
}
}
bool CloseDurableInstanceManager()
{
IAsyncResult result = this.host.durableInstanceManager.BeginClose(
this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleDurableInstanceManagerEndClose), this);
return SyncContinue(result);
}
bool CloseHost()
{
IAsyncResult result = this.host.BeginHostClose(
this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndHostClose), this);
return SyncContinue(result);
}
static bool HandleDurableInstanceManagerEndClose(IAsyncResult result)
{
CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;
thisPtr.host.durableInstanceManager.EndClose(result);
thisPtr.host.WorkflowServiceHostPerformanceCounters.Dispose();
return true;
}
static bool HandleEndHostClose(IAsyncResult result)
{
CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;
thisPtr.host.EndHostClose(result);
return thisPtr.CloseDurableInstanceManager();
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Numerics.Tests
{
public static class MyBigIntImp
{
public static BigInteger DoUnaryOperatorMine(BigInteger num1, string op)
{
List<byte> bytes1 = new List<byte>(num1.ToByteArray());
int factor;
double result;
switch (op)
{
case "uSign":
if (IsZero(bytes1))
{
return new BigInteger(0);
}
if (IsZero(Max(bytes1, new List<byte>(new byte[] { 0 }))))
{
return new BigInteger(-1);
}
return new BigInteger(1);
case "u~":
return new BigInteger(Not(bytes1).ToArray());
case "uLog10":
factor = unchecked((int)BigInteger.Log(num1, 10));
if (factor > 100)
{
for (int i = 0; i < factor - 100; i++)
{
num1 = num1 / 10;
}
}
result = Math.Log10((double)num1);
if (factor > 100)
{
for (int i = 0; i < factor - 100; i++)
{
result = result + 1;
}
}
return ApproximateBigInteger(result);
case "uLog":
factor = unchecked((int)BigInteger.Log(num1, 10));
if (factor > 100)
{
for (int i = 0; i < factor - 100; i++)
{
num1 = num1 / 10;
}
}
result = Math.Log((double)num1);
if (factor > 100)
{
for (int i = 0; i < factor - 100; i++)
{
result = result + Math.Log(10);
}
}
return ApproximateBigInteger(result);
case "uAbs":
if ((bytes1[bytes1.Count - 1] & 0x80) != 0)
{
bytes1 = Negate(bytes1);
}
return new BigInteger(bytes1.ToArray());
case "u--":
return new BigInteger(Add(bytes1, new List<byte>(new byte[] { 0xff })).ToArray());
case "u++":
return new BigInteger(Add(bytes1, new List<byte>(new byte[] { 1 })).ToArray());
case "uNegate":
case "u-":
return new BigInteger(Negate(bytes1).ToArray());
case "u+":
return num1;
case "uMultiply":
case "u*":
return new BigInteger(Multiply(bytes1, bytes1).ToArray());
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
public static BigInteger DoBinaryOperatorMine(BigInteger num1, BigInteger num2, string op)
{
BigInteger num3;
return DoBinaryOperatorMine(num1, num2, op, out num3);
}
public static BigInteger DoBinaryOperatorMine(BigInteger num1, BigInteger num2, string op, out BigInteger num3)
{
List<byte> bytes1 = new List<byte>(num1.ToByteArray());
List<byte> bytes2 = new List<byte>(num2.ToByteArray());
switch (op)
{
case "bMin":
return new BigInteger(Negate(Max(Negate(bytes1), Negate(bytes2))).ToArray());
case "bMax":
return new BigInteger(Max(bytes1, bytes2).ToArray());
case "b>>":
return new BigInteger(ShiftLeft(bytes1, Negate(bytes2)).ToArray());
case "b<<":
return new BigInteger(ShiftLeft(bytes1, bytes2).ToArray());
case "b^":
return new BigInteger(Xor(bytes1, bytes2).ToArray());
case "b|":
return new BigInteger(Or(bytes1, bytes2).ToArray());
case "b&":
return new BigInteger(And(bytes1, bytes2).ToArray());
case "bLog":
return ApproximateBigInteger(Math.Log((double)num1, (double)num2));
case "bGCD":
return new BigInteger(GCD(bytes1, bytes2).ToArray());
case "bPow":
int arg2 = (int)num2;
bytes2 = new List<byte>(new BigInteger(arg2).ToByteArray());
return new BigInteger(Pow(bytes1, bytes2).ToArray());
case "bDivRem":
BigInteger ret = new BigInteger(Divide(bytes1, bytes2).ToArray());
bytes1 = new List<byte>(num1.ToByteArray());
bytes2 = new List<byte>(num2.ToByteArray());
num3 = new BigInteger(Remainder(bytes1, bytes2).ToArray());
return ret;
case "bRemainder":
case "b%":
return new BigInteger(Remainder(bytes1, bytes2).ToArray());
case "bDivide":
case "b/":
return new BigInteger(Divide(bytes1, bytes2).ToArray());
case "bMultiply":
case "b*":
return new BigInteger(Multiply(bytes1, bytes2).ToArray());
case "bSubtract":
case "b-":
bytes2 = Negate(bytes2);
goto case "bAdd";
case "bAdd":
case "b+":
return new BigInteger(Add(bytes1, bytes2).ToArray());
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
public static BigInteger DoTertanaryOperatorMine(BigInteger num1, BigInteger num2, BigInteger num3, string op)
{
List<byte> bytes1 = new List<byte>(num1.ToByteArray());
List<byte> bytes2 = new List<byte>(num2.ToByteArray());
List<byte> bytes3 = new List<byte>(num3.ToByteArray());
switch (op)
{
case "tModPow":
return new BigInteger(ModPow(bytes1, bytes2, bytes3).ToArray());
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
public static List<byte> Add(List<byte> bytes1, List<byte> bytes2)
{
List<byte> bnew = new List<byte>();
bool num1neg = (bytes1[bytes1.Count - 1] & 0x80) != 0;
bool num2neg = (bytes2[bytes2.Count - 1] & 0x80) != 0;
byte extender = 0;
bool bnewneg;
bool carry;
NormalizeLengths(bytes1, bytes2);
carry = false;
for (int i = 0; i < bytes1.Count; i++)
{
int temp = bytes1[i] + bytes2[i];
if (carry)
{
temp++;
}
carry = false;
if (temp > byte.MaxValue)
{
temp -= byte.MaxValue + 1;
carry = true;
}
bnew.Add((byte)temp);
}
bnewneg = (bnew[bnew.Count - 1] & 0x80) != 0;
if ((num1neg == num2neg) & (num1neg != bnewneg))
{
if (num1neg)
{
extender = 0xff;
}
bnew.Add(extender);
}
return bnew;
}
public static List<byte> Negate(List<byte> bytes)
{
bool carry;
List<byte> bnew = new List<byte>();
bool bsame;
for (int i = 0; i < bytes.Count; i++)
{
bytes[i] ^= 0xFF;
}
carry = false;
for (int i = 0; i < bytes.Count; i++)
{
int temp = (i == 0 ? 0x01 : 0x00) + bytes[i];
if (carry)
{
temp++;
}
carry = false;
if (temp > byte.MaxValue)
{
temp -= byte.MaxValue + 1;
carry = true;
}
bnew.Add((byte)temp);
}
bsame = ((bnew[bnew.Count - 1] & 0x80) != 0);
bsame &= ((bnew[bnew.Count - 1] & 0x7f) == 0);
for (int i = bnew.Count - 2; i >= 0; i--)
{
bsame &= (bnew[i] == 0);
}
if (bsame)
{
bnew.Add((byte)0);
}
return bnew;
}
public static List<byte> Multiply(List<byte> bytes1, List<byte> bytes2)
{
NormalizeLengths(bytes1, bytes2);
List<byte> bresult = new List<byte>();
for (int i = 0; i < bytes1.Count; i++)
{
bresult.Add((byte)0x00);
bresult.Add((byte)0x00);
}
NormalizeLengths(bytes2, bresult);
NormalizeLengths(bytes1, bresult);
BitArray ba2 = new BitArray(bytes2.ToArray());
for (int i = ba2.Length - 1; i >= 0; i--)
{
if (ba2[i])
{
bresult = Add(bytes1, bresult);
}
if (i != 0)
{
bresult = ShiftLeftDrop(bresult);
}
}
bresult = SetLength(bresult, bytes2.Count);
return bresult;
}
public static List<byte> Divide(List<byte> bytes1, List<byte> bytes2)
{
bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0);
bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0);
if (!numPos)
{
bytes1 = Negate(bytes1);
}
if (!denPos)
{
bytes2 = Negate(bytes2);
}
bool qPos = (numPos == denPos);
Trim(bytes1);
Trim(bytes2);
BitArray ba1 = new BitArray(bytes1.ToArray());
BitArray ba2 = new BitArray(bytes2.ToArray());
int ba11loc = 0;
for (int i = ba1.Length - 1; i >= 0; i--)
{
if (ba1[i])
{
ba11loc = i;
break;
}
}
int ba21loc = 0;
for (int i = ba2.Length - 1; i >= 0; i--)
{
if (ba2[i])
{
ba21loc = i;
break;
}
}
int shift = ba11loc - ba21loc;
if (shift < 0)
{
return new List<byte>(new byte[] { (byte)0 });
}
BitArray br = new BitArray(shift + 1, false);
for (int i = 0; i < shift; i++)
{
bytes2 = ShiftLeftGrow(bytes2);
}
while (shift >= 0)
{
bytes2 = Negate(bytes2);
bytes1 = Add(bytes1, bytes2);
bytes2 = Negate(bytes2);
if (bytes1[bytes1.Count - 1] < 128)
{
br[shift] = true;
}
else
{
bytes1 = Add(bytes1, bytes2);
}
bytes2 = ShiftRight(bytes2);
shift--;
}
List<byte> result = GetBytes(br);
if (!qPos)
{
result = Negate(result);
}
return result;
}
public static List<byte> Remainder(List<byte> bytes1, List<byte> bytes2)
{
bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0);
bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0);
if (!numPos)
{
bytes1 = Negate(bytes1);
}
if (!denPos)
{
bytes2 = Negate(bytes2);
}
Trim(bytes1);
Trim(bytes2);
BitArray ba1 = new BitArray(bytes1.ToArray());
BitArray ba2 = new BitArray(bytes2.ToArray());
int ba11loc = 0;
for (int i = ba1.Length - 1; i >= 0; i--)
{
if (ba1[i])
{
ba11loc = i;
break;
}
}
int ba21loc = 0;
for (int i = ba2.Length - 1; i >= 0; i--)
{
if (ba2[i])
{
ba21loc = i;
break;
}
}
int shift = ba11loc - ba21loc;
if (shift < 0)
{
if (!numPos)
{
bytes1 = Negate(bytes1);
}
return bytes1;
}
BitArray br = new BitArray(shift + 1, false);
for (int i = 0; i < shift; i++)
{
bytes2 = ShiftLeftGrow(bytes2);
}
while (shift >= 0)
{
bytes2 = Negate(bytes2);
bytes1 = Add(bytes1, bytes2);
bytes2 = Negate(bytes2);
if (bytes1[bytes1.Count - 1] < 128)
{
br[shift] = true;
}
else
{
bytes1 = Add(bytes1, bytes2);
}
bytes2 = ShiftRight(bytes2);
shift--;
}
if (!numPos)
{
bytes1 = Negate(bytes1);
}
return bytes1;
}
public static List<byte> Pow(List<byte> bytes1, List<byte> bytes2)
{
if (IsZero(bytes2))
{
return new List<byte>(new byte[] { 1 });
}
BitArray ba2 = new BitArray(bytes2.ToArray());
int last1 = 0;
List<byte> result = null;
for (int i = ba2.Length - 1; i >= 0; i--)
{
if (ba2[i])
{
last1 = i;
break;
}
}
for (int i = 0; i <= last1; i++)
{
if (ba2[i])
{
if (result == null)
{
result = bytes1;
}
else
{
result = Multiply(result, bytes1);
}
Trim(bytes1);
Trim(result);
}
if (i != last1)
{
bytes1 = Multiply(bytes1, bytes1);
Trim(bytes1);
}
}
return (result == null) ? new List<byte>(new byte[] { 1 }) : result;
}
public static List<byte> ModPow(List<byte> bytes1, List<byte> bytes2, List<byte> bytes3)
{
if (IsZero(bytes2))
{
return Remainder(new List<byte>(new byte[] { 1 }), bytes3);
}
BitArray ba2 = new BitArray(bytes2.ToArray());
int last1 = 0;
List<byte> result = null;
for (int i = ba2.Length - 1; i >= 0; i--)
{
if (ba2[i])
{
last1 = i;
break;
}
}
bytes1 = Remainder(bytes1, Copy(bytes3));
for (int i = 0; i <= last1; i++)
{
if (ba2[i])
{
if (result == null)
{
result = bytes1;
}
else
{
result = Multiply(result, bytes1);
result = Remainder(result, Copy(bytes3));
}
Trim(bytes1);
Trim(result);
}
if (i != last1)
{
bytes1 = Multiply(bytes1, bytes1);
bytes1 = Remainder(bytes1, Copy(bytes3));
Trim(bytes1);
}
}
return (result == null) ? Remainder(new List<byte>(new byte[] { 1 }), bytes3) : result;
}
public static List<byte> GCD(List<byte> bytes1, List<byte> bytes2)
{
List<byte> temp;
bool numPos = ((bytes1[bytes1.Count - 1] & 0x80) == 0);
bool denPos = ((bytes2[bytes2.Count - 1] & 0x80) == 0);
if (!numPos)
{
bytes1 = Negate(bytes1);
}
if (!denPos)
{
bytes2 = Negate(bytes2);
}
Trim(bytes1);
Trim(bytes2);
while (!IsZero(bytes2))
{
temp = Copy(bytes2);
bytes2 = Remainder(bytes1, bytes2);
bytes1 = temp;
}
return bytes1;
}
public static List<byte> Max(List<byte> bytes1, List<byte> bytes2)
{
bool b1Pos = ((bytes1[bytes1.Count - 1] & 0x80) == 0);
bool b2Pos = ((bytes2[bytes2.Count - 1] & 0x80) == 0);
if (b1Pos != b2Pos)
{
if (b1Pos)
{
return bytes1;
}
if (b2Pos)
{
return bytes2;
}
}
List<byte> sum = Add(bytes1, Negate(Copy(bytes2)));
if ((sum[sum.Count - 1] & 0x80) != 0)
{
return bytes2;
}
return bytes1;
}
public static List<byte> And(List<byte> bytes1, List<byte> bytes2)
{
List<byte> bnew = new List<byte>();
NormalizeLengths(bytes1, bytes2);
for (int i = 0; i < bytes1.Count; i++)
{
bnew.Add((byte)(bytes1[i] & bytes2[i]));
}
return bnew;
}
public static List<byte> Or(List<byte> bytes1, List<byte> bytes2)
{
List<byte> bnew = new List<byte>();
NormalizeLengths(bytes1, bytes2);
for (int i = 0; i < bytes1.Count; i++)
{
bnew.Add((byte)(bytes1[i] | bytes2[i]));
}
return bnew;
}
public static List<byte> Xor(List<byte> bytes1, List<byte> bytes2)
{
List<byte> bnew = new List<byte>();
NormalizeLengths(bytes1, bytes2);
for (int i = 0; i < bytes1.Count; i++)
{
bnew.Add((byte)(bytes1[i] ^ bytes2[i]));
}
return bnew;
}
public static List<byte> Not(List<byte> bytes)
{
List<byte> bnew = new List<byte>();
for (int i = 0; i < bytes.Count; i++)
{
bnew.Add((byte)(bytes[i] ^ 0xFF));
}
return bnew;
}
public static List<byte> ShiftLeft(List<byte> bytes1, List<byte> bytes2)
{
int byteShift = (int)new BigInteger(Divide(Copy(bytes2), new List<byte>(new byte[] { 8 })).ToArray());
sbyte bitShift = (sbyte)new BigInteger(Remainder(bytes2, new List<byte>(new byte[] { 8 })).ToArray());
for (int i = 0; i < Math.Abs(bitShift); i++)
{
if (bitShift < 0)
{
bytes1 = ShiftRight(bytes1);
}
else
{
bytes1 = ShiftLeftGrow(bytes1);
}
}
if (byteShift < 0)
{
byteShift = -byteShift;
if (byteShift >= bytes1.Count)
{
if ((bytes1[bytes1.Count - 1] & 0x80) != 0)
{
bytes1 = new List<byte>(new byte[] { 0xFF });
}
else
{
bytes1 = new List<byte>(new byte[] { 0 });
}
}
else
{
List<byte> temp = new List<byte>();
for (int i = byteShift; i < bytes1.Count; i++)
{
temp.Add(bytes1[i]);
}
bytes1 = temp;
}
}
else
{
List<byte> temp = new List<byte>();
for (int i = 0; i < byteShift; i++)
{
temp.Add((byte)0);
}
for (int i = 0; i < bytes1.Count; i++)
{
temp.Add(bytes1[i]);
}
bytes1 = temp;
}
return bytes1;
}
public static List<byte> ShiftLeftGrow(List<byte> bytes)
{
List<byte> bresult = new List<byte>();
for (int i = 0; i < bytes.Count; i++)
{
byte newbyte = bytes[i];
if (newbyte > 127)
{
newbyte -= 128;
}
newbyte = (byte)(newbyte * 2);
if ((i != 0) && (bytes[i - 1] >= 128))
{
newbyte++;
}
bresult.Add(newbyte);
}
if ((bytes[bytes.Count - 1] > 63) && (bytes[bytes.Count - 1] < 128))
{
bresult.Add((byte)0);
}
if ((bytes[bytes.Count - 1] > 127) && (bytes[bytes.Count - 1] < 192))
{
bresult.Add((byte)0xFF);
}
return bresult;
}
public static List<byte> ShiftLeftDrop(List<byte> bytes)
{
List<byte> bresult = new List<byte>();
for (int i = 0; i < bytes.Count; i++)
{
byte newbyte = bytes[i];
if (newbyte > 127)
{
newbyte -= 128;
}
newbyte = (byte)(newbyte * 2);
if ((i != 0) && (bytes[i - 1] >= 128))
{
newbyte++;
}
bresult.Add(newbyte);
}
return bresult;
}
public static List<byte> ShiftRight(List<byte> bytes)
{
List<byte> bresult = new List<byte>();
for (int i = 0; i < bytes.Count; i++)
{
byte newbyte = bytes[i];
newbyte = (byte)(newbyte / 2);
if ((i != (bytes.Count - 1)) && ((bytes[i + 1] & 0x01) == 1))
{
newbyte += 128;
}
if ((i == (bytes.Count - 1)) && ((bytes[bytes.Count - 1] & 0x80) != 0))
{
newbyte += 128;
}
bresult.Add(newbyte);
}
return bresult;
}
public static List<byte> SetLength(List<byte> bytes, int size)
{
List<byte> bresult = new List<byte>();
for (int i = 0; i < size; i++)
{
bresult.Add(bytes[i]);
}
return bresult;
}
public static List<byte> Copy(List<byte> bytes)
{
List<byte> ret = new List<byte>();
for (int i = 0; i < bytes.Count; i++)
{
ret.Add(bytes[i]);
}
return ret;
}
public static void NormalizeLengths(List<byte> bytes1, List<byte> bytes2)
{
bool num1neg = (bytes1[bytes1.Count - 1] & 0x80) != 0;
bool num2neg = (bytes2[bytes2.Count - 1] & 0x80) != 0;
byte extender = 0;
if (bytes1.Count < bytes2.Count)
{
if (num1neg)
{
extender = 0xff;
}
while (bytes1.Count < bytes2.Count)
{
bytes1.Add(extender);
}
}
if (bytes2.Count < bytes1.Count)
{
if (num2neg)
{
extender = 0xff;
}
while (bytes2.Count < bytes1.Count)
{
bytes2.Add(extender);
}
}
}
public static void Trim(List<byte> bytes)
{
while (bytes.Count > 1)
{
if ((bytes[bytes.Count - 1] & 0x80) == 0)
{
if ((bytes[bytes.Count - 1] == 0) & ((bytes[bytes.Count - 2] & 0x80) == 0))
{
bytes.RemoveAt(bytes.Count - 1);
}
else
{
break;
}
}
else
{
if ((bytes[bytes.Count - 1] == 0xFF) & ((bytes[bytes.Count - 2] & 0x80) != 0))
{
bytes.RemoveAt(bytes.Count - 1);
}
else
{
break;
}
}
}
}
public static List<byte> GetBytes(BitArray ba)
{
int length = ((ba.Length) / 8) + 1;
List<byte> mask = new List<byte>(new byte[] { 0 });
for (int i = length - 1; i >= 0; i--)
{
for (int j = 7; j >= 0; j--)
{
mask = ShiftLeftGrow(mask);
if ((8 * i + j < ba.Length) && (ba[8 * i + j]))
{
mask[0] |= (byte)1;
}
}
}
return mask;
}
public static String Print(byte[] bytes)
{
String ret = "make ";
for (int i = 0; i < bytes.Length; i++)
{
ret += bytes[i] + " ";
}
ret += "endmake ";
return ret;
}
public static String PrintFormatX(byte[] bytes)
{
string ret = String.Empty;
for (int i = 0; i < bytes.Length; i++)
{
ret += bytes[i].ToString("x");
}
return ret;
}
public static String PrintFormatX2(byte[] bytes)
{
string ret = String.Empty;
for (int i = 0; i < bytes.Length; i++)
{
ret += bytes[i].ToString("x2") + " ";
}
return ret;
}
public static bool IsZero(List<byte> list)
{
return IsZero(list.ToArray());
}
public static bool IsZero(byte[] value)
{
for (int i = 0; i < value.Length; i++)
{
if (value[i] != 0)
{
return false;
}
}
return true;
}
public static byte[] GetNonZeroRandomByteArray(Random random, int size)
{
byte[] value = new byte[size];
while (IsZero(value))
{
random.NextBytes(value);
}
return value;
}
public static byte[] GetRandomByteArray(Random random, int size)
{
byte[] value = new byte[size];
random.NextBytes(value);
return value;
}
public static BigInteger ApproximateBigInteger(double value)
{
//Special case values;
if (Double.IsNaN(value))
{
return new BigInteger(-101);
}
if (Double.IsNegativeInfinity(value))
{
return new BigInteger(-102);
}
if (Double.IsPositiveInfinity(value))
{
return new BigInteger(-103);
}
BigInteger result = new BigInteger(Math.Round(value, 0));
if (result != 0)
{
bool pos = (value > 0);
if (!pos)
{
value = -value;
}
int size = (int)Math.Floor(Math.Log10(value));
//keep only the first 17 significant digits;
if (size > 17)
{
result = result - (result % BigInteger.Pow(10, size - 17));
}
if (!pos)
{
value = -value;
}
}
return result;
}
}
}
| |
/************************************************************************************
Filename : OVRVoiceMod.cs
Content : Interface to Oculus voice mod
Created : December 14th, 2015
Copyright : Copyright 2015 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Runtime.InteropServices;
//-------------------------------------------------------------------------------------
// ***** OVRVoiceMod
//
/// <summary>
/// OVRVoiceMod interfaces into the Oculus voice-mod engine. This component should be added
/// into the scene once.
///
/// </summary>
public class OVRVoiceMod : MonoBehaviour
{
public const int ovrVoiceModSuccess = 0;
// Error codes that may return from VoiceMod engine
public enum ovrVoiceModError
{
Unknown = -2250, //< An unknown error has occurred
CannotCreateContext = -2251, //< Unable to create a context
InvalidParam = -2252, //< An invalid parameter, e.g. NULL pointer or out of range
BadSampleRate = -2253, //< An unsupported sample rate was declared
MissingDLL = -2254, //< The DLL or shared library could not be found
BadVersion = -2255, //< Mismatched versions between header and libs
UndefinedFunction = -2256 //< An undefined function
};
/// Flags (unused at this time)
public enum ovrViceModFlag
{
None = 0x0000,
};
/// NOTE: Opaque typedef for voice mod context is an unsigned int (uint)
// * * * * * * * * * * * * *
// Import functions
public const string strOVRLS = "OVRVoiceMod";
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_Initialize(int SampleRate, int BufferSize);
[DllImport(strOVRLS)]
private static extern void ovrVoiceModDll_Shutdown();
[DllImport(strOVRLS)]
private static extern IntPtr ovrVoicemodDll_GetVersion(ref int Major,
ref int Minor,
ref int Patch);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_CreateContext(ref uint Context);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_DestroyContext(uint Context);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_SendParameter(uint Context, int Parameter, int Value);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_ProcessFrame(uint Context, uint Flags, float [] AudioBuffer);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_ProcessFrameInterleaved(uint Context, uint Flags, float [] AudioBuffer);
[DllImport(strOVRLS)]
private static extern int ovrVoiceModDll_GetAverageAbsVolume(uint Context, ref float Volume);
// * * * * * * * * * * * * *
// Public members
// * * * * * * * * * * * * *
// Static members
private static int sOVRVoiceModInit = (int)ovrVoiceModError.Unknown;
// interface through this static member.
public static OVRVoiceMod sInstance = null;
// * * * * * * * * * * * * *
// MonoBehaviour overrides
/// <summary>
/// Awake this instance.
/// </summary>
void Awake ()
{
// We can only have one instance of OVRLipSync in a scene (use this for local property query)
if(sInstance == null)
{
sInstance = this;
}
else
{
Debug.LogWarning (System.String.Format ("OVRVoiceMod Awake: Only one instance of OVRVoiceMod can exist in the scene."));
return;
}
int samplerate;
int bufsize;
int numbuf;
// Get the current sample rate
samplerate = AudioSettings.outputSampleRate;
// Get the current buffer size and number of buffers
AudioSettings.GetDSPBufferSize (out bufsize, out numbuf);
String str = System.String.Format
("OvrVoiceMod Awake: Queried SampleRate: {0:F0} BufferSize: {1:F0}", samplerate, bufsize);
Debug.LogWarning (str);
sOVRVoiceModInit = ovrVoiceModDll_Initialize(samplerate, bufsize);
if(sOVRVoiceModInit != ovrVoiceModSuccess)
{
Debug.LogWarning (System.String.Format
("OvrVoiceMod Awake: Failed to init VoiceMod library"));
}
// Important: Use the touchpad mechanism for input, call Create on the OVRTouchpad helper class
OVRTouchpad.Create();
}
/// <summary>
/// Start this instance.
/// Note: make sure to always have a Start function for classes that have editor scripts.
/// </summary>
void Start()
{
}
/// <summary>
/// Run processes that need to be updated in our game thread
/// </summary>
void Update()
{
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
if(sInstance != this)
{
Debug.LogWarning ("OVRVoiceMod OnDestroy: This is not the correct OVRVoiceMod instance.");
}
ovrVoiceModDll_Shutdown();
sOVRVoiceModInit = (int)ovrVoiceModError.Unknown;
}
// * * * * * * * * * * * * *
// Public Functions
/// <summary>
/// Determines if is initialized.
/// </summary>
/// <returns><c>true</c> if is initialized; otherwise, <c>false</c>.</returns>
public static int IsInitialized()
{
return sOVRVoiceModInit;
}
/// <summary>
/// Creates the context.
/// </summary>
/// <returns>The context.</returns>
/// <param name="context">Context.</param>
public static int CreateContext(ref uint context)
{
if(IsInitialized() != ovrVoiceModSuccess)
return (int)ovrVoiceModError.CannotCreateContext;
return ovrVoiceModDll_CreateContext(ref context);
}
/// <summary>
/// Destroies the context.
/// </summary>
/// <returns>The context.</returns>
/// <param name="context">Context.</param>
public static int DestroyContext (uint context)
{
if(IsInitialized() != ovrVoiceModSuccess)
return (int)ovrVoiceModError.Unknown;
return ovrVoiceModDll_DestroyContext(context);
}
/// <summary>
/// Sends the parameter.
/// </summary>
/// <returns>The parameter.</returns>
/// <param name="context">Context.</param>
/// <param name="parameter">Parameter.</param>
/// <param name="value">Value.</param>
public static int SendParameter(uint context, int parameter, int value)
{
if(IsInitialized() != ovrVoiceModSuccess)
return (int)ovrVoiceModError.Unknown;
return ovrVoiceModDll_SendParameter(context, parameter, value);
}
/// <summary>
/// Processes the frame.
/// </summary>
/// <returns>The frame.</returns>
/// <param name="context">Context.</param>
/// <param name="audioBuffer">Audio buffer.</param>
public static int ProcessFrame(uint context, float [] audioBuffer)
{
if(IsInitialized() != ovrVoiceModSuccess)
return (int)ovrVoiceModError.Unknown;
return ovrVoiceModDll_ProcessFrame(context, (uint)ovrViceModFlag.None , audioBuffer);
}
/// <summary>
/// Processes the frame interleaved.
/// </summary>
/// <returns>The frame interleaved.</returns>
/// <param name="context">Context.</param>
/// <param name="audioBuffer">Audio buffer.</param>
public static int ProcessFrameInterleaved(uint context, float [] audioBuffer)
{
if(IsInitialized() != ovrVoiceModSuccess)
return (int)ovrVoiceModError.Unknown;
return ovrVoiceModDll_ProcessFrameInterleaved(context, (uint)ovrViceModFlag.None, audioBuffer);
}
/// <summary>
/// Gets the average abs volume.
/// </summary>
/// <returns>The average abs volume.</returns>
/// <param name="context">Context.</param>
/// <param name="volume">Volume.</param>
public static float GetAverageAbsVolume(uint context)
{
if(IsInitialized() != ovrVoiceModSuccess)
return 0.0f;
float volume = 0;
int result = ovrVoiceModDll_GetAverageAbsVolume(context, ref volume);
return volume;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
// You use a namespace to define globally unique objects
namespace CSharpTutA.cs
{
// A class defines the variables and methods used
// by objects. I'll get more into this later
class Program
{
// The main function is where execution begins
// static functions belong to the class and
// can be executed without needing to create
// an object
// void means that this function doesn't return
// a value after it executes, but it is
// common to use int instead and return an
// integer value 0 : when successfully executed
// or -1 when an error occurred
// This function can receive multiple string
// values that are saved into an array
static void Main(string[] args)
{
// Write a string to the console followed
// be a newline
// Write() doesn't include a newline
// The Console class provides functions for input
// output and error streams for console applications
Console.WriteLine("Hello World");
// for loops allow you to cycle through information
// We will get command line arguments passed and print
// them
for(int i = 0; i < args.Length; i++)
{
// We use format parameters to place the string
// version of passed objects into the output
Console.WriteLine("Arg {0} : {1}", i, args[i]);
}
// Passing command line arguments in Visual Studio
// Right click on project name in Solution Explorer
// Select Properties
// Select Debug tab on the left
// Enter parameters in Command Line Arguments textbox
// Click Start
// Get an array of the command line arguments
string[] myArgs = Environment.GetCommandLineArgs();
// Use the Join function to combine arguments with a comma
Console.WriteLine(string.Join(", ", myArgs));
// Call for the function to execute
// SayHello();
// ---------- DATA TYPES ----------
// Bools store true or false
bool canIVote = true;
// INTEGERS
// Integers are 32-bit signed integers
Console.WriteLine("Biggest Integer : {0}", int.MaxValue);
Console.WriteLine("Smallest Integer : {0}", int.MinValue);
// LONGS
// Longs are 64-bit signed integers
Console.WriteLine("Biggest Long : {0}", long.MaxValue);
Console.WriteLine("Smallest Long : {0}", long.MinValue);
// DECIMALS
// Decimals store 128-bit precise decimal values
// It is accurate to 28 digits
decimal decPiVal = 3.1415926535897932384626433832M;
decimal decBigNum = 3.00000000000000000000000000011M;
Console.WriteLine("DEC : PI + bigNum = {0}", decPiVal + decBigNum);
Console.WriteLine("Biggest Decimal : {0}", Decimal.MaxValue);
// DOUBLES
// Doubles are 64-bit float types
Console.WriteLine("Biggest Double : {0}", Double.MaxValue.ToString("#"));
// It is precise to 14 digits
double dblPiVal = 3.14159265358979;
double dblBigNum = 3.00000000000002;
Console.WriteLine("DBL : PI + bigNum = {0}", dblPiVal + dblBigNum);
// FLOATS
// Floats are 32-bit float types
Console.WriteLine("Biggest Float : {0}", float.MaxValue.ToString("#"));
// It is precise to 6 digits
float fltPiVal = 3.141592F;
float fltBigNum = 3.000002F;
Console.WriteLine("FLT : PI + bigNum = {0}", fltPiVal + fltBigNum);
// Other Data Types
// byte : 8-bit unsigned int 0 to 255
// char : 16-bit unicode character
// sbyte : 8-bit signed int 128 to 127
// short : 16-bit signed int -32,768 to 32,767
// uint : 32-bit unsigned int 0 to 4,294,967,295
// ulong : 64-bit unsigned int 0 to 18,446,744,073,709,551,615
// ushort : 16-bit unsigned int 0 to 65,535
// You can convert from string to other types with Parse
bool boolFromStr = bool.Parse("True");
int intFromStr = int.Parse("100");
double dblFromStr = double.Parse("1.234");
// ---------- DATETIME & TIMESPAN ----------
// Used to define dates
DateTime awesomeDate = new DateTime(1974, 12, 21);
Console.WriteLine("Day of Week : {0}", awesomeDate.DayOfWeek);
// You can change values
awesomeDate = awesomeDate.AddDays(4);
awesomeDate = awesomeDate.AddMonths(1);
awesomeDate = awesomeDate.AddYears(1);
Console.WriteLine("New Date : {0}", awesomeDate.Date);
// TimeSpan
// Used to define a time
TimeSpan lunchTime = new TimeSpan(12, 30, 0);
// Change values
lunchTime = lunchTime.Subtract(new TimeSpan(0, 15, 0));
lunchTime = lunchTime.Add(new TimeSpan(1, 0, 0));
Console.WriteLine("New Time : {0}", lunchTime.ToString());
// ---------- BIGINTEGER ----------
// Used to store very large numbers
// Select Project -> Add Reference
// Select Assemblies -> System.Numerics.dll click Ok
// Add this line using System.Numerics; at the top
// Define the value using a text literal
BigInteger bigNum = BigInteger.Parse("12345123451234512345");
Console.WriteLine("Big Num * 2 = {0}", bigNum * 2);
// ---------- FORMATTING OUTPUT ----------
// Format output for currency
Console.WriteLine("Currency : {0:c}", 23.455);
// Pad with zeroes
Console.WriteLine("Pad with 0s : {0:d4}", 23);
// Define decimals
Console.WriteLine("3 Decimals : {0:f3}", 23.4555);
// Add commas and decimals
Console.WriteLine("Commas : {0:n4}", 2300);
// ---------- STRINGS ----------
// Strings store a series of characters
string randString = "This is a string";
// Get number of characters in string
Console.WriteLine("String Length : {0}", randString.Length);
// Check if string contains other string
Console.WriteLine("String Contains is : {0}",
randString.Contains("is"));
// Index of string match
Console.WriteLine("Index of is : {0}",
randString.IndexOf("is"));
// Remove number of characters starting at an index
Console.WriteLine("Remove string : {0}",
randString.Remove(10, 6));
// Add a string starting at an index
Console.WriteLine("Insert String : {0}",
randString.Insert(10, "short "));
// Replace a string with another
Console.WriteLine("Replace String : {0}",
randString.Replace("string", "sentence"));
// Compare strings and ignore case
// < 0 : str1 preceeds str2
// = : Zero
// > 0 : str2 preceeds str1
Console.WriteLine("Compare A to B : {0}",
String.Compare("A", "B", StringComparison.OrdinalIgnoreCase));
// Check if strings are equal
Console.WriteLine("A = a : {0}",
String.Equals("A", "a", StringComparison.OrdinalIgnoreCase));
// Add padding left
Console.WriteLine("Pad Left : {0}",
randString.PadLeft(20, '.'));
// Add padding right
Console.WriteLine("Pad Right : {0} Stuff",
randString.PadRight(20, '.'));
// Trim whitespace
Console.WriteLine("Trim : {0}",
randString.Trim());
// Make uppercase
Console.WriteLine("Uppercase : {0}",
randString.ToUpper());
// Make lowercase
Console.WriteLine("Lowercase : {0}",
randString.ToLower());
// Use Format to create strings
string newString = String.Format("{0} saw a {1} {2} in the {3}",
"Paul", "rabbit", "eating", "field");
// You can add newlines with \n and join strings with +
Console.Write(newString + "\n");
// Other escape characters
// \' \" \\ \t \a
// Verbatim strings ignore escape characters
Console.Write(@"Exactly What I Typed");
// Excepts input up until a newline, but it is here to
// keep the console open after output
// Read() excepts a single character
Console.ReadLine();
}
// You can create your own functions (methods)
private static void SayHello()
{
// Defines a variable that will store a string
// of characters
string name = "";
Console.Write("What is your name : ");
// Save the input the user provides
name = Console.ReadLine();
Console.WriteLine("Hello {0}", name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.Apple;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
public partial class DSA : AsymmetricAlgorithm
{
public static new DSA Create()
{
return new DSAImplementation.DSASecurityTransforms();
}
#endif
internal static partial class DSAImplementation
{
public sealed partial class DSASecurityTransforms : DSA
{
private SecKeyPair _keys;
public DSASecurityTransforms()
: this(1024)
{
}
public DSASecurityTransforms(int keySize)
{
KeySize = keySize;
}
internal DSASecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal DSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(minSize: 512, maxSize: 1024, skipSize: 64) };
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override DSAParameters ExportParameters(bool includePrivateParameters)
{
SecKeyPair keys = GetKeys();
if (keys.PublicKey == null ||
(includePrivateParameters && keys.PrivateKey == null))
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
DSAParameters parameters = new DSAParameters();
DerSequenceReader publicKeyReader =
Interop.AppleCrypto.SecKeyExport(keys.PublicKey, exportPrivate: false);
publicKeyReader.ReadSubjectPublicKeyInfo(ref parameters);
if (includePrivateParameters)
{
DerSequenceReader privateKeyReader =
Interop.AppleCrypto.SecKeyExport(keys.PrivateKey, exportPrivate: true);
privateKeyReader.ReadPkcs8Blob(ref parameters);
}
KeyBlobHelpers.TrimPaddingByte(ref parameters.P);
KeyBlobHelpers.TrimPaddingByte(ref parameters.Q);
KeyBlobHelpers.PadOrTrim(ref parameters.G, parameters.P.Length);
KeyBlobHelpers.PadOrTrim(ref parameters.Y, parameters.P.Length);
if (includePrivateParameters)
{
KeyBlobHelpers.PadOrTrim(ref parameters.X, parameters.Q.Length);
}
return parameters;
}
public override void ImportParameters(DSAParameters parameters)
{
if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MissingFields);
// J is not required and is not even used on CNG blobs.
// It should, however, be less than P (J == (P-1) / Q).
// This validation check is just to maintain parity with DSACng and DSACryptoServiceProvider,
// which also perform this check.
if (parameters.J != null && parameters.J.Length >= parameters.P.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPJ);
int keySize = parameters.P.Length;
bool hasPrivateKey = parameters.X != null;
if (parameters.G.Length != keySize || parameters.Y.Length != keySize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
if (!(8 * parameters.P.Length).IsLegalSize(LegalKeySizes))
throw new CryptographicException(SR.Cryptography_InvalidKeySize);
if (parameters.Q.Length != 20)
throw new CryptographicException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey);
if (hasPrivateKey)
{
SafeSecKeyRefHandle privateKey = ImportKey(parameters);
DSAParameters publicOnly = parameters;
publicOnly.X = null;
SafeSecKeyRefHandle publicKey;
try
{
publicKey = ImportKey(publicOnly);
}
catch
{
privateKey.Dispose();
throw;
}
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
private static SafeSecKeyRefHandle ImportKey(DSAParameters parameters)
{
bool hasPrivateKey = parameters.X != null;
byte[] blob = hasPrivateKey ? parameters.ToPrivateKeyBlob() : parameters.ToSubjectPublicKeyInfo();
return Interop.AppleCrypto.ImportEphemeralKey(blob, hasPrivateKey);
}
public override byte[] CreateSignature(byte[] rgbHash)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
byte[] derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, rgbHash);
// Since the AppleCrypto implementation is limited to FIPS 186-2, signature field sizes
// are always 160 bits / 20 bytes (the size of SHA-1, and the only legal length for Q).
byte[] ieeeFormatSignature = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(
derFormatSignature,
0,
derFormatSignature.Length,
fieldSizeBits: 160);
return ieeeFormatSignature;
}
public override bool VerifySignature(byte[] hash, byte[] signature)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
return VerifySignature((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}
public override bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature)
{
byte[] derFormatSignature = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature);
return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
derFormatSignature);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
// Matching DSACryptoServiceProvider's "I only understand SHA-1/FIPS 186-2" exception
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
protected override bool TryHashData(ReadOnlySpan<byte> source, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
AsymmetricAlgorithmHelpers.TryHashData(source, destination, hashAlgorithm, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
base.Dispose(disposing);
}
internal SecKeyPair GetKeys()
{
SecKeyPair current = _keys;
if (current != null)
{
return current;
}
// macOS 10.11 and macOS 10.12 declare DSA invalid for key generation.
// Rather than write code which might or might not work, returning
// (OSStatus)-4 (errSecUnimplemented), just make the exception occur here.
//
// When the native code can be verified, then it can be added.
throw new PlatformNotSupportedException(SR.Cryptography_DSA_KeyGenNotSupported);
}
private void SetKey(SecKeyPair newKeyPair)
{
SecKeyPair current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
int size = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey);
KeySizeValue = size;
}
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#else
internal static class KeySizeHelpers
{
public static bool IsLegalSize(this int size, KeySizes[] legalSizes)
{
for (int i = 0; i < legalSizes.Length; i++)
{
KeySizes currentSizes = legalSizes[i];
// If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
if (currentSizes.SkipSize == 0)
{
if (currentSizes.MinSize == size)
return true;
}
else if (size >= currentSizes.MinSize && size <= currentSizes.MaxSize)
{
// If the number is in range, check to see if it's a legal increment above MinSize
int delta = size - currentSizes.MinSize;
// While it would be unusual to see KeySizes { 10, 20, 5 } and { 11, 14, 1 }, it could happen.
// So don't return false just because this one doesn't match.
if (delta % currentSizes.SkipSize == 0)
{
return true;
}
}
}
return false;
}
}
#endif
internal static class DsaKeyBlobHelpers
{
private static readonly Oid s_idDsa = new Oid("1.2.840.10040.4.1");
internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref DSAParameters parameters)
{
// SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DerSequenceReader algorithm = keyInfo.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
// EC Public Key
if (algorithmOid != s_idDsa.Value)
{
throw new CryptographicException();
}
// Dss-Parms ::= SEQUENCE {
// p INTEGER,
// q INTEGER,
// g INTEGER
// }
DerSequenceReader algParameters = algorithm.ReadSequence();
byte[] publicKeyBlob = keyInfo.ReadBitString();
// We don't care about the rest of the blob here, but it's expected to not exist.
ReadSubjectPublicKeyInfo(algParameters, publicKeyBlob, ref parameters);
}
internal static void ReadSubjectPublicKeyInfo(
this DerSequenceReader algParameters,
byte[] publicKeyBlob,
ref DSAParameters parameters)
{
parameters.P = algParameters.ReadIntegerBytes();
parameters.Q = algParameters.ReadIntegerBytes();
parameters.G = algParameters.ReadIntegerBytes();
DerSequenceReader privateKeyReader = DerSequenceReader.CreateForPayload(publicKeyBlob);
parameters.Y = privateKeyReader.ReadIntegerBytes();
KeyBlobHelpers.TrimPaddingByte(ref parameters.P);
KeyBlobHelpers.TrimPaddingByte(ref parameters.Q);
KeyBlobHelpers.PadOrTrim(ref parameters.G, parameters.P.Length);
KeyBlobHelpers.PadOrTrim(ref parameters.Y, parameters.P.Length);
}
internal static byte[] ToSubjectPublicKeyInfo(this DSAParameters parameters)
{
// SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
// Dss-Parms ::= SEQUENCE {
// p INTEGER,
// q INTEGER,
// g INTEGER
// }
return DerEncoder.ConstructSequence(
DerEncoder.ConstructSegmentedSequence(
DerEncoder.SegmentedEncodeOid(s_idDsa),
DerEncoder.ConstructSegmentedSequence(
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.P),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Q),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.G)
)
),
DerEncoder.SegmentedEncodeBitString(
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Y))
);
}
internal static void ReadPkcs8Blob(this DerSequenceReader reader, ref DSAParameters parameters)
{
// Since the PKCS#8 blob for DSS/DSA does not include the public key (Y) this
// structure is only read after filling the public half.
Debug.Assert(parameters.P != null);
Debug.Assert(parameters.Q != null);
Debug.Assert(parameters.G != null);
Debug.Assert(parameters.Y != null);
// OneAsymmetricKey ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] Attributes OPTIONAL,
// ...,
// [[2: publicKey [1] PublicKey OPTIONAL ]],
// ...
// }
//
// PrivateKeyInfo ::= OneAsymmetricKey
//
// PrivateKey ::= OCTET STRING
int version = reader.ReadInteger();
// We understand both version 0 and 1 formats,
// which are now known as v1 and v2, respectively.
if (version > 1)
{
throw new CryptographicException();
}
{
// Ensure we're reading DSA, extract the parameters
DerSequenceReader algorithm = reader.ReadSequence();
string algorithmOid = algorithm.ReadOidAsString();
if (algorithmOid != s_idDsa.Value)
{
throw new CryptographicException();
}
// The Dss-Params SEQUENCE is present here, but not needed since
// we got it from the public key already.
}
byte[] privateKeyBlob = reader.ReadOctetString();
DerSequenceReader privateKeyReader = DerSequenceReader.CreateForPayload(privateKeyBlob);
parameters.X = privateKeyReader.ReadIntegerBytes();
}
internal static byte[] ToPrivateKeyBlob(this DSAParameters parameters)
{
Debug.Assert(parameters.X != null);
// DSAPrivateKey ::= SEQUENCE(
// version INTEGER,
// p INTEGER,
// q INTEGER,
// g INTEGER,
// y INTEGER,
// x INTEGER,
// )
return DerEncoder.ConstructSequence(
DerEncoder.SegmentedEncodeUnsignedInteger(new byte[] { 0 }),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.P),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Q),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.G),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.Y),
DerEncoder.SegmentedEncodeUnsignedInteger(parameters.X));
}
}
}
| |
// <copyright file="RiakClientTests.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace RiakClientTests.Live
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using RiakClient;
using RiakClient.Extensions;
using RiakClient.Models;
[TestFixture, IntegrationTest, SkipMono]
public class RiakClientTests : LiveRiakConnectionTestBase
{
[Test]
[Ignore("Nondeterministic or failing")]
public void WritingLargeObjectIsSuccessful()
{
var text = Enumerable.Range(0, 2000000)
.Aggregate(new StringBuilder(),
(sb, i) => sb.Append(i.ToString()))
.ToString();
var riakObject = new RiakObject(TestBucket, "large", text, RiakConstants.ContentTypes.TextPlain);
var result = Client.Put(riakObject);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
}
[Test]
public void DeleteIsSuccessful()
{
var riakObject = new RiakObject(TestBucket, TestKey, TestJson, RiakConstants.ContentTypes.ApplicationJson);
var riakObjectId = riakObject.ToRiakObjectId();
var putResult = Client.Put(riakObject);
putResult.IsSuccess.ShouldBeTrue(putResult.ErrorMessage);
var delResult = Client.Delete(riakObjectId);
delResult.IsSuccess.ShouldBeTrue(delResult.ErrorMessage);
var getResult = Client.Get(riakObjectId);
getResult.IsSuccess.ShouldBeFalse(getResult.ErrorMessage);
getResult.ResultCode.ShouldEqual(ResultCode.NotFound);
getResult.Value.ShouldBeNull();
}
[Test]
public void DeleteIsSuccessfulInBatch()
{
Client.Batch(batch =>
{
var riakObject = new RiakObject(TestBucket, TestKey, TestJson,
RiakConstants.ContentTypes.ApplicationJson);
var riakObjectId = riakObject.ToRiakObjectId();
var putResult = batch.Put(riakObject);
putResult.IsSuccess.ShouldBeTrue(putResult.ErrorMessage);
var delResult = batch.Delete(riakObjectId);
delResult.IsSuccess.ShouldBeTrue(delResult.ErrorMessage);
var getResult = batch.Get(riakObjectId);
getResult.IsSuccess.ShouldBeFalse();
getResult.ResultCode.ShouldEqual(ResultCode.NotFound);
getResult.Value.ShouldBeNull();
});
}
[Test]
public void AsyncDeleteIsSuccessful()
{
var riakObject = new RiakObject(TestBucket, TestKey, TestJson, RiakConstants.ContentTypes.ApplicationJson);
var riakObjectId = riakObject.ToRiakObjectId();
var putResult = Client.Put(riakObject);
putResult.IsSuccess.ShouldBeTrue(putResult.ErrorMessage);
var result = Client.Async.Delete(riakObjectId).Result;
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
var getResult = Client.Get(riakObjectId);
getResult.IsSuccess.ShouldBeFalse();
getResult.ResultCode.ShouldEqual(ResultCode.NotFound);
getResult.Value.ShouldBeNull();
}
[Test]
public void AsyncDeleteMultipleIsSuccessful()
{
var one = new RiakObject(TestBucket, "one", TestJson, RiakConstants.ContentTypes.ApplicationJson);
var two = new RiakObject(TestBucket, "two", TestJson, RiakConstants.ContentTypes.ApplicationJson);
Client.Put(one);
Client.Put(two);
var oneObjectId = one.ToRiakObjectId();
var twoObjectId = two.ToRiakObjectId();
var list = new List<RiakObjectId> { oneObjectId, twoObjectId };
var results = Client.Async.Delete(list).Result;
foreach (var riakResult in results)
{
riakResult.IsSuccess.ShouldBeTrue(riakResult.ErrorMessage);
}
var oneResult = Client.Get(oneObjectId);
oneResult.IsSuccess.ShouldBeFalse();
oneResult.ResultCode.ShouldEqual(ResultCode.NotFound);
oneResult.Value.ShouldBeNull();
var twoResult = Client.Get(twoObjectId);
twoResult.IsSuccess.ShouldBeFalse();
twoResult.ResultCode.ShouldEqual(ResultCode.NotFound);
twoResult.Value.ShouldBeNull();
}
[Test]
public void AsyncGetMultipleReturnsAllObjects()
{
var one = new RiakObject(TestBucket, "one", TestJson, RiakConstants.ContentTypes.ApplicationJson);
var two = new RiakObject(TestBucket, "two", TestJson, RiakConstants.ContentTypes.ApplicationJson);
Client.Put(one);
Client.Put(two);
var oneObjectId = one.ToRiakObjectId();
var twoObjectId = two.ToRiakObjectId();
var list = new List<RiakObjectId> { oneObjectId, twoObjectId };
var results = Client.Async.Get(list).Result;
foreach (var result in results)
{
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
result.Value.ShouldNotBeNull();
}
}
[Test]
public void AsyncGetWithRiakObjectIdReturnsData()
{
var riakObject = new RiakObject(TestBucket, TestKey, TestJson, RiakConstants.ContentTypes.ApplicationJson);
var riakObjectId = riakObject.ToRiakObjectId();
Client.Put(riakObject);
Func<RiakResult<RiakObject>> asyncGet = () => Client.Async.Get(riakObjectId).Result;
var asyncGetResult = asyncGet.WaitUntil();
asyncGetResult.IsSuccess.ShouldBeTrue(asyncGetResult.ErrorMessage);
asyncGetResult.Value.ShouldNotBeNull();
asyncGetResult.Value.Bucket.ShouldEqual(TestBucket);
asyncGetResult.Value.Key.ShouldEqual(TestKey);
asyncGetResult.Value.Value.FromRiakString().ShouldEqual(TestJson);
}
[Test]
public void AsyncPutIsSuccessful()
{
var riakObject = new RiakObject(TestBucket, TestKey, TestJson, RiakConstants.ContentTypes.ApplicationJson);
var result = Client.Async.Put(riakObject).Result;
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
result.Value.ShouldNotBeNull();
}
[Test]
public void AsyncPutMultipleIsSuccessful()
{
var one = new RiakObject(TestBucket, "one", TestJson, RiakConstants.ContentTypes.ApplicationJson);
var two = new RiakObject(TestBucket, "two", TestJson, RiakConstants.ContentTypes.ApplicationJson);
var results = Client.Async.Put(new List<RiakObject> { one, two }).Result;
foreach (var riakResult in results)
{
riakResult.IsSuccess.ShouldBeTrue(riakResult.ErrorMessage);
riakResult.Value.ShouldNotBeNull();
}
}
[Test]
public void ListKeysFromIndexReturnsAllKeys()
{
const int keyCount = 10;
var bucket = TestBucket + "_" + Guid.NewGuid();
var originalKeyList = new List<string>();
for (var i = 0; i < keyCount; i++)
{
string idx = i.ToString();
var id = new RiakObjectId(TestBucketType, bucket, idx);
var o = new RiakObject(id, "{ value: \"this is an object\" }");
originalKeyList.Add(idx);
Client.Put(o);
}
var result = Client.ListKeysFromIndex(TestBucketType, bucket);
var keys = result.Value;
keys.Count.ShouldEqual(keyCount);
foreach (var key in keys)
{
originalKeyList.ShouldContain(key);
}
}
[Test]
public void UpdatingCounterOnBucketWithoutAllowMultFails()
{
const string counter = "counter";
var bucket = TestBucket + "_" + Guid.NewGuid();
var result = Client.IncrementCounter(bucket, counter, 1);
result.Result.IsSuccess.ShouldBeFalse();
}
[Test]
public void UpdatingCounterOnBucketWithAllowMultIsSuccessful()
{
const string counter = "counter";
var bucket = TestBucket + "_" + Guid.NewGuid();
var props = Client.GetBucketProperties(bucket).Value;
props.SetAllowMultiple(true);
Client.SetBucketProperties(bucket, props);
var result = Client.IncrementCounter(bucket, counter, 1);
result.Result.IsSuccess.ShouldBeTrue();
}
[Test]
[Ignore("Nondeterministic or failing")]
public void UpdatingCounterOnBucketWithReturnValueShouldReturnIncrementedCounterValue()
{
const string counter = "counter";
var bucket = TestBucket + "_" + Guid.NewGuid();
var props = Client.GetBucketProperties(bucket).Value ?? new RiakBucketProperties();
props.SetAllowMultiple(true);
Client.SetBucketProperties(bucket, props);
Client.IncrementCounter(bucket, counter, 1, new RiakCounterUpdateOptions().SetReturnValue(true));
var readResult = Client.GetCounter(bucket, counter);
var currentCounter = readResult.Value;
var result = Client.IncrementCounter(bucket, counter, 1, new RiakCounterUpdateOptions().SetReturnValue(true));
result.Result.IsSuccess.ShouldBeTrue();
result.Result.ShouldNotBeNull();
result.Value.ShouldBeGreaterThan(currentCounter);
}
[Test]
[Ignore("Nondeterministic or failing")]
public void ReadingWithTimeoutSetToZeroShouldImmediatelyReturn()
{
var bucket = TestBucket + "_" + Guid.NewGuid();
for (var i = 0; i < 10; i++)
{
var o = new RiakObject(bucket, i.ToString(), "{ value: \"this is an object\" }");
Client.Put(o);
}
var result = Client.Get(bucket, "2",
new RiakGetOptions().SetTimeout(new Timeout(0)).SetPr(Quorum.WellKnown.All));
result.IsSuccess.ShouldBeFalse();
}
}
}
| |
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 CuvooApi.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;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Buffers.Text
{
public static partial class Utf16Formatter
{
#region Constants
private const char Seperator = ',';
// Invariant formatting uses groups of 3 for each number group seperated by commas.
// ex. 1,234,567,890
private const int GroupSize = 3;
#endregion Constants
private static bool TryFormatDecimalInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int charsNeeded = digitCount + (int)((value >> 63) & 1);
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
int idx = 0;
if (value < 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (value == long.MinValue)
{
if (!TryFormatDecimalUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
value = -value;
}
if (precision != StandardFormat.NoPrecision)
{
int leadingZeros = (int)precision - digitCount;
while (leadingZeros-- > 0)
Unsafe.Add(ref utf16Bytes, idx++) = '0';
}
idx += FormattingHelpers.WriteDigits(value, digitCount, ref utf16Bytes, idx);
bytesWritten = idx * sizeof(char);
return true;
}
private static bool TryFormatDecimalUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten);
// Remove a single digit from the number. This will get it below long.MaxValue
// Then we call the faster long version and follow-up with writing the last
// digit. This ends up being faster by a factor of 2 than to just do the entire
// operation using the unsigned versions.
value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit);
if (precision != StandardFormat.NoPrecision && precision > 0)
precision -= 1;
if (!TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten))
return false;
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer.Slice(bytesWritten));
if (span.Length < sizeof(char))
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
FormattingHelpers.WriteDigits(lastDigit, 1, ref utf16Bytes, 0);
bytesWritten += sizeof(char);
return true;
}
private static bool TryFormatNumericInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int groupSeperators = (int)FormattingHelpers.DivMod(digitCount, GroupSize, out long firstGroup);
if (firstGroup == 0)
{
firstGroup = 3;
groupSeperators--;
}
int trailingZeros = (precision == StandardFormat.NoPrecision) ? 2 : precision;
int charsNeeded = (int)((value >> 63) & 1) + digitCount + groupSeperators;
int idx = charsNeeded;
if (trailingZeros > 0)
charsNeeded += trailingZeros + 1; // +1 for period.
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
long v = value;
if (v < 0)
{
Unsafe.Add(ref utf16Bytes, 0) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (v == long.MinValue)
{
if (!TryFormatNumericUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
v = -v;
}
// Write out the trailing zeros
if (trailingZeros > 0)
{
Unsafe.Add(ref utf16Bytes, idx) = Period;
FormattingHelpers.WriteDigits(0, trailingZeros, ref utf16Bytes, idx + 1);
}
// Starting from the back, write each group of digits except the first group
while (digitCount > 3)
{
idx -= 3;
v = FormattingHelpers.DivMod(v, 1000, out long groupValue);
FormattingHelpers.WriteDigits(groupValue, 3, ref utf16Bytes, idx);
Unsafe.Add(ref utf16Bytes, --idx) = Seperator;
digitCount -= 3;
}
// Write the first group of digits.
FormattingHelpers.WriteDigits(v, (int)firstGroup, ref utf16Bytes, idx - (int)firstGroup);
bytesWritten = charsNeeded * sizeof(char);
return true;
}
private static bool TryFormatNumericUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatNumericInt64((long)value, precision, buffer, out bytesWritten);
// The ulong path is much slower than the long path here, so we are doing the last group
// inside this method plus the zero padding but routing to the long version for the rest.
value = FormattingHelpers.DivMod(value, 1000, out ulong lastGroup);
if (!TryFormatNumericInt64((long)value, 0, buffer, out bytesWritten))
return false;
if (precision == StandardFormat.NoPrecision)
precision = 2;
// Since this method routes entirely to the long version if the number is smaller than
// long.MaxValue, we are guaranteed to need to write 3 more digits here before the set
// of trailing zeros.
int extraChars = 4; // 3 digits + group seperator
if (precision > 0)
extraChars += precision + 1; // +1 for period.
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer.Slice(bytesWritten));
if (span.Length < extraChars)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
var idx = 0;
// Write the last group
Unsafe.Add(ref utf16Bytes, idx++) = Seperator;
idx += FormattingHelpers.WriteDigits(lastGroup, 3, ref utf16Bytes, idx);
// Write out the trailing zeros
if (precision > 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Period;
idx += FormattingHelpers.WriteDigits(0, precision, ref utf16Bytes, idx);
}
bytesWritten += extraChars * sizeof(char);
return true;
}
private static bool TryFormatHexUInt64(ulong value, byte precision, bool useLower, Span<byte> buffer, out int bytesWritten)
{
const string HexTableLower = "0123456789abcdef";
const string HexTableUpper = "0123456789ABCDEF";
var digits = 1;
var v = value;
if (v > 0xFFFFFFFF)
{
digits += 8;
v >>= 0x20;
}
if (v > 0xFFFF)
{
digits += 4;
v >>= 0x10;
}
if (v > 0xFF)
{
digits += 2;
v >>= 0x8;
}
if (v > 0xF) digits++;
int paddingCount = (precision == StandardFormat.NoPrecision) ? 0 : precision - digits;
if (paddingCount < 0) paddingCount = 0;
int charsNeeded = digits + paddingCount;
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
string hexTable = useLower ? HexTableLower : HexTableUpper;
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
int idx = charsNeeded;
for (v = value; digits-- > 0; v >>= 4)
Unsafe.Add(ref utf16Bytes, --idx) = hexTable[(int)(v & 0xF)];
while (paddingCount-- > 0)
Unsafe.Add(ref utf16Bytes, --idx) = '0';
bytesWritten = charsNeeded * sizeof(char);
return true;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DeviceFarm.Model
{
/// <summary>
/// Represents a device type that an app is tested against.
/// </summary>
public partial class Device
{
private string _arn;
private string _carrier;
private CPU _cpu;
private DeviceFormFactor _formFactor;
private long? _heapSize;
private string _image;
private string _manufacturer;
private long? _memory;
private string _model;
private string _name;
private string _os;
private DevicePlatform _platform;
private string _radio;
private Resolution _resolution;
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The device's ARN.
/// </para>
/// </summary>
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Carrier.
/// <para>
/// The device's carrier.
/// </para>
/// </summary>
public string Carrier
{
get { return this._carrier; }
set { this._carrier = value; }
}
// Check to see if Carrier property is set
internal bool IsSetCarrier()
{
return this._carrier != null;
}
/// <summary>
/// Gets and sets the property Cpu.
/// <para>
/// Information about the device's CPU.
/// </para>
/// </summary>
public CPU Cpu
{
get { return this._cpu; }
set { this._cpu = value; }
}
// Check to see if Cpu property is set
internal bool IsSetCpu()
{
return this._cpu != null;
}
/// <summary>
/// Gets and sets the property FormFactor.
/// <para>
/// The device's form factor.
/// </para>
///
/// <para>
/// Allowed values include:
/// </para>
/// <ul> <li>
/// <para>
/// PHONE: The phone form factor.
/// </para>
/// </li> <li>
/// <para>
/// TABLET: The tablet form factor.
/// </para>
/// </li> </ul>
/// </summary>
public DeviceFormFactor FormFactor
{
get { return this._formFactor; }
set { this._formFactor = value; }
}
// Check to see if FormFactor property is set
internal bool IsSetFormFactor()
{
return this._formFactor != null;
}
/// <summary>
/// Gets and sets the property HeapSize.
/// <para>
/// The device's heap size, expressed in bytes.
/// </para>
/// </summary>
public long HeapSize
{
get { return this._heapSize.GetValueOrDefault(); }
set { this._heapSize = value; }
}
// Check to see if HeapSize property is set
internal bool IsSetHeapSize()
{
return this._heapSize.HasValue;
}
/// <summary>
/// Gets and sets the property Image.
/// <para>
/// The device's image name.
/// </para>
/// </summary>
public string Image
{
get { return this._image; }
set { this._image = value; }
}
// Check to see if Image property is set
internal bool IsSetImage()
{
return this._image != null;
}
/// <summary>
/// Gets and sets the property Manufacturer.
/// <para>
/// The device's manufacturer name.
/// </para>
/// </summary>
public string Manufacturer
{
get { return this._manufacturer; }
set { this._manufacturer = value; }
}
// Check to see if Manufacturer property is set
internal bool IsSetManufacturer()
{
return this._manufacturer != null;
}
/// <summary>
/// Gets and sets the property Memory.
/// <para>
/// The device's total memory size, expressed in bytes.
/// </para>
/// </summary>
public long Memory
{
get { return this._memory.GetValueOrDefault(); }
set { this._memory = value; }
}
// Check to see if Memory property is set
internal bool IsSetMemory()
{
return this._memory.HasValue;
}
/// <summary>
/// Gets and sets the property Model.
/// <para>
/// The device's model name.
/// </para>
/// </summary>
public string Model
{
get { return this._model; }
set { this._model = value; }
}
// Check to see if Model property is set
internal bool IsSetModel()
{
return this._model != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The device's display name.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Os.
/// <para>
/// The device's operating system type.
/// </para>
/// </summary>
public string Os
{
get { return this._os; }
set { this._os = value; }
}
// Check to see if Os property is set
internal bool IsSetOs()
{
return this._os != null;
}
/// <summary>
/// Gets and sets the property Platform.
/// <para>
/// The device's platform.
/// </para>
///
/// <para>
/// Allowed values include:
/// </para>
/// <ul> <li>
/// <para>
/// ANDROID: The Android platform.
/// </para>
/// </li> <li>
/// <para>
/// IOS: The iOS platform.
/// </para>
/// </li> </ul>
/// </summary>
public DevicePlatform Platform
{
get { return this._platform; }
set { this._platform = value; }
}
// Check to see if Platform property is set
internal bool IsSetPlatform()
{
return this._platform != null;
}
/// <summary>
/// Gets and sets the property Radio.
/// <para>
/// The device's radio.
/// </para>
/// </summary>
public string Radio
{
get { return this._radio; }
set { this._radio = value; }
}
// Check to see if Radio property is set
internal bool IsSetRadio()
{
return this._radio != null;
}
/// <summary>
/// Gets and sets the property Resolution.
/// </summary>
public Resolution Resolution
{
get { return this._resolution; }
set { this._resolution = value; }
}
// Check to see if Resolution property is set
internal bool IsSetResolution()
{
return this._resolution != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
using Epi.Data;
namespace Epi.Core.AnalysisInterpreter.Rules
{
public partial class Rule_Assign : AnalysisRule
{
public string QualifiedId;
AnalysisRule value = null;
Epi.View View = null;
object ReturnResult = null;
public Rule_Assign(Rule_Context pContext, NonterminalToken pTokens) : base(pContext)
{
//ASSIGN <Qualified ID> '=' <Expression>
//<Let_Statement> ::= LET Identifier '=' <Expression>
//<Simple_Assign_Statement> ::= Identifier '=' <Expression>
switch(pTokens.Rule.Lhs.ToString())
{
case "<Assign_Statement>":
//NonterminalToken T = (NonterminalToken)pTokens.Tokens[1];
//this.QualifiedId = T.Tokens[0].ToString();
this.QualifiedId = this.SetQualifiedId(pTokens.Tokens[1]);
//this.value = new Rule_Expression(pContext, (NonterminalToken)pTokens.Tokens[3]);
this.value = AnalysisRule.BuildStatments(pContext, pTokens.Tokens[3]);
break;
case "<Let_Statement>":
//this.QualifiedId = pTokens.Tokens[1].ToString();
this.QualifiedId = this.SetQualifiedId(pTokens.Tokens[1]);
//this.value = new Rule_Expression(pContext, (NonterminalToken)pTokens.Tokens[3]);
this.value = AnalysisRule.BuildStatments(pContext, pTokens.Tokens[3]);
break;
case "<Simple_Assign_Statement>":
//Identifier '=' <Expression>
//T = (NonterminalToken)pTokens.Tokens[1];
//this.QualifiedId = this.GetCommandElement(pTokens.Tokens, 0);
this.QualifiedId = this.SetQualifiedId(pTokens.Tokens[0]);
//this.value = new Rule_Expression(pContext, (NonterminalToken)pTokens.Tokens[2]);
this.value = AnalysisRule.BuildStatments(pContext, pTokens.Tokens[2]);
break;
}
}
/// <summary>
/// peforms an assign rule by assigning an expression to a variable. return the variable that was assigned
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
IVariable var;
string dataValue = string.Empty;
if (this.Context.CurrentDataRow != null)
{
if (this.Context.MemoryRegion.TryGetVariable(this.QualifiedId, out var))
{
if (var.VarType != VariableType.Standard && var.VarType != VariableType.DataSource)
{
result = this.value.Execute();
ReturnResult = result;
if (!Util.IsEmpty(result))
{
var.Expression = result.ToString();
}
else
{
var.Expression = "Null";
}
}
AssignNonProjectDataFunction();
}
else
{
AssignNonProjectDataFunction();
}
}
else
{
if (this.Context.MemoryRegion.TryGetVariable(this.QualifiedId, out var))
{
if (var.VarType != VariableType.Standard && var.VarType != VariableType.DataSource)
{
result = this.value.Execute();
ReturnResult = result;
if (!Util.IsEmpty(result))
{
//result = this.value.Execute();
var.Expression = result.ToString();
}
else
{
var.Expression = "Null";
}
this.Context.GetOutput(this.AssignMapDataFunction());
}
else
{
if (this.Context.DataSet.Tables.Contains("Output"))
{
if (this.Context.DataSet.Tables["Output"].Rows.Count == 0)
{
System.Data.DataRow R = this.Context.DataSet.Tables["Output"].NewRow();
this.Context.DataSet.Tables["Output"].Rows.Add(R);
}
}
this.Context.GetOutput(this.AssignMapDataFunction());
}
}
else
{
if (this.Context.DataSet.Tables.Contains("Output"))
{
if (this.Context.DataSet.Tables["Output"].Rows.Count == 0)
{
System.Data.DataRow R = this.Context.DataSet.Tables["Output"].NewRow();
this.Context.DataSet.Tables["Output"].Rows.Add(R);
}
}
this.Context.GetOutput(this.AssignMapDataFunction());
}
}
return ReturnResult;
}
private Epi.DataType GuessDataTypeFromExpression(string expression)
{
double d = 0.0;
DateTime dt;
if (double.TryParse(expression, out d))
{
return DataType.Number;
}
if (System.Text.RegularExpressions.Regex.IsMatch(expression, "([+,-])"))
{
return DataType.Boolean;
}
if (DateTime.TryParse(expression, out dt))
{
return DataType.Date;
}
return DataType.Unknown;
}
private Rule_Context.MapDataDelegate AssignMapDataFunction()
{
//object result = this.value.Execute();
if (this.Context.CurrentRead == null)
{
return AssignNonProjectDataFunction;
}
else
{
if(this.View == null)
{
return AssignNonProjectDataFunction;
}
else
{
return AssignProjectDataFunction;
}
}
}
private void AssignNonProjectDataFunction()
{
object result = this.value.Execute();
if (Util.IsEmpty(result))
{
this.Context.CurrentDataRow[this.QualifiedId] = DBNull.Value;
}
else
{
try
{
Type ToDataType = this.Context.DataSet.Tables["output"].Columns[this.QualifiedId].DataType;
IVariable var;
DateTime dateTime;
if (ToDataType is IConvertible && result is IConvertible)
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
else
{
if (ToDataType.ToString().Equals("System.DateTime" , StringComparison.OrdinalIgnoreCase) && result is TimeSpan)
{
TimeSpan LHS = (TimeSpan) result;
this.Context.CurrentDataRow[this.QualifiedId] = new DateTime(1900,1,1,LHS.Hours,LHS.Minutes, LHS.Seconds);
}
else if (ToDataType.ToString().Equals("System.TimeSpan", StringComparison.OrdinalIgnoreCase) && result is DateTime)
{
DateTime LHS = (DateTime)result;
this.Context.CurrentDataRow[this.QualifiedId] = new TimeSpan(LHS.Ticks);
}
else if (ToDataType.ToString().Equals("System.DateTime", StringComparison.OrdinalIgnoreCase) && this.Context.VariableValueList.ContainsKey(this.QualifiedId) && this.Context.MemoryRegion.TryGetVariable(this.QualifiedId, out var) && result is DateTime)
{
if (var.DataType == DataType.Date)
{
dateTime = (DateTime)result;
DateTime dt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
this.Context.CurrentDataRow[this.QualifiedId] = dt;
}
else
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
}
else
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
}
}
catch(System.Exception ex)
{
if (ex != null)
{
throw new System.Exception(string.Format("You have attempted to assign an incompatible value ({0}) to {1}", result, this.QualifiedId));
}
}
}
this.ReturnResult = result;
}
private void AssignProjectDataFunction()
{
object result = this.value.Execute();
if (Util.IsEmpty(result))
{
this.Context.CurrentDataRow[this.QualifiedId] = DBNull.Value;
}
else
{
if (this.View.Fields.Contains(this.QualifiedId))
{
Epi.Fields.Field F = this.View.Fields[this.QualifiedId];
switch (F.FieldType)
{
case MetaFieldType.YesNo:
int temp_int = 0;
if (int.TryParse(result.ToString(), out temp_int))
{
if (temp_int == 0 || temp_int == 1)
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
else
{
throw new System.Exception(string.Format("You have attempted to assign an incompatible value ({0}) to {1}", result, this.QualifiedId));
}
}
else
{
throw new System.Exception(string.Format("You have attempted to assign an incompatible value ({0}) to {1}", result, this.QualifiedId));
}
break;
default:
try
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
catch (System.Exception ex)
{
if (ex != null)
{
throw new System.Exception(string.Format("You have attempted to assign an incompatible value ({0}) to {1}", result, this.QualifiedId));
}
}
break;
}
}
else
{
try
{
this.Context.CurrentDataRow[this.QualifiedId] = result;
}
catch (System.Exception ex)
{
if (ex != null)
{
throw new System.Exception(string.Format("You have attempted to assign an incompatible value ({0}) to {1}", result, this.QualifiedId));
}
}
}
}
this.ReturnResult = result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace IdentityApplicationAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Text;
using MiscUtil.Conversion;
namespace Colyseus.Schema
{
/// <summary>
/// Utility class for decoding values from the server
/// </summary>
public class ColyseusDecoder
{
/// <summary>
/// The bit converter used to decode data
/// </summary>
public static LittleEndianBitConverter bitConverter = new LittleEndianBitConverter();
/// <summary>
/// Singleton instance
/// </summary>
protected static ColyseusDecoder Instance = new ColyseusDecoder();
/// <summary>
/// Getter function for the singleton <see cref="Instance" />
/// </summary>
/// <returns>The singleton <see cref="Instance" /></returns>
public static ColyseusDecoder GetInstance()
{
return Instance;
}
/// <summary>
/// Decodes incoming data into an <see cref="object" /> based off of the <paramref name="type" /> provided
/// </summary>
/// <param name="type">What type of <see cref="object" /> we expect this data to be.
/// <para>Will determine the Decode method used</para>
/// </param>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns>A decoded <see cref="object" /> that has been decoded with a <paramref name="type" /> specified method</returns>
public object DecodePrimitiveType(string type, byte[] bytes, Iterator it)
{
if (type == "string")
{
return DecodeString(bytes, it);
}
if (type == "number")
{
return DecodeNumber(bytes, it);
}
if (type == "int8")
{
return DecodeInt8(bytes, it);
}
if (type == "uint8")
{
return DecodeUint8(bytes, it);
}
if (type == "int16")
{
return DecodeInt16(bytes, it);
}
if (type == "uint16")
{
return DecodeUint16(bytes, it);
}
if (type == "int32")
{
return DecodeInt32(bytes, it);
}
if (type == "uint32")
{
return DecodeUint32(bytes, it);
}
if (type == "int64")
{
return DecodeInt64(bytes, it);
}
if (type == "uint64")
{
return DecodeUint64(bytes, it);
}
if (type == "float32")
{
return DecodeFloat32(bytes, it);
}
if (type == "float64")
{
return DecodeFloat64(bytes, it);
}
if (type == "boolean")
{
return DecodeBoolean(bytes, it);
}
return null;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a <see cref="float" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a <see cref="float" /></returns>
public float DecodeNumber(byte[] bytes, Iterator it)
{
byte prefix = bytes[it.Offset++];
if (prefix < 0x80)
{
// positive fixint
return prefix;
}
if (prefix == 0xca)
{
// float 32
return DecodeFloat32(bytes, it);
}
if (prefix == 0xcb)
{
// float 64
return (float) DecodeFloat64(bytes, it);
}
if (prefix == 0xcc)
{
// uint 8
return DecodeUint8(bytes, it);
}
if (prefix == 0xcd)
{
// uint 16
return DecodeUint16(bytes, it);
}
if (prefix == 0xce)
{
// uint 32
return DecodeUint32(bytes, it);
}
if (prefix == 0xcf)
{
// uint 64
return DecodeUint64(bytes, it);
}
if (prefix == 0xd0)
{
// int 8
return DecodeInt8(bytes, it);
}
if (prefix == 0xd1)
{
// int 16
return DecodeInt16(bytes, it);
}
if (prefix == 0xd2)
{
// int 32
return DecodeInt32(bytes, it);
}
if (prefix == 0xd3)
{
// int 64
return DecodeInt64(bytes, it);
}
if (prefix > 0xdf)
{
// negative fixint
return (0xff - prefix + 1) * -1;
}
return float.NaN;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into an 8-bit <see cref="int" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into an 8-bit <see cref="int" /></returns>
public sbyte DecodeInt8(byte[] bytes, Iterator it)
{
return Convert.ToSByte((DecodeUint8(bytes, it) << 24) >> 24);
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into an 8-bit <see cref="uint" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into an 8-bit <see cref="uint" /></returns>
public byte DecodeUint8(byte[] bytes, Iterator it)
{
return bytes[it.Offset++];
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 16-bit <see cref="int" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 16-bit <see cref="int" /></returns>
public short DecodeInt16(byte[] bytes, Iterator it)
{
short value = bitConverter.ToInt16(bytes, it.Offset);
it.Offset += 2;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 16-bit <see cref="uint" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 16-bit <see cref="uint" /></returns>
public ushort DecodeUint16(byte[] bytes, Iterator it)
{
ushort value = bitConverter.ToUInt16(bytes, it.Offset);
it.Offset += 2;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 32-bit <see cref="int" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 32-bit <see cref="int" /></returns>
public int DecodeInt32(byte[] bytes, Iterator it)
{
int value = bitConverter.ToInt32(bytes, it.Offset);
it.Offset += 4;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 32-bit <see cref="uint" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 32-bit <see cref="uint" /></returns>
public uint DecodeUint32(byte[] bytes, Iterator it)
{
uint value = bitConverter.ToUInt32(bytes, it.Offset);
it.Offset += 4;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 32-bit <see cref="float" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 32-bit <see cref="float" /></returns>
public float DecodeFloat32(byte[] bytes, Iterator it)
{
float value = bitConverter.ToSingle(bytes, it.Offset);
it.Offset += 4;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 64-bit <see cref="float" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 64-bit <see cref="float" /></returns>
public double DecodeFloat64(byte[] bytes, Iterator it)
{
double value = bitConverter.ToDouble(bytes, it.Offset);
it.Offset += 8;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 64-bit <see cref="int" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 64-bit <see cref="int" /></returns>
public long DecodeInt64(byte[] bytes, Iterator it)
{
long value = bitConverter.ToInt64(bytes, it.Offset);
it.Offset += 8;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a 64-bit <see cref="uint" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a 64-bit <see cref="uint" /></returns>
public ulong DecodeUint64(byte[] bytes, Iterator it)
{
ulong value = bitConverter.ToUInt64(bytes, it.Offset);
it.Offset += 8;
return value;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a <see cref="bool" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a <see cref="bool" /></returns>
public bool DecodeBoolean(byte[] bytes, Iterator it)
{
return DecodeUint8(bytes, it) > 0;
}
/// <summary>
/// Decode method to decode <paramref name="bytes" /> into a <see cref="string" />
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns><paramref name="bytes" /> decoded into a <see cref="string" /></returns>
public string DecodeString(byte[] bytes, Iterator it)
{
int prefix = bytes[it.Offset++];
int length;
if (prefix < 0xc0)
{
// fixstr
length = prefix & 0x1f;
}
else if (prefix == 0xd9)
{
length = (int) DecodeUint8(bytes, it);
}
else if (prefix == 0xda)
{
length = DecodeUint16(bytes, it);
}
else if (prefix == 0xdb)
{
length = (int) DecodeUint32(bytes, it);
}
else
{
length = 0;
}
string str = Encoding.UTF8.GetString(bytes, it.Offset, length);
it.Offset += length;
return str;
}
/// <summary>
/// Checks if
/// <code>bytes[it.Offset] == (byte)SPEC.SWITCH_TO_STRUCTURE</code>
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns>
/// True if the current <see cref="Iterator.Offset" /> works with this array of <paramref name="bytes" />, false
/// otherwise
/// </returns>
public bool SwitchStructureCheck(byte[] bytes, Iterator it)
{
return bytes[it.Offset] == (byte) SPEC.SWITCH_TO_STRUCTURE;
}
/// <summary>
/// Checks if the incoming <paramref name="bytes" /> is a number
/// </summary>
/// <param name="bytes">The incoming data</param>
/// <param name="it">The iterator who's <see cref="Iterator.Offset" /> will be used to Decode the data</param>
/// <returns>True if <paramref name="bytes" /> can be resolved into a number, false otherwise</returns>
public bool NumberCheck(byte[] bytes, Iterator it)
{
byte prefix = bytes[it.Offset];
return prefix < 0x80 || prefix >= 0xca && prefix <= 0xd3;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
namespace CreateVirtualMachineUsingSpecializedDiskFromSnapshot
{
public class Program
{
private static string userName = "tirekicker";
private static string password = "12NewPA$$w0rd!";
private static Region region = Region.USWestCentral;
/**
* Azure Compute sample for managing virtual machines -
* - Create an managed virtual machine from PIR image with data disks
* - Create snapshot from the virtual machine's OS and data disks
* - Create managed disks from the snapshots
* - Create virtual machine by attaching the managed disks
* - Get SAS Uri to the virtual machine's managed disks.
*/
public static void RunSample(IAzure azure)
{
var linuxVmName1 = Utilities.CreateRandomName("VM1");
var linuxVmName2 = Utilities.CreateRandomName("VM2");
var managedOSSnapshotName = Utilities.CreateRandomName("ss-os-");
var managedDataDiskSnapshotPrefix = Utilities.CreateRandomName("ss-data-");
var managedNewOSDiskName = Utilities.CreateRandomName("ds-os-nw-");
var managedNewDataDiskNamePrefix = Utilities.CreateRandomName("ds-data-nw-");
var rgName = Utilities.CreateRandomName("rgCOMV");
var publicIpDnsLabel = Utilities.CreateRandomName("pip");
var apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh";
var apacheInstallCommand = "bash install_apache.sh";
var apacheInstallScriptUris = new List<string>();
apacheInstallScriptUris.Add(apacheInstallScript);
try
{
//=============================================================
// Create a Linux VM using a PIR image with managed OS and data disks and customize virtual
// machine using custom script extension
Utilities.Log("Creating a un-managed Linux VM");
var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithNewPrimaryNetwork("10.0.0.0/28")
.WithPrimaryPrivateIPAddressDynamic()
.WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(userName)
.WithRootPassword(password)
.WithNewDataDisk(100)
.WithNewDataDisk(100, 1, CachingTypes.ReadWrite)
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.DefineNewExtension("CustomScriptForLinux")
.WithPublisher("Microsoft.OSTCExtensions")
.WithType("CustomScriptForLinux")
.WithVersion("1.4")
.WithMinorVersionAutoUpgrade()
.WithPublicSetting("fileUris", apacheInstallScriptUris)
.WithPublicSetting("commandToExecute", apacheInstallCommand)
.Attach()
.Create();
Utilities.Log("Created a Linux VM with managed OS and data disks: " + linuxVM.Id);
Utilities.PrintVirtualMachine(linuxVM);
// Gets the specialized managed OS and Data disks of the virtual machine
//
var osDisk = azure.Disks.GetById(linuxVM.OSDiskId);
var dataDisks = new List<IDisk>();
foreach (var disk in linuxVM.DataDisks.Values)
{
var dataDisk = azure.Disks.GetById(disk.Id);
dataDisks.Add(dataDisk);
}
//=============================================================
// Delete the virtual machine
Utilities.Log("Deleting VM: " + linuxVM.Id);
azure.VirtualMachines.DeleteById(linuxVM.Id);
Utilities.Log("Deleted the VM");
//=============================================================
// Create Snapshot from the OS managed disk
Utilities.Log($"Creating managed snapshot from the managed disk (holding specialized OS): {osDisk.Id}");
var osSnapshot = azure.Snapshots.Define(managedOSSnapshotName)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithLinuxFromDisk(osDisk)
.Create();
Utilities.Log("Created managed snapshot holding OS: " + osSnapshot.Id);
// Utilities.Print(osSnapshot); TODO
//=============================================================
// Create Managed snapshot from the Data managed disks
var dataSnapshots = new List<ISnapshot>();
var i = 0;
foreach (var dataDisk in dataDisks)
{
Utilities.Log($"Creating managed snapshot from the managed disk (holding data): {dataDisk.Id} ");
var dataSnapshot = azure.Snapshots.Define(managedDataDiskSnapshotPrefix + "-" + i)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithDataFromDisk(dataDisk)
.WithSku(DiskSkuTypes.StandardLRS)
.Create();
dataSnapshots.Add(dataSnapshot);
Utilities.Log("Created managed snapshot holding data: " + dataSnapshot.Id);
// Utilities.Print(dataDisk); TODO
i++;
}
//=============================================================
// Create Managed disk from the specialized OS snapshot
Utilities.Log(String.Format("Creating managed disk from the snapshot holding OS: %s ", osSnapshot.Id));
var newOSDisk = azure.Disks.Define(managedNewOSDiskName)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithLinuxFromSnapshot(osSnapshot)
.WithSizeInGB(100)
.Create();
Utilities.Log("Created managed disk holding OS: " + osDisk.Id);
// Utilities.Print(osDisk); TODO
//=============================================================
// Create Managed disks from the data snapshots
var newDataDisks = new List<IDisk>();
i = 0;
foreach (var dataSnapshot in dataSnapshots)
{
Utilities.Log($"Creating managed disk from the Data snapshot: {dataSnapshot.Id} ");
var dataDisk = azure.Disks.Define(managedNewDataDiskNamePrefix + "-" + i)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithData()
.FromSnapshot(dataSnapshot)
.Create();
newDataDisks.Add(dataDisk);
Utilities.Log("Created managed disk holding data: " + dataDisk.Id);
// Utilities.Print(dataDisk); TODO
i++;
}
//
//=============================================================
// Create a Linux VM by attaching the managed disks
Utilities.Log("Creating a Linux VM using specialized OS and data disks");
var linuxVM2 = azure.VirtualMachines.Define(linuxVmName2)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithNewPrimaryNetwork("10.0.0.0/28")
.WithPrimaryPrivateIPAddressDynamic()
.WithoutPrimaryPublicIPAddress()
.WithSpecializedOSDisk(newOSDisk, OperatingSystemTypes.Linux)
.WithExistingDataDisk(newDataDisks[0])
.WithExistingDataDisk(newDataDisks[1], 1, CachingTypes.ReadWrite)
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.Create();
Utilities.PrintVirtualMachine(linuxVM2);
//=============================================================
//
Utilities.Log("Deleting OS snapshot - " + osSnapshot.Id);
azure.Snapshots.DeleteById(osSnapshot.Id);
Utilities.Log("Deleted OS snapshot");
foreach (var dataSnapshot in dataSnapshots)
{
Utilities.Log("Deleting data snapshot - " + dataSnapshot.Id);
azure.Snapshots.DeleteById(dataSnapshot.Id);
Utilities.Log("Deleted data snapshot");
}
// Getting the SAS URIs requires virtual machines to be de-allocated
// [Access not permitted because'disk' is currently attached to running VM]
//
Utilities.Log("De-allocating the virtual machine - " + linuxVM2.Id);
linuxVM2.Deallocate();
//=============================================================
// Get the readonly SAS URI to the OS and data disks
Utilities.Log("Getting OS and data disks SAS Uris");
// OS Disk SAS Uri
osDisk = azure.Disks.GetById(linuxVM2.OSDiskId);
var osDiskSasUri = osDisk.GrantAccess(24 * 60);
Utilities.Log("OS disk SAS Uri: " + osDiskSasUri);
// Data disks SAS Uri
foreach (var disk in linuxVM2.DataDisks.Values)
{
var dataDisk = azure.Disks.GetById(disk.Id);
var dataDiskSasUri = dataDisk.GrantAccess(24 * 60);
Utilities.Log($"Data disk (lun: {disk.Lun}) SAS Uri: {dataDiskSasUri}");
}
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: XObject.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Java.IO;
using Java.Util;
using Org.Xmlpull.V1;
namespace System.Xml.Linq
{
public abstract class XObject
{
private object annotations;
internal XContainer parent;
/// <summary>
/// Raised when this XObject or any of its descendants have changed.
/// </summary>
public event EventHandler<XObjectChangeEventArgs> Changed
{
add
{
if (value == null)
return;
var ann = Annotation<XObjectChangeAnnotation>();
if (ann == null)
{
ann = new XObjectChangeAnnotation();
AddAnnotation(ann);
}
ann.Changed += value;
}
remove
{
if (value == null)
return;
var ann = Annotation<XObjectChangeAnnotation>();
if (ann != null)
{
ann.Changed -= value;
if ((ann.Changed == null) && (ann.Changing == null))
{
RemoveAnnotations<XObjectChangeAnnotation>();
}
}
}
}
/// <summary>
/// Raised when this XObject or any of its descendants will change.
/// </summary>
public event EventHandler<XObjectChangeEventArgs> Changing
{
add
{
if (value == null)
return;
var ann = Annotation<XObjectChangeAnnotation>();
if (ann == null)
{
ann = new XObjectChangeAnnotation();
AddAnnotation(ann);
}
ann.Changing += value;
}
remove
{
if (value == null)
return;
var ann = Annotation<XObjectChangeAnnotation>();
if (ann != null)
{
ann.Changing -= value;
if ((ann.Changed == null) && (ann.Changing == null))
{
RemoveAnnotations<XObjectChangeAnnotation>();
}
}
}
}
/// <summary>
/// Gets the base URI for this object.
/// </summary>
public string BaseUri
{
get { throw new NotImplementedException("System.Xml.Linq.XObject.BaseUri"); }
}
/// <summary>
/// Gets the containing document
/// </summary>
public XDocument Document
{
get { return Root as XDocument; }
}
/// <summary>
/// Gets the deepest parent.
/// </summary>
internal XObject Root
{
get
{
var x = this;
while (x.parent != null)
{
x = x.parent;
}
return x;
}
}
/// <summary>
/// Gets the type of this node.
/// </summary>
public abstract XmlNodeType NodeType { get; }
/// <summary>
/// Gets the parent of this object, or null if the object has no parent.
/// </summary>
public XElement Parent
{
get { return parent as XElement; }
}
/// <summary>
/// Add an object to the annotation list of this object.
/// </summary>
public void AddAnnotation(object annotation)
{
if (annotation == null)
throw new ArgumentNullException("annotation");
if (annotations == null)
{
// Add first annotation
if (annotation is ArrayList<object>)
{
// Make sure we can see the difference between a single object and a list.
var list = new ArrayList<object>();
list.Add(annotation);
annotations = list;
}
else
{
// Single object
annotations = annotation;
}
}
else
{
// Add second... annotation
var list = annotations as ArrayList<object>;
if (list == null)
{
// Convert first to list
list = new ArrayList<object>();
list.Add(annotations);
list.Add(annotation);
annotations = list;
}
else
{
// Add to list
list.Add(annotation);
}
}
}
/// <summary>
/// Remove all annotations of the T.
/// </summary>
public void RemoveAnnotations<T>()
where T : class
{
if (annotations == null)
return;
var list = annotations as ArrayList<object>;
if (list == null)
{
// Single object
if (annotations is T)
{
annotations = null;
}
}
else
{
var i = 0;
while (i < list.Count)
{
if (list[i] is T)
{
list.Remove(i);
}
else
{
i++;
}
}
if (list.Count == 0)
{
annotations = null;
}
}
}
/// <summary>
/// Remove all annotations of the given type.
/// </summary>
public void RemoveAnnotations(Type type)
{
if (annotations == null)
return;
var list = annotations as ArrayList<object>;
if (list == null)
{
// Single object
if (type.JavaIsInstance(type))
{
annotations = null;
}
}
else
{
var i = 0;
while (i < list.Count)
{
if (type.JavaIsInstance(list[i]))
{
list.Remove(i);
}
else
{
i++;
}
}
if (list.Count == 0)
{
annotations = null;
}
}
}
/// <summary>
/// Gets the first annotation of type T.
/// </summary>
public T Annotation<T>()
where T : class
{
if (annotations == null)
return default(T);
var list = annotations as ArrayList<object>;
if (list == null)
{
return annotations as T;
}
for (var i = 0; i < list.Count; i++)
{
var result = list[i] as T;
if (result != null)
return result;
}
return default(T);
}
/// <summary>
/// Gets the first annotation of the given type.
/// </summary>
public object Annotation(Type type)
{
if (annotations == null)
return null;
var list = annotations as ArrayList<object>;
if (list == null)
{
if (type.JavaIsInstance(annotations))
return annotations;
return null;
}
for (var i = 0; i < list.Count; i++)
{
var result = list[i];
if (type.JavaIsInstance(result))
return result;
}
return null;
}
/// <summary>
/// Gets all annotations of type T.
/// </summary>
public IEnumerable<T> Annotations<T>()
where T : class
{
if (annotations != null)
{
var list = annotations as ArrayList<object>;
if (list == null)
{
var result = annotations as T;
if (result != null)
yield return result;
}
else
{
for (var i = 0; i < list.Count; i++)
{
var result = list[i] as T;
if (result != null)
yield return result;
}
}
}
}
/// <summary>
/// Gets all annotations of type T.
/// </summary>
public IEnumerable<object> Annotations(Type type)
{
if (annotations != null)
{
var list = annotations as ArrayList<object>;
if (list == null)
{
if (type.JavaIsInstance(annotations))
yield return annotations;
}
else
{
for (var i = 0; i < list.Count; i++)
{
var result = list[i];
if (type.JavaIsInstance(result))
yield return result;
}
}
}
}
/// <summary>
/// Serialize this object to the given serializer.
/// </summary>
public abstract void WriteTo(IXmlSerializer serializer);
/// <summary>
/// Fire the changed event.
/// </summary>
internal void NotifyChanged(object sender, XObjectChangeEventArgs args)
{
var x = this;
while (x != null)
{
var ann = x.Annotation<XObjectChangeAnnotation>();
if ((ann != null) && (ann.Changed != null))
{
ann.Changed(sender, args);
}
x = x.Parent;
}
}
/// <summary>
/// Fire the changing event.
/// </summary>
/// <return>true if any eventhandler is found.</return>
internal bool NotifyChanging(object sender, XObjectChangeEventArgs args)
{
var x = this;
var result = false;
while (x != null)
{
var ann = x.Annotation<XObjectChangeAnnotation>();
if (ann != null)
{
result = true;
if (ann.Changing != null)
{
ann.Changing(sender, args);
}
}
x = x.Parent;
}
return result;
}
/// <summary>
/// Convert the given value to a string.
/// </summary>
internal static string ConvertToString(object value)
{
var text = value as string;
if (text != null)
return text;
if (value is double) text = XmlConvert.ToString((double)value);
else if (value is float) text = XmlConvert.ToString((float) value);
else if (value is bool) text = XmlConvert.ToString((bool)value);
// TODO
if (text == null)
{
throw new ArgumentException("Not a valid string");
}
return text;
}
/// <summary>
/// Convert to XML representation.
/// </summary>
internal string ToXml(SaveOptions options)
{
var writer = new StringWriter();
ToXml(writer, options);
return writer.ToString();
}
/// <summary>
/// Convert to XML representation.
/// </summary>
internal void ToXml(Writer writer, SaveOptions options)
{
var serializer = Android.Util.Xml.NewSerializer();
serializer.SetOutput(writer);
WriteTo(serializer);
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.