context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using UnityEngine;
using UnityEngine.TestTools.NUnitExtensions;
using UnityEngine.TestTools.TestRunner;
using UnityEngine.TestTools;
using UnityEngine.TestTools.TestRunner.GUI;
using UnityEditor.Callbacks;
using UnityEngine.TestRunner.NUnitExtensions;
using UnityEngine.TestRunner.NUnitExtensions.Runner;
namespace UnityEditor.TestTools.TestRunner
{
internal interface IUnityTestAssemblyRunnerFactory
{
IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory);
}
internal class UnityTestAssemblyRunnerFactory : IUnityTestAssemblyRunnerFactory
{
public IUnityTestAssemblyRunner Create(TestPlatform testPlatform, WorkItemFactory factory)
{
return new UnityTestAssemblyRunner(new UnityTestAssemblyBuilder(), factory);
}
}
[Serializable]
internal class EditModeRunner : ScriptableObject, IDisposable
{
[SerializeField]
private TestRunnerFilter m_Filter;
//The counter from the IEnumerator object
[SerializeField]
private int m_CurrentPC;
[SerializeField]
private bool m_ExecuteOnEnable;
[SerializeField]
private List<string> m_AlreadyStartedTests;
[SerializeField]
private List<TestResultSerializer> m_ExecutedTests;
[SerializeField]
private List<ScriptableObject> m_CallbackObjects = new List<ScriptableObject>();
[SerializeField]
private TestStartedEvent m_TestStartedEvent = new TestStartedEvent();
[SerializeField]
private TestFinishedEvent m_TestFinishedEvent = new TestFinishedEvent();
[SerializeField]
private RunStartedEvent m_RunStartedEvent = new RunStartedEvent();
[SerializeField]
private RunFinishedEvent m_RunFinishedEvent = new RunFinishedEvent();
[SerializeField]
private TestRunnerStateSerializer m_TestRunnerStateSerializer = new TestRunnerStateSerializer();
[SerializeField]
private TestFileCleanupVerifier m_CleanupVerifier = new TestFileCleanupVerifier();
[SerializeField]
private bool m_RunningTests;
[SerializeField]
private TestPlatform m_TestPlatform;
[SerializeField]
private object m_CurrentYieldObject;
[SerializeField]
private BeforeAfterTestCommandState m_SetUpTearDownState;
[SerializeField]
private BeforeAfterTestCommandState m_OuterUnityTestActionState;
internal IUnityTestAssemblyRunner m_Runner;
private ConstructDelegator m_ConstructDelegator;
private IEnumerator m_RunStep;
public IUnityTestAssemblyRunnerFactory UnityTestAssemblyRunnerFactory { get; set; }
public void Init(TestRunnerFilter filter, TestPlatform platform)
{
m_Filter = filter;
m_TestPlatform = platform;
m_AlreadyStartedTests = new List<string>();
m_ExecutedTests = new List<TestResultSerializer>();
InitRunner();
}
private void InitRunner()
{
//We give the EditMode platform here so we dont suddenly create Playmode work items in the test Runner.
m_Runner = (UnityTestAssemblyRunnerFactory ?? new UnityTestAssemblyRunnerFactory()).Create(TestPlatform.EditMode, new EditmodeWorkItemFactory());
var testAssemblyProvider = new EditorLoadedTestAssemblyProvider(new EditorCompilationInterfaceProxy(), new EditorAssembliesProxy());
var loadedTests = m_Runner.Load(
testAssemblyProvider.GetAssembliesGroupedByType(m_TestPlatform).Select(x => x.Assembly).ToArray(),
UnityTestAssemblyBuilder.GetNUnitTestBuilderSettings(m_TestPlatform));
loadedTests.ParseForNameDuplicates();
hideFlags |= HideFlags.DontSave;
EnumerableSetUpTearDownCommand.ActivePcHelper = new EditModePcHelper();
OuterUnityTestActionCommand.ActivePcHelper = new EditModePcHelper();
}
public void OnEnable()
{
if (m_ExecuteOnEnable)
{
InitRunner();
m_ExecuteOnEnable = false;
foreach (var callback in m_CallbackObjects)
{
AddListeners(callback as ITestRunnerListener);
}
m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer);
EnumeratorStepHelper.SetEnumeratorPC(m_CurrentPC);
UnityWorkItemDataHolder.alreadyExecutedTests = m_ExecutedTests.Select(x => x.fullName).ToList();
UnityWorkItemDataHolder.alreadyStartedTests = m_AlreadyStartedTests;
Run();
}
}
public void TestStartedEvent(ITest test)
{
m_AlreadyStartedTests.Add(test.FullName);
}
public void TestFinishedEvent(ITestResult testResult)
{
m_AlreadyStartedTests.Remove(testResult.FullName);
m_ExecutedTests.Add(TestResultSerializer.MakeFromTestResult(testResult));
}
public void Run()
{
EditModeTestCallbacks.RestoringTestContext += OnRestoringTest;
var context = m_Runner.GetCurrentContext();
if (m_SetUpTearDownState == null)
{
m_SetUpTearDownState = CreateInstance<BeforeAfterTestCommandState>();
}
context.SetUpTearDownState = m_SetUpTearDownState;
if (m_OuterUnityTestActionState == null)
{
m_OuterUnityTestActionState = CreateInstance<BeforeAfterTestCommandState>();
}
context.OuterUnityTestActionState = m_OuterUnityTestActionState;
m_CleanupVerifier.RegisterExistingFiles();
if (!m_RunningTests)
{
m_RunStartedEvent.Invoke(m_Runner.LoadedTest);
}
if (m_ConstructDelegator == null)
m_ConstructDelegator = new ConstructDelegator(m_TestRunnerStateSerializer);
Reflect.ConstructorCallWrapper = m_ConstructDelegator.Delegate;
m_TestStartedEvent.AddListener(TestStartedEvent);
m_TestFinishedEvent.AddListener(TestFinishedEvent);
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
RunningTests = true;
EditorApplication.LockReloadAssemblies();
var testListenerWrapper = new TestListenerWrapper(m_TestStartedEvent, m_TestFinishedEvent);
m_RunStep = m_Runner.Run(testListenerWrapper, m_Filter.BuildNUnitFilter()).GetEnumerator();
m_RunningTests = true;
EditorApplication.update += TestConsumer;
}
private void OnBeforeAssemblyReload()
{
EditorApplication.update -= TestConsumer;
if (m_ExecuteOnEnable)
{
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
return;
}
if (m_Runner != null && m_Runner.TopLevelWorkItem != null)
m_Runner.TopLevelWorkItem.ResultedInDomainReload = true;
if (RunningTests)
{
Debug.LogError("TestRunner: Unexpected assembly reload happened while running tests");
EditorUtility.ClearProgressBar();
if (m_Runner.GetCurrentContext() != null && m_Runner.GetCurrentContext().CurrentResult != null)
{
m_Runner.GetCurrentContext().CurrentResult.SetResult(ResultState.Cancelled, "Unexpected assembly reload happened");
}
OnRunCancel();
}
}
private bool RunningTests;
private Stack<IEnumerator> StepStack = new Stack<IEnumerator>();
private bool MoveNextAndUpdateYieldObject()
{
var result = m_RunStep.MoveNext();
if (result)
{
m_CurrentYieldObject = m_RunStep.Current;
while (m_CurrentYieldObject is IEnumerator) // going deeper
{
var currentEnumerator = (IEnumerator)m_CurrentYieldObject;
// go deeper and add parent to stack
StepStack.Push(m_RunStep);
m_RunStep = currentEnumerator;
m_CurrentYieldObject = m_RunStep.Current;
}
if (StepStack.Count > 0 && m_CurrentYieldObject != null) // not null and not IEnumerator, nested
{
Debug.LogError("EditMode test can only yield null, but not <" + m_CurrentYieldObject.GetType().Name + ">");
}
return true;
}
if (StepStack.Count == 0) // done
return false;
m_RunStep = StepStack.Pop(); // going up
return MoveNextAndUpdateYieldObject();
}
private void TestConsumer()
{
var moveNext = MoveNextAndUpdateYieldObject();
if (m_CurrentYieldObject != null)
{
InvokeDelegator();
}
if (!moveNext && !m_Runner.IsTestComplete)
{
CompleteTestRun();
throw new IndexOutOfRangeException("There are no more elements to process and IsTestComplete is false");
}
if (m_Runner.IsTestComplete)
{
CompleteTestRun();
}
}
private void CompleteTestRun()
{
EditorApplication.update -= TestConsumer;
TestLauncherBase.ExecutePostBuildCleanupMethods(this.GetLoadedTests(), this.GetFilter(), Application.platform);
m_CleanupVerifier.VerifyNoNewFilesAdded();
m_RunFinishedEvent.Invoke(m_Runner.Result);
if (m_ConstructDelegator != null)
m_ConstructDelegator.DestroyCurrentTestObjectIfExists();
Dispose();
UnityWorkItemDataHolder.alreadyExecutedTests = null;
}
private void OnRestoringTest()
{
var item = m_ExecutedTests.Find(t => t.fullName == UnityTestExecutionContext.CurrentContext.CurrentTest.FullName);
if (item != null)
{
item.RestoreTestResult(UnityTestExecutionContext.CurrentContext.CurrentResult);
}
}
private static bool IsCancelled()
{
return UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.AbortRequested || UnityTestExecutionContext.CurrentContext.ExecutionStatus == TestExecutionStatus.StopRequested;
}
private void InvokeDelegator()
{
if (m_CurrentYieldObject == null)
{
return;
}
if (IsCancelled())
{
return;
}
if (m_CurrentYieldObject is RestoreTestContextAfterDomainReload)
{
if (m_TestRunnerStateSerializer.ShouldRestore())
{
m_TestRunnerStateSerializer.RestoreContext();
}
return;
}
try
{
if (m_CurrentYieldObject is IEditModeTestYieldInstruction)
{
var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)m_CurrentYieldObject;
if (editModeTestYieldInstruction.ExpectDomainReload)
{
PrepareForDomainReload();
}
return;
}
}
catch (Exception e)
{
UnityTestExecutionContext.CurrentContext.CurrentResult.RecordException(e);
return;
}
Debug.LogError("EditMode test can only yield null");
}
private void CompilationFailureWatch()
{
if (EditorApplication.isCompiling)
return;
EditorApplication.update -= CompilationFailureWatch;
if (EditorUtility.scriptCompilationFailed)
{
EditorUtility.ClearProgressBar();
OnRunCancel();
}
}
private void PrepareForDomainReload()
{
m_TestRunnerStateSerializer.SaveContext();
m_CurrentPC = EnumeratorStepHelper.GetEnumeratorPC(TestEnumerator.Enumerator);
m_ExecuteOnEnable = true;
RunningTests = false;
}
public T AddEventHandler<T>() where T : ScriptableObject, ITestRunnerListener
{
var eventHandler = CreateInstance<T>();
eventHandler.hideFlags |= HideFlags.DontSave;
m_CallbackObjects.Add(eventHandler);
AddListeners(eventHandler);
return eventHandler;
}
private void AddListeners(ITestRunnerListener eventHandler)
{
m_TestStartedEvent.AddListener(eventHandler.TestStarted);
m_TestFinishedEvent.AddListener(eventHandler.TestFinished);
m_RunStartedEvent.AddListener(eventHandler.RunStarted);
m_RunFinishedEvent.AddListener(eventHandler.RunFinished);
}
public void Dispose()
{
Reflect.MethodCallWrapper = null;
EditorApplication.update -= TestConsumer;
DestroyImmediate(this);
if (m_CallbackObjects != null)
{
foreach (var obj in m_CallbackObjects)
{
DestroyImmediate(obj);
}
m_CallbackObjects.Clear();
}
RunningTests = false;
EditorApplication.UnlockReloadAssemblies();
}
public void OnRunCancel()
{
UnityWorkItemDataHolder.alreadyExecutedTests = null;
m_ExecuteOnEnable = false;
m_Runner.StopRun();
}
public ITest GetLoadedTests()
{
return m_Runner.LoadedTest;
}
public ITestFilter GetFilter()
{
return m_Filter.BuildNUnitFilter();
}
}
}
| |
// 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.Linq.Expressions.Tests
{
public interface I
{
void M();
}
public class C : IEquatable<C>, I
{
void I.M()
{
}
public override bool Equals(object o)
{
return o is C && Equals((C)o);
}
public bool Equals(C c)
{
return c != null;
}
public override int GetHashCode()
{
return 0;
}
}
public class D : C, IEquatable<D>
{
public int Val;
public string S;
public D()
{
}
public D(int val)
: this(val, "")
{
}
public D(int val, string s)
{
Val = val;
S = s;
}
public override bool Equals(object o)
{
return o is D && Equals((D)o);
}
public bool Equals(D d)
{
return d != null && d.Val == Val;
}
public override int GetHashCode()
{
return Val;
}
}
public enum E
{
A = 1,
B = 2,
Red = 0,
Green,
Blue
}
public enum El : long
{
A,
B,
C
}
public enum Eu : uint
{
Foo,
Bar,
Baz
}
public struct S : IEquatable<S>
{
public override bool Equals(object o)
{
return (o is S) && Equals((S)o);
}
public bool Equals(S other)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
public struct Sp : IEquatable<Sp>
{
public Sp(int i, double d)
{
I = i;
D = d;
}
public int I;
public double D;
public override bool Equals(object o)
{
return (o is Sp) && Equals((Sp)o);
}
public bool Equals(Sp other)
{
return other.I == I && other.D.Equals(D);
}
public override int GetHashCode()
{
return I.GetHashCode() ^ D.GetHashCode();
}
}
public struct Ss : IEquatable<Ss>
{
public Ss(S s)
{
Val = s;
}
public S Val;
public override bool Equals(object o)
{
return (o is Ss) && Equals((Ss)o);
}
public bool Equals(Ss other)
{
return other.Val.Equals(Val);
}
public override int GetHashCode()
{
return Val.GetHashCode();
}
}
public struct Sc : IEquatable<Sc>
{
public Sc(string s)
{
S = s;
}
public string S;
public override bool Equals(object o)
{
return (o is Sc) && Equals((Sc)o);
}
public bool Equals(Sc other)
{
return other.S == S;
}
public override int GetHashCode()
{
return S.GetHashCode();
}
}
public struct Scs : IEquatable<Scs>
{
public Scs(string s, S val)
{
S = s;
Val = val;
}
public string S;
public S Val;
public override bool Equals(object o)
{
return (o is Scs) && Equals((Scs)o);
}
public bool Equals(Scs other)
{
return other.S == S && other.Val.Equals(Val);
}
public override int GetHashCode()
{
return S.GetHashCode() ^ Val.GetHashCode();
}
}
public class BaseClass
{
}
public class FC
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public struct FS
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public class PC
{
public int II { get; set; }
public static int SI { get; set; }
public int this[int i]
{
get { return 1; }
set { }
}
}
public struct PS
{
public int II { get; set; }
public static int SI { get; set; }
}
internal class CompilationTypes : IEnumerable<object[]>
{
private static readonly object[] False = new object[] { false };
private static readonly object[] True = new object[] { true };
public IEnumerator<object[]> GetEnumerator()
{
yield return False;
yield return True;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class NoOpVisitor : ExpressionVisitor
{
internal static readonly NoOpVisitor Instance = new NoOpVisitor();
private NoOpVisitor()
{
}
}
}
| |
#region Copyright ?2007 Rotem Sapir
/*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim
* that you wrote the original software. If you use this software in a product,
* an acknowledgment in the product documentation is required, as shown here:
*
* Portions Copyright ?2007 Rotem Sapir
*
* 2. No substantial portion of the source code of this library may be redistributed
* without the express written permission of the copyright holders, where
* "substantial" is defined as enough code to be recognizably from this library.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Xml;
namespace Xnlab.SQLMon.Controls.Tree
{
public class TreeBuilder : IDisposable
{
#region Private Members
private Color _fontColor = Color.Black;
private int _boxWidth = 120;
private int _boxHeight = 60;
private int _margin = 20;
private int _horizontalSpace = 30;
private int _verticalSpace = 30;
private int _fontSize = 9;
private int _imgWidth = 0;
private int _imgHeight = 0;
private Graphics _gr;
private Color _lineColor = Color.Black;
private float _lineWidth = 2;
private Color _boxFillColor = Color.White;
private Color _bgColor = Color.White;
private Tree _tree;
private XmlDocument _nodeTree;
double _percentageChangeX;// = ActualWidth / imgWidth;
double _percentageChangeY;// = ActualHeight / imgHeight;
#endregion
#region Public Properties
public XmlDocument XmlTree
{
get
{
return _nodeTree;
}
}
public Color BoxFillColor
{
get { return _boxFillColor; }
set { _boxFillColor = value; }
}
public int BoxWidth
{
get { return _boxWidth; }
set { _boxWidth = value; }
}
public int BoxHeight
{
get { return _boxHeight; }
set { _boxHeight = value; }
}
public int Margin
{
get { return _margin; }
set { _margin = value; }
}
public int HorizontalSpace
{
get { return _horizontalSpace; }
set { _horizontalSpace = value; }
}
public int VerticalSpace
{
get { return _verticalSpace; }
set { _verticalSpace = value; }
}
public int FontSize
{
get { return _fontSize; }
set { _fontSize = value; }
}
public Color LineColor
{
get { return _lineColor; }
set { _lineColor = value; }
}
public float LineWidth
{
get { return _lineWidth; }
set { _lineWidth = value; }
}
public Color BgColor
{
get { return _bgColor; }
set { _bgColor = value; }
}
public Color FontColor
{
get { return _fontColor; }
set { _fontColor = value; }
}
#endregion
#region Public Methods
/// <summary>
/// ctor
/// </summary>
/// <param name="TreeData"></param>
public TreeBuilder(Tree data)
{
_tree = data;
}
public void Dispose()
{
_tree = null;
if (_gr != null)
{
_gr.Dispose();
_gr = null;
}
}
/// <summary>
/// This overloaded method can be used to return the image using it's default calculated size, without resizing
/// </summary>
/// <param name="startFromNodeId"></param>
/// <param name="imageType"></param>
/// <returns></returns>
public Stream GenerateTree(
string startFromNodeId,
ImageFormat imageType)
{
return GenerateTree(-1, -1, startFromNodeId, imageType);
}
/// <summary>
/// Creates the tree
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="startFromNodeId"></param>
/// <param name="imageType"></param>
/// <returns></returns>
public Stream GenerateTree(int width,
int height,
string startFromNodeId,
ImageFormat imageType)
{
var result = new MemoryStream();
//reset image size
_imgHeight = 0;
_imgWidth = 0;
//reset percentage change
_percentageChangeX = 1.0;
_percentageChangeY = 1.0;
//define the image
_nodeTree = null;
_nodeTree = new XmlDocument();
var rootDescription = string.Empty;
var rootNote = string.Empty;
var backColor = _boxFillColor;
var foreColor = _fontColor;
var node = _tree.Find(startFromNodeId);
if (node != null)
{
rootDescription = node.Description;
rootNote = node.Note;
backColor = node.BackColor;
foreColor = node.ForeColor;
}
var rootNode = GetXmlNode(startFromNodeId, rootDescription, rootNote, backColor, foreColor);
_nodeTree.AppendChild(rootNode);
BuildTree(rootNode, 0);
//check for intersection. line below should be remarked if not debugging
//as it affects performance measurably.
//OverlapExists();
var bmp = new Bitmap(_imgWidth, _imgHeight);
_gr = Graphics.FromImage(bmp);
_gr.Clear(_bgColor);
DrawChart(rootNode);
//if caller does not care about size, use original calculated size
if (width < 0)
{
width = _imgWidth;
}
if (height < 0)
{
height = _imgHeight;
}
var resizedBmp = new Bitmap(bmp, new Size(width, height));
//after resize, determine the change percentage
_percentageChangeX = Convert.ToDouble(width) / _imgWidth;
_percentageChangeY = Convert.ToDouble(height) / _imgHeight;
//after resize - change the coordinates of the list, in order return the proper coordinates
//for each node
if (_percentageChangeX != 1.0 || _percentageChangeY != 1.0)
{
//only resize coordinates if there was a resize
CalculateImageMapData();
}
resizedBmp.Save(result, imageType);
resizedBmp.Dispose();
bmp.Dispose();
_gr.Dispose();
return result;
}
/// <summary>
/// the node holds the x,y in attributes
/// use them to calculate the position
/// This is public so it can be used by other classes trying to calculate the
/// cursor/mouse location
/// </summary>
/// <param name="oNode"></param>
/// <returns></returns>
public Rectangle GetRectangleFromNode(XmlNode oNode)
{
if (oNode.Attributes["X"] == null || oNode.Attributes["Y"] == null)
{
throw new Exception("Both attributes X,Y must exist for node.");
}
var x = Convert.ToInt32(oNode.Attributes["X"].InnerText);
var y = Convert.ToInt32(oNode.Attributes["Y"].InnerText);
var result = new Rectangle(x, y, (int)(_boxWidth * _percentageChangeX), (int)(_boxHeight * _percentageChangeY));
return result;
}
#endregion
#region Private Methods
/// <summary>
/// convert the datatable to an XML document
/// </summary>
/// <param name="oNode"></param>
/// <param name="y"></param>
private void BuildTree(XmlNode oNode, int y)
{
XmlNode childNode = null;
//has children
foreach (var childRow in _tree.Parents(oNode.Attributes["nodeID"].InnerText))
{
//for each child node call this function again
childNode = GetXmlNode(childRow.Id, childRow.Description, childRow.Note, childRow.BackColor, childRow.ForeColor);
oNode.AppendChild(childNode);
BuildTree(childNode, y + 1);
}
//build node data
//after checking for nodes we can add the current node
int startX;
int startY;
var resultsArr = new int[] {GetXPosByOwnChildren(oNode),
GetXPosByParentPreviousSibling(oNode),
GetXPosByPreviousSibling(oNode),
_margin };
Array.Sort(resultsArr);
startX = resultsArr[3];
startY = (y * (_boxHeight + _verticalSpace)) + _margin;
var width = _boxWidth;
var height = _boxHeight;
//update the coordinates of this box into the matrix, for later calculations
oNode.Attributes["X"].InnerText = startX.ToString();
oNode.Attributes["Y"].InnerText = startY.ToString();
//update the image size
if (_imgWidth < (startX + width + _margin))
{
_imgWidth = startX + width + _margin;
}
if (_imgHeight < (startY + height + _margin))
{
_imgHeight = startY + height + _margin;
}
}
/************************************************************************************************************************
* The box position is affected by:
* 1. The previous sibling (box on the same level)
* 2. The positions of it's children
* 3. The position of it's uncle (parents' previous sibling)/ cousins (parents' previous sibling children)
* What determines the position is the farthest x of all the above. If all/some of the above have no value, the margin
* becomes the dtermining factor.
* **********************************************************************************************************************
*/
private int GetXPosByPreviousSibling(XmlNode currentNode)
{
var result = -1;
var x = -1;
var prevSibling = currentNode.PreviousSibling;
if (prevSibling != null)
{
if (prevSibling.HasChildNodes)
{
//Result = Convert.ToInt32(PrevSibling.LastChild.Attributes["X"].InnerText ) + _BoxWidth + _HorizontalSpace;
//need to loop through all children for all generations of previous sibling
x = Convert.ToInt32(GetMaxXOfDescendants(prevSibling.LastChild));
result = x + _boxWidth + _horizontalSpace;
}
else
{
result = Convert.ToInt32(prevSibling.Attributes["X"].InnerText) + _boxWidth + _horizontalSpace;
}
}
return result;
}
private int GetXPosByOwnChildren(XmlNode currentNode)
{
var result = -1;
if (currentNode.HasChildNodes)
{
var lastChildX = Convert.ToInt32(currentNode.LastChild.Attributes["X"].InnerText);
var firstChildX = Convert.ToInt32(currentNode.FirstChild.Attributes["X"].InnerText);
result = (((lastChildX + _boxWidth) - firstChildX) / 2) - (_boxWidth / 2) + firstChildX;
}
return result;
}
private int GetXPosByParentPreviousSibling(XmlNode currentNode)
{
var result = -1;
var x = -1;
var parentPrevSibling = currentNode.ParentNode.PreviousSibling;
if (parentPrevSibling != null)
{
if (parentPrevSibling.HasChildNodes)
{
//X = Convert.ToInt32(ParentPrevSibling.LastChild.Attributes["X"].InnerText);
x = GetMaxXOfDescendants(parentPrevSibling.LastChild);
result = x + _boxWidth + _horizontalSpace;
}
else
{
x = Convert.ToInt32(parentPrevSibling.Attributes["X"].InnerText);
result = x + _boxWidth + _horizontalSpace;
}
}
else //ParentPrevSibling == null
{
if (currentNode.ParentNode.Name != "#document")
{
result = GetXPosByParentPreviousSibling(currentNode.ParentNode);
}
}
return result;
}
/// <summary>
/// Get the maximum x of the lowest child on the current tree of nodes
/// Recursion does not work here, so we'll use a loop to climb down the tree
/// Recursion is not a solution because we need to return the value of the last leaf of the tree.
/// That would require managing a global variable.
/// </summary>
/// <param name="currentNode"></param>
/// <returns></returns>
private int GetMaxXOfDescendants(XmlNode currentNode)
{
var result = -1;
while (currentNode.HasChildNodes)
{
currentNode = currentNode.LastChild;
}
result = Convert.ToInt32(currentNode.Attributes["X"].InnerText);
return result;
//int Result = -1;
//if (CurrentNode.HasChildNodes)
//{
// GetMaxXOfDescendants(CurrentNode.LastChild);
//}
//else
//{
// Result = Convert.ToInt32(CurrentNode.Attributes["X"].InnerText);
//}
//return Result;
}
/// <summary>
/// create an xml node based on supplied data
/// </summary>
/// <returns></returns>
private XmlNode GetXmlNode(string nodeId, string nodeDescription, string nodeNote, Color backColor, Color foreColor)
{
//build the node
XmlNode resultNode = _nodeTree.CreateElement("Node");
var attNodeId = _nodeTree.CreateAttribute("nodeID");
var attNodeDescription = _nodeTree.CreateAttribute("nodeDescription");
var attNodeNote = _nodeTree.CreateAttribute("nodeNote");
var attStartX = _nodeTree.CreateAttribute("X");
var attStartY = _nodeTree.CreateAttribute("Y");
var attBackColor = _nodeTree.CreateAttribute("nodeBackColor");
var attForeColor = _nodeTree.CreateAttribute("nodeForeColor");
//set the values of what we know
attNodeId.InnerText = nodeId;
attNodeDescription.InnerText = nodeDescription;
attNodeNote.InnerText = nodeNote;
attStartX.InnerText = "0";
attStartY.InnerText = "0";
attBackColor.InnerText = backColor.ToArgb().ToString();
attForeColor.InnerText = foreColor.ToArgb().ToString();
resultNode.Attributes.Append(attNodeId);
resultNode.Attributes.Append(attNodeDescription);
resultNode.Attributes.Append(attNodeNote);
resultNode.Attributes.Append(attStartX);
resultNode.Attributes.Append(attStartY);
resultNode.Attributes.Append(attBackColor);
resultNode.Attributes.Append(attForeColor);
return resultNode;
}
/// <summary>
/// Draws the actual chart image.
/// </summary>
private void DrawChart(XmlNode oNode)
{
// Create font and brush.
var drawFont = new Font("verdana", _fontSize);
var drawBrush = new SolidBrush(Color.FromArgb(Convert.ToInt32(oNode.Attributes["nodeForeColor"].Value)));
var boxPen = new Pen(_lineColor, _lineWidth);
var drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Center;
//find children
foreach (XmlNode childNode in oNode.ChildNodes)
{
DrawChart(childNode);
}
var currentRectangle = GetRectangleFromNode(oNode);
_gr.DrawRectangle(boxPen, currentRectangle);
_gr.FillRectangle(new SolidBrush(Color.FromArgb(Convert.ToInt32(oNode.Attributes["nodeBackColor"].Value))), currentRectangle);
// Create string to draw.
var drawString = Environment.NewLine + oNode.Attributes["nodeNote"].InnerText;// +
//Environment.NewLine +
// oNode.Attributes["nodeDescription"].InnerText;
// Draw string to screen.
_gr.DrawString(drawString, drawFont, drawBrush, currentRectangle, drawFormat);
//draw connecting lines
if (oNode.ParentNode.Name != "#document")
{
//all but the top box should have lines growing out of their top
_gr.DrawLine(boxPen, currentRectangle.Left + (_boxWidth / 2),
currentRectangle.Top,
currentRectangle.Left + (_boxWidth / 2),
currentRectangle.Top - (_verticalSpace / 2));
}
if (oNode.HasChildNodes)
{
//all nodes which have nodes should have lines coming from bottom down
_gr.DrawLine(boxPen, currentRectangle.Left + (_boxWidth / 2),
currentRectangle.Top + _boxHeight,
currentRectangle.Left + (_boxWidth / 2),
currentRectangle.Top + _boxHeight + (_verticalSpace / 2));
}
if (oNode.PreviousSibling != null)
{
//the prev node has the same boss - connect the 2 nodes
_gr.DrawLine(boxPen, GetRectangleFromNode(oNode.PreviousSibling).Left + (_boxWidth / 2) - (_lineWidth / 2),
GetRectangleFromNode(oNode.PreviousSibling).Top - (_verticalSpace / 2),
currentRectangle.Left + (_boxWidth / 2) + (_lineWidth / 2),
currentRectangle.Top - (_verticalSpace / 2));
}
}
/// <summary>
/// After resizing the image, all positions of the rectanlges need to be
/// recalculated too.
/// </summary>
/// <param name="ActualWidth"></param>
/// <param name="ActualHeight"></param>
private void CalculateImageMapData()
{
var x = 0;
var newX = 0;
var y = 0;
var newY = 0;
foreach (XmlNode oNode in _nodeTree.SelectNodes("//Node"))
{
//go through all nodes and resize the coordinates
x = Convert.ToInt32(oNode.Attributes["X"].InnerText);
y = Convert.ToInt32(oNode.Attributes["Y"].InnerText);
newX = (int)(x * _percentageChangeX);
newY = (int)(y * _percentageChangeY);
oNode.Attributes["X"].InnerText = newX.ToString();
oNode.Attributes["Y"].InnerText = newY.ToString();
}
}
/// <summary>
/// used for testing purposes, to see if overlap exists between at least 2 boxes.
/// </summary>
/// <returns></returns>
private bool OverlapExists()
{
var listOfRectangles = new List<Rectangle>(); //the list of all objects
int x;
int y;
Rectangle currentRect;
foreach (XmlNode oNode in _nodeTree.SelectNodes("//Node"))
{
//go through all nodes and resize the coordinates
x = Convert.ToInt32(oNode.Attributes["X"].InnerText);
y = Convert.ToInt32(oNode.Attributes["Y"].InnerText);
currentRect = new Rectangle(x, y, _boxWidth, _boxHeight);
//before adding the node we check if the space it is supposed to occupy is already occupied.
foreach (var rect in listOfRectangles)
{
if (currentRect.IntersectsWith(rect))
{
//problem
return true;
}
}
listOfRectangles.Add(currentRect);
}
return false;
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Data;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class SelectingItemsControlTests
{
[Fact]
public void SelectedIndex_Should_Initially_Be_Minus_1()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Item_IsSelected_Should_Initially_Be_False()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
Assert.False(items[0].IsSelected);
Assert.False(items[1].IsSelected);
}
[Fact]
public void Setting_SelectedItem_Should_Set_Item_IsSelected_True()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItem = items[1];
Assert.False(items[0].IsSelected);
Assert.True(items[1].IsSelected);
}
[Fact]
public void Setting_SelectedItem_Before_ApplyTemplate_Should_Set_Item_IsSelected_True()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.SelectedItem = items[1];
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
Assert.False(items[0].IsSelected);
Assert.True(items[1].IsSelected);
}
[Fact]
public void Setting_SelectedIndex_Before_ApplyTemplate_Should_Set_Item_IsSelected_True()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.SelectedIndex = 1;
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
Assert.False(items[0].IsSelected);
Assert.True(items[1].IsSelected);
}
[Fact]
public void Setting_SelectedItem_Should_Set_SelectedIndex()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItem = items[1];
Assert.Equal(items[1], target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
}
[Fact]
public void Setting_SelectedItem_To_Not_Present_Item_Should_Clear_Selection()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItem = items[1];
Assert.Equal(items[1], target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
target.SelectedItem = new Item();
Assert.Null(target.SelectedItem);
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Setting_SelectedIndex_Should_Set_SelectedItem()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
Assert.Equal(items[1], target.SelectedItem);
}
[Fact]
public void Setting_SelectedIndex_Out_Of_Bounds_Should_Clear_Selection()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 2;
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Setting_SelectedItem_To_Non_Existent_Item_Should_Clear_Selection()
{
var target = new SelectingItemsControl
{
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItem = new Item();
Assert.Equal(-1, target.SelectedIndex);
Assert.Null(target.SelectedItem);
}
[Fact]
public void Adding_Selected_Item_Should_Update_Selection()
{
var items = new AvaloniaList<Item>(new[]
{
new Item(),
new Item(),
});
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
items.Add(new Item { IsSelected = true });
Assert.Equal(2, target.SelectedIndex);
Assert.Equal(items[2], target.SelectedItem);
}
[Fact]
public void Setting_Items_To_Null_Should_Clear_Selection()
{
var items = new AvaloniaList<Item>
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
Assert.Equal(items[1], target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
target.Items = null;
Assert.Null(target.SelectedItem);
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Removing_Selected_Item_Should_Clear_Selection()
{
var items = new AvaloniaList<Item>
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
Assert.Equal(items[1], target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
items.RemoveAt(1);
Assert.Null(target.SelectedItem);
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Resetting_Items_Collection_Should_Clear_Selection()
{
// Need to use ObservableCollection here as AvaloniaList signals a Clear as an
// add + remove.
var items = new ObservableCollection<Item>
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
Assert.Equal(items[1], target.SelectedItem);
Assert.Equal(1, target.SelectedIndex);
items.Clear();
Assert.Null(target.SelectedItem);
Assert.Equal(-1, target.SelectedIndex);
}
[Fact]
public void Raising_IsSelectedChanged_On_Item_Should_Update_Selection()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItem = items[1];
Assert.False(items[0].IsSelected);
Assert.True(items[1].IsSelected);
items[0].IsSelected = true;
items[0].RaiseEvent(new RoutedEventArgs(SelectingItemsControl.IsSelectedChangedEvent));
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(items[0], target.SelectedItem);
Assert.True(items[0].IsSelected);
Assert.False(items[1].IsSelected);
}
[Fact]
public void Clearing_IsSelected_And_Raising_IsSelectedChanged_On_Item_Should_Update_Selection()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItem = items[1];
Assert.False(items[0].IsSelected);
Assert.True(items[1].IsSelected);
items[1].IsSelected = false;
items[1].RaiseEvent(new RoutedEventArgs(SelectingItemsControl.IsSelectedChangedEvent));
Assert.Equal(-1, target.SelectedIndex);
Assert.Null(target.SelectedItem);
}
[Fact]
public void Raising_IsSelectedChanged_On_Someone_Elses_Item_Should_Not_Update_Selection()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItem = items[1];
var notChild = new Item
{
IsSelected = true,
};
target.RaiseEvent(new RoutedEventArgs
{
RoutedEvent = SelectingItemsControl.IsSelectedChangedEvent,
Source = notChild,
});
Assert.Equal(target.SelectedItem, items[1]);
}
[Fact]
public void Setting_SelectedIndex_Should_Raise_SelectionChanged_Event()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
};
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Same(items[1], e.AddedItems.Cast<object>().Single());
Assert.Empty(e.RemovedItems);
called = true;
};
target.SelectedIndex = 1;
Assert.True(called);
}
[Fact]
public void Clearing_SelectedIndex_Should_Raise_SelectionChanged_Event()
{
var items = new[]
{
new Item(),
new Item(),
};
var target = new SelectingItemsControl
{
Items = items,
Template = Template(),
SelectedIndex = 1,
};
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Same(items[1], e.RemovedItems.Cast<object>().Single());
Assert.Empty(e.AddedItems);
called = true;
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedIndex = -1;
Assert.True(called);
}
[Fact]
public void Order_Of_Setting_Items_And_SelectedIndex_During_Initialization_Should_Not_Matter()
{
var items = new[] { "Foo", "Bar" };
var target = new SelectingItemsControl();
((ISupportInitialize)target).BeginInit();
target.SelectedIndex = 1;
target.Items = items;
((ISupportInitialize)target).EndInit();
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
}
[Fact]
public void Order_Of_Setting_Items_And_SelectedItem_During_Initialization_Should_Not_Matter()
{
var items = new[] { "Foo", "Bar" };
var target = new SelectingItemsControl();
((ISupportInitialize)target).BeginInit();
target.SelectedItem = "Bar";
target.Items = items;
((ISupportInitialize)target).EndInit();
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
}
[Fact]
public void Changing_DataContext_Should_Not_Clear_Nested_ViewModel_SelectedItem()
{
var items = new[]
{
new Item(),
new Item(),
};
var vm = new MasterViewModel
{
Child = new ChildViewModel
{
Items = items,
SelectedItem = items[1],
}
};
var target = new SelectingItemsControl { DataContext = vm };
var itemsBinding = new Binding("Child.Items");
var selectedBinding = new Binding("Child.SelectedItem");
target.Bind(SelectingItemsControl.ItemsProperty, itemsBinding);
target.Bind(SelectingItemsControl.SelectedItemProperty, selectedBinding);
Assert.Equal(1, target.SelectedIndex);
Assert.Same(vm.Child.SelectedItem, target.SelectedItem);
items = new[]
{
new Item { Value = "Item1" },
new Item { Value = "Item2" },
new Item { Value = "Item3" },
};
vm = new MasterViewModel
{
Child = new ChildViewModel
{
Items = items,
SelectedItem = items[2],
}
};
target.DataContext = vm;
Assert.Equal(2, target.SelectedIndex);
Assert.Same(vm.Child.SelectedItem, target.SelectedItem);
}
[Fact]
public void Nested_ListBox_Does_Not_Change_Parent_SelectedIndex()
{
SelectingItemsControl nested;
var root = new SelectingItemsControl
{
Template = Template(),
Items = new IControl[]
{
new Border(),
nested = new ListBox
{
Template = Template(),
Items = new[] { "foo", "bar" },
SelectedIndex = 1,
}
},
SelectedIndex = 0,
};
root.ApplyTemplate();
root.Presenter.ApplyTemplate();
nested.ApplyTemplate();
nested.Presenter.ApplyTemplate();
Assert.Equal(0, root.SelectedIndex);
Assert.Equal(1, nested.SelectedIndex);
nested.SelectedIndex = 0;
Assert.Equal(0, root.SelectedIndex);
}
[Fact]
public void Setting_SelectedItem_With_Pointer_Should_Set_TabOnceActiveElement()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz " },
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.Presenter.Panel.Children[1].RaiseEvent(new PointerPressedEventArgs
{
RoutedEvent = InputElement.PointerPressedEvent,
MouseButton = MouseButton.Left,
});
var panel = target.Presenter.Panel;
Assert.Equal(
KeyboardNavigation.GetTabOnceActiveElement((InputElement)panel),
panel.Children[1]);
}
[Fact]
public void Removing_SelectedItem_Should_Clear_TabOnceActiveElement()
{
var items = new ObservableCollection<string>(new[] { "Foo", "Bar", "Baz " });
var target = new ListBox
{
Template = Template(),
Items = items,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.Presenter.Panel.Children[1].RaiseEvent(new PointerPressedEventArgs
{
RoutedEvent = InputElement.PointerPressedEvent,
MouseButton = MouseButton.Left,
});
items.RemoveAt(1);
var panel = target.Presenter.Panel;
Assert.Null(KeyboardNavigation.GetTabOnceActiveElement((InputElement)panel));
}
private FuncControlTemplate Template()
{
return new FuncControlTemplate<SelectingItemsControl>(control =>
new ItemsPresenter
{
Name = "itemsPresenter",
[~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty],
[~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty],
});
}
private class Item : Control, ISelectable
{
public string Value { get; set; }
public bool IsSelected { get; set; }
}
private class MasterViewModel : NotifyingBase
{
private ChildViewModel _child;
public ChildViewModel Child
{
get { return _child; }
set
{
_child = value;
RaisePropertyChanged();
}
}
}
private class ChildViewModel : NotifyingBase
{
public IList<Item> Items { get; set; }
public Item SelectedItem { get; set; }
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime
{
using System;
using System.Collections.Generic;
using System.Threading;
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.PrivatePrimitive, SupportsAsync = true, ReleaseMethod = "Dispatch")]
sealed class InputQueue<T> : IDisposable where T : class
{
static Action<object> completeOutstandingReadersCallback;
static Action<object> completeWaitersFalseCallback;
static Action<object> completeWaitersTrueCallback;
static Action<object> onDispatchCallback;
static Action<object> onInvokeDequeuedCallback;
QueueState queueState;
[Fx.Tag.SynchronizationObject(Blocking = false, Kind = Fx.Tag.SynchronizationKind.LockStatement)]
ItemQueue itemQueue;
[Fx.Tag.SynchronizationObject]
Queue<IQueueReader> readerQueue;
[Fx.Tag.SynchronizationObject]
List<IQueueWaiter> waiterList;
public InputQueue()
{
this.itemQueue = new ItemQueue();
this.readerQueue = new Queue<IQueueReader>();
this.waiterList = new List<IQueueWaiter>();
this.queueState = QueueState.Open;
}
public InputQueue(Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator)
: this()
{
Fx.Assert(asyncCallbackGenerator != null, "use default ctor if you don't have a generator");
AsyncCallbackGenerator = asyncCallbackGenerator;
}
public int PendingCount
{
get
{
lock (ThisLock)
{
return this.itemQueue.ItemCount;
}
}
}
// Users like ServiceModel can hook this abort ICommunicationObject or handle other non-IDisposable objects
public Action<T> DisposeItemCallback
{
get;
set;
}
// Users like ServiceModel can hook this to wrap the AsyncQueueReader callback functionality for tracing, etc
Func<Action<AsyncCallback, IAsyncResult>> AsyncCallbackGenerator
{
get;
set;
}
object ThisLock
{
get { return this.itemQueue; }
}
public IAsyncResult BeginDequeue(TimeSpan timeout, AsyncCallback callback, object state)
{
Item item = default(Item);
lock (ThisLock)
{
if (queueState == QueueState.Open)
{
if (itemQueue.HasAvailableItem)
{
item = itemQueue.DequeueAvailableItem();
}
else
{
AsyncQueueReader reader = new AsyncQueueReader(this, timeout, callback, state);
readerQueue.Enqueue(reader);
return reader;
}
}
else if (queueState == QueueState.Shutdown)
{
if (itemQueue.HasAvailableItem)
{
item = itemQueue.DequeueAvailableItem();
}
else if (itemQueue.HasAnyItem)
{
AsyncQueueReader reader = new AsyncQueueReader(this, timeout, callback, state);
readerQueue.Enqueue(reader);
return reader;
}
}
}
InvokeDequeuedCallback(item.DequeuedCallback);
return new CompletedAsyncResult<T>(item.GetValue(), callback, state);
}
public IAsyncResult BeginWaitForItem(TimeSpan timeout, AsyncCallback callback, object state)
{
lock (ThisLock)
{
if (queueState == QueueState.Open)
{
if (!itemQueue.HasAvailableItem)
{
AsyncQueueWaiter waiter = new AsyncQueueWaiter(timeout, callback, state);
waiterList.Add(waiter);
return waiter;
}
}
else if (queueState == QueueState.Shutdown)
{
if (!itemQueue.HasAvailableItem && itemQueue.HasAnyItem)
{
AsyncQueueWaiter waiter = new AsyncQueueWaiter(timeout, callback, state);
waiterList.Add(waiter);
return waiter;
}
}
}
return new CompletedAsyncResult<bool>(true, callback, state);
}
public void Close()
{
Dispose();
}
[Fx.Tag.Blocking(CancelMethod = "Close")]
public T Dequeue(TimeSpan timeout)
{
T value;
if (!this.Dequeue(timeout, out value))
{
throw Fx.Exception.AsError(new TimeoutException(InternalSR.TimeoutInputQueueDequeue(timeout)));
}
return value;
}
[Fx.Tag.Blocking(CancelMethod = "Close")]
public bool Dequeue(TimeSpan timeout, out T value)
{
WaitQueueReader reader = null;
Item item = new Item();
lock (ThisLock)
{
if (queueState == QueueState.Open)
{
if (itemQueue.HasAvailableItem)
{
item = itemQueue.DequeueAvailableItem();
}
else
{
reader = new WaitQueueReader(this);
readerQueue.Enqueue(reader);
}
}
else if (queueState == QueueState.Shutdown)
{
if (itemQueue.HasAvailableItem)
{
item = itemQueue.DequeueAvailableItem();
}
else if (itemQueue.HasAnyItem)
{
reader = new WaitQueueReader(this);
readerQueue.Enqueue(reader);
}
else
{
value = default(T);
return true;
}
}
else // queueState == QueueState.Closed
{
value = default(T);
return true;
}
}
if (reader != null)
{
return reader.Wait(timeout, out value);
}
else
{
InvokeDequeuedCallback(item.DequeuedCallback);
value = item.GetValue();
return true;
}
}
public void Dispatch()
{
IQueueReader reader = null;
Item item = new Item();
IQueueReader[] outstandingReaders = null;
IQueueWaiter[] waiters = null;
bool itemAvailable = true;
lock (ThisLock)
{
itemAvailable = !((queueState == QueueState.Closed) || (queueState == QueueState.Shutdown));
this.GetWaiters(out waiters);
if (queueState != QueueState.Closed)
{
itemQueue.MakePendingItemAvailable();
if (readerQueue.Count > 0)
{
item = itemQueue.DequeueAvailableItem();
reader = readerQueue.Dequeue();
if (queueState == QueueState.Shutdown && readerQueue.Count > 0 && itemQueue.ItemCount == 0)
{
outstandingReaders = new IQueueReader[readerQueue.Count];
readerQueue.CopyTo(outstandingReaders, 0);
readerQueue.Clear();
itemAvailable = false;
}
}
}
}
if (outstandingReaders != null)
{
if (completeOutstandingReadersCallback == null)
{
completeOutstandingReadersCallback = new Action<object>(CompleteOutstandingReadersCallback);
}
ActionItem.Schedule(completeOutstandingReadersCallback, outstandingReaders);
}
if (waiters != null)
{
CompleteWaitersLater(itemAvailable, waiters);
}
if (reader != null)
{
InvokeDequeuedCallback(item.DequeuedCallback);
reader.Set(item);
}
}
[Fx.Tag.Blocking(CancelMethod = "Close", Conditional = "!result.IsCompleted")]
public bool EndDequeue(IAsyncResult result, out T value)
{
CompletedAsyncResult<T> typedResult = result as CompletedAsyncResult<T>;
if (typedResult != null)
{
value = CompletedAsyncResult<T>.End(result);
return true;
}
return AsyncQueueReader.End(result, out value);
}
[Fx.Tag.Blocking(CancelMethod = "Close", Conditional = "!result.IsCompleted")]
public T EndDequeue(IAsyncResult result)
{
T value;
if (!this.EndDequeue(result, out value))
{
throw Fx.Exception.AsError(new TimeoutException());
}
return value;
}
[Fx.Tag.Blocking(CancelMethod = "Dispatch", Conditional = "!result.IsCompleted")]
public bool EndWaitForItem(IAsyncResult result)
{
CompletedAsyncResult<bool> typedResult = result as CompletedAsyncResult<bool>;
if (typedResult != null)
{
return CompletedAsyncResult<bool>.End(result);
}
return AsyncQueueWaiter.End(result);
}
public void EnqueueAndDispatch(T item)
{
EnqueueAndDispatch(item, null);
}
// dequeuedCallback is called as an item is dequeued from the InputQueue. The
// InputQueue lock is not held during the callback. However, the user code will
// not be notified of the item being available until the callback returns. If you
// are not sure if the callback will block for a long time, then first call
// IOThreadScheduler.ScheduleCallback to get to a "safe" thread.
public void EnqueueAndDispatch(T item, Action dequeuedCallback)
{
EnqueueAndDispatch(item, dequeuedCallback, true);
}
public void EnqueueAndDispatch(Exception exception, Action dequeuedCallback, bool canDispatchOnThisThread)
{
Fx.Assert(exception != null, "EnqueueAndDispatch: exception parameter should not be null");
EnqueueAndDispatch(new Item(exception, dequeuedCallback), canDispatchOnThisThread);
}
public void EnqueueAndDispatch(T item, Action dequeuedCallback, bool canDispatchOnThisThread)
{
Fx.Assert(item != null, "EnqueueAndDispatch: item parameter should not be null");
EnqueueAndDispatch(new Item(item, dequeuedCallback), canDispatchOnThisThread);
}
public bool EnqueueWithoutDispatch(T item, Action dequeuedCallback)
{
Fx.Assert(item != null, "EnqueueWithoutDispatch: item parameter should not be null");
return EnqueueWithoutDispatch(new Item(item, dequeuedCallback));
}
public bool EnqueueWithoutDispatch(Exception exception, Action dequeuedCallback)
{
Fx.Assert(exception != null, "EnqueueWithoutDispatch: exception parameter should not be null");
return EnqueueWithoutDispatch(new Item(exception, dequeuedCallback));
}
public void Shutdown()
{
this.Shutdown(null);
}
// Don't let any more items in. Differs from Close in that we keep around
// existing items in our itemQueue for possible future calls to Dequeue
public void Shutdown(Func<Exception> pendingExceptionGenerator)
{
IQueueReader[] outstandingReaders = null;
lock (ThisLock)
{
if (queueState == QueueState.Shutdown)
{
return;
}
if (queueState == QueueState.Closed)
{
return;
}
this.queueState = QueueState.Shutdown;
if (readerQueue.Count > 0 && this.itemQueue.ItemCount == 0)
{
outstandingReaders = new IQueueReader[readerQueue.Count];
readerQueue.CopyTo(outstandingReaders, 0);
readerQueue.Clear();
}
}
if (outstandingReaders != null)
{
for (int i = 0; i < outstandingReaders.Length; i++)
{
Exception exception = (pendingExceptionGenerator != null) ? pendingExceptionGenerator() : null;
outstandingReaders[i].Set(new Item(exception, null));
}
}
}
[Fx.Tag.Blocking(CancelMethod = "Dispatch")]
public bool WaitForItem(TimeSpan timeout)
{
WaitQueueWaiter waiter = null;
bool itemAvailable = false;
lock (ThisLock)
{
if (queueState == QueueState.Open)
{
if (itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else
{
waiter = new WaitQueueWaiter();
waiterList.Add(waiter);
}
}
else if (queueState == QueueState.Shutdown)
{
if (itemQueue.HasAvailableItem)
{
itemAvailable = true;
}
else if (itemQueue.HasAnyItem)
{
waiter = new WaitQueueWaiter();
waiterList.Add(waiter);
}
else
{
return true;
}
}
else // queueState == QueueState.Closed
{
return true;
}
}
if (waiter != null)
{
return waiter.Wait(timeout);
}
else
{
return itemAvailable;
}
}
public void Dispose()
{
bool dispose = false;
lock (ThisLock)
{
if (queueState != QueueState.Closed)
{
queueState = QueueState.Closed;
dispose = true;
}
}
if (dispose)
{
while (readerQueue.Count > 0)
{
IQueueReader reader = readerQueue.Dequeue();
reader.Set(default(Item));
}
while (itemQueue.HasAnyItem)
{
Item item = itemQueue.DequeueAnyItem();
DisposeItem(item);
InvokeDequeuedCallback(item.DequeuedCallback);
}
}
}
void DisposeItem(Item item)
{
T value = item.Value;
if (value != null)
{
if (value is IDisposable)
{
((IDisposable)value).Dispose();
}
else
{
Action<T> disposeItemCallback = this.DisposeItemCallback;
if (disposeItemCallback != null)
{
disposeItemCallback(value);
}
}
}
}
static void CompleteOutstandingReadersCallback(object state)
{
IQueueReader[] outstandingReaders = (IQueueReader[])state;
for (int i = 0; i < outstandingReaders.Length; i++)
{
outstandingReaders[i].Set(default(Item));
}
}
static void CompleteWaiters(bool itemAvailable, IQueueWaiter[] waiters)
{
for (int i = 0; i < waiters.Length; i++)
{
waiters[i].Set(itemAvailable);
}
}
static void CompleteWaitersFalseCallback(object state)
{
CompleteWaiters(false, (IQueueWaiter[])state);
}
static void CompleteWaitersLater(bool itemAvailable, IQueueWaiter[] waiters)
{
if (itemAvailable)
{
if (completeWaitersTrueCallback == null)
{
completeWaitersTrueCallback = new Action<object>(CompleteWaitersTrueCallback);
}
ActionItem.Schedule(completeWaitersTrueCallback, waiters);
}
else
{
if (completeWaitersFalseCallback == null)
{
completeWaitersFalseCallback = new Action<object>(CompleteWaitersFalseCallback);
}
ActionItem.Schedule(completeWaitersFalseCallback, waiters);
}
}
static void CompleteWaitersTrueCallback(object state)
{
CompleteWaiters(true, (IQueueWaiter[])state);
}
static void InvokeDequeuedCallback(Action dequeuedCallback)
{
if (dequeuedCallback != null)
{
dequeuedCallback();
}
}
static void InvokeDequeuedCallbackLater(Action dequeuedCallback)
{
if (dequeuedCallback != null)
{
if (onInvokeDequeuedCallback == null)
{
onInvokeDequeuedCallback = new Action<object>(OnInvokeDequeuedCallback);
}
ActionItem.Schedule(onInvokeDequeuedCallback, dequeuedCallback);
}
}
static void OnDispatchCallback(object state)
{
((InputQueue<T>)state).Dispatch();
}
static void OnInvokeDequeuedCallback(object state)
{
Fx.Assert(state != null, "InputQueue.OnInvokeDequeuedCallback: (state != null)");
Action dequeuedCallback = (Action)state;
dequeuedCallback();
}
void EnqueueAndDispatch(Item item, bool canDispatchOnThisThread)
{
bool disposeItem = false;
IQueueReader reader = null;
bool dispatchLater = false;
IQueueWaiter[] waiters = null;
bool itemAvailable = true;
lock (ThisLock)
{
itemAvailable = !((queueState == QueueState.Closed) || (queueState == QueueState.Shutdown));
this.GetWaiters(out waiters);
if (queueState == QueueState.Open)
{
if (canDispatchOnThisThread)
{
if (readerQueue.Count == 0)
{
itemQueue.EnqueueAvailableItem(item);
}
else
{
reader = readerQueue.Dequeue();
}
}
else
{
if (readerQueue.Count == 0)
{
itemQueue.EnqueueAvailableItem(item);
}
else
{
itemQueue.EnqueuePendingItem(item);
dispatchLater = true;
}
}
}
else // queueState == QueueState.Closed || queueState == QueueState.Shutdown
{
disposeItem = true;
}
}
if (waiters != null)
{
if (canDispatchOnThisThread)
{
CompleteWaiters(itemAvailable, waiters);
}
else
{
CompleteWaitersLater(itemAvailable, waiters);
}
}
if (reader != null)
{
InvokeDequeuedCallback(item.DequeuedCallback);
reader.Set(item);
}
if (dispatchLater)
{
if (onDispatchCallback == null)
{
onDispatchCallback = new Action<object>(OnDispatchCallback);
}
ActionItem.Schedule(onDispatchCallback, this);
}
else if (disposeItem)
{
InvokeDequeuedCallback(item.DequeuedCallback);
DisposeItem(item);
}
}
// This will not block, however, Dispatch() must be called later if this function
// returns true.
bool EnqueueWithoutDispatch(Item item)
{
lock (ThisLock)
{
// Open
if (queueState != QueueState.Closed && queueState != QueueState.Shutdown)
{
if (readerQueue.Count == 0 && waiterList.Count == 0)
{
itemQueue.EnqueueAvailableItem(item);
return false;
}
else
{
itemQueue.EnqueuePendingItem(item);
return true;
}
}
}
DisposeItem(item);
InvokeDequeuedCallbackLater(item.DequeuedCallback);
return false;
}
void GetWaiters(out IQueueWaiter[] waiters)
{
if (waiterList.Count > 0)
{
waiters = waiterList.ToArray();
waiterList.Clear();
}
else
{
waiters = null;
}
}
// Used for timeouts. The InputQueue must remove readers from its reader queue to prevent
// dispatching items to timed out readers.
bool RemoveReader(IQueueReader reader)
{
Fx.Assert(reader != null, "InputQueue.RemoveReader: (reader != null)");
lock (ThisLock)
{
if (queueState == QueueState.Open || queueState == QueueState.Shutdown)
{
bool removed = false;
for (int i = readerQueue.Count; i > 0; i--)
{
IQueueReader temp = readerQueue.Dequeue();
if (object.ReferenceEquals(temp, reader))
{
removed = true;
}
else
{
readerQueue.Enqueue(temp);
}
}
return removed;
}
}
return false;
}
enum QueueState
{
Open,
Shutdown,
Closed
}
interface IQueueReader
{
void Set(Item item);
}
interface IQueueWaiter
{
void Set(bool itemAvailable);
}
struct Item
{
Action dequeuedCallback;
Exception exception;
T value;
public Item(T value, Action dequeuedCallback)
: this(value, null, dequeuedCallback)
{
}
public Item(Exception exception, Action dequeuedCallback)
: this(null, exception, dequeuedCallback)
{
}
Item(T value, Exception exception, Action dequeuedCallback)
{
this.value = value;
this.exception = exception;
this.dequeuedCallback = dequeuedCallback;
}
public Action DequeuedCallback
{
get { return this.dequeuedCallback; }
}
public Exception Exception
{
get { return this.exception; }
}
public T Value
{
get { return this.value; }
}
public T GetValue()
{
if (this.exception != null)
{
throw Fx.Exception.AsError(this.exception);
}
return this.value;
}
}
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.AsyncResult, SupportsAsync = true, ReleaseMethod = "Set")]
class AsyncQueueReader : AsyncResult, IQueueReader
{
static Action<object> timerCallback = new Action<object>(AsyncQueueReader.TimerCallback);
bool expired;
InputQueue<T> inputQueue;
T item;
IOThreadTimer timer;
public AsyncQueueReader(InputQueue<T> inputQueue, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
if (inputQueue.AsyncCallbackGenerator != null)
{
base.VirtualCallback = inputQueue.AsyncCallbackGenerator();
}
this.inputQueue = inputQueue;
if (timeout != TimeSpan.MaxValue)
{
this.timer = new IOThreadTimer(timerCallback, this, false);
this.timer.Set(timeout);
}
}
[Fx.Tag.Blocking(Conditional = "!result.IsCompleted", CancelMethod = "Set")]
public static bool End(IAsyncResult result, out T value)
{
AsyncQueueReader readerResult = AsyncResult.End<AsyncQueueReader>(result);
if (readerResult.expired)
{
value = default(T);
return false;
}
else
{
value = readerResult.item;
return true;
}
}
public void Set(Item item)
{
this.item = item.Value;
if (this.timer != null)
{
this.timer.Cancel();
}
Complete(false, item.Exception);
}
static void TimerCallback(object state)
{
AsyncQueueReader thisPtr = (AsyncQueueReader)state;
if (thisPtr.inputQueue.RemoveReader(thisPtr))
{
thisPtr.expired = true;
thisPtr.Complete(false);
}
}
}
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.AsyncResult, SupportsAsync = true, ReleaseMethod = "Set")]
class AsyncQueueWaiter : AsyncResult, IQueueWaiter
{
static Action<object> timerCallback = new Action<object>(AsyncQueueWaiter.TimerCallback);
bool itemAvailable;
[Fx.Tag.SynchronizationObject(Blocking = false)]
object thisLock = new object();
IOThreadTimer timer;
public AsyncQueueWaiter(TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
{
if (timeout != TimeSpan.MaxValue)
{
this.timer = new IOThreadTimer(timerCallback, this, false);
this.timer.Set(timeout);
}
}
object ThisLock
{
get
{
return this.thisLock;
}
}
[Fx.Tag.Blocking(Conditional = "!result.IsCompleted", CancelMethod = "Set")]
public static bool End(IAsyncResult result)
{
AsyncQueueWaiter waiterResult = AsyncResult.End<AsyncQueueWaiter>(result);
return waiterResult.itemAvailable;
}
public void Set(bool itemAvailable)
{
bool timely;
lock (ThisLock)
{
timely = (this.timer == null) || this.timer.Cancel();
this.itemAvailable = itemAvailable;
}
if (timely)
{
Complete(false);
}
}
static void TimerCallback(object state)
{
AsyncQueueWaiter thisPtr = (AsyncQueueWaiter)state;
thisPtr.Complete(false);
}
}
class ItemQueue
{
int head;
Item[] items;
int pendingCount;
int totalCount;
public ItemQueue()
{
this.items = new Item[1];
}
public bool HasAnyItem
{
get { return this.totalCount > 0; }
}
public bool HasAvailableItem
{
get { return this.totalCount > this.pendingCount; }
}
public int ItemCount
{
get { return this.totalCount; }
}
public Item DequeueAnyItem()
{
if (this.pendingCount == this.totalCount)
{
this.pendingCount--;
}
return DequeueItemCore();
}
public Item DequeueAvailableItem()
{
Fx.AssertAndThrow(this.totalCount != this.pendingCount, "ItemQueue does not contain any available items");
return DequeueItemCore();
}
public void EnqueueAvailableItem(Item item)
{
EnqueueItemCore(item);
}
public void EnqueuePendingItem(Item item)
{
EnqueueItemCore(item);
this.pendingCount++;
}
public void MakePendingItemAvailable()
{
Fx.AssertAndThrow(this.pendingCount != 0, "ItemQueue does not contain any pending items");
this.pendingCount--;
}
Item DequeueItemCore()
{
Fx.AssertAndThrow(totalCount != 0, "ItemQueue does not contain any items");
Item item = this.items[this.head];
this.items[this.head] = new Item();
this.totalCount--;
this.head = (this.head + 1) % this.items.Length;
return item;
}
void EnqueueItemCore(Item item)
{
if (this.totalCount == this.items.Length)
{
Item[] newItems = new Item[this.items.Length * 2];
for (int i = 0; i < this.totalCount; i++)
{
newItems[i] = this.items[(head + i) % this.items.Length];
}
this.head = 0;
this.items = newItems;
}
int tail = (this.head + this.totalCount) % this.items.Length;
this.items[tail] = item;
this.totalCount++;
}
}
[Fx.Tag.SynchronizationObject(Blocking = false)]
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, ReleaseMethod = "Set")]
class WaitQueueReader : IQueueReader
{
Exception exception;
InputQueue<T> inputQueue;
T item;
[Fx.Tag.SynchronizationObject]
ManualResetEvent waitEvent;
public WaitQueueReader(InputQueue<T> inputQueue)
{
this.inputQueue = inputQueue;
waitEvent = new ManualResetEvent(false);
}
public void Set(Item item)
{
lock (this)
{
Fx.Assert(this.item == null, "InputQueue.WaitQueueReader.Set: (this.item == null)");
Fx.Assert(this.exception == null, "InputQueue.WaitQueueReader.Set: (this.exception == null)");
this.exception = item.Exception;
this.item = item.Value;
waitEvent.Set();
}
}
[Fx.Tag.Blocking(CancelMethod = "Set")]
public bool Wait(TimeSpan timeout, out T value)
{
bool isSafeToClose = false;
try
{
if (!TimeoutHelper.WaitOne(waitEvent, timeout))
{
if (this.inputQueue.RemoveReader(this))
{
value = default(T);
isSafeToClose = true;
return false;
}
else
{
waitEvent.WaitOne();
}
}
isSafeToClose = true;
}
finally
{
if (isSafeToClose)
{
waitEvent.Close();
}
}
if (this.exception != null)
{
throw Fx.Exception.AsError(this.exception);
}
value = item;
return true;
}
}
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, ReleaseMethod = "Set")]
class WaitQueueWaiter : IQueueWaiter
{
bool itemAvailable;
[Fx.Tag.SynchronizationObject]
ManualResetEvent waitEvent;
public WaitQueueWaiter()
{
waitEvent = new ManualResetEvent(false);
}
public void Set(bool itemAvailable)
{
lock (this)
{
this.itemAvailable = itemAvailable;
waitEvent.Set();
}
}
[Fx.Tag.Blocking(CancelMethod = "Set")]
public bool Wait(TimeSpan timeout)
{
if (!TimeoutHelper.WaitOne(waitEvent, timeout))
{
return false;
}
return this.itemAvailable;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Salient.JsonClient;
using SOAPI2.Converters;
using SOAPI2.Model;
namespace SOAPI2
{
public partial class SoapiClient
{
public SoapiClient(string apiKey, string appId) // #TODO: uri from SMD target
: base(new Uri("https://api.stackexchange.com/2.0/"), new RequestController(TimeSpan.FromSeconds(0), 2, new RequestFactory(), new ErrorResponseDTOJsonExceptionFactory(), new ThrottledRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "data"), new ThrottledRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "trading"), new ThrottledRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "default")))
{
#if SILVERLIGHT
#if WINDOWS_PHONE
UserAgent = "SOAPI2.PHONE7."+ GetVersionNumber();
#else
UserAgent = "SOAPI2.SILVERLIGHT."+ GetVersionNumber();
#endif
#else
UserAgent = "SOAPI2." + GetVersionNumber();
#endif
_client = this;
_appId = appId;
_apiKey = apiKey;
this.Answers = new _Answers(this);
this.Badges = new _Badges(this);
this.Comments = new _Comments(this);
this.Events = new _Events(this);
this.Posts = new _Posts(this);
this.Privileges = new _Privileges(this);
this.Questions = new _Questions(this);
this.Revisions = new _Revisions(this);
this.Search = new _Search(this);
this.Suggested_Edits = new _Suggested_Edits(this);
this.Info = new _Info(this);
this.Tags = new _Tags(this);
this.Users = new _Users(this);
this.Access_Tokens = new _Access_Tokens(this);
this.Applications = new _Applications(this);
this.Errors = new _Errors(this);
this.Filters = new _Filters(this);
this.Inbox = new _Inbox(this);
this.Sites = new _Sites(this);
}
public SoapiClient(string apiKey, string appId,Uri uri, IRequestController requestController)
: base(uri, requestController)
{
#if SILVERLIGHT
#if WINDOWS_PHONE
UserAgent = "SOAPI2.PHONE7."+ GetVersionNumber();
#else
UserAgent = "SOAPI2.SILVERLIGHT."+ GetVersionNumber();
#endif
#else
UserAgent = "SOAPI2." + GetVersionNumber();
#endif
_client = this;
_appId = appId;
_apiKey = apiKey;
this.Answers = new _Answers(this);
this.Badges = new _Badges(this);
this.Comments = new _Comments(this);
this.Events = new _Events(this);
this.Posts = new _Posts(this);
this.Privileges = new _Privileges(this);
this.Questions = new _Questions(this);
this.Revisions = new _Revisions(this);
this.Search = new _Search(this);
this.Suggested_Edits = new _Suggested_Edits(this);
this.Info = new _Info(this);
this.Tags = new _Tags(this);
this.Users = new _Users(this);
this.Access_Tokens = new _Access_Tokens(this);
this.Applications = new _Applications(this);
this.Errors = new _Errors(this);
this.Filters = new _Filters(this);
this.Inbox = new _Inbox(this);
this.Sites = new _Sites(this);
}
public class _Answers
{
private SoapiClient _client;
public _Answers(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<AnswerClass> Answers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortAnswers? sort)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("answers", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AnswerClass> AnswersByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortAnswersByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("answers", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> AnswersByIdsComments(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortAnswersByIdsComments? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/comments?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("answers", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Answers Answers{get; private set;}
public class _Badges
{
private SoapiClient _client;
public _Badges(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<BadgeClass> Badges(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortBadges? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> BadgesByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortBadgesByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> BadgesName(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortBadgesName? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("/name?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> BadgesRecipients(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate)
{
string uriTemplate = _client.AppendApiKey("/recipients?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> BadgesByIdsRecipients(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/recipients?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> BadgesTags(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortBadgesTags? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("/tags?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("badges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Badges Badges{get; private set;}
public class _Comments
{
private SoapiClient _client;
public _Comments(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<CommentClass> Comments(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortComments? sort)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("comments", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> CommentsByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortCommentsByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("comments", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Comments Comments{get; private set;}
public class _Events
{
private SoapiClient _client;
public _Events(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<EventClass> Events(string site, int? page, int? pagesize, DateTimeOffset? since)
{
throw new NotImplementedException("Requires Authentication");
}
}
public _Events Events{get; private set;}
public class _Posts
{
private SoapiClient _client;
public _Posts(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<PostClass> Posts(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortPosts? sort)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<PostClass>>("posts", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<PostClass> PostsByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortPostsByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<PostClass>>("posts", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> PostsByIdsComments(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortPostsByIdsComments? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/comments?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("posts", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<RevisionClass> PostsByIdsRevisions(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/revisions?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<RevisionClass>>("posts", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<SuggestedEditClass> PostsByIdsSuggestedEdits(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortPostsByIdsSuggestedEdits? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/suggested-edits?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<SuggestedEditClass>>("posts", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Posts Posts{get; private set;}
public class _Privileges
{
private SoapiClient _client;
public _Privileges(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<PrivilegeClass> Privileges(string site, int? page, int? pagesize)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<PrivilegeClass>>("privileges", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Privileges Privileges{get; private set;}
public class _Questions
{
private SoapiClient _client;
public _Questions(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<QuestionClass> Questions(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestions? sort, string tagged)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AnswerClass> QuestionsByIdsAnswers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsByIdsAnswers? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/answers?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> QuestionsByIdsComments(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsByIdsComments? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/comments?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsByIdsLinked(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsByIdsLinked? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/linked?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsByIdsRelated(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsByIdsRelated? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/related?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionTimelineClass> QuestionsByIdsTimeline(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/timeline?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<QuestionTimelineClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsFeatured(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsFeatured? sort, string tagged)
{
string uriTemplate = _client.AppendApiKey("/featured?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsUnanswered(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsUnanswered? sort, string tagged)
{
string uriTemplate = _client.AppendApiKey("/unanswered?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> QuestionsNoAnswers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortQuestionsNoAnswers? sort, string tagged)
{
string uriTemplate = _client.AppendApiKey("/no-answers?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("questions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Questions Questions{get; private set;}
public class _Revisions
{
private SoapiClient _client;
public _Revisions(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<RevisionClass> RevisionsByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<RevisionClass>>("revisions", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Revisions Revisions{get; private set;}
public class _Search
{
private SoapiClient _client;
public _Search(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<QuestionClass> Search(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortSearch? sort, string tagged, string nottagged, string intitle)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}¬tagged={nottagged}&intitle={intitle}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("search", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
{"nottagged",nottagged},
{"intitle",intitle},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> Similar(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortSimilar? sort, string tagged, string nottagged, string title)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&tagged={tagged}¬tagged={nottagged}&title={title}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("similar", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tagged",tagged},
{"nottagged",nottagged},
{"title",title},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Search Search{get; private set;}
public class _Suggested_Edits
{
private SoapiClient _client;
public _Suggested_Edits(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<SuggestedEditClass> SuggestedEdits(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortSuggestedEdits? sort)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<SuggestedEditClass>>("suggested-edits", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<SuggestedEditClass> SuggestedEditsByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortSuggestedEditsByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<SuggestedEditClass>>("suggested-edits", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Suggested_Edits Suggested_Edits{get; private set;}
public class _Info
{
private SoapiClient _client;
public _Info(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<InfoClass> Info(string site)
{
string uriTemplate = _client.AppendApiKey("?site={site}");
return _client.Request<ResponseWrapperClass<InfoClass>>("info", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Info Info{get; private set;}
public class _Tags
{
private SoapiClient _client;
public _Tags(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<TagClass> Tags(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTags? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<TagClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagClass> TagsByTagsInfo(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTagsByTagsInfo? sort, string tags)
{
string uriTemplate = _client.AppendApiKey("/{tags}/info?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<TagClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagClass> TagsModeratorOnly(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTagsModeratorOnly? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("/moderator-only?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<TagClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagClass> TagsRequired(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTagsRequired? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("/required?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<TagClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagSynonymClass> TagsSynonyms(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTagsSynonyms? sort)
{
string uriTemplate = _client.AppendApiKey("/synonyms?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<TagSynonymClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> TagsByTagsFaq(string site, int? page, int? pagesize, string tags)
{
string uriTemplate = _client.AppendApiKey("/{tags}/faq?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagClass> TagsByTagsRelated(string site, int? page, int? pagesize, string tags)
{
string uriTemplate = _client.AppendApiKey("/{tags}/related?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TagClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagSynonymClass> TagsByTagsSynonyms(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortTagsByTagsSynonyms? sort, string tags)
{
string uriTemplate = _client.AppendApiKey("/{tags}/synonyms?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<TagSynonymClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagScoreClass> TagsByTagTopAnswerersByPeriod(string site, int? page, int? pagesize, string tag, Period period)
{
string uriTemplate = _client.AppendApiKey("/{tag}/top-answerers/{period}?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TagScoreClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"tag",tag},
{"period",period},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagScoreClass> TagsByTagTopAskersByPeriod(string site, int? page, int? pagesize, string tag, Period period)
{
string uriTemplate = _client.AppendApiKey("/{tag}/top-askers/{period}?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TagScoreClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"tag",tag},
{"period",period},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagWikiClass> TagsByTagsWikis(string site, int? page, int? pagesize, string tags)
{
string uriTemplate = _client.AppendApiKey("/{tags}/wikis?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TagWikiClass>>("tags", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Tags Tags{get; private set;}
public class _Users
{
private SoapiClient _client;
public _Users(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<UserClass> Users(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsers? sort, string inname)
{
string uriTemplate = _client.AppendApiKey("?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}&inname={inname}");
return _client.Request<ResponseWrapperClass<UserClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"inname",inname},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<UserClass> UsersByIds(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIds? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<UserClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AnswerClass> UsersByIdsAnswers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsAnswers? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/answers?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<BadgeClass> UsersByIdsBadges(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsBadges? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/badges?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<BadgeClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> UsersByIdsComments(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsComments? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/comments?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> UsersByIdsCommentsToId(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsCommentsToId? sort, string ids, int toid)
{
string uriTemplate = _client.AppendApiKey("/{ids}/comments/{toid}?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
{"toid",toid},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsFavorites(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsFavorites? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/favorites?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<CommentClass> UsersByIdsMentioned(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsMentioned? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/mentioned?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<CommentClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<PrivilegeClass> UsersByIdPrivileges(string site, int? page, int? pagesize, int id)
{
string uriTemplate = _client.AppendApiKey("/{id}/privileges?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<PrivilegeClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"id",id},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsQuestions(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsQuestions? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/questions?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsQuestionsFeatured(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsQuestionsFeatured? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/questions/featured?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsQuestionsNoAnswers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsQuestionsNoAnswers? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/questions/no-answers?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsQuestionsUnaccepted(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsQuestionsUnaccepted? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/questions/unaccepted?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdsQuestionsUnanswered(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsQuestionsUnanswered? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/questions/unanswered?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<ReputationClass> UsersByIdsReputation(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/reputation?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<ReputationClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<SuggestedEditClass> UsersByIdsSuggestedEdits(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsSuggestedEdits? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/suggested-edits?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<SuggestedEditClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TagClass> UsersByIdsTags(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdsTags? sort, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/tags?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<TagClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AnswerClass> UsersByIdTagsByTagsTopAnswers(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdTagsByTagsTopAnswers? sort, int id, string tags)
{
string uriTemplate = _client.AppendApiKey("/{id}/tags/{tags}/top-answers?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"id",id},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<QuestionClass> UsersByIdTagsByTagsTopQuestions(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersByIdTagsByTagsTopQuestions? sort, int id, string tags)
{
string uriTemplate = _client.AppendApiKey("/{id}/tags/{tags}/top-questions?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<QuestionClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
{"id",id},
{"tags",tags},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<UserTimelineClass> UsersByIdsTimeline(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/timeline?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}");
return _client.Request<ResponseWrapperClass<UserTimelineClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TopTagClass> UsersByIdTopAnswerTags(string site, int? page, int? pagesize, int id)
{
string uriTemplate = _client.AppendApiKey("/{id}/top-answer-tags?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TopTagClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"id",id},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<TopTagClass> UsersByIdTopQuestionTags(string site, int? page, int? pagesize, int id)
{
string uriTemplate = _client.AppendApiKey("/{id}/top-question-tags?site={site}&page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<TopTagClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"id",id},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AnswerClass> UsersModerators(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersModerators? sort)
{
string uriTemplate = _client.AppendApiKey("/moderators?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<AnswerClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<UserClass> UsersModeratorsElected(string site, int? page, int? pagesize, DateTimeOffset? fromdate, DateTimeOffset? todate, Order? order, object min, object max, SortUsersModeratorsElected? sort)
{
string uriTemplate = _client.AppendApiKey("/moderators/elected?site={site}&page={page}&pagesize={pagesize}&fromdate={fromdate}&todate={todate}&order={order}&min={min}&max={max}&sort={sort}");
return _client.Request<ResponseWrapperClass<UserClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"site",site},
{"page",page},
{"pagesize",pagesize},
{"fromdate",fromdate},
{"todate",todate},
{"order",order},
{"min",min},
{"max",max},
{"sort",sort},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<InboxItemClass> UsersByIdInbox(string site, int? page, int? pagesize, int id)
{
throw new NotImplementedException("Requires Authentication");
}
public ResponseWrapperClass<InboxItemClass> UsersByIdInboxUnread(string site, int? page, int? pagesize, int id, DateTimeOffset? since)
{
throw new NotImplementedException("Requires Authentication");
}
public ResponseWrapperClass<NetworkUserClass> UsersByIdAssociated(int? page, int? pagesize, string ids)
{
string uriTemplate = _client.AppendApiKey("/{ids}/associated?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<NetworkUserClass>>("users", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
{"ids",ids},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Users Users{get; private set;}
public class _Access_Tokens
{
private SoapiClient _client;
public _Access_Tokens(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<AccessTokenClass> AccessTokensInvalidate(int? page, int? pagesize, string accessTokens)
{
string uriTemplate = _client.AppendApiKey("/{accessTokens}/invalidate?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<AccessTokenClass>>("access-tokens", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
{"accessTokens",accessTokens},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public ResponseWrapperClass<AccessTokenClass> AccessTokens(int? page, int? pagesize, string accessTokens)
{
string uriTemplate = _client.AppendApiKey("/{accessTokens}?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<AccessTokenClass>>("access-tokens", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
{"accessTokens",accessTokens},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Access_Tokens Access_Tokens{get; private set;}
public class _Applications
{
private SoapiClient _client;
public _Applications(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<AccessTokenClass> AppsDeAuthenticate(int? page, int? pagesize, string accessTokens)
{
string uriTemplate = _client.AppendApiKey("/{accessTokens}/de-authenticate?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<AccessTokenClass>>("apps", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
{"accessTokens",accessTokens},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Applications Applications{get; private set;}
public class _Errors
{
private SoapiClient _client;
public _Errors(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<ErrorClass> Errors(int? page, int? pagesize)
{
string uriTemplate = _client.AppendApiKey("?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<ErrorClass>>("errors", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
public void ErrorsById(int id)
{
string uriTemplate = _client.AppendApiKey("/{id}");
_client.Request<object>("errors", uriTemplate , "GET",
new Dictionary<string, object>
{
{"id",id},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Errors Errors{get; private set;}
public class _Filters
{
private SoapiClient _client;
public _Filters(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<FilterClass> FiltersCreate(string include, string exclude, string @base, bool? @unsafe)
{
string uriTemplate = _client.AppendApiKey("/create");
return _client.Request<ResponseWrapperClass<FilterClass>>("filters", uriTemplate , "POST",
new Dictionary<string, object>
{
{"include",include},
{"exclude",exclude},
{"base",@base},
{"unsafe",@unsafe},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.FORM);
}
public ResponseWrapperClass<FilterClass> Filters(string filters)
{
string uriTemplate = _client.AppendApiKey("/{filters}");
return _client.Request<ResponseWrapperClass<FilterClass>>("filters", uriTemplate , "GET",
new Dictionary<string, object>
{
{"filters",filters},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Filters Filters{get; private set;}
public class _Inbox
{
private SoapiClient _client;
public _Inbox(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<InboxItemClass> Inbox(int? page, int? pagesize)
{
throw new NotImplementedException("Requires Authentication");
}
public ResponseWrapperClass<InboxItemClass> InboxUnread(int? page, int? pagesize, DateTimeOffset? since)
{
throw new NotImplementedException("Requires Authentication");
}
}
public _Inbox Inbox{get; private set;}
public class _Sites
{
private SoapiClient _client;
public _Sites(SoapiClient client)
{
_client=client;
}
public ResponseWrapperClass<SiteClass> Sites(int? page, int? pagesize)
{
string uriTemplate = _client.AppendApiKey("?page={page}&pagesize={pagesize}");
return _client.Request<ResponseWrapperClass<SiteClass>>("sites", uriTemplate , "GET",
new Dictionary<string, object>
{
{"page",page},
{"pagesize",pagesize},
}
, TimeSpan.FromMilliseconds(360000), "default",ContentType.JSON);
}
}
public _Sites Sites{get; private set;}
}
}
| |
using System;
namespace MongoDB
{
/// <summary>
/// Native type that maps to a database reference. Use Database.FollowReference(DBRef) to retrieve the document
/// that it refers to.
/// </summary>
/// <remarks>
/// DBRefs are just a specification for a specially formatted Document. At this time the database
/// does no special handling of them. Any referential integrity must be maintained by the application
/// not the database.
/// </remarks>
[Serializable]
public sealed class DBRef : IEquatable<DBRef>
{
internal const string IdName = "$id";
internal const string MetaName = "metadata";
internal const string RefName = "$ref";
private readonly Document _document;
private string _collectionName;
private object _id;
private Document _metadata;
/// <summary>
/// Initializes a new instance of the <see cref = "DBRef" /> class.
/// </summary>
public DBRef(){
_document = new Document();
}
/// <summary>
/// Constructs a DBRef from a document that matches the DBref specification.
/// </summary>
public DBRef(Document document){
if(document == null)
throw new ArgumentNullException("document");
if(IsDocumentDBRef(document) == false)
throw new ArgumentException("Document is not a valid DBRef");
_collectionName = (String)document[RefName];
_id = document[IdName];
_document = document;
if(document.ContainsKey("metadata"))
MetaData = (Document)document["metadata"];
}
/// <summary>
/// Initializes a new instance of the <see cref="DBRef"/> class.
/// </summary>
/// <param name="databaseReference">The database reference.</param>
public DBRef(DBRef databaseReference){
if(databaseReference == null)
throw new ArgumentNullException("databaseReference");
_document = new Document();
CollectionName = databaseReference.CollectionName;
Id = databaseReference.Id;
if(databaseReference.MetaData != null)
MetaData = new Document().Merge(databaseReference.MetaData);
}
/// <summary>
/// Initializes a new instance of the <see cref="DBRef"/> class.
/// </summary>
/// <param name="collectionName">Name of the collection.</param>
/// <param name="id">The id.</param>
public DBRef(string collectionName, object id){
if(collectionName == null)
throw new ArgumentNullException("collectionName");
if(id == null)
throw new ArgumentNullException("id");
_document = new Document();
CollectionName = collectionName;
Id = id;
}
/// <summary>
/// The name of the collection the referenced document is in.
/// </summary>
public string CollectionName{
get { return _collectionName; }
set{
_collectionName = value;
_document[RefName] = value;
}
}
/// <summary>
/// Object value of the id. It isn't an Oid because document ids are not required to be oids.
/// </summary>
public object Id{
get { return _id; }
set{
_id = value;
_document[IdName] = value;
}
}
/// <summary>
/// An extension to the spec that allows storing of arbitrary data about a reference.
/// </summary>
/// <value>The meta data.</value>
/// <remarks>
/// This is a non-standard feature.
/// </remarks>
public Document MetaData{
get { return _metadata; }
set{
_metadata = value;
_document[MetaName] = value;
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj){
if(ReferenceEquals(null, obj))
return false;
if(ReferenceEquals(this, obj))
return true;
return obj.GetType() == typeof(DBRef) && Equals((DBRef)obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode(){
unchecked
{
var result = (_document != null ? _document.GetHashCode() : 0);
result = (result*397) ^ (_collectionName != null ? _collectionName.GetHashCode() : 0);
result = (result*397) ^ (_id != null ? _id.GetHashCode() : 0);
result = (result*397) ^ (_metadata != null ? _metadata.GetHashCode() : 0);
return result;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString(){
return _document.ToString();
}
/// <summary>
/// Deprecated. Use the new DBRef(Document) constructor instead.
/// </summary>
public static DBRef FromDocument(Document document){
return new DBRef(document);
}
/// <summary>
/// Determines whether [is document DB ref] [the specified document].
/// </summary>
/// <param name="document">The document.</param>
/// <returns>
/// <c>true</c> if [is document DB ref] [the specified document]; otherwise, <c>false</c>.
/// </returns>
public static bool IsDocumentDBRef(Document document){
return document != null && document.ContainsKey(RefName) && document.ContainsKey(IdName);
}
/// <summary>
/// Performs an explicit conversion from <see cref="MongoDB.DBRef"/> to <see cref="MongoDB.Document"/>.
/// </summary>
/// <param name="dbRef">The db ref.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Document(DBRef dbRef){
return dbRef._document;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(DBRef other)
{
if(ReferenceEquals(null, other))
return false;
if(ReferenceEquals(this, other))
return true;
return Equals(other._document, _document) && Equals(other._collectionName, _collectionName) && Equals(other._id, _id) && Equals(other._metadata, _metadata);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(DBRef left, DBRef right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(DBRef left, DBRef right)
{
return !Equals(left, right);
}
}
}
| |
#if WITH_PATRICIA
using System;
using Volante;
using System.IO;
/**
* Get country for IP address using PATRICIA Trie.
*/
public class IpCountry
{
const int PagePoolSize = 32*1024*1024;
class Root : Persistent {
internal IIndex<string,Country> countries;
internal IPatriciaTrie<Country> trie;
}
class Country : Persistent {
internal string name;
internal Country(string name) {
this.name = name;
}
Country() {}
}
public static void Main(string[] args)
{
IDatabase db = DatabaseFactory.CreateDatabase();
db.Open("ipcountry.dbs", PagePoolSize);
Root root = (Root)db.Root;
if (root == null) {
root = new Root();
root.countries = db.CreateIndex<string,Country>(IndexType.Unique);
root.trie = db.CreatePatriciaTrie<Country>();
loadCountries(root.countries);
db.Root = root;
}
for (int i = 0; i < args.Length; i++) {
loadIpCountryTable(root, args[i]);
}
string ip;
while ((ip = Console.ReadLine()) != null) {
Country country = root.trie.FindBestMatch(PatriciaTrieKey.FromIpAddress(ip));
if (country != null) {
Console.WriteLine(ip + "->" + country.name);
}
}
db.Close();
}
static void loadIpCountryTable(Root root, string fileName) {
FileStream fs = new FileStream(fileName, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string line;
while ((line = sr.ReadLine()) != null) {
int sep1 = line.IndexOf('|');
if (sep1 >= 0) {
int sep2 = line.IndexOf('|', sep1+1);
int sep3 = line.IndexOf('|', sep2+1);
int sep4 = line.IndexOf('|', sep3+1);
if (sep2 > sep1 && sep4 > sep3) {
String iso = line.Substring(sep1+1, sep2-sep1-1).ToUpper();
String ip = line.Substring(sep3+1, sep4-sep3-1);
if (ip.IndexOf('.') > 0 && iso.Length == 2) {
Country c = (Country)root.countries[iso];
if (c == null) {
Console.WriteLine("Unknown country code: " + iso);
} else {
root.trie.Add(PatriciaTrieKey.FromIpAddress(ip), c);
}
}
}
}
}
}
static void addCountry(IIndex<string,Country> countries, string country, string iso) {
countries[iso] = new Country(country);
}
static void loadCountries(IIndex<string,Country> countries) {
addCountry(countries, "Burundi", "BI");
addCountry(countries, "Central African Republic", "CF");
addCountry(countries, "Chad", "TD");
addCountry(countries, "Congo", "CG");
addCountry(countries, "Rwanda", "RW");
addCountry(countries, "Zaire (Congo)", "ZR");
addCountry(countries, "Djibouti", "DJ");
addCountry(countries, "Eritrea", "ER");
addCountry(countries, "Ethiopia", "ET");
addCountry(countries, "Kenya", "KE");
addCountry(countries, "Somalia", "SO");
addCountry(countries, "Tanzania", "TZ");
addCountry(countries, "Uganda", "UG");
addCountry(countries, "Comoros", "KM");
addCountry(countries, "Madagascar", "MG");
addCountry(countries, "Mauritius", "MU");
addCountry(countries, "Mayotte", "YT");
addCountry(countries, "Reunion", "RE");
addCountry(countries, "Seychelles", "SC");
addCountry(countries, "Algeria", "DZ");
addCountry(countries, "Egypt", "EG");
addCountry(countries, "Libya", "LY");
addCountry(countries, "Morocco", "MA");
addCountry(countries, "Sudan", "SD");
addCountry(countries, "Tunisia", "TN");
addCountry(countries, "Western Sahara", "EH");
addCountry(countries, "Angola", "AO");
addCountry(countries, "Botswana", "BW");
addCountry(countries, "Lesotho", "LS");
addCountry(countries, "Malawi", "MW");
addCountry(countries, "Mozambique", "MZ");
addCountry(countries, "Namibia", "NA");
addCountry(countries, "South Africa", "ZA");
addCountry(countries, "Swaziland", "SZ");
addCountry(countries, "Zambia", "ZM");
addCountry(countries, "Zimbabwe", "ZW");
addCountry(countries, "Benin", "BJ");
addCountry(countries, "Burkina Faso", "BF");
addCountry(countries, "Cameroon", "CM");
addCountry(countries, "Cape Verde", "CV");
addCountry(countries, "Cote d'Ivoire", "CI");
addCountry(countries, "Equatorial Guinea", "GQ");
addCountry(countries, "Gabon", "GA");
addCountry(countries, "Gambia, The", "GM");
addCountry(countries, "Ghana", "GH");
addCountry(countries, "Guinea", "GN");
addCountry(countries, "Guinea-Bissau", "GW");
addCountry(countries, "Liberia", "LR");
addCountry(countries, "Mali", "ML");
addCountry(countries, "Mauritania", "MR");
addCountry(countries, "Niger", "NE");
addCountry(countries, "Nigeria", "NG");
addCountry(countries, "Sao Tome and Principe", "ST");
addCountry(countries, "Senegal", "SN");
addCountry(countries, "Sierra Leone", "SL");
addCountry(countries, "Togo", "TG");
addCountry(countries, "Belize", "BZ");
addCountry(countries, "Costa Rica", "CR");
addCountry(countries, "El Salvador", "SV");
addCountry(countries, "Guatemala", "GT");
addCountry(countries, "Honduras", "HN");
addCountry(countries, "Mexico", "MX");
addCountry(countries, "Nicaragua", "NI");
addCountry(countries, "Panama", "PA");
addCountry(countries, "Canada", "CA");
addCountry(countries, "Greenland", "GL");
addCountry(countries, "Saint-Pierre et Miquelon", "PM");
addCountry(countries, "United States", "US");
addCountry(countries, "Argentina", "AR");
addCountry(countries, "Bolivia", "BO");
addCountry(countries, "Brazil", "BR");
addCountry(countries, "Chile", "CL");
addCountry(countries, "Colombia", "CO");
addCountry(countries, "Ecuador", "EC");
addCountry(countries, "Falkland Islands", "FK");
addCountry(countries, "French Guiana", "GF");
addCountry(countries, "Guyana", "GY");
addCountry(countries, "Paraguay", "PY");
addCountry(countries, "Peru", "PE");
addCountry(countries, "Suriname", "SR");
addCountry(countries, "Uruguay", "UY");
addCountry(countries, "Venezuela", "VE");
addCountry(countries, "Anguilla", "AI");
addCountry(countries, "Antigua&Barbuda", "AG");
addCountry(countries, "Aruba", "AW");
addCountry(countries, "Bahamas, The", "BS");
addCountry(countries, "Barbados", "BB");
addCountry(countries, "Bermuda", "BM");
addCountry(countries, "British Virgin Islands", "VG");
addCountry(countries, "Cayman Islands", "KY");
addCountry(countries, "Cuba", "CU");
addCountry(countries, "Dominica", "DM");
addCountry(countries, "Dominican Republic", "DO");
addCountry(countries, "Grenada", "GD");
addCountry(countries, "Guadeloupe", "GP");
addCountry(countries, "Haiti", "HT");
addCountry(countries, "Jamaica", "JM");
addCountry(countries, "Martinique", "MQ");
addCountry(countries, "Montserrat", "MS");
addCountry(countries, "Netherlands Antilles", "AN");
addCountry(countries, "Puerto Rico", "PR");
addCountry(countries, "Saint Kitts and Nevis", "KN");
addCountry(countries, "Saint Lucia", "LC");
addCountry(countries, "Saint Vincent and the Grenadines", "VC");
addCountry(countries, "Trinidad and Tobago", "TT");
addCountry(countries, "Turks and Caicos Islands", "TC");
addCountry(countries, "Virgin Islands", "VI");
addCountry(countries, "Kazakhstan", "KZ");
addCountry(countries, "Kyrgyzstan", "KG");
addCountry(countries, "Tajikistan", "TJ");
addCountry(countries, "Turkmenistan", "TM");
addCountry(countries, "Uzbekistan", "UZ");
addCountry(countries, "China", "CN");
addCountry(countries, "Hong Kong", "HK");
addCountry(countries, "Japan", "JP");
addCountry(countries, "Korea, North", "KP");
addCountry(countries, "Korea, South", "KR");
addCountry(countries, "Taiwan", "TW");
addCountry(countries, "Mongolia", "MN");
addCountry(countries, "Russia", "RU");
addCountry(countries, "Afghanistan", "AF");
addCountry(countries, "Bangladesh", "BD");
addCountry(countries, "Bhutan", "BT");
addCountry(countries, "India", "IN");
addCountry(countries, "Maldives", "MV");
addCountry(countries, "Nepal", "NP");
addCountry(countries, "Pakistan", "PK");
addCountry(countries, "Sri Lanka", "LK");
addCountry(countries, "Brunei", "BN");
addCountry(countries, "Cambodia", "KH");
addCountry(countries, "Christmas Island", "CX");
addCountry(countries, "Cocos (Keeling) Islands", "CC");
addCountry(countries, "Indonesia", "ID");
addCountry(countries, "Laos", "LA");
addCountry(countries, "Malaysia", "MY");
addCountry(countries, "Myanmar (Burma)", "MM");
addCountry(countries, "Philippines", "PH");
addCountry(countries, "Singapore", "SG");
addCountry(countries, "Thailand", "TH");
addCountry(countries, "Vietnam", "VN");
addCountry(countries, "Armenia", "AM");
addCountry(countries, "Azerbaijan", "AZ");
addCountry(countries, "Bahrain", "BH");
addCountry(countries, "Cyprus", "CY");
addCountry(countries, "Georgia", "GE");
addCountry(countries, "Iran", "IR");
addCountry(countries, "Iraq", "IQ");
addCountry(countries, "Israel", "IL");
addCountry(countries, "Jordan", "JO");
addCountry(countries, "Kuwait", "KW");
addCountry(countries, "Lebanon", "LB");
addCountry(countries, "Oman", "OM");
addCountry(countries, "Qatar", "QA");
addCountry(countries, "Saudi Arabia", "SA");
addCountry(countries, "Syria", "SY");
addCountry(countries, "Turkey", "TR");
addCountry(countries, "United Arab Emirates", "AE");
addCountry(countries, "Yemen", "YE");
addCountry(countries, "Austria", "AT");
addCountry(countries, "Czech Republic", "CZ");
addCountry(countries, "Hungary", "HU");
addCountry(countries, "Liechtenstein", "LI");
addCountry(countries, "Slovakia", "SK");
addCountry(countries, "Switzerland", "CH");
addCountry(countries, "Belarus", "BY");
addCountry(countries, "Estonia", "EE");
addCountry(countries, "Latvia", "LV");
addCountry(countries, "Lithuania", "LT");
addCountry(countries, "Moldova", "MD");
addCountry(countries, "Poland", "PL");
addCountry(countries, "Ukraine", "UA");
addCountry(countries, "Denmark", "DK");
addCountry(countries, "Faroe Islands", "FO");
addCountry(countries, "Finland", "FI");
addCountry(countries, "Iceland", "IS");
addCountry(countries, "Norway", "NO");
addCountry(countries, "Svalbard", "SJ");
addCountry(countries, "Sweden", "SE");
addCountry(countries, "Albania", "AL");
addCountry(countries, "Bosnia Herzegovina", "BA");
addCountry(countries, "Bulgaria", "BG");
addCountry(countries, "Croatia", "HR");
addCountry(countries, "Greece", "GR");
addCountry(countries, "Macedonia", "MK");
addCountry(countries, "Romania", "RO");
addCountry(countries, "Slovenia", "SI");
addCountry(countries, "Yugoslavia", "YU");
addCountry(countries, "Andorra", "AD");
addCountry(countries, "Gibraltar", "GI");
addCountry(countries, "Portugal", "PT");
addCountry(countries, "Spain", "ES");
addCountry(countries, "Vatican", "VA");
addCountry(countries, "Italy", "IT");
addCountry(countries, "Malta", "MT");
addCountry(countries, "San Marino", "SM");
addCountry(countries, "Belgium", "BE");
addCountry(countries, "France", "FR");
addCountry(countries, "Germany", "DE");
addCountry(countries, "Ireland", "IE");
addCountry(countries, "Luxembourg", "LU");
addCountry(countries, "Monaco", "MC");
addCountry(countries, "Netherlands", "NL");
addCountry(countries, "United Kingdom", "GB");
addCountry(countries, "United Kingdom", "UK");
addCountry(countries, "American Samoa", "AS");
addCountry(countries, "Australia", "AU");
addCountry(countries, "Cook Islands", "CK");
addCountry(countries, "Fiji", "FJ");
addCountry(countries, "French Polynesia", "PF");
addCountry(countries, "Guam", "GU");
addCountry(countries, "Kiribati", "KI");
addCountry(countries, "Marshall Islands", "MH");
addCountry(countries, "Micronesia", "FM");
addCountry(countries, "Nauru", "NR");
addCountry(countries, "New Caledonia", "NC");
addCountry(countries, "New Zealand", "NZ");
addCountry(countries, "Niue", "NU");
addCountry(countries, "Norfolk Island", "NF");
addCountry(countries, "Northern Mariana Islands", "MP");
addCountry(countries, "Palau", "PW");
addCountry(countries, "Papua New-Guinea", "PG");
addCountry(countries, "Pitcairn Islands", "PN");
addCountry(countries, "Solomon Islands", "SB");
addCountry(countries, "Tokelau", "TK");
addCountry(countries, "Tonga", "TO");
addCountry(countries, "Tuvalu", "TV");
addCountry(countries, "Vanuatu", "VU");
addCountry(countries, "Wallis & Futuna", "WF");
addCountry(countries, "Western Samoa", "WS");
}
}
#else
using System;
public class IpCountry
{
public static void Main(string[] args)
{
Console.WriteLine("IpCountry not available if not compiled with WITH_PATRICIA");
}
}
#endif
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetSuspectBlobPoolsSpectraS3Request : Ds3Request
{
private string _blobId;
public string BlobId
{
get { return _blobId; }
set { WithBlobId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _poolId;
public string PoolId
{
get { return _poolId; }
set { WithPoolId(value); }
}
public GetSuspectBlobPoolsSpectraS3Request WithBlobId(Guid? blobId)
{
this._blobId = blobId.ToString();
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId.ToString());
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithBlobId(string blobId)
{
this._blobId = blobId;
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId);
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPoolId(Guid? poolId)
{
this._poolId = poolId.ToString();
if (poolId != null)
{
this.QueryParams.Add("pool_id", poolId.ToString());
}
else
{
this.QueryParams.Remove("pool_id");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request WithPoolId(string poolId)
{
this._poolId = poolId;
if (poolId != null)
{
this.QueryParams.Add("pool_id", poolId);
}
else
{
this.QueryParams.Remove("pool_id");
}
return this;
}
public GetSuspectBlobPoolsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/suspect_blob_pool";
}
}
}
}
| |
using Content.Client.Resources;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Maths;
namespace Content.Client.Stylesheets
{
public abstract class StyleBase
{
public const string ClassHighDivider = "HighDivider";
public const string ClassLowDivider = "LowDivider";
public const string StyleClassLabelHeading = "LabelHeading";
public const string StyleClassLabelSubText = "LabelSubText";
public const string StyleClassItalic = "Italic";
public const string ClassAngleRect = "AngleRect";
public const string ButtonOpenRight = "OpenRight";
public const string ButtonOpenLeft = "OpenLeft";
public const string ButtonOpenBoth = "OpenBoth";
public const string ButtonSquare = "ButtonSquare";
public const string ButtonCaution = "Caution";
public const int DefaultGrabberSize = 10;
public abstract Stylesheet Stylesheet { get; }
protected StyleRule[] BaseRules { get; }
protected StyleBoxTexture BaseButton { get; }
protected StyleBoxTexture BaseButtonOpenRight { get; }
protected StyleBoxTexture BaseButtonOpenLeft { get; }
protected StyleBoxTexture BaseButtonOpenBoth { get; }
protected StyleBoxTexture BaseButtonSquare { get; }
protected StyleBoxTexture BaseAngleRect { get; }
protected StyleBase(IResourceCache resCache)
{
var notoSans12 = resCache.GetFont
(
new []
{
"/Fonts/NotoSans/NotoSans-Regular.ttf",
"/Fonts/NotoSans/NotoSansSymbols-Regular.ttf",
"/Fonts/NotoSans/NotoSansSymbols2-Regular.ttf"
},
12
);
var notoSans12Italic = resCache.GetFont
(
new []
{
"/Fonts/NotoSans/NotoSans-Italic.ttf",
"/Fonts/NotoSans/NotoSansSymbols-Regular.ttf",
"/Fonts/NotoSans/NotoSansSymbols2-Regular.ttf"
},
12
);
var textureCloseButton = resCache.GetTexture("/Textures/Interface/Nano/cross.svg.png");
// Button styles.
var buttonTex = resCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
BaseButton = new StyleBoxTexture
{
Texture = buttonTex,
};
BaseButton.SetPatchMargin(StyleBox.Margin.All, 10);
BaseButton.SetPadding(StyleBox.Margin.All, 1);
BaseButton.SetContentMarginOverride(StyleBox.Margin.Vertical, 2);
BaseButton.SetContentMarginOverride(StyleBox.Margin.Horizontal, 14);
BaseButtonOpenRight = new StyleBoxTexture(BaseButton)
{
Texture = new AtlasTexture(buttonTex, UIBox2.FromDimensions((0, 0), (14, 24))),
};
BaseButtonOpenRight.SetPatchMargin(StyleBox.Margin.Right, 0);
BaseButtonOpenRight.SetContentMarginOverride(StyleBox.Margin.Right, 8);
BaseButtonOpenRight.SetPadding(StyleBox.Margin.Right, 2);
BaseButtonOpenLeft = new StyleBoxTexture(BaseButton)
{
Texture = new AtlasTexture(buttonTex, UIBox2.FromDimensions((10, 0), (14, 24))),
};
BaseButtonOpenLeft.SetPatchMargin(StyleBox.Margin.Left, 0);
BaseButtonOpenLeft.SetContentMarginOverride(StyleBox.Margin.Left, 8);
BaseButtonOpenLeft.SetPadding(StyleBox.Margin.Left, 1);
BaseButtonOpenBoth = new StyleBoxTexture(BaseButton)
{
Texture = new AtlasTexture(buttonTex, UIBox2.FromDimensions((10, 0), (3, 24))),
};
BaseButtonOpenBoth.SetPatchMargin(StyleBox.Margin.Horizontal, 0);
BaseButtonOpenBoth.SetContentMarginOverride(StyleBox.Margin.Horizontal, 8);
BaseButtonOpenBoth.SetPadding(StyleBox.Margin.Right, 2);
BaseButtonOpenBoth.SetPadding(StyleBox.Margin.Left, 1);
BaseButtonSquare = new StyleBoxTexture(BaseButton)
{
Texture = new AtlasTexture(buttonTex, UIBox2.FromDimensions((10, 0), (3, 24))),
};
BaseButtonSquare.SetPatchMargin(StyleBox.Margin.Horizontal, 0);
BaseButtonSquare.SetContentMarginOverride(StyleBox.Margin.Horizontal, 8);
BaseButtonSquare.SetPadding(StyleBox.Margin.Right, 2);
BaseButtonSquare.SetPadding(StyleBox.Margin.Left, 1);
BaseAngleRect = new StyleBoxTexture
{
Texture = buttonTex,
};
BaseAngleRect.SetPatchMargin(StyleBox.Margin.All, 10);
var vScrollBarGrabberNormal = new StyleBoxFlat
{
BackgroundColor = Color.Gray.WithAlpha(0.35f), ContentMarginLeftOverride = DefaultGrabberSize,
ContentMarginTopOverride = DefaultGrabberSize
};
var vScrollBarGrabberHover = new StyleBoxFlat
{
BackgroundColor = new Color(140, 140, 140).WithAlpha(0.35f), ContentMarginLeftOverride = DefaultGrabberSize,
ContentMarginTopOverride = DefaultGrabberSize
};
var vScrollBarGrabberGrabbed = new StyleBoxFlat
{
BackgroundColor = new Color(160, 160, 160).WithAlpha(0.35f), ContentMarginLeftOverride = DefaultGrabberSize,
ContentMarginTopOverride = DefaultGrabberSize
};
var hScrollBarGrabberNormal = new StyleBoxFlat
{
BackgroundColor = Color.Gray.WithAlpha(0.35f), ContentMarginTopOverride = DefaultGrabberSize
};
var hScrollBarGrabberHover = new StyleBoxFlat
{
BackgroundColor = new Color(140, 140, 140).WithAlpha(0.35f), ContentMarginTopOverride = DefaultGrabberSize
};
var hScrollBarGrabberGrabbed = new StyleBoxFlat
{
BackgroundColor = new Color(160, 160, 160).WithAlpha(0.35f), ContentMarginTopOverride = DefaultGrabberSize
};
BaseRules = new[]
{
// Default font.
new StyleRule(
new SelectorElement(null, null, null, null),
new[]
{
new StyleProperty("font", notoSans12),
}),
// Default font.
new StyleRule(
new SelectorElement(null, new[] {StyleClassItalic}, null, null),
new[]
{
new StyleProperty("font", notoSans12Italic),
}),
// Window close button base texture.
new StyleRule(
new SelectorElement(typeof(TextureButton), new[] {DefaultWindow.StyleClassWindowCloseButton}, null,
null),
new[]
{
new StyleProperty(TextureButton.StylePropertyTexture, textureCloseButton),
new StyleProperty(Control.StylePropertyModulateSelf, Color.FromHex("#4B596A")),
}),
// Window close button hover.
new StyleRule(
new SelectorElement(typeof(TextureButton), new[] {DefaultWindow.StyleClassWindowCloseButton}, null,
new[] {TextureButton.StylePseudoClassHover}),
new[]
{
new StyleProperty(Control.StylePropertyModulateSelf, Color.FromHex("#7F3636")),
}),
// Window close button pressed.
new StyleRule(
new SelectorElement(typeof(TextureButton), new[] {DefaultWindow.StyleClassWindowCloseButton}, null,
new[] {TextureButton.StylePseudoClassPressed}),
new[]
{
new StyleProperty(Control.StylePropertyModulateSelf, Color.FromHex("#753131")),
}),
// Scroll bars
new StyleRule(new SelectorElement(typeof(VScrollBar), null, null, null),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
vScrollBarGrabberNormal),
}),
new StyleRule(
new SelectorElement(typeof(VScrollBar), null, null, new[] {ScrollBar.StylePseudoClassHover}),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
vScrollBarGrabberHover),
}),
new StyleRule(
new SelectorElement(typeof(VScrollBar), null, null, new[] {ScrollBar.StylePseudoClassGrabbed}),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
vScrollBarGrabberGrabbed),
}),
new StyleRule(new SelectorElement(typeof(HScrollBar), null, null, null),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
hScrollBarGrabberNormal),
}),
new StyleRule(
new SelectorElement(typeof(HScrollBar), null, null, new[] {ScrollBar.StylePseudoClassHover}),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
hScrollBarGrabberHover),
}),
new StyleRule(
new SelectorElement(typeof(HScrollBar), null, null, new[] {ScrollBar.StylePseudoClassGrabbed}),
new[]
{
new StyleProperty(ScrollBar.StylePropertyGrabber,
hScrollBarGrabberGrabbed),
}),
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Csla;
using Csla.Data;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeCachedList (read only list).<br/>
/// This is a generated <see cref="ProductTypeCachedList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeCachedInfo"/> objects.
/// Cached. Updated by ProductTypeItem
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeCachedList : ReadOnlyBindingListBase<ProductTypeCachedList, ProductTypeCachedInfo>
#else
public partial class ProductTypeCachedList : ReadOnlyListBase<ProductTypeCachedList, ProductTypeCachedInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Collection Business Methods
/// <summary>
/// Determines whether a <see cref="ProductTypeCachedInfo"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeCachedInfo is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeCachedInfo in this)
{
if (productTypeCachedInfo.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Private Fields
private static ProductTypeCachedList _list;
#endregion
#region Cache Management Methods
/// <summary>
/// Clears the in-memory ProductTypeCachedList cache so it is reloaded on the next request.
/// </summary>
public static void InvalidateCache()
{
_list = null;
}
/// <summary>
/// Used by async loaders to load the cache.
/// </summary>
/// <param name="list">The list to cache.</param>
internal static void SetCache(ProductTypeCachedList list)
{
_list = list;
}
internal static bool IsCached
{
get { return _list != null; }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeCachedList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeCachedList"/> collection.</returns>
public static ProductTypeCachedList GetProductTypeCachedList()
{
if (_list == null)
_list = DataPortal.Fetch<ProductTypeCachedList>();
return _list;
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeCachedList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeCachedList(EventHandler<DataPortalResult<ProductTypeCachedList>> callback)
{
if (_list == null)
DataPortal.BeginFetch<ProductTypeCachedList>((o, e) =>
{
_list = e.Object;
callback(o, e);
});
else
callback(null, new DataPortalResult<ProductTypeCachedList>(_list, null, null));
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeCachedList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeCachedList()
{
// Use factory methods and do not use direct creation.
ProductTypeItemSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="ProductTypeItem"/> to update the list of <see cref="ProductTypeCachedInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void ProductTypeItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (ProductTypeItem)e.NewObject;
if (((ProductTypeItem)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(ProductTypeCachedInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((ProductTypeItem)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.ProductTypeId == obj.ProductTypeId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeCachedList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices"))
{
using (var cmd = new SqlCommand("dbo.GetProductTypeCachedList", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="ProductTypeCachedList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<ProductTypeCachedInfo>(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <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);
#endregion
#region ProductTypeItemSaved nested class
// TODO: edit "ProductTypeCachedList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: ProductTypeItemSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="ProductTypeItem"/>
/// to update the list of <see cref="ProductTypeCachedInfo"/> objects.
/// </summary>
private static class ProductTypeItemSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a ProductTypeCachedList instance to handle Saved events.
/// to update the list of <see cref="ProductTypeCachedInfo"/> objects.
/// </summary>
/// <param name="obj">The ProductTypeCachedList instance.</param>
public static void Register(ProductTypeCachedList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (ProductTypeCachedList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
ProductTypeItem.ProductTypeItemSaved += ProductTypeItemSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="ProductTypeItem"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void ProductTypeItemSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((ProductTypeCachedList) reference.Target).ProductTypeItemSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered ProductTypeCachedList instances.
/// </summary>
public static void Unregister()
{
ProductTypeItem.ProductTypeItemSaved -= ProductTypeItemSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Numerics.Hashing;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating three single precision floating point values and provides hardware accelerated methods.
/// </summary>
public partial struct Vector3 : IEquatable<Vector3>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0,0).
/// </summary>
public static Vector3 Zero
{
[Intrinsic]
get
{
return new Vector3();
}
}
/// <summary>
/// Returns the vector (1,1,1).
/// </summary>
public static Vector3 One
{
[Intrinsic]
get
{
return new Vector3(1.0f, 1.0f, 1.0f);
}
}
/// <summary>
/// Returns the vector (1,0,0).
/// </summary>
public static Vector3 UnitX { get { return new Vector3(1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0).
/// </summary>
public static Vector3 UnitY { get { return new Vector3(0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1).
/// </summary>
public static Vector3 UnitZ { get { return new Vector3(0.0f, 0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public Instance Methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override readonly int GetHashCode()
{
int hash = this.X.GetHashCode();
hash = HashHelpers.Combine(hash, this.Y.GetHashCode());
hash = HashHelpers.Combine(hash, this.Z.GetHashCode());
return hash;
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector3 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector3; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly bool Equals(object? obj)
{
if (!(obj is Vector3))
return false;
return Equals((Vector3)obj);
}
/// <summary>
/// Returns a String representing this Vector3 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override readonly string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector3 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector3 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format, IFormatProvider? formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(((IFormattable)this.X).ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(((IFormattable)this.Y).ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(((IFormattable)this.Z).ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector.
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector3.Dot(this, this);
return MathF.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y + Z * Z;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the length of the vector squared. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector3.Dot(this, this);
}
else
{
return X * X + Y * Y + Z * Z;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector3 value1, Vector3 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 difference = value1 - value2;
float ls = Vector3.Dot(difference, difference);
return MathF.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float ls = dx * dx + dy * dy + dz * dz;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector3 value1, Vector3 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 difference = value1 - value2;
return Vector3.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
return dx * dx + dy * dy + dz * dz;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="value">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Normalize(Vector3 value)
{
if (Vector.IsHardwareAccelerated)
{
float length = value.Length();
return value / length;
}
else
{
float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z;
float length = MathF.Sqrt(ls);
return new Vector3(value.X / length, value.Y / length, value.Z / length);
}
}
/// <summary>
/// Computes the cross product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The cross product.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Cross(Vector3 vector1, Vector3 vector2)
{
return new Vector3(
vector1.Y * vector2.Z - vector1.Z * vector2.Y,
vector1.Z * vector2.X - vector1.X * vector2.Z,
vector1.X * vector2.Y - vector1.Y * vector2.X);
}
/// <summary>
/// Returns the reflection of a vector off a surface that has the specified normal.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="normal">The normal of the surface being reflected off.</param>
/// <returns>The reflected vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Reflect(Vector3 vector, Vector3 normal)
{
if (Vector.IsHardwareAccelerated)
{
float dot = Vector3.Dot(vector, normal);
Vector3 temp = normal * dot * 2f;
return vector - temp;
}
else
{
float dot = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z;
float tempX = normal.X * dot * 2f;
float tempY = normal.Y * dot * 2f;
float tempZ = normal.Z * dot * 2f;
return new Vector3(vector.X - tempX, vector.Y - tempY, vector.Z - tempZ);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (min.X > x) ? min.X : x; // max(x, minx)
x = (max.X < x) ? max.X : x; // min(x, maxx)
float y = value1.Y;
y = (min.Y > y) ? min.Y : y; // max(y, miny)
y = (max.Y < y) ? max.Y : y; // min(y, maxy)
float z = value1.Z;
z = (min.Z > z) ? min.Z : z; // max(z, minz)
z = (max.Z < z) ? max.Z : z; // min(z, maxz)
return new Vector3(x, y, z);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 firstInfluence = value1 * (1f - amount);
Vector3 secondInfluence = value2 * amount;
return firstInfluence + secondInfluence;
}
else
{
return new Vector3(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount,
value1.Z + (value2.Z - value1.Z) * amount);
}
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Transform(Vector3 position, Matrix4x4 matrix)
{
return new Vector3(
position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43);
}
/// <summary>
/// Transforms a vector normal by the given matrix.
/// </summary>
/// <param name="normal">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix)
{
return new Vector3(
normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31,
normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32,
normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Transform(Vector3 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector3(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2));
}
#endregion Public Static Methods
#region Public operator methods
// All these methods should be inlined as they are implemented
// over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Add(Vector3 left, Vector3 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Subtract(Vector3 left, Vector3 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(Vector3 left, Vector3 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(Vector3 left, float right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Multiply(float left, Vector3 right)
{
return left * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Divide(Vector3 left, Vector3 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Divide(Vector3 left, float divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Negate(Vector3 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// DurationOperations operations.
/// </summary>
internal partial class DurationOperations : Microsoft.Rest.IServiceOperations<AutoRestDurationTestService>, IDurationOperations
{
/// <summary>
/// Initializes a new instance of the DurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DurationOperations(AutoRestDurationTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestService
/// </summary>
public AutoRestDurationTestService Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>();
_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<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>();
_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<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>();
_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<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace KabMan.Forms.Connection
{
partial class NewConnectionName
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewConnectionName));
this.repositoryItemLookUpEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.btnSave = new DevExpress.XtraEditors.SimpleButton();
this.btnClose = new DevExpress.XtraEditors.SimpleButton();
this.CCostumer = new DevExpress.XtraEditors.TextEdit();
this.CProject = new DevExpress.XtraEditors.TextEdit();
this.CDeviceType = new KabMan.Controls.C_LookUpControl();
this.CName = new DevExpress.XtraEditors.TextEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
this.CManagerValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CCostumer.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CProject.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CDeviceType.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).BeginInit();
this.SuspendLayout();
//
// repositoryItemLookUpEdit1
//
this.repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1";
this.repositoryItemLookUpEdit1.NullText = "";
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.btnSave);
this.layoutControl1.Controls.Add(this.btnClose);
this.layoutControl1.Controls.Add(this.CCostumer);
this.layoutControl1.Controls.Add(this.CProject);
this.layoutControl1.Controls.Add(this.CDeviceType);
this.layoutControl1.Controls.Add(this.CName);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(382, 163);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(205, 131);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(80, 22);
this.btnSave.StyleController = this.layoutControl1;
this.btnSave.TabIndex = 11;
this.btnSave.Text = "Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(296, 131);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(80, 22);
this.btnClose.StyleController = this.layoutControl1;
this.btnClose.TabIndex = 10;
this.btnClose.Text = "Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// CCostumer
//
this.CCostumer.Location = new System.Drawing.Point(58, 100);
this.CCostumer.Name = "CCostumer";
this.CCostumer.Size = new System.Drawing.Size(318, 20);
this.CCostumer.StyleController = this.layoutControl1;
this.CCostumer.TabIndex = 8;
//
// CProject
//
this.CProject.Location = new System.Drawing.Point(58, 69);
this.CProject.Name = "CProject";
this.CProject.Size = new System.Drawing.Size(318, 20);
this.CProject.StyleController = this.layoutControl1;
this.CProject.TabIndex = 7;
//
// CDeviceType
//
this.CDeviceType.AddButtonEnabled = true;
this.CDeviceType.Columns = this.repositoryItemLookUpEdit1.Columns;
this.CDeviceType.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDeviceType.FormParameters")));
this.CDeviceType.Location = new System.Drawing.Point(58, 7);
this.CDeviceType.Name = "CDeviceType";
this.CDeviceType.NullText = "";
this.CDeviceType.Parameters = new KabMan.Controls.NameValuePair[0];
this.CDeviceType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)});
this.CDeviceType.Properties.NullText = "";
this.CDeviceType.RefreshButtonVisible = true;
this.CDeviceType.Size = new System.Drawing.Size(318, 20);
this.CDeviceType.StoredProcedure = null;
this.CDeviceType.StyleController = this.layoutControl1;
this.CDeviceType.TabIndex = 6;
this.CDeviceType.TriggerControl = null;
this.CDeviceType.EditValueChanged += new System.EventHandler(this.CDeviceType_EditValueChanged);
//
// CName
//
this.CName.Location = new System.Drawing.Point(58, 38);
this.CName.Name = "CName";
this.CName.Size = new System.Drawing.Size(318, 20);
this.CName.StyleController = this.layoutControl1;
this.CName.TabIndex = 5;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem2,
this.emptySpaceItem1,
this.layoutControlItem3,
this.layoutControlItem4,
this.layoutControlItem5,
this.layoutControlItem1,
this.layoutControlItem6});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(382, 163);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.CName;
this.layoutControlItem2.CustomizationFormText = "Name";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(380, 31);
this.layoutControlItem2.Text = "Name";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(46, 13);
//
// emptySpaceItem1
//
this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1";
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 124);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(198, 37);
this.emptySpaceItem1.Text = "emptySpaceItem1";
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.CDeviceType;
this.layoutControlItem3.CustomizationFormText = "Device";
this.layoutControlItem3.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(380, 31);
this.layoutControlItem3.Text = "Device";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(46, 13);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.CProject;
this.layoutControlItem4.CustomizationFormText = "Project";
this.layoutControlItem4.Location = new System.Drawing.Point(0, 62);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(380, 31);
this.layoutControlItem4.Text = "Project";
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(46, 13);
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.CCostumer;
this.layoutControlItem5.CustomizationFormText = "Costumer";
this.layoutControlItem5.Location = new System.Drawing.Point(0, 93);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(380, 31);
this.layoutControlItem5.Text = "Customer";
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem5.TextSize = new System.Drawing.Size(46, 13);
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.btnClose;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(289, 124);
this.layoutControlItem1.MaxSize = new System.Drawing.Size(91, 33);
this.layoutControlItem1.MinSize = new System.Drawing.Size(91, 33);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(91, 37);
this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.btnSave;
this.layoutControlItem6.CustomizationFormText = "layoutControlItem6";
this.layoutControlItem6.Location = new System.Drawing.Point(198, 124);
this.layoutControlItem6.MaxSize = new System.Drawing.Size(91, 33);
this.layoutControlItem6.MinSize = new System.Drawing.Size(91, 33);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(91, 37);
this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem6.Text = "layoutControlItem6";
this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem6.TextToControlDistance = 0;
this.layoutControlItem6.TextVisible = false;
//
// NewConnectionName
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(382, 163);
this.Controls.Add(this.layoutControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "NewConnectionName";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "New Server";
((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CCostumer.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CProject.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CDeviceType.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.TextEdit CName;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private KabMan.Controls.C_LookUpControl CDeviceType;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraEditors.TextEdit CProject;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraEditors.TextEdit CCostumer;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit1;
private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider CManagerValidator;
private DevExpress.XtraEditors.SimpleButton btnSave;
private DevExpress.XtraEditors.SimpleButton btnClose;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TypeMetadata.cs" company="KlusterKite">
// All rights reserved
// </copyright>
// <summary>
// Property or method return type description
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace KlusterKite.API.Provider
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using KlusterKite.API.Attributes;
using KlusterKite.API.Client;
/// <summary>
/// Property or method return type description
/// </summary>
internal class TypeMetadata
{
/// <summary>
/// The return types of a field
/// </summary>
public enum EnMetaType
{
/// <summary>
/// This is scalar field
/// </summary>
Scalar,
/// <summary>
/// The field is an object
/// </summary>
Object,
/// <summary>
/// The field is an array
/// </summary>
Array,
/// <summary>
/// The field represents connection
/// </summary>
Connection
}
/// <summary>
/// Gets or sets the converter type
/// </summary>
public Type ConverterType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this property / method has asynchronous access
/// </summary>
public bool IsAsync { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this property / method forwards resolve to other API provider
/// </summary>
public bool IsForwarding { get; set; }
/// <summary>
/// Gets or sets the type key property
/// </summary>
public PropertyInfo KeyProperty { get; set; }
/// <summary>
/// Gets or sets the type key property
/// </summary>
public string KeyPropertyName { get; set; }
/// <summary>
/// Gets or sets the meta type
/// </summary>
public EnMetaType MetaType { get; set; }
/// <summary>
/// Gets or sets the parsed scalar type
/// </summary>
public EnScalarType ScalarType { get; set; }
/// <summary>
/// Gets or sets the true returning type
/// </summary>
public Type Type { get; set; }
/// <summary>
/// Gets or sets the real type that represents connection
/// </summary>
public Type RealConnectionType { get; set; }
/// <summary>
/// Gets or sets the type name to look for resolver
/// </summary>
public string TypeName { get; set; }
/// <summary>
/// Checks the type to be scalar
/// </summary>
/// <param name="type">The type</param>
/// <returns>The corresponding scalar type</returns>
public static EnScalarType CheckScalarType(Type type)
{
if (type == typeof(string))
{
return EnScalarType.String;
}
if (type == typeof(bool))
{
return EnScalarType.Boolean;
}
if (type == typeof(Guid))
{
return EnScalarType.Guid;
}
if (type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(uint)
|| type == typeof(ulong) || type == typeof(ushort)
|| (type.GetTypeInfo().IsSubclassOf(typeof(Enum)) && type.GetTypeInfo().GetCustomAttribute(typeof(FlagsAttribute)) != null))
{
return EnScalarType.Integer;
}
if (type == typeof(float) || type == typeof(double))
{
return EnScalarType.Float;
}
if (type == typeof(decimal))
{
return EnScalarType.Decimal;
}
if (type == typeof(DateTime) || type == typeof(DateTimeOffset))
{
return EnScalarType.DateTime;
}
return EnScalarType.None;
}
/// <summary>
/// Parses the metadata of returning type for the field
/// </summary>
/// <param name="type">The original field return type</param>
/// <param name="attribute">The description attribute</param>
/// <returns>The type metadata</returns>
public static TypeMetadata GenerateTypeMetadata(Type type, PublishToApiAttribute attribute)
{
var metadata = new TypeMetadata();
var asyncType = ApiDescriptionAttribute.CheckType(type, typeof(Task<>));
if (asyncType != null)
{
metadata.IsAsync = true;
type = asyncType.GenericTypeArguments[0];
}
var converter = (attribute as DeclareFieldAttribute)?.Converter;
if (attribute.ReturnType != null)
{
type = attribute.ReturnType;
metadata.IsForwarding = true;
}
else if (converter != null)
{
var valueConverter =
converter.GetInterfaces()
.FirstOrDefault(
i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IValueConverter<>));
if (valueConverter == null)
{
throw new InvalidOperationException(
$"Converter {converter.FullName} should implement the IValueConverter<>");
}
type = valueConverter.GenericTypeArguments[0];
metadata.ConverterType = converter;
}
var nullable = ApiDescriptionAttribute.CheckType(type, typeof(Nullable<>));
if (nullable != null)
{
type = nullable.GenericTypeArguments[0];
}
var scalarType = CheckScalarType(type);
metadata.MetaType = EnMetaType.Scalar;
if (scalarType == EnScalarType.None)
{
var enumerable = ApiDescriptionAttribute.CheckType(type, typeof(IEnumerable<>));
var connection = ApiDescriptionAttribute.CheckType(type, typeof(INodeConnection<>));
if (connection != null)
{
metadata.MetaType = EnMetaType.Connection;
metadata.RealConnectionType = type;
type = connection.GenericTypeArguments[0];
scalarType = CheckScalarType(type);
}
else if (enumerable != null)
{
metadata.MetaType = EnMetaType.Array;
type = enumerable.GenericTypeArguments[0];
scalarType = CheckScalarType(type);
}
else
{
metadata.MetaType = EnMetaType.Object;
}
}
if (scalarType != EnScalarType.None && type.GetTypeInfo().IsSubclassOf(typeof(Enum)))
{
type = Enum.GetUnderlyingType(type);
}
// todo: check forwarding type
metadata.ScalarType = scalarType;
metadata.Type = type;
if (metadata.ScalarType == EnScalarType.None && !type.GetTypeInfo().IsSubclassOf(typeof(Enum)))
{
var keyProperty =
type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(p => p.GetCustomAttribute<DeclareFieldAttribute>()?.IsKey == true);
if (keyProperty != null)
{
metadata.KeyProperty = keyProperty;
metadata.KeyPropertyName = PublishToApiAttribute.GetMemberName(keyProperty);
}
}
var typeName = ApiDescriptionAttribute.GetTypeName(type);
metadata.TypeName = typeName;
////metadata.TypeName = metadata.GetFlags().HasFlag(EnFieldFlags.IsConnection) ? $"{typeName}_Connection" : typeName;
return metadata;
}
/// <summary>
/// Gets the <see cref="KlusterKite.API.Client.EnFieldFlags"/> from metadata
/// </summary>
/// <returns>The field flags</returns>
public EnFieldFlags GetFlags()
{
EnFieldFlags flags;
switch (this.MetaType)
{
case EnMetaType.Object:
flags = EnFieldFlags.None;
break;
case EnMetaType.Array:
flags = EnFieldFlags.IsArray;
break;
case EnMetaType.Connection:
flags = EnFieldFlags.IsConnection;
break;
case EnMetaType.Scalar:
flags = EnFieldFlags.None;
break;
default:
flags = EnFieldFlags.None;
break;
}
flags |= EnFieldFlags.Queryable;
return flags;
}
}
}
| |
// 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.IO;
using System.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== ValidateElement =====================
public class TCValidateElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateElement(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Theory]
[InlineData("name", "first")]
[InlineData("name", "second")]
[InlineData("ns", "first")]
[InlineData("ns", "second")]
public void PassNull_LocalName_NamespaceUri_Invalid_First_Second_Overload(string type, string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
string name = "root";
string ns = "";
XmlSchemaInfo info = new XmlSchemaInfo();
if (type == "name")
name = null;
else
ns = null;
val.Initialize();
try
{
if (overload == "first")
val.ValidateElement(name, ns, info);
else
val.ValidateElement(name, ns, info, null, null, null, null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Theory]
[InlineData("first")]
[InlineData("second")]
public void PassNullXmlSchemaInfo__Valid_First_Second_Overload(string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
val.Initialize();
if (overload == "first")
val.ValidateElement("root", "", null);
else
val.ValidateElement("root", "", null, null, null, null, null);
return;
}
[Theory]
[InlineData("first")]
[InlineData("second")]
public void PassInvalidName_First_Second_Overload(string overload)
{
XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root />"));
val.Initialize();
try
{
if (overload == "first")
val.ValidateElement("$$##", "", null);
else
val.ValidateElement("$$##", "", null, null, null, null, null);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_UndeclaredElement", new string[] { "$$##" });
return;
}
Assert.True(false);
}
[Theory]
[InlineData("SimpleElement", XmlSchemaContentType.TextOnly, "first")]
[InlineData("ElementOnlyElement", XmlSchemaContentType.ElementOnly, "first")]
[InlineData("EmptyElement", XmlSchemaContentType.Empty, "first")]
[InlineData("MixedElement", XmlSchemaContentType.Mixed, "first")]
[InlineData("SimpleElement", XmlSchemaContentType.TextOnly, "second")]
[InlineData("ElementOnlyElement", XmlSchemaContentType.ElementOnly, "second")]
[InlineData("EmptyElement", XmlSchemaContentType.Empty, "second")]
[InlineData("MixedElement", XmlSchemaContentType.Mixed, "second")]
public void CallValidateElementAndCHeckXmlSchemaInfoFOr_Simple_Complex_Empty_Mixed_Element_First_Second_Overload(string elemType, XmlSchemaContentType schemaContentType, string overload)
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
string name = elemType;
schemas.Add("", Path.Combine(TestData, XSDFILE_VALIDATE_TEXT));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
if (overload == "first")
val.ValidateElement(name, "", info);
else
val.ValidateElement(name, "", info, null, null, null, null);
Assert.Equal(info.ContentType, schemaContentType);
Assert.Equal(info.Validity, XmlSchemaValidity.NotKnown);
Assert.Equal(info.SchemaElement, schemas.GlobalElements[new XmlQualifiedName(name)]);
Assert.Equal(info.IsNil, false);
Assert.Equal(info.IsDefault, false);
if (name == "SimpleElement")
Assert.True(info.SchemaType is XmlSchemaSimpleType);
else
Assert.True(info.SchemaType is XmlSchemaComplexType);
return;
}
[Fact]
public void SanityTestsForNestedElements()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
schemas.Add("", Path.Combine(TestData, XSDFILE_VALIDATE_END_ELEMENT));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
val.ValidateElement("NestedElement", "", info);
val.ValidateEndOfAttributes(null);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("NestedElement"));
Assert.True(info.SchemaType is XmlSchemaComplexType);
val.ValidateElement("foo", "", info);
val.ValidateEndOfAttributes(null);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("foo"));
Assert.True(info.SchemaType is XmlSchemaComplexType);
val.ValidateElement("bar", "", info);
Assert.Equal(info.SchemaElement.QualifiedName, new XmlQualifiedName("bar"));
Assert.True(info.SchemaType is XmlSchemaSimpleType);
Assert.Equal(info.SchemaType.TypeCode, XmlTypeCode.String);
return;
}
// ====== second overload ======
[Theory]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation)]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema)]
public void CheckSchemaLocationIs_UsedWhenSpecified_NotUsedWhenFlagIsNotSet(XmlSchemaValidationFlags allFlags)
{
XmlSchemaValidator val;
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:element name=\"root\" />\n" +
"</xs:schema>")));
val = CreateValidator(schemas, ns, allFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("root", "", info, "t:type1", null, "uri:tempuri " + Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE), null);
if ((int)allFlags == (int)AllFlags)
{
Assert.True(!holder.IsCalledA);
Assert.True(info.SchemaType is XmlSchemaComplexType);
}
else
{
Assert.True(holder.IsCalledA);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_XsiTypeNotFound", new string[] { "uri:tempuri:type1" });
}
return;
}
[Theory]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation)]
[InlineData(XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema)]
public void CheckNoNamespaceSchemaLocationIs_UsedWhenSpecified_NotUsedWhenFlagIsSet(XmlSchemaValidationFlags allFlags)
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:element name=\"root\" />\n" +
"</xs:schema>")));
val = CreateValidator(schemas, allFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("root", "", info, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE));
if ((int)allFlags == (int)AllFlags)
{
Assert.True(!holder.IsCalledA);
Assert.True(info.SchemaType is XmlSchemaComplexType);
}
else
{
Assert.True(holder.IsCalledA);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_XsiTypeNotFound", new string[] { "type1" });
}
return;
}
[Theory]
[InlineData(null)]
[InlineData("false")]
public void CallWith_Null_False_XsiNil(string xsiNil)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("NillableElement", "", info, null, xsiNil, null, null);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateEndElement(info);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, new object[] { "Sch_IncompleteContentExpecting",
new object[] { "Sch_ElementName", "NillableElement" },
new object[] { "Sch_ElementName", "foo" } });
return;
}
Assert.True(false);
}
[Fact]
public void CallWithXsiNilTrue()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("NillableElement", "", info, null, "true", null, null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(info.Validity, XmlSchemaValidity.Valid);
return;
}
[Fact]
public void ProvideValidXsiType()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("uri:tempuri", Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE));
val = CreateValidator(schemas, ns, 0);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("foo", "uri:tempuri", null, "t:type1", null, null, null);
return;
}
[Fact]
public void ProvideInvalidXsiType()
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("uri:tempuri", Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE));
val = CreateValidator(schemas, ns, 0);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
try
{
val.ValidateElement("foo", "uri:tempuri", null, "type1", null, null, null);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_XsiTypeNotFound", new string[] { "type1" });
return;
}
Assert.True(false);
}
[Fact]
public void CheckThatWarningOccursWhenInvalidSchemaLocationIsProvided()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
schemas.Add("uri:tempuri", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" +
" targetNamespace=\"uri:tempuri\">\n" +
" <xs:complexType name=\"rootType\">\n" +
" <xs:sequence />\n" +
" </xs:complexType>\n" +
"</xs:schema>")));
val = CreateValidator(schemas, ns, AllFlags);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
ns.AddNamespace("t", "uri:tempuri");
val.Initialize();
val.ValidateElement("root", "", info, "t:rootType", null, "uri:tempuri " + Path.Combine(TestData, "__NonExistingFile__.xsd"), null);
Assert.True(holder.IsCalledA);
Assert.Equal(holder.lastSeverity, XmlSeverityType.Warning);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_CannotLoadSchema", new string[] { "uri:tempuri", null });
return;
}
[Fact]
public void CheckThatWarningOccursWhenInvalidNoNamespaceSchemaLocationIsProvided()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
schemas.Add("", XmlReader.Create(new StringReader("<?xml version=\"1.0\" ?>\n" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <xs:complexType name=\"rootType\">\n" +
" <xs:sequence />\n" +
" </xs:complexType>\n" +
"</xs:schema>")));
val = CreateValidator(schemas);
val.XmlResolver = new XmlUrlResolver();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("root", "", info, "rootType", null, null, Path.Combine(TestData, "__NonExistingFile__.xsd"));
Assert.True(holder.IsCalledA);
Assert.Equal(holder.lastSeverity, XmlSeverityType.Warning);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_CannotLoadSchema", new string[] { "", null });
return;
}
[Fact]
public void CheckThatWarningOccursWhenUndefinedElementIsValidatedWithLaxValidation()
{
XmlSchemaValidator val;
CValidationEventHolder holder = new CValidationEventHolder();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("LaxElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateElement("undefined", "", null);
Assert.True(holder.IsCalledA);
Assert.Equal(holder.lastSeverity, XmlSeverityType.Warning);
_exVerifier.IsExceptionOk(holder.lastException, "Sch_NoElementSchemaFound", new string[] { "undefined" });
return;
}
[Fact]
public void CheckThatWarningsDontOccurWhenIgnoreValidationWarningsIsSet()
{
XmlSchemaValidator val;
CValidationEventHolder holder = new CValidationEventHolder();
val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT, "", XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation);
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("LaxElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateElement("undefined", "", null);
Assert.True(!holder.IsCalledA);
return;
}
//342447
[Fact]
public void VerifyThatSubstitutionGroupMembersAreResolvedAndAddedToTheList()
{
XmlSchemaValidator val;
XmlSchemaSet schemas = new XmlSchemaSet();
XmlSchemaParticle[] actualParticles;
string[] expectedParticles = { "eleA", "eleB", "eleC" };
schemas.Add("", Path.Combine(TestData, "Bug342447.xsd"));
schemas.Compile();
val = CreateValidator(schemas);
val.Initialize();
val.ValidateElement("eleSeq", "", null);
actualParticles = val.GetExpectedParticles();
Assert.Equal(actualParticles.GetLength(0), expectedParticles.GetLength(0));
int count = 0;
foreach (XmlSchemaElement element in actualParticles)
{
Assert.Equal(element.QualifiedName.ToString(), expectedParticles[count++]);
}
return;
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "This checks a quirked behavior and Full Framework always gets old behavior as Xunit runner always targets 4.5.2 TFM ")]
[Fact]
public void StringPassedToValidateEndElementDoesNotSatisfyIdentityConstraints()
{
Initialize();
string xsd =
"<xs:schema targetNamespace='http://tempuri.org/XMLSchema.xsd' elementFormDefault='qualified' xmlns='http://tempuri.org/XMLSchema.xsd' xmlns:mstns='http://tempuri.org/XMLSchema.xsd' xmlns:xs='http://www.w3.org/2001/XMLSchema'>" +
"<xs:element name='root'>" +
"<xs:complexType> <xs:sequence> <xs:element name='B' type='mstns:B'/> </xs:sequence> </xs:complexType>" +
"<xs:unique name='pNumKey'><xs:selector xpath='mstns:B/mstns:part'/><xs:field xpath='.'/></xs:unique>" +
"</xs:element>" +
"<xs:complexType name='B'><xs:sequence><xs:element name='part' maxOccurs='unbounded' type='xs:string'></xs:element></xs:sequence></xs:complexType>" +
"</xs:schema>";
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(XmlSchema.Read(new StringReader(xsd), ValidationCallback));
ss.Compile();
string ns = "http://tempuri.org/XMLSchema.xsd";
XmlNamespaceManager nsmgr = new XmlNamespaceManager(ss.NameTable);
XmlSchemaValidator val = new XmlSchemaValidator(ss.NameTable, ss, nsmgr, XmlSchemaValidationFlags.ProcessIdentityConstraints);
val.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
val.Initialize();
XmlSchemaInfo si = new XmlSchemaInfo();
val.ValidateElement("root", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateElement("B", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateText("1");
val.ValidateEndElement(si);
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateEndElement(si, "1");
val.ValidateElement("part", ns, si);
val.ValidateEndOfAttributes(si);
val.ValidateText("1");
val.ValidateEndElement(si);
val.ValidateEndElement(si);
val.ValidateEndElement(si);
Assert.Equal(warningCount, 0);
Assert.Equal(errorCount, 2);
return;
}
//TFS_469834
[Fact]
public void XmlSchemaValidatorDoesNotEnforceIdentityConstraintsOnDefaultAttributesInSomeCases()
{
Initialize();
string xml = @"<?xml version='1.0'?>
<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='idF016.xsd'>
<uid val='test'/> <uid/></root>";
string xsd = @"<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
<xsd:element name='root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element ref='uid' maxOccurs='unbounded'/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique id='foo123' name='uuid'>
<xsd:selector xpath='.//uid'/>
<xsd:field xpath='@val'/>
</xsd:unique>
</xsd:element>
<xsd:element name='uid' nillable='true'>
<xsd:complexType>
<xsd:attribute name='val' type='xsd:string' default='test'/>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
schemas.Compile();
XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes;
XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags);
validator.Initialize();
using (XmlReader r = XmlReader.Create(new StringReader(xsd)))
{
while (r.Read())
{
switch (r.NodeType)
{
case XmlNodeType.Element:
namespaceManager.PushScope();
if (r.MoveToFirstAttribute())
{
do
{
if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/")
{
namespaceManager.AddNamespace(r.LocalName, r.Value);
}
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null);
if (r.MoveToFirstAttribute())
{
do
{
if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/")
{
validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null);
}
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
validator.ValidateEndOfAttributes(null);
if (r.IsEmptyElement) goto case XmlNodeType.EndElement;
break;
case XmlNodeType.EndElement:
validator.ValidateEndElement(null);
namespaceManager.PopScope();
break;
case XmlNodeType.Text:
validator.ValidateText(r.Value);
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
validator.ValidateWhitespace(r.Value);
break;
default:
break;
}
}
validator.EndValidation();
}
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
using (XmlReader r = XmlReader.Create(new StringReader(xml), rs))
{
try
{
while (r.Read()) ;
}
catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); return; }
}
Assert.True(false);
}
public void RunTest(ArrayList schemaList, string xml)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.XmlResolver = new XmlUrlResolver();
for (int i = 0; i < schemaList.Count; ++i)
{
XmlSchema schema = XmlSchema.Read(new StringReader((string)schemaList[i]), new ValidationEventHandler(ValidationCallback));
settings.Schemas.Add(schema);
}
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
while (reader.Read()) ;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.StreamAnalytics
{
/// <summary>
/// Operations for managing the transformation definition of the stream
/// analytics job.
/// </summary>
internal partial class TransformationOperations : IServiceOperations<StreamAnalyticsManagementClient>, ITransformationOperations
{
/// <summary>
/// Initializes a new instance of the TransformationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TransformationOperations(StreamAnalyticsManagementClient client)
{
this._client = client;
}
private StreamAnalyticsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.StreamAnalytics.StreamAnalyticsManagementClient.
/// </summary>
public StreamAnalyticsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Transformation != null)
{
if (parameters.Transformation.Name == null)
{
throw new ArgumentNullException("parameters.Transformation.Name");
}
if (parameters.Transformation.Properties == null)
{
throw new ArgumentNullException("parameters.Transformation.Properties");
}
if (parameters.Transformation.Properties.Query == null)
{
throw new ArgumentNullException("parameters.Transformation.Properties.Query");
}
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + Uri.EscapeDataString(parameters.Transformation.Name) + "?";
url = url + "api-version=2014-12-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationCreateOrUpdateParametersValue = new JObject();
requestDoc = transformationCreateOrUpdateParametersValue;
if (parameters.Transformation != null)
{
transformationCreateOrUpdateParametersValue["name"] = parameters.Transformation.Name;
JObject propertiesValue = new JObject();
transformationCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Transformation.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Transformation.Properties.Etag;
}
if (parameters.Transformation.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Transformation.Properties.StreamingUnits.Value;
}
propertiesValue["query"] = parameters.Transformation.Properties.Query;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update a transformation for a stream analytics job. The
/// raw json content will be used.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job. It is in json format.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string jobName, string transformationName, TransformationCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Content == null)
{
throw new ArgumentNullException("parameters.Content");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + Uri.EscapeDataString(transformationName) + "?";
url = url + "api-version=2014-12-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Content;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation get operation.
/// </returns>
public async Task<TransformationsGetResponse> GetAsync(string resourceGroupName, string jobName, string transformationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + Uri.EscapeDataString(transformationName) + "?";
url = url + "api-version=2014-12-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationsGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update an transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to update an transformation for
/// the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation patch operation.
/// </returns>
public async Task<TransformationPatchResponse> UpdateAsync(string resourceGroupName, string jobName, string transformationName, TransformationPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Query == null)
{
throw new ArgumentNullException("parameters.Properties.Query");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + Uri.EscapeDataString(transformationName) + "?";
url = url + "api-version=2014-12-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationPatchParametersValue = new JObject();
requestDoc = transformationPatchParametersValue;
JObject propertiesValue = new JObject();
transformationPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Properties.Etag;
}
if (parameters.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Properties.StreamingUnits.Value;
}
propertiesValue["query"] = parameters.Properties.Query;
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TransformationPatchResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationPatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
result.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 TestNotZAndNotCUInt64()
{
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.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();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 BooleanBinaryOpTest__TestNotZAndNotCUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt64> _fld1;
public Vector256<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestNotZAndNotCUInt64 testClass)
{
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestNotZAndNotCUInt64 testClass)
{
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestNotZAndNotCUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public BooleanBinaryOpTest__TestNotZAndNotCUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestNotZAndNotC(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestNotZAndNotC(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt64>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(pClsVar1)),
Avx.LoadVector256((UInt64*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx.TestNotZAndNotC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt64();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestNotZAndNotCUInt64();
fixed (Vector256<UInt64>* pFld1 = &test._fld1)
fixed (Vector256<UInt64>* pFld2 = &test._fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestNotZAndNotC(
Avx.LoadVector256((UInt64*)(&test._fld1)),
Avx.LoadVector256((UInt64*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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(Vector256<UInt64> op1, Vector256<UInt64> op2, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
succeeded = (((expectedResult1 == false) && (expectedResult2 == false)) == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
function GuiEditorUndoManager::onAddUndo( %this )
{
GuiEditor.updateUndoMenu();
}
//-----------------------------------------------------------------------------------------
// Undo adding an object
function UndoActionAddObject::create( %set, %trash, %treeView )
{
%act = UndoActionAddDelete::create( UndoActionAddObject, %set, %trash, %treeView );
%act.actionName = "Add Objects";
return %act;
}
function UndoActionAddObject::undo(%this)
{
%this.trashObjects();
}
function UndoActionAddObject::redo(%this)
{
%this.restoreObjects();
}
//-----------------------------------------------------------------------------------------
// Undo Deleting an object
function UndoActionDeleteObject::create( %set, %trash, %treeView )
{
%act = UndoActionAddDelete::create( UndoActionDeleteObject, %set, %trash, %treeView, true );
%act.designatedDeleter = true;
%act.actionName = "Delete Objects";
return %act;
}
function UndoActionDeleteObject::undo( %this )
{
%this.restoreObjects();
}
function UndoActionDeleteObject::redo( %this )
{
%this.trashObjects();
}
//-----------------------------------------------------------------------------------------
// Behavior common to Add and Delete UndoActions
function UndoActionAddDelete::create( %class, %set, %trash, %treeView, %clearNames )
{
// record objects
// record parents
// record trash
// return new subclass %class of UndoActionAddDelete
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%act = new UndoScriptAction() { class = %class; superclass = UndoActionAddDelete; };
// Restore the instant group.
popInstantGroup();
for(%i = 0; %i < %set.getCount(); %i++)
{
%obj = %set.getObject(%i);
%act.object[ %i ] = %obj.getId();
%act.parent[ %i ] = %obj.getParent();
%act.objectName[ %i ] = %obj.name;
// Clear object name so we don't get name clashes with the trash.
if( %clearNames )
%obj.name = "";
}
%act.objCount = %set.getCount();
%act.trash = %trash;
%act.tree = %treeView;
return %act;
}
function UndoActionAddDelete::trashObjects(%this)
{
// Move objects to trash.
for( %i = 0; %i < %this.objCount; %i ++ )
{
%object = %this.object[ %i ];
%this.trash.add( %object );
%object.name = "";
}
// Note that we're responsible for deleting those objects we've moved to the trash.
%this.designatedDeleter = true;
// Update the tree view.
if( isObject( %this.tree ) )
%this.tree.update();
}
function UndoActionAddDelete::restoreObjects(%this)
{
// Move objects to saved parent and restore names.
for( %i = 0; %i < %this.objCount; %i ++ )
{
%object = %this.object[ %i ];
%object.name = %this.objectName[ %i ];
%this.parent[ %i ].add( %object );
}
// Note that we no longer own the objects, and should not delete them when we're deleted.
%this.designatedDeleter = false;
// Update the tree view.
if( isObject( %this.tree ) )
%this.tree.update();
}
function UndoActionAddObject::onRemove(%this)
{
// if this undoAction owns objects in the trash, delete them.
if( !%this.designatedDeleter)
return;
for( %i = 0; %i < %this.objCount; %i ++)
%this.object[ %i ].delete();
}
//-----------------------------------------------------------------------------------------
// Undo grouping/ungrouping of controls.
function GuiEditorGroupUngroupAction::groupControls( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
%this.group[ %i ].group();
GuiEditorTreeView.update();
}
function GuiEditorGroupUngroupAction::ungroupControls( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
%this.group[ %i ].ungroup();
GuiEditorTreeView.update();
}
function GuiEditorGroupUngroupAction::onRemove( %this )
{
for( %i = 0; %i < %this.count; %i ++ )
if( isObject( %this.group[ %i ] ) )
%this.group[ %i ].delete();
}
function GuiEditorGroupAction::create( %set, %root )
{
// Create action object.
pushInstantGroup();
%action = new UndoScriptAction()
{
actionName = "Group";
className = GuiEditorGroupAction;
superClass = GuiEditorGroupUngroupAction;
count = 1;
group[ 0 ] = new ScriptObject()
{
className = GuiEditorGroup;
count = %set.getCount();
groupParent = GuiEditor.getCurrentAddSet();
};
};
popInstantGroup();
// Add objects from set to group.
%group = %action.group[ 0 ];
%num = %set.getCount();
for( %i = 0; %i < %num; %i ++ )
{
%ctrl = %set.getObject( %i );
if( %ctrl != %root )
%group.ctrl[ %i ] = %ctrl;
}
return %action;
}
function GuiEditorGroupAction::undo( %this )
{
%this.ungroupControls();
}
function GuiEditorGroupAction::redo( %this )
{
%this.groupControls();
}
function GuiEditorUngroupAction::create( %set, %root )
{
// Create action object.
pushInstantGroup();
%action = new UndoScriptAction()
{
actionName = "Ungroup";
className = GuiEditorUngroupAction;
superClass = GuiEditorGroupUngroupAction;
};
// Add groups from set to action.
%groupCount = 0;
%numInSet = %set.getCount();
for( %i = 0; %i < %numInSet; %i ++ )
{
%obj = %set.getObject( %i );
if( %obj.getClassName() $= "GuiControl" && %obj != %root )
{
// Create group object.
%group = new ScriptObject()
{
className = GuiEditorGroup;
count = %obj.getCount();
groupParent = %obj.parentGroup;
groupObject = %obj;
};
%action.group[ %groupCount ] = %group;
%groupCount ++;
// Add controls.
%numControls = %obj.getCount();
for( %j = 0; %j < %numControls; %j ++ )
%group.ctrl[ %j ] = %obj.getObject( %j );
}
}
popInstantGroup();
%action.count = %groupCount;
return %action;
}
function GuiEditorUngroupAction::undo( %this )
{
%this.groupControls();
}
function GuiEditorUngroupAction::redo( %this )
{
%this.ungroupControls();
}
//------------------------------------------------------------------------------
// Undo Any State Change.
function GenericUndoAction::create()
{
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%act = new UndoScriptAction() { class = GenericUndoAction; };
%act.actionName = "Edit Objects";
// Restore the instant group.
popInstantGroup();
return %act;
}
function GenericUndoAction::watch(%this, %object)
{
// make sure we're working with the object id, because it cannot change.
%object = %object.getId();
%fieldCount = %object.getFieldCount();
%dynFieldCount = %object.getDynamicFieldCount();
// inspect all the fields on the object, including dyanamic ones.
// record field names and values.
for(%i = 0; %i < %fieldCount; %i++)
{
%field = %object.getField(%i);
%this.fieldNames[%object] = %this.fieldNames[%object] SPC %field;
%this.fieldValues[%object, %field] = %object.getFieldValue(%field);
}
for(%i = 0; %i < %dynFieldCount; %i++)
{
%field = %object.getDynamicField(%i);
%this.fieldNames[%object] = %this.fieldNames[%object] SPC %field;
%this.fieldValues[%object, %field] = %object.getFieldValue(%field);
}
// clean spurious spaces from the field name list
%this.fieldNames[%object] = trim(%this.fieldNames[%object]);
// record that we know this object
%this.objectIds[%object] = 1;
%this.objectIdList = %this.objectIdList SPC %object;
}
function GenericUndoAction::learn(%this, %object)
{
// make sure we're working with the object id, because it cannot change.
%object = %object.getId();
%fieldCount = %object.getFieldCount();
%dynFieldCount = %object.getDynamicFieldCount();
// inspect all the fields on the object, including dyanamic ones.
// record field names and values.
for(%i = 0; %i < %fieldCount; %i++)
{
%field = %object.getField(%i);
%this.newFieldNames[%object] = %this.newFieldNames[%object] SPC %field;
%this.newFieldValues[%object, %field] = %object.getFieldValue(%field);
}
for(%i = 0; %i < %dynFieldCount; %i++)
{
%field = %object.getDynamicField(%i);
%this.newFieldNames[%object] = %this.newFieldNames[%object] SPC %field;
%this.newFieldValues[%object, %field] = %object.getFieldValue(%field);
}
// trim
%this.newFieldNames[%object] = trim(%this.newFieldNames[%object]);
// look for differences
//----------------------------------------------------------------------
%diffs = false;
%newFieldNames = %this.newFieldNames[%object];
%oldFieldNames = %this.fieldNames[%object];
%numNewFields = getWordCount(%newFieldNames);
%numOldFields = getWordCount(%oldFieldNames);
// compare the old field list to the new field list.
// if a field is on the old list that isn't on the new list,
// add it to the newNullFields list.
for(%i = 0; %i < %numOldFields; %i++)
{
%field = getWord(%oldFieldNames, %i);
%newVal = %this.newFieldValues[%object, %field];
%oldVal = %this.fieldValues[%object, %field];
if(%newVal !$= %oldVal)
{
%diffs = true;
if(%newVal $= "")
{
%newNullFields = %newNullFields SPC %field;
}
}
}
// scan the new field list
// add missing fields to the oldNullFields list
for(%i = 0; %i < %numNewFields; %i++)
{
%field = getWord(%newFieldNames, %i);
%newVal = %this.newFieldValues[%object, %field];
%oldVal = %this.fieldValues[%object, %field];
if(%newVal !$= %oldVal)
{
%diffs = true;
if(%oldVal $= "")
{
%oldNullFields = %oldNullFields SPC %field;
}
}
}
%this.newNullFields[%object] = trim(%newNullFields);
%this.oldNullFields[%object] = trim(%oldNullFields);
return %diffs;
}
function GenericUndoAction::watchSet(%this, %set)
{
// scan the set
// this.watch each object.
%setcount = %set.getCount();
%i = 0;
for(; %i < %setcount; %i++)
{
%object = %set.getObject(%i);
%this.watch(%object);
}
}
function GenericUndoAction::learnSet(%this, %set)
{
// scan the set
// this.learn any objects that we have a this.objectIds[] entry for.
%diffs = false;
for(%i = 0; %i < %set.getCount(); %i++)
{
%object = %set.getObject(%i).getId();
if(%this.objectIds[%object] != 1)
continue;
if(%this.learn(%object))
%diffs = true;
}
return %diffs;
}
function GenericUndoAction::undo(%this)
{
// set the objects to the old values
// scan through our objects
%objectList = %this.objectIdList;
for(%i = 0; %i < getWordCount(%objectList); %i++)
{
%object = getWord(%objectList, %i);
// scan through the old extant fields
%fieldNames = %this.fieldNames[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, %this.fieldValues[%object, %field]);
}
// null out the fields in the null list
%fieldNames = %this.oldNullFields[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, "");
}
}
// update the tree view
if(isObject(%this.tree))
%this.tree.update();
}
function GenericUndoAction::redo(%this)
{
// set the objects to the new values
// set the objects to the new values
// scan through our objects
%objectList = %this.objectIdList;
for(%i = 0; %i < getWordCount(%objectList); %i++)
{
%object = getWord(%objectList, %i);
// scan through the new extant fields
%fieldNames = %this.newFieldNames[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, %this.newFieldValues[%object, %field]);
}
// null out the fields in the null list
%fieldNames = %this.newNullFields[%object];
for(%j = 0; %j < getWordCount(%fieldNames); %j++)
{
%field = getWord(%fieldNames, %j);
%object.setFieldValue(%field, "");
}
}
// update the tree view
if(isObject(%this.tree))
%this.tree.update();
}
//-----------------------------------------------------------------------------------------
// Gui Editor Undo hooks from code
function GuiEditor::onPreEdit(%this, %selection)
{
if ( isObject(%this.pendingGenericUndoAction) )
{
error("Error: attempting to create two generic undo actions at once in the same editor!");
return;
}
//echo("pre edit");
%act = GenericUndoAction::create();
%act.watchSet(%selection);
%act.tree = GuiEditorTreeView;
%this.pendingGenericUndoAction = %act;
%this.updateUndoMenu();
}
function GuiEditor::onPostEdit(%this, %selection)
{
if(!isObject(%this.pendingGenericUndoAction))
error("Error: attempting to complete a GenericUndoAction that hasn't been started!");
%act = %this.pendingGenericUndoAction;
%this.pendingGenericUndoAction = "";
%diffs = %act.learnSet(%selection);
if(%diffs)
{
//echo("adding generic undoaction to undo manager");
//%act.dump();
%act.addToManager(%this.getUndoManager());
}
else
{
//echo("deleting empty generic undoaction");
%act.delete();
}
%this.updateUndoMenu();
}
function GuiEditor::onPreSelectionNudged(%this, %selection)
{
%this.onPreEdit(%selection);
%this.pendingGenericUndoAction.actionName = "Nudge";
}
function GuiEditor::onPostSelectionNudged(%this, %selection)
{
%this.onPostEdit(%selection);
}
function GuiEditor::onAddNewCtrl(%this, %ctrl)
{
%set = new SimSet();
%set.add(%ctrl);
%act = UndoActionAddObject::create(%set, %this.getTrash(), GuiEditorTreeView);
%set.delete();
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
//GuiEditorInspectFields.update(0);
}
function GuiEditor::onAddNewCtrlSet(%this, %selection)
{
%act = UndoActionAddObject::create(%selection, %this.getTrash(), GuiEditorTreeView);
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
}
function GuiEditor::onTrashSelection(%this, %selection)
{
%act = UndoActionDeleteObject::create(%selection, %this.getTrash(), GuiEditorTreeView);
%act.addToManager(%this.getUndoManager());
%this.updateUndoMenu();
}
function GuiEditor::onControlInspectPreApply(%this, %object)
{
%set = new SimSet();
%set.add(%object);
%this.onPreEdit(%set);
%this.pendingGenericUndoAction.actionName = "Change Properties";
%set.delete();
}
function GuiEditor::onControlInspectPostApply(%this, %object)
{
%set = new SimSet();
%set.add(%object);
%this.onPostEdit(%set);
%set.delete();
GuiEditorTreeView.update();
}
function GuiEditor::onFitIntoParents( %this )
{
%selected = %this.getSelection();
//TODO
}
| |
/************************************************************************
* Copyright (c) 2006-2008, Jason Whitehorn (jason.whitehorn@gmail.com)
* 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.Text;
using NUnit.Framework;
using aspNETserve;
namespace IntegrationTests.NetServeTests {
/// <summary>
/// battery of test to verify that the HttpRequest object
/// of the running servers Context is behaving correctly.
/// </summary>
[TestFixture]
public class HttpRequestObjectTests : BaseTest{
[Test]
[Ignore]
public void AcceptTypesTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void AnonymousIDTest() {
throw new NotImplementedException();
}
[Test]
public void ApplicationPathTest() {
string value = GetServerVariable("Context.Request.ApplicationPath");
Assert.AreEqual("/", value);
}
[Test]
public void ApplicationPathVirtualPathTest(){
string value = GetServerVariable("Context.Request.ApplicationPath", "/vDir");
Assert.AreEqual("/vDir", value);
}
[Test]
public void AppRelativeCurrentExecutionFilePathTest() {
string value = GetServerVariable("Context.Request.AppRelativeCurrentExecutionFilePath");
Assert.AreEqual("~/GetServerVariable.aspx", value);
}
[Test]
[Ignore]
public void BrowserTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void ClientCertificateTest() {
throw new NotImplementedException();
}
[Test]
public void ContentEncodingTest() {
string value = GetServerVariable("Context.Request.ContentEncoding");
Assert.AreEqual("System.Text.UTF8Encoding", value);
}
[Test]
public void ContentLengthTest() {
string value = GetServerVariable("Context.Request.ContentLength");
Assert.AreEqual("0", value);
}
[Test]
[Ignore]
public void ContentTypeTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void CookiesTest() {
throw new NotImplementedException();
}
[Test]
public void CurrentExecutionFilePathTest() {
string value = GetServerVariable("Context.Request.CurrentExecutionFilePath");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
public void FilePathTest() {
string value = GetServerVariable("Context.Request.FilePath");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
[Ignore]
public void FilesTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void FilterTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void FormTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void HeadersTest() {
throw new NotImplementedException();
}
[Test]
public void HttpMethodTest() {
string value = GetServerVariable("Context.Request.HttpMethod");
Assert.AreEqual("GET", value);
}
[Test]
[Ignore]
public void InputStreamTest() {
throw new NotImplementedException();
}
[Test]
public void IsAuthenticatedTest() {
string value = GetServerVariable("Context.Request.IsAuthenticated");
Assert.AreEqual("False", value);
}
[Test]
public void IsLocalTest() {
string value = GetServerVariable("Context.Request.IsLocal");
Assert.AreEqual("True", value);
}
[Test]
public void IsSecureConnectionTest() {
string value = GetServerVariable("Context.Request.IsSecureConnection");
Assert.AreEqual("False", value);
}
[Test]
[Ignore]
public void ItemTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void LogonUserIdentityTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void ParamsTest() {
throw new NotImplementedException();
}
[Test]
public void PathTest() {
string value = GetServerVariable("Context.Request.Path");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
public void PathInfoTest() {
using (Server s = new Server(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), "/", PhysicalPath, _port)) {
s.Start();
string url = string.Format("http://localhost:{0}/Tail.aspx", _port);
Console.WriteLine("Getting: " + url);
string page = GetPage(url);
Console.WriteLine(page);
Assert.AreEqual(true, page.Contains("<span id=\"lblTail\"></span>"));
url = string.Format("http://localhost:{0}/Tail.aspx/foo", _port);
Console.WriteLine("Getting: " + url);
page = GetPage(url);
Console.WriteLine(page);
Assert.AreEqual(true, page.Contains("<span id=\"lblTail\">/foo</span>"));
s.Stop();
}
}
[Test]
public void PhysicalApplicationPathTest() {
string value = GetServerVariable("Context.Request.PhysicalApplicationPath");
Assert.AreEqual(PhysicalPath, value);
}
[Test]
public void PhysicalPathTest() {
string value = GetServerVariable("Context.Request.PhysicalPath");
Assert.AreEqual(PhysicalPath + "GetServerVariable.aspx", value);
}
[Test]
public void QueryStringTest() {
string value = GetServerVariable("Context.Request.QueryString");
Assert.AreEqual("var=Context.Request.QueryString", value);
}
[Test]
public void RawUrlTest() {
string value = GetServerVariable("Context.Request.RawUrl");
Assert.AreEqual(@"/GetServerVariable.aspx?var=Context.Request.RawUrl", value);
}
[Test]
public void RequestTypeTest() {
string value = GetServerVariable("Context.Request.RequestType");
Assert.AreEqual("GET", value);
}
[Test]
[Ignore]
public void ServerVariablesTest() {
throw new NotImplementedException();
}
[Test]
public void TotalBytesTest() {
string value = GetServerVariable("Context.Request.TotalBytes");
Assert.AreEqual("0", value);
}
[Test]
public void UrlTest() {
string value = GetServerVariable("Context.Request.Url");
Assert.AreEqual("http://localhost:" + _port + "/GetServerVariable.aspx?var=Context.Request.Url", value);
}
[Test]
[Ignore]
public void UrlReferrerTest() {
throw new NotImplementedException();
}
[Test]
public void UserAgentTest() {
string value = GetServerVariable("Context.Request.UserAgent");
Assert.AreEqual(_userAgent, value);
}
[Test]
public void UserHostAddressTest() {
string value = GetServerVariable("Context.Request.UserHostAddress");
Assert.AreEqual("127.0.0.1", value);
}
[Test]
public void UserHostNameTest() {
string value = GetServerVariable("Context.Request.UserHostName");
Assert.AreEqual("127.0.0.1", value);
}
[Test]
[Ignore]
public void UserLanguagesTest() {
throw new NotImplementedException();
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager.Forms
{
partial class PrebuiltConfigForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PrebuiltConfigForm));
this.btnCancel = new System.Windows.Forms.Button();
this.btnNext = new System.Windows.Forms.Button();
this.btnBack = new System.Windows.Forms.Button();
this.smoothLabel5 = new global::Controls.SmoothLabel();
this.wizMain = new global::Controls.Wizard.Wizard();
this.pgFinish = new global::Controls.Wizard.WizardPage();
this.label2 = new System.Windows.Forms.Label();
this.pgGreeting = new global::Controls.Wizard.WizardPage();
this.lblGreetingTitle = new System.Windows.Forms.Label();
this.lblGreetingDescription = new System.Windows.Forms.Label();
this.greetingControl = new CallButler.Manager.Controls.GreetingControl(ManagementInterfaceClient.ManagementClient, ManagementInterfaceClient.AuthInfo);
this.pgDetails = new global::Controls.Wizard.WizardPage();
this.lblTextTitle = new System.Windows.Forms.Label();
this.lblTextDescription = new System.Windows.Forms.Label();
this.lblTextDisplayName = new System.Windows.Forms.Label();
this.txtTextValue = new System.Windows.Forms.TextBox();
this.pgChooseConfig = new global::Controls.Wizard.WizardPage();
this.prebuiltConfigControl = new CallButler.Manager.ViewControls.PrebuiltConfigControl();
this.label1 = new System.Windows.Forms.Label();
this.reflectionPicture1 = new global::Controls.ReflectionPicture();
this.wizMain.SuspendLayout();
this.pgFinish.SuspendLayout();
this.pgGreeting.SuspendLayout();
this.pgDetails.SuspendLayout();
this.pgChooseConfig.SuspendLayout();
this.SuspendLayout();
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnCancel.Name = "btnCancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnNext
//
resources.ApplyResources(this.btnNext, "btnNext");
this.btnNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnNext.Name = "btnNext";
this.btnNext.UseVisualStyleBackColor = true;
this.btnNext.Click += new System.EventHandler(this.btnNext_Click);
//
// btnBack
//
resources.ApplyResources(this.btnBack, "btnBack");
this.btnBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.btnBack.Name = "btnBack";
this.btnBack.UseVisualStyleBackColor = true;
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
//
// smoothLabel5
//
resources.ApplyResources(this.smoothLabel5, "smoothLabel5");
this.smoothLabel5.ForeColor = System.Drawing.Color.CornflowerBlue;
this.smoothLabel5.Name = "smoothLabel5";
//
// wizMain
//
this.wizMain.AlwaysShowFinishButton = false;
this.wizMain.BackColor = System.Drawing.Color.Transparent;
this.wizMain.CloseOnCancel = false;
this.wizMain.CloseOnFinish = false;
this.wizMain.Controls.Add(this.pgFinish);
this.wizMain.Controls.Add(this.pgGreeting);
this.wizMain.Controls.Add(this.pgDetails);
this.wizMain.Controls.Add(this.pgChooseConfig);
this.wizMain.DisplayButtons = false;
resources.ApplyResources(this.wizMain, "wizMain");
this.wizMain.Name = "wizMain";
this.wizMain.PageIndex = 3;
this.wizMain.Pages.AddRange(new global::Controls.Wizard.WizardPage[] {
this.pgChooseConfig,
this.pgDetails,
this.pgGreeting,
this.pgFinish});
this.wizMain.ShowTabs = false;
this.wizMain.TabBackColor = System.Drawing.Color.WhiteSmoke;
this.wizMain.TabBackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile;
this.wizMain.TabDividerLineType = global::Controls.Wizard.WizardTabDividerLineType.SingleLine;
//
// pgFinish
//
this.pgFinish.Controls.Add(this.label2);
resources.ApplyResources(this.pgFinish, "pgFinish");
this.pgFinish.IsFinishPage = false;
this.pgFinish.Name = "pgFinish";
this.pgFinish.TabLinkColor = System.Drawing.SystemColors.ControlText;
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// pgGreeting
//
this.pgGreeting.Controls.Add(this.lblGreetingTitle);
this.pgGreeting.Controls.Add(this.lblGreetingDescription);
this.pgGreeting.Controls.Add(this.greetingControl);
resources.ApplyResources(this.pgGreeting, "pgGreeting");
this.pgGreeting.IsFinishPage = false;
this.pgGreeting.Name = "pgGreeting";
this.pgGreeting.TabLinkColor = System.Drawing.SystemColors.ControlText;
//
// lblGreetingTitle
//
resources.ApplyResources(this.lblGreetingTitle, "lblGreetingTitle");
this.lblGreetingTitle.Name = "lblGreetingTitle";
//
// lblGreetingDescription
//
resources.ApplyResources(this.lblGreetingDescription, "lblGreetingDescription");
this.lblGreetingDescription.Name = "lblGreetingDescription";
//
// greetingControl
//
this.greetingControl.BackColor = System.Drawing.Color.WhiteSmoke;
resources.ApplyResources(this.greetingControl, "greetingControl");
this.greetingControl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.greetingControl.Name = "greetingControl";
//
// pgDetails
//
this.pgDetails.Controls.Add(this.lblTextTitle);
this.pgDetails.Controls.Add(this.lblTextDescription);
this.pgDetails.Controls.Add(this.lblTextDisplayName);
this.pgDetails.Controls.Add(this.txtTextValue);
resources.ApplyResources(this.pgDetails, "pgDetails");
this.pgDetails.IsFinishPage = false;
this.pgDetails.Name = "pgDetails";
this.pgDetails.TabLinkColor = System.Drawing.SystemColors.ControlText;
//
// lblTextTitle
//
resources.ApplyResources(this.lblTextTitle, "lblTextTitle");
this.lblTextTitle.Name = "lblTextTitle";
//
// lblTextDescription
//
resources.ApplyResources(this.lblTextDescription, "lblTextDescription");
this.lblTextDescription.Name = "lblTextDescription";
//
// lblTextDisplayName
//
resources.ApplyResources(this.lblTextDisplayName, "lblTextDisplayName");
this.lblTextDisplayName.Name = "lblTextDisplayName";
//
// txtTextValue
//
resources.ApplyResources(this.txtTextValue, "txtTextValue");
this.txtTextValue.Name = "txtTextValue";
//
// pgChooseConfig
//
this.pgChooseConfig.Controls.Add(this.prebuiltConfigControl);
this.pgChooseConfig.Controls.Add(this.label1);
resources.ApplyResources(this.pgChooseConfig, "pgChooseConfig");
this.pgChooseConfig.IsFinishPage = false;
this.pgChooseConfig.Name = "pgChooseConfig";
this.pgChooseConfig.TabLinkColor = System.Drawing.SystemColors.ControlText;
//
// prebuiltConfigControl
//
resources.ApplyResources(this.prebuiltConfigControl, "prebuiltConfigControl");
this.prebuiltConfigControl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.prebuiltConfigControl.Name = "prebuiltConfigControl";
this.prebuiltConfigControl.SelectedConfigurationChanged += new System.EventHandler(this.prebuiltConfigControl_SelectedConfigurationChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// reflectionPicture1
//
resources.ApplyResources(this.reflectionPicture1, "reflectionPicture1");
this.reflectionPicture1.Image = global::CallButler.Manager.Properties.Resources.office_building_128_shadow;
this.reflectionPicture1.Name = "reflectionPicture1";
//
// PrebuiltConfigForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.BackgroundImage = global::CallButler.Manager.Properties.Resources.cb_header;
this.Controls.Add(this.reflectionPicture1);
this.Controls.Add(this.smoothLabel5);
this.Controls.Add(this.btnBack);
this.Controls.Add(this.btnNext);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.wizMain);
this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PrebuiltConfigForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.wizMain.ResumeLayout(false);
this.pgFinish.ResumeLayout(false);
this.pgGreeting.ResumeLayout(false);
this.pgDetails.ResumeLayout(false);
this.pgDetails.PerformLayout();
this.pgChooseConfig.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private global::Controls.Wizard.Wizard wizMain;
private global::Controls.Wizard.WizardPage pgChooseConfig;
private CallButler.Manager.ViewControls.PrebuiltConfigControl prebuiltConfigControl;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnBack;
private global::Controls.Wizard.WizardPage pgDetails;
private System.Windows.Forms.TextBox txtTextValue;
private System.Windows.Forms.Label lblTextDisplayName;
private System.Windows.Forms.Label lblTextDescription;
private global::Controls.Wizard.WizardPage pgFinish;
private System.Windows.Forms.Label label2;
private global::Controls.Wizard.WizardPage pgGreeting;
private System.Windows.Forms.Label lblGreetingDescription;
private CallButler.Manager.Controls.GreetingControl greetingControl;
private System.Windows.Forms.Label lblGreetingTitle;
private System.Windows.Forms.Label lblTextTitle;
private global::Controls.SmoothLabel smoothLabel5;
private global::Controls.ReflectionPicture reflectionPicture1;
}
}
| |
//
// System.IO.StreamReader.cs
//
// Authors:
// Dietmar Maurer (dietmar@ximian.com)
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// (C) Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004 Novell (http://www.novell.com)
// Copyright 2011, 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Runtime.InteropServices;
#if NET_4_5
using System.Threading.Tasks;
#endif
namespace System.IO
{
[Serializable]
[ComVisible(true)]
public class StreamReader : TextReader
{
sealed class NullStreamReader : StreamReader
{
public override int Peek()
{
return -1;
}
public override int Read()
{
return -1;
}
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
public override string ReadToEnd()
{
return String.Empty;
}
public override Stream BaseStream
{
get { return Stream.Null; }
}
public override Encoding CurrentEncoding
{
get { return Encoding.Unicode; }
}
}
const int DefaultBufferSize = 1024;
const int DefaultFileBufferSize = 4096;
const int MinimumBufferSize = 128;
//
// The input buffer
//
byte[] input_buffer;
// Input buffer ready for recycling
static byte[] input_buffer_recycle;
static object input_buffer_recycle_lock = new object();
//
// The decoded buffer from the above input buffer
//
char[] decoded_buffer;
static char[] decoded_buffer_recycle;
Encoding encoding;
Decoder decoder;
StringBuilder line_builder;
Stream base_stream;
//
// Decoded bytes in decoded_buffer.
//
int decoded_count;
//
// Current position in the decoded_buffer
//
int pos;
//
// The buffer size that we are using
//
int buffer_size;
int do_checks;
bool mayBlock;
#if NET_4_5
IDecoupledTask async_task;
readonly bool leave_open;
#endif
public new static readonly StreamReader Null = new NullStreamReader();
private StreamReader() { }
public StreamReader(Stream stream)
: this(stream, Encoding.UTF8, true, DefaultBufferSize) { }
public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
: this(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
public StreamReader(Stream stream, Encoding encoding)
: this(stream, encoding, true, DefaultBufferSize) { }
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
#if NET_4_5
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false)
{
}
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
#else
const bool leave_open = false;
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
#endif
{
#if NET_4_5
leave_open = leaveOpen;
#endif
Initialize(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
}
public StreamReader(string path)
: this(path, Encoding.UTF8, true, DefaultFileBufferSize) { }
public StreamReader(string path, bool detectEncodingFromByteOrderMarks)
: this(path, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding)
: this(path, encoding, true, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(path, encoding, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
{
if (null == path)
throw new ArgumentNullException("path");
if (String.Empty == path)
throw new ArgumentException("Empty path not allowed");
if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1)
throw new ArgumentException("path contains invalid characters");
if (null == encoding)
throw new ArgumentNullException("encoding");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", "The minimum size of the buffer must be positive");
Stream stream = File.OpenRead(path);
Initialize(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
}
internal void Initialize(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
{
if (null == stream)
throw new ArgumentNullException("stream");
if (null == encoding)
throw new ArgumentNullException("encoding");
if (!stream.CanRead)
throw new ArgumentException("Cannot read stream");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", "The minimum size of the buffer must be positive");
if (bufferSize < MinimumBufferSize)
bufferSize = MinimumBufferSize;
// since GetChars() might add flushed character, it
// should have additional char buffer for extra 1
// (probably 1 is ok, but might be insufficient. I'm not sure)
var decoded_buffer_size = encoding.GetMaxCharCount(bufferSize) + 1;
//
// Instead of allocating a new default buffer use the
// last one if there is any available
//
if (bufferSize <= DefaultBufferSize && input_buffer_recycle != null)
{
lock (input_buffer_recycle_lock)
{
if (input_buffer_recycle != null)
{
input_buffer = input_buffer_recycle;
input_buffer_recycle = null;
}
if (decoded_buffer_recycle != null && decoded_buffer_size <= decoded_buffer_recycle.Length)
{
decoded_buffer = decoded_buffer_recycle;
decoded_buffer_recycle = null;
}
}
}
if (input_buffer == null)
input_buffer = new byte[bufferSize];
else
Array.Clear(input_buffer, 0, bufferSize);
if (decoded_buffer == null)
decoded_buffer = new char[decoded_buffer_size];
else
Array.Clear(decoded_buffer, 0, decoded_buffer_size);
base_stream = stream;
this.buffer_size = bufferSize;
this.encoding = encoding;
decoder = encoding.GetDecoder();
byte[] preamble = encoding.GetPreamble();
do_checks = detectEncodingFromByteOrderMarks ? 1 : 0;
do_checks += (preamble.Length == 0) ? 0 : 2;
decoded_count = 0;
pos = 0;
}
public virtual Stream BaseStream
{
get
{
return base_stream;
}
}
public virtual Encoding CurrentEncoding
{
get
{
if (encoding == null)
throw new Exception();
return encoding;
}
}
public bool EndOfStream
{
get { return Peek() < 0; }
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
if (disposing && base_stream != null && !leave_open)
base_stream.Close();
if (input_buffer != null && input_buffer.Length == DefaultBufferSize && input_buffer_recycle == null)
{
lock (input_buffer_recycle_lock)
{
if (input_buffer_recycle == null)
{
input_buffer_recycle = input_buffer;
}
if (decoded_buffer_recycle == null)
{
decoded_buffer_recycle = decoded_buffer;
}
}
}
input_buffer = null;
decoded_buffer = null;
encoding = null;
decoder = null;
base_stream = null;
base.Dispose(disposing);
}
//
// Provides auto-detection of the encoding, as well as skipping over
// byte marks at the beginning of a stream.
//
int DoChecks(int count)
{
if ((do_checks & 2) == 2)
{
byte[] preamble = encoding.GetPreamble();
int c = preamble.Length;
if (count >= c)
{
int i;
for (i = 0; i < c; i++)
if (input_buffer[i] != preamble[i])
break;
if (i == c)
return i;
}
}
if ((do_checks & 1) == 1)
{
if (count < 2)
return 0;
if (input_buffer[0] == 0xfe && input_buffer[1] == 0xff)
{
this.encoding = Encoding.BigEndianUnicode;
return 2;
}
if (input_buffer[0] == 0xff && input_buffer[1] == 0xfe && count < 4)
{
// If we don't have enough bytes we can't check for UTF32, so use Unicode
this.encoding = Encoding.Unicode;
return 2;
}
if (count < 3)
return 0;
if (input_buffer[0] == 0xef && input_buffer[1] == 0xbb && input_buffer[2] == 0xbf)
{
this.encoding = Encoding.UTF8;
return 3;
}
if (count < 4)
{
if (input_buffer[0] == 0xff && input_buffer[1] == 0xfe && input_buffer[2] != 0)
{
this.encoding = Encoding.Unicode;
return 2;
}
return 0;
}
if (input_buffer[0] == 0 && input_buffer[1] == 0
&& input_buffer[2] == 0xfe && input_buffer[3] == 0xff)
{
this.encoding = Encoding.BigEndianUTF32;
return 4;
}
if (input_buffer[0] == 0xff && input_buffer[1] == 0xfe)
{
if (input_buffer[2] == 0 && input_buffer[3] == 0)
{
this.encoding = Encoding.UTF32;
return 4;
}
this.encoding = Encoding.Unicode;
return 2;
}
}
return 0;
}
public void DiscardBufferedData()
{
CheckState();
pos = decoded_count = 0;
mayBlock = false;
// Discard internal state of the decoder too.
decoder = encoding.GetDecoder();
}
// the buffer is empty, fill it again
// Keep in sync with ReadBufferAsync
int ReadBuffer()
{
pos = 0;
// keep looping until the decoder gives us some chars
decoded_count = 0;
do
{
var cbEncoded = base_stream.Read(input_buffer, 0, buffer_size);
if (cbEncoded <= 0)
return 0;
decoded_count = ReadBufferCore(cbEncoded);
} while (decoded_count == 0);
return decoded_count;
}
int ReadBufferCore(int cbEncoded)
{
int parse_start;
mayBlock = cbEncoded < buffer_size;
if (do_checks > 0)
{
Encoding old = encoding;
parse_start = DoChecks(cbEncoded);
if (old != encoding)
{
int old_decoded_size = old.GetMaxCharCount(buffer_size) + 1;
int new_decoded_size = encoding.GetMaxCharCount(buffer_size) + 1;
if (old_decoded_size != new_decoded_size)
decoded_buffer = new char[new_decoded_size];
decoder = encoding.GetDecoder();
}
do_checks = 0;
cbEncoded -= parse_start;
}
else
{
parse_start = 0;
}
return decoder.GetChars(input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
}
//
// Peek can block:
// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96484
//
public override int Peek()
{
CheckState();
if (pos >= decoded_count && ReadBuffer() == 0)
return -1;
return decoded_buffer[pos];
}
//
// Used internally by our console, as it previously depended on Peek() being a
// routine that would not block.
//
internal bool DataAvailable()
{
return pos < decoded_count;
}
public override int Read()
{
CheckState();
if (pos >= decoded_count && ReadBuffer() == 0)
return -1;
return decoded_buffer[pos++];
}
// Keep in sync with ReadAsync
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException("index", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException("count", "< 0");
// re-ordered to avoid possible integer overflow
if (index > buffer.Length - count)
throw new ArgumentException("index + count > buffer.Length");
CheckState();
int chars_read = 0;
while (count > 0)
{
if (pos >= decoded_count && ReadBuffer() == 0)
return chars_read > 0 ? chars_read : 0;
int cch = Math.Min(decoded_count - pos, count);
Array.Copy(decoded_buffer, pos, buffer, index, cch);
pos += cch;
index += cch;
count -= cch;
chars_read += cch;
if (mayBlock)
break;
}
return chars_read;
}
bool foundCR;
int FindNextEOL()
{
char c = '\0';
for (; pos < decoded_count; pos++)
{
c = decoded_buffer[pos];
if (c == '\n')
{
pos++;
int res = (foundCR) ? (pos - 2) : (pos - 1);
if (res < 0)
res = 0; // if a new buffer starts with a \n and there was a \r at
// the end of the previous one, we get here.
foundCR = false;
return res;
}
else if (foundCR)
{
foundCR = false;
if (pos == 0)
return -2; // Need to flush the current buffered line.
// This is a \r at the end of the previous decoded buffer that
// is not followed by a \n in the current decoded buffer.
return pos - 1;
}
foundCR = (c == '\r');
}
return -1;
}
// Keep in sync with ReadLineAsync
public override string ReadLine()
{
CheckState();
if (pos >= decoded_count && ReadBuffer() == 0)
return null;
int begin = pos;
int end = FindNextEOL();
if (end < decoded_count && end >= begin)
return new string(decoded_buffer, begin, end - begin);
if (end == -2)
return line_builder.ToString(0, line_builder.Length);
if (line_builder == null)
line_builder = new StringBuilder();
else
line_builder.Length = 0;
while (true)
{
if (foundCR) // don't include the trailing CR if present
decoded_count--;
line_builder.Append(decoded_buffer, begin, decoded_count - begin);
if (ReadBuffer() == 0)
{
if (line_builder.Capacity > 32768)
{
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString(0, sb.Length);
}
return line_builder.ToString(0, line_builder.Length);
}
begin = pos;
end = FindNextEOL();
if (end < decoded_count && end >= begin)
{
line_builder.Append(decoded_buffer, begin, end - begin);
if (line_builder.Capacity > 32768)
{
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString(0, sb.Length);
}
return line_builder.ToString(0, line_builder.Length);
}
if (end == -2)
return line_builder.ToString(0, line_builder.Length);
}
}
// Keep in sync with ReadToEndAsync
public override string ReadToEnd()
{
CheckState();
StringBuilder text = new StringBuilder();
do
{
text.Append(decoded_buffer, pos, decoded_count - pos);
} while (ReadBuffer() != 0);
return text.ToString();
}
void CheckState()
{
if (base_stream == null)
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
#if NET_4_5
if (async_task != null && !async_task.IsCompleted)
throw new InvalidOperationException ();
#endif
}
#if NET_4_5
public override int ReadBlock ([In, Out] char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException ("index", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
// re-ordered to avoid possible integer overflow
if (index > buffer.Length - count)
throw new ArgumentException ("index + count > buffer.Length");
CheckState ();
return base.ReadBlock (buffer, index, count);
}
public override Task<int> ReadAsync (char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException ("index", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
// re-ordered to avoid possible integer overflow
if (index > buffer.Length - count)
throw new ArgumentException ("index + count > buffer.Length");
CheckState ();
DecoupledTask<int> res;
async_task = res = new DecoupledTask<int> (ReadAsyncCore (buffer, index, count));
return res.Task;
}
async Task<int> ReadAsyncCore (char[] buffer, int index, int count)
{
int chars_read = 0;
while (count > 0) {
if (pos >= decoded_count && await ReadBufferAsync ().ConfigureAwait (false) == 0)
return chars_read > 0 ? chars_read : 0;
int cch = Math.Min (decoded_count - pos, count);
Array.Copy (decoded_buffer, pos, buffer, index, cch);
pos += cch;
index += cch;
count -= cch;
chars_read += cch;
if (mayBlock)
break;
}
return chars_read;
}
public override Task<int> ReadBlockAsync (char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException ("index", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", "< 0");
// re-ordered to avoid possible integer overflow
if (index > buffer.Length - count)
throw new ArgumentException ("index + count > buffer.Length");
CheckState ();
DecoupledTask<int> res;
async_task = res = new DecoupledTask<int> (ReadAsyncCore (buffer, index, count));
return res.Task;
}
public override Task<string> ReadLineAsync ()
{
CheckState ();
DecoupledTask<string> res;
async_task = res = new DecoupledTask<string> (ReadLineAsyncCore ());
return res.Task;
}
async Task<string> ReadLineAsyncCore ()
{
if (pos >= decoded_count && await ReadBufferAsync ().ConfigureAwait (false) == 0)
return null;
int begin = pos;
int end = FindNextEOL ();
if (end < decoded_count && end >= begin)
return new string (decoded_buffer, begin, end - begin);
if (end == -2)
return line_builder.ToString (0, line_builder.Length);
if (line_builder == null)
line_builder = new StringBuilder ();
else
line_builder.Length = 0;
while (true) {
if (foundCR) // don't include the trailing CR if present
decoded_count--;
line_builder.Append (decoded_buffer, begin, decoded_count - begin);
if (await ReadBufferAsync ().ConfigureAwait (false) == 0) {
if (line_builder.Capacity > 32768) {
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString (0, sb.Length);
}
return line_builder.ToString (0, line_builder.Length);
}
begin = pos;
end = FindNextEOL ();
if (end < decoded_count && end >= begin) {
line_builder.Append (decoded_buffer, begin, end - begin);
if (line_builder.Capacity > 32768) {
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString (0, sb.Length);
}
return line_builder.ToString (0, line_builder.Length);
}
if (end == -2)
return line_builder.ToString (0, line_builder.Length);
}
}
public override Task<string> ReadToEndAsync ()
{
CheckState ();
DecoupledTask<string> res;
async_task = res = new DecoupledTask<string> (ReadToEndAsyncCore ());
return res.Task;
}
async Task<string> ReadToEndAsyncCore ()
{
StringBuilder text = new StringBuilder ();
do {
text.Append (decoded_buffer, pos, decoded_count - pos);
} while (await ReadBufferAsync () != 0);
return text.ToString ();
}
async Task<int> ReadBufferAsync ()
{
pos = 0;
// keep looping until the decoder gives us some chars
decoded_count = 0;
do {
var cbEncoded = await base_stream.ReadAsync (input_buffer, 0, buffer_size).ConfigureAwait (false);
if (cbEncoded <= 0)
return 0;
decoded_count = ReadBufferCore (cbEncoded);
} while (decoded_count == 0);
return decoded_count;
}
#endif
}
}
| |
namespace System.Workflow.Activities
{
#region Imports
using System;
using System.Diagnostics;
using System.CodeDom;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Runtime;
using System.Workflow.Activities.Common;
#endregion
[ToolboxItem(false)]
[Designer(typeof(EventHandlersDesigner), typeof(IDesigner))]
[ToolboxBitmap(typeof(EventHandlersActivity), "Resources.events.png")]
[ActivityValidator(typeof(EventHandlersValidator))]
[SRCategory(SR.Standard)]
[AlternateFlowActivityAttribute]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class EventHandlersActivity : CompositeActivity, IActivityEventListener<ActivityExecutionStatusChangedEventArgs>
{
public EventHandlersActivity()
{
}
public EventHandlersActivity(string name)
: base(name)
{
}
#region Runtime State Specific Dependency Property
static DependencyProperty ActivityStateProperty = DependencyProperty.Register("ActivityState", typeof(List<EventHandlerEventActivitySubscriber>), typeof(EventHandlersActivity));
static DependencyProperty IsScopeCompletedProperty = DependencyProperty.Register("IsScopeCompleted", typeof(bool), typeof(EventHandlersActivity), new PropertyMetadata(false));
private List<EventHandlerEventActivitySubscriber> ActivityState
{
get
{
return (List<EventHandlerEventActivitySubscriber>)base.GetValue(ActivityStateProperty);
}
set
{
if (value == null)
base.RemoveProperty(ActivityStateProperty);
else
base.SetValue(ActivityStateProperty, value);
}
}
private bool IsScopeCompleted
{
get
{
return (bool)base.GetValue(IsScopeCompletedProperty);
}
set
{
base.SetValue(IsScopeCompletedProperty, value);
}
}
#endregion
internal void UnsubscribeAndClose()
{
base.Invoke<EventArgs>(this.OnUnsubscribeAndClose, EventArgs.Empty);
}
#region Protected Methods
protected override void OnClosed(IServiceProvider provider)
{
base.RemoveProperty(EventHandlersActivity.ActivityStateProperty);
base.RemoveProperty(EventHandlersActivity.IsScopeCompletedProperty);
}
protected override void Initialize(IServiceProvider provider)
{
if (this.Parent == null)
throw new InvalidOperationException(SR.GetString(SR.Error_MustHaveParent));
base.Initialize(provider);
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
List<EventHandlerEventActivitySubscriber> eventActivitySubscribers = new List<EventHandlerEventActivitySubscriber>();
this.ActivityState = eventActivitySubscribers;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
EventDrivenActivity childActivity = this.EnabledActivities[i] as EventDrivenActivity;
EventHandlerEventActivitySubscriber eventDrivenSubscriber = new EventHandlerEventActivitySubscriber(childActivity);
eventActivitySubscribers.Add(eventDrivenSubscriber);
childActivity.EventActivity.Subscribe(executionContext, eventDrivenSubscriber);
}
return ActivityExecutionStatus.Executing;
}
protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (this.ActivityState == null)
return ActivityExecutionStatus.Closed;
bool scopeCompleted = this.IsScopeCompleted;
bool canCloseNow = true;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
EventDrivenActivity childActivity = this.EnabledActivities[i] as EventDrivenActivity;
EventHandlerEventActivitySubscriber eventActivitySubscriber = this.ActivityState[i] as EventHandlerEventActivitySubscriber;
eventActivitySubscriber.PendingExecutionCount = 0;
ActivityExecutionContextManager contextManager = executionContext.ExecutionContextManager;
ActivityExecutionContext childContext = contextManager.GetExecutionContext(childActivity);
if (childContext != null)
{
switch (childContext.Activity.ExecutionStatus)
{
case ActivityExecutionStatus.Canceling:
case ActivityExecutionStatus.Faulting:
canCloseNow = false;
break;
case ActivityExecutionStatus.Executing:
childContext.CancelActivity(childContext.Activity);
canCloseNow = false;
break;
}
}
if (!scopeCompleted) //UnSubscribe from event.
{
childActivity.EventActivity.Unsubscribe(executionContext, eventActivitySubscriber);
}
}
if (canCloseNow)
{
this.ActivityState = null;
return ActivityExecutionStatus.Closed;
}
else
{
return this.ExecutionStatus;
}
}
protected override void OnActivityChangeAdd(ActivityExecutionContext executionContext, Activity addedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (addedActivity == null)
throw new ArgumentNullException("addedActivity");
EventDrivenActivity eda = addedActivity as EventDrivenActivity;
EventHandlersActivity activity = (EventHandlersActivity)executionContext.Activity as EventHandlersActivity;
EventHandlerEventActivitySubscriber eventActivitySubscriber = new EventHandlerEventActivitySubscriber(eda);
if (activity.ExecutionStatus == ActivityExecutionStatus.Executing && activity.ActivityState != null && !activity.IsScopeCompleted)
{
eda.EventActivity.Subscribe(executionContext, eventActivitySubscriber);
activity.ActivityState.Insert(activity.EnabledActivities.IndexOf(addedActivity), eventActivitySubscriber);
}
}
protected override void OnActivityChangeRemove(ActivityExecutionContext executionContext, Activity removedActivity)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
if (removedActivity == null)
throw new ArgumentNullException("removedActivity");
EventDrivenActivity eda = removedActivity as EventDrivenActivity;
// find out the status of the scope
EventHandlersActivity activity = (EventHandlersActivity)executionContext.Activity as EventHandlersActivity;
if (activity.ExecutionStatus == ActivityExecutionStatus.Executing && activity.ActivityState != null && !activity.IsScopeCompleted)
{
for (int i = 0; i < activity.ActivityState.Count; ++i)
{
EventHandlerEventActivitySubscriber eventSubscriber = activity.ActivityState[i];
if (eventSubscriber.eventDrivenActivity.QualifiedName.Equals(removedActivity.QualifiedName))
{
eda.EventActivity.Unsubscribe(executionContext, eventSubscriber);
activity.ActivityState.RemoveAt(i);
return;
}
}
}
}
protected override void OnWorkflowChangesCompleted(ActivityExecutionContext executionContext)
{
if (executionContext == null)
throw new ArgumentNullException("executionContext");
base.OnWorkflowChangesCompleted(executionContext);
if (this.ActivityState != null)
{
switch (this.ExecutionStatus)
{
case ActivityExecutionStatus.Executing:
if (this.IsScopeCompleted && AllHandlersAreQuiet(this, executionContext))
executionContext.CloseActivity();
break;
case ActivityExecutionStatus.Faulting:
case ActivityExecutionStatus.Canceling:
if (AllHandlersAreQuiet(this, executionContext))
executionContext.CloseActivity();
break;
default:
break;
}
}
}
#endregion
#region Private Impls
#region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members
void IActivityEventListener<ActivityExecutionStatusChangedEventArgs>.OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException(SR.Error_SenderMustBeActivityExecutionContext, "sender");
EventDrivenActivity eda = e.Activity as EventDrivenActivity;
EventHandlersActivity eventHandlers = context.Activity as EventHandlersActivity;
e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this);
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
contextManager.CompleteExecutionContext(contextManager.GetExecutionContext(eda));
switch (eventHandlers.ExecutionStatus)
{
case ActivityExecutionStatus.Executing:
for (int i = 0; i < eventHandlers.EnabledActivities.Count; ++i)
{
if (eventHandlers.EnabledActivities[i].QualifiedName.Equals(eda.QualifiedName))
{
EventHandlerEventActivitySubscriber eventActivitySubscriber = eventHandlers.ActivityState[i];
if (eventActivitySubscriber.PendingExecutionCount > 0)
{
eventActivitySubscriber.PendingExecutionCount--;
eventActivitySubscriber.IsBlocked = false;
ActivityExecutionContext childContext = contextManager.CreateExecutionContext(eventHandlers.EnabledActivities[i]);
childContext.Activity.RegisterForStatusChange(Activity.ClosedEvent, this);
childContext.ExecuteActivity(childContext.Activity);
}
else
{
eventActivitySubscriber.IsBlocked = true;
if (eventHandlers.IsScopeCompleted && AllHandlersAreQuiet(eventHandlers, context))
context.CloseActivity();
}
break;
}
}
break;
case ActivityExecutionStatus.Canceling:
case ActivityExecutionStatus.Faulting:
if (AllHandlersAreQuiet(eventHandlers, context))
context.CloseActivity();
break;
}
}
#endregion
#region Helpers
private bool AllHandlersAreQuiet(EventHandlersActivity handlers, ActivityExecutionContext context)
{
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
for (int i = 0; i < handlers.EnabledActivities.Count; ++i)
{
EventDrivenActivity eventDriven = handlers.EnabledActivities[i] as EventDrivenActivity;
if (contextManager.GetExecutionContext(eventDriven) != null || (handlers.ActivityState != null && handlers.ActivityState[i].PendingExecutionCount > 0))
return false;
}
return true;
}
private void OnUnsubscribeAndClose(object sender, EventArgs args)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (args == null)
throw new ArgumentNullException("args");
ActivityExecutionContext context = (ActivityExecutionContext)sender;
if (context == null)
throw new ArgumentException("sender");
EventHandlersActivity handlers = context.Activity as EventHandlersActivity;
if (context.Activity.ExecutionStatus != ActivityExecutionStatus.Executing)
return;
Debug.Assert(!handlers.IsScopeCompleted, "Only notified of scope body completion once");
handlers.IsScopeCompleted = true;
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
bool readyToClose = true;
for (int i = 0; i < handlers.EnabledActivities.Count; ++i)
{
EventDrivenActivity evtDriven = handlers.EnabledActivities[i] as EventDrivenActivity;
EventHandlerEventActivitySubscriber eventSubscriber = handlers.ActivityState[i];
evtDriven.EventActivity.Unsubscribe(context, eventSubscriber);
if (contextManager.GetExecutionContext(evtDriven) != null || handlers.ActivityState[i].PendingExecutionCount != 0)
readyToClose = false;
}
if (readyToClose)
{
handlers.ActivityState = null;
context.CloseActivity();
}
}
#endregion
#region EventSubscriber
[Serializable]
private sealed class EventHandlerEventActivitySubscriber : IActivityEventListener<QueueEventArgs>
{
bool isBlocked;
int numOfMsgs;
internal EventDrivenActivity eventDrivenActivity;
internal EventHandlerEventActivitySubscriber(EventDrivenActivity eventDriven)
{
isBlocked = true;
numOfMsgs = 0;
this.eventDrivenActivity = eventDriven;
}
internal bool IsBlocked
{
get
{
return isBlocked;
}
set
{
isBlocked = value;
}
}
internal int PendingExecutionCount
{
get
{
return numOfMsgs;
}
set
{
numOfMsgs = value;
}
}
void IActivityEventListener<QueueEventArgs>.OnEvent(object sender, QueueEventArgs e)
{
if (sender == null)
throw new ArgumentNullException("sender");
if (e == null)
throw new ArgumentNullException("e");
ActivityExecutionContext context = sender as ActivityExecutionContext;
if (context == null)
throw new ArgumentException("sender");
EventHandlersActivity handlers = context.Activity as EventHandlersActivity;
if (handlers.ExecutionStatus != ActivityExecutionStatus.Executing)
return;
if (!handlers.EnabledActivities.Contains(eventDrivenActivity))
return; //Activity is dynamically removed.
if (IsBlocked)
{
IsBlocked = false;
ActivityExecutionContextManager contextManager = context.ExecutionContextManager;
ActivityExecutionContext childContext = contextManager.CreateExecutionContext(eventDrivenActivity);
childContext.Activity.RegisterForStatusChange(Activity.ClosedEvent, handlers);
childContext.ExecuteActivity(childContext.Activity);
}
else
{
PendingExecutionCount++;
}
}
}
#endregion
#endregion
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
private Activity GetDynamicActivity(Activity childActivity)
{
if (childActivity == null)
throw new ArgumentNullException("childActivity");
if (!this.EnabledActivities.Contains(childActivity))
throw new ArgumentException(SR.GetString(SR.Error_EventHandlersChildNotFound), "childActivity");
else
{
Activity[] dynamicChildActivity = this.GetDynamicActivities(childActivity);
if (dynamicChildActivity.Length != 0)
return dynamicChildActivity[0];
else
return null;
}
}
public Activity GetDynamicActivity(String childActivityName)
{
if (childActivityName == null)
throw new ArgumentNullException("childActivityName");
Activity childActivity = null;
for (int i = 0; i < this.EnabledActivities.Count; ++i)
{
if (this.EnabledActivities[i].QualifiedName.Equals(childActivityName))
{
childActivity = this.EnabledActivities[i];
break;
}
}
if (childActivity != null)
return GetDynamicActivity(childActivity);
throw new ArgumentException(SR.GetString(SR.Error_EventHandlersChildNotFound), "childActivityName");
}
}
internal sealed class EventHandlersValidator : CompositeActivityValidator
{
public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
{
ValidationErrorCollection validationErrors = base.Validate(manager, obj);
EventHandlersActivity eventHandlers = obj as EventHandlersActivity;
if (eventHandlers == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(EventHandlersActivity).FullName), "obj");
if (eventHandlers.Parent == null)
{
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_MustHaveParent), ErrorNumbers.Error_EventHandlersDeclParentNotScope));
return validationErrors;
}
// Parent must support event handlers
if (!(eventHandlers.Parent is EventHandlingScopeActivity))
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_EventHandlersDeclParentNotScope, eventHandlers.Parent.QualifiedName), ErrorNumbers.Error_EventHandlersDeclParentNotScope));
bool bNotAllEventHandler = false;
foreach (Activity activity in eventHandlers.EnabledActivities)
{
if (!(activity is EventDrivenActivity))
bNotAllEventHandler = true;
}
// validate that all child activities are event driven activities.
if (bNotAllEventHandler)
validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ListenNotAllEventDriven), ErrorNumbers.Error_ListenNotAllEventDriven));
return validationErrors;
}
}
}
| |
namespace CupCake.Messages.Blocks
{
public enum Block
{
GravityNothing = 0,
GravityLeft = 1,
GravityUp = 2,
GravityRight = 3,
GravityDot = 4,
Crown = 5,
KeyRed = 6,
KeyGreen = 7,
KeyBlue = 8,
BasicGrey = 9,
BasicDarkBlue = 10,
BasicPurple = 11,
BasicRed = 12,
BasicYellow = 13,
BasicGreen = 14,
BasicLightBlue = 15,
BasicBlack = 182,
BgBasicGrey = 500,
BgBasicDarkBlue = 501,
BgBasicPurple = 502,
BgBasicRed = 503,
BgBasicYellow = 504,
BgBasicGreen = 505,
BgBasicLightBlue = 506,
BrickSaturatedBrown = 16,
BrickDarkGreen = 17,
BrickPurple = 18,
BrickLightGreen = 19,
BrickRed = 20,
BrickPaleBrown = 21,
BgBrickSaturatedBrown = 507,
BgBrickDarkGreen = 508,
BgBrickPurple = 509,
BgBrickLightGreen = 510,
BgBrickRed = 511,
BgBrickPaleBrown = 512,
Special1 = 22,
Special2 = 32,
SpecialNormalBlack = 33,
SpecialFullyBlack = 44,
DoorRed = 23,
DoorGreen = 24,
DoorBlue = 25,
CoinDoor = 43,
BlueCoinDoor = 213,
TimedDoor = 156,
DoorPurpleSwitch = 184,
DoorBuildersClub = 200,
DoorZombie = 207,
GateRed = 26,
GateGreen = 27,
GateBlue = 28,
CoinGate = 165,
BlueCoinGate = 214,
TimedGate = 157,
GatePurpleSwitch = 185,
GateBuildersClub = 201,
GateZombie = 206,
MetalWhite = 29,
MetalRed = 30,
MetalYellow = 31,
Grass1 = 34,
Grass2 = 35,
Grass3 = 36,
BetaPink = 37,
BetaGreen = 38,
BetaBlue = 39,
BetaRed = 40,
BetaYellow = 41,
BetaGrey = 42,
Factory1 = 45,
Factory2 = 46,
Factory3 = 47,
Factory4 = 48,
Factory5 = 49,
SecretUnpassable = 50,
SecretPassable = 243,
GlassRed = 51,
GlassPink = 52,
GlassPurple = 53,
GlassDarkBlue = 54,
GlassLightBlue = 55,
GlassGreen = 56,
GlassYellow = 57,
GlassOrange = 58,
Summer2011Sand = 59,
DecorSummer2011Sunshade = 228,
DecorSummer20111 = 229,
DecorSummer20112 = 230,
DecorSummer2011Rock = 231,
CandyPink = 60,
CandyOneWayPink = 61,
CandyOneWayRed = 62,
CandyOneWayBlue = 63,
CandyOneWayGreen = 64,
CandyStripeyRedWhite = 65,
CandyStripeyYellowBlackPink = 66,
CandyChocolate = 67,
DecorCandy = 227,
BgCandyPink = 539,
BgCandyBlue = 540,
Halloween20111 = 68,
Halloween20112 = 69,
DecorHalloween2011GraveStone = 224,
DecorHalloween20112 = 225,
DecorHalloween20113 = 226,
BgHalloween20111 = 541,
BgHalloween20112 = 542,
BgHalloween20113 = 543,
BgHalloween20114 = 544,
MineralRed = 70,
MineralPink = 71,
MineralDarkBlue = 72,
MineralLightBlue = 73,
MineralGreen = 74,
MineralYellow = 75,
MineralOrange = 76,
MusicPiano = 77,
MusicDrum = 83,
Christmas2011YellowBox = 78,
Christmas2011WhiteBox = 79,
Christmas2011RedBox = 80,
Christmas2011BlueBox = 81,
Christmas2011GreenBox = 82,
DecorChristmas2011Star = 218,
DecorChristmas2011Wreath = 219,
DecorChristmas2011SphereBlue = 220,
DecorChristmas2011SphereGreen = 221,
DecorChristmas2011SphereRed = 222,
SciFiRed = 84,
SciFiBlue = 85,
SciFiGrey = 86,
SciFiWhite = 87,
SciFiBrown = 88,
SciFiOneWayRed = 89,
SciFiOneWayBlue = 90,
SciFiOneWayGreen = 91,
Prison = 92,
DecorPrison = 261,
BgPrisonBrickWall = 550,
BgPrisonPicture = 551,
BgPrisonWindowBlue = 552,
BgPrisonWindowBlack = 553,
Pirate1 = 93,
PirateChest = 94,
DecorPirate1 = 271,
DecorPirateSkull = 272,
BgPirate1 = 554,
BgPirate2 = 555,
BgPirate3 = 556,
BgPirate4 = 557,
BgPirate5 = 558,
BgPirate6 = 559,
BgPirateSkull = 560,
Viking = 95,
DecorVikingRedShield = 273,
DecorVikingBlueShield = 274,
DecorVikingAx = 275,
BgViking1 = 561,
BgViking2 = 562,
BgViking3 = 563,
NinjaWhite = 96,
NinjaGrey = 97,
DecorNinja1 = 276,
DecorNinja2 = 277,
DecorNinja3 = 278,
DecorNinja4 = 279,
DecorNinja5 = 280,
DecorNinja6 = 281,
DecorNinja7 = 282,
DecorNinja8 = 283,
DecorNinja9 = 284,
BgNinjaWhiteWall = 564,
BgNinjaGreyWall = 565,
BgNinjaLitWindow = 566,
BgNinjaDarkWindow = 567,
CoinGold = 100,
CoinBlue = 101,
SwitchPurple = 113,
BoostLeft = 114,
BoostRight = 115,
BoostUp = 116,
BoostDown = 117,
LadderCastle = 118,
LadderNinja = 120,
LadderJungleVertical = 98,
LadderJungleHorizontal = 99,
Water = 119,
DecorWater = 300,
BgWaterBasic = 574,
BgWaterOctopus = 575,
BgWaterFish = 576,
BgWaterSeaHorse = 577,
BgWaterSeaweed = 578,
ToolWinTrophy = 121,
ToolSpawnPoint = 255,
ToolCheckpoint = 360,
CowboyBrownLit = 122,
CowboyRedLit = 123,
CowboyBlueLit = 124,
CowboyBrownDark = 125,
CowboyRedDark = 126,
CowboyBlueDark = 127,
DecorCowboyPoleLit = 285,
DecorCowboyPoleDark = 286,
DecorCowboyDoorBrownLeft = 287,
DecorCowboyDoorBrownRight = 288,
DecorCowboyDoorRedLeft = 289,
DecorCowboyDoorRedRight = 290,
DecorCowboyDoorBlueLeft = 291,
DecorCowboyDoorBlueRight = 292,
DecorCowboyWindow = 293,
DecorCowboyTableBrownLit = 294,
DecorCowboyTableBrownDark = 295,
DecorCowboyTableRedLit = 296,
DecorCowboyTableRedDark = 297,
DecorCowboyTableBlueLit = 298,
DecorCowboyTableBlueDark = 299,
BgCowboyBrownLit = 568,
BgCowboyBrownDark = 569,
BgCowboyRedLit = 570,
BgCowboyRedDark = 571,
BgCowboyBlueLit = 572,
BgCowboyBlueDark = 573,
PlasticLightGreen = 128,
PlasticRed = 129,
PlasticYellow = 130,
PlasticLightBlue = 131,
PlasticDarkBlue = 132,
PlasticPink = 133,
PlasticDarkGreen = 134,
PlasticOrange = 135,
SandLightYellow = 137,
SandGrey = 138,
SandDarkerYellow = 139,
SandOrange = 140,
SandLightBrown = 141,
SandDarkBrown = 142,
DecorSandLightYellow = 301,
DecorSandGrey = 302,
DecorSandDarkerYellow = 303,
DecorSandOrange = 304,
DecorSandLightBrown = 305,
DecorSandDarkBrown = 306,
BgSandLightYellow = 579,
BgSandGrey = 580,
BgSandDarkerYellow = 581,
BgSandOrange = 582,
BgSandLightBrown = 583,
BgSandDarkBrown = 584,
Cloud = 143,
DecorCloud1 = 311,
DecorCloud2 = 312,
DecorCloud3 = 313,
DecorCloud4 = 314,
DecorCloud5 = 315,
DecorCloud6 = 316,
DecorCloud7 = 317,
DecorCloud8 = 318,
PlateIron1 = 144,
PlateIron2 = 145,
IndustrialOneWay = 146,
Industrial2 = 147,
Industrial3 = 148,
Industrial4 = 149,
IndustrialConveyorBelt1 = 150,
IndustrialConveyorBelt2 = 151,
IndustrialConveyorBelt3 = 152,
IndustrialConveyorBelt4 = 153,
BgIndustrialNoPlate = 585,
BgIndustrialGreyPlate = 586,
BgIndustrialBluePlate = 587,
BgIndustrialGreenPlate = 588,
BgIndustrialYellowPlate = 589,
Timbered = 154,
BgTimberedHouseTopHay = 590,
BgTimberedHouseTopRed = 591,
BgTimberedHouseTopGrey = 592,
BgTimbered4 = 593,
BgTimbered5 = 594,
BgTimbered6 = 595,
BgTimbered7 = 596,
BgTimbered8 = 597,
BgTimbered9 = 598,
CastleOneWay = 158,
CastleWall = 159,
CastleWindow = 160,
DecorCastle1 = 325,
DecorCastle2 = 326,
BgCastle = 599,
MedievalAnvil = 162,
MedievalBarrel = 163,
DecorMedievalBlueBanner = 327,
DecorMedievalRedBanner = 328,
DecorMedievalSword = 329,
DecorMedievalShield = 330,
DecorMedievalRock = 331,
BgMedieval = 600,
PipeHoleOnLeft = 166,
PipeHorizontalMiddle = 167,
PipeHoleOnRight = 168,
PipeHoleOnUp = 169,
PipeVerticalMiddle = 170,
PipeHoleOnDown = 171,
RocketWhite = 172,
RocketBlue = 173,
RocketGreen = 174,
RocketRed = 175,
DecorRocketGreenSign = 332,
DecorRocketRed = 333,
DecorRocketBlue = 334,
DecorRocketComputer = 335,
BgRocketWhite = 601,
BgRocketBlue = 602,
BgRocketGreen = 603,
BgRocketRed = 604,
Mars1 = 176,
Mars2 = 177,
Mars3 = 178,
Mars4 = 179,
Mars5 = 180,
Mars6 = 181,
DecorMars = 336,
BgMarsNoStars = 605,
BgMarsSmallStar = 606,
BgMarsBigStar = 607,
CheckeredGrey = 186,
CheckeredDarkBlue = 187,
CheckeredPurple = 188,
CheckeredRed = 189,
CheckeredYellow = 190,
CheckeredGreen = 191,
CheckeredLightBlue = 192,
JungleRuinsRoundedEdgeFace = 193,
JungleRuinsOneWay = 194,
JungleRuinsNonRoundedGrey = 195,
JungleRuinsRed = 196,
JungleRuinsBlue = 197,
JungleRuinsYellow = 198,
JungleVase = 199,
LavaYellow = 202,
LavaOrange = 203,
LavaRed = 204,
BgLavaYellow = 627,
BgLavaOrange = 628,
BgLavaRed = 629,
SpartaGrey = 208,
SpartaGreen = 209,
SpartaRed = 210,
SpartaOneWay = 211,
DecorSpartaPillarTop = 382,
DecorSpartaPillarMiddle = 383,
DecorSpartaPillarBottom = 384,
BgSpartaGrey = 638,
BgSpartaGreen = 639,
BgSpartaRed = 640,
Farm = 212,
DecorFarmCrop = 386,
DecorFarmPlants = 387,
DecorFarmFenceLeftEnded = 388,
DecorFarmFenceRightEnded = 389,
DecorAutumn20141 = 390,
DecorAutumn20142 = 391,
DecorAutumn2014Grass1 = 392,
DecorAutumn2014Grass2 = 393,
DecorAutumn2014Grass3 = 394,
DecorAutumn2014Acorn = 395,
DecorAutumn2014Pumpkin = 396,
Christmas2014Ice = 215,
Christmas2014OneWay = 216,
DecorChristmas2014Snow1 = 398,
DecorChristmas2014Snow2 = 399,
DecorChristmas2014Snow3 = 400,
DecorChristmas2014CandyCane = 401,
DecorChristmas2014Wreath = 402,
DecorChristmas2014Stocking = 403,
DecorChristmas2014Bow = 404,
Hologram = 397,
DecorPrizeTrophy = 223,
DecorSpring2011Grass1 = 233,
DecorSpring2011Grass2 = 234,
DecorSpring2011Grass3 = 235,
DecorSpring2011OblongBush1 = 236,
DecorSpring2011OblongBush2 = 237,
DecorSpring2011OblongBush3 = 238,
DecorSpring2011Flower = 239,
DecorSpring2011GlobularBush = 240,
Diamond = 241,
Portal = 242,
WorldPortal = 374,
InvisiblePortal = 381,
DecorNewYear2010Purple = 244,
DecorNewYear2010Yellow = 245,
DecorNewYear2010Blue = 246,
DecorNewYear2010Red = 247,
DecorNewYear2010Green = 248,
DecorChristmas20101 = 249,
DecorChristmas20102 = 250,
DecorChristmas2010SnowFreeTree = 251,
DecorChristmas2010SnowyTree = 252,
DecorChristmas2010SnowyFence = 253,
DecorChristmas2010SnowFreeFence = 254,
DecorEaster2012BlueEgg = 256,
DecorEaster2012PinkEgg = 257,
DecorEaster2012YellowEgg = 258,
DecorEaster2012RedEgg = 259,
DecorEaster2012GreenEgg = 260,
DecorWindowFully = 262,
DecorWindowLightGreen = 263,
DecorWindowDarkGreen = 264,
DecorWindowLightBlue = 265,
DecorWindowDarkBlue = 266,
DecorWindowPink = 267,
DecorWindowRed = 268,
DecorWindowOrange = 269,
DecorWindowYellow = 270,
DecorSummer2012Ball = 307,
DecorSummer2012Bucket = 308,
DecorSummer2012Grubber = 309,
DecorSummer2012Cocktail = 310,
DecorWarningSignFire = 319,
DecorWarningSignSkull = 320,
DecorWarningSignLightning = 321,
DecorWarningSignCross = 322,
DecorWarningSignHorizontalLine = 323,
DecorWarningSignVerticalLine = 324,
Cake = 337,
DecorMonsterRockGroundBig = 338,
DecorMonsterRockGroundSmall = 339,
DecorMonsterRockCeiling = 340,
DecorMonsterEyeOrange = 341,
DecorMonsterEyeBlue = 342,
BgMonsterNormal = 608,
BgMonsterDark = 609,
DecorFogFilled = 343,
DecorFog2 = 344,
DecorFog3 = 345,
DecorFog4 = 346,
DecorFog5 = 347,
DecorFog6 = 348,
DecorFog7 = 349,
DecorFog8 = 350,
DecorFog9 = 351,
DecorHalloween20121 = 352,
DecorHalloween20122 = 353,
DecorHalloween2012WiresVertical = 354,
DecorHalloween2012WiresHorizontal = 355,
DecorHalloween20125 = 356,
DecorJungleGrass = 357,
DecorJungle2 = 358,
DecorJungleTrophy = 359,
HazardSpike = 361,
HazardFire = 368,
Swamp = 369,
DecorSwamp1 = 370,
DecorSwamp2 = 371,
DecorSwamp3 = 372,
DecorSwamp4 = 373,
BgSwamp = 630,
DecorChristmas2012BlueVertical = 362,
DecorChristmas2012BlueHorizontal = 363,
DecorChristmas2012BlueCross = 364,
DecorChristmas2012RedVertical = 365,
DecorChristmas2012RedHorizontal = 366,
DecorChristmas2012RedCross = 367,
DecorSciFi2013BlueSlope = 375,
DecorSciFi2013BlueStraight = 376,
DecorSciFi2013YellowSlope = 377,
DecorSciFi2013YellowStraight = 378,
DecorSciFi2013GreenSlope = 379,
DecorSciFi2013GreenStraight = 380,
BgSciFi2013 = 637,
DecorSign = 385,
BgCheckeredGrey = 513,
BgCheckeredDarkBlue = 514,
BgCheckeredPurple = 515,
BgCheckeredRed = 516,
BgCheckeredYellow = 517,
BgCheckeredGreen = 518,
BgCheckeredLightBlue = 519,
BgDarkGrey = 520,
BgDarkDarkBlue = 521,
BgDarkPurple = 522,
BgDarkRed = 523,
BgDarkYellow = 524,
BgDarkGreen = 525,
BgDarkLightBlue = 526,
BgPastelYellow = 527,
BgPastelDarkerGreen = 528,
BgPastelLimeGreen = 529,
BgPastelLightBlue = 530,
BgPastelDarkerBlue = 531,
BgPastelRed = 532,
BgCanvasSaturatedBrown = 533,
BgCanvasPaleBrown = 534,
BgCanvasYellow = 535,
BgCanvasGreen = 536,
BgCanvasBlue = 537,
BgCanvasGrey = 538,
BgCarnivalStripeyRedYellow = 545,
BgCarnivalStripeyPurpleBlue = 546,
BgCarnivalPink = 547,
BgCarnivalChecker = 548,
BgCarnivalGreen = 549,
BgNormalGrey = 610,
BgNormalDarkBlue = 611,
BgNormalPurple = 612,
BgNormalRed = 613,
BgNormalYellow = 614,
BgNormalGreen = 615,
BgNormalLightBlue = 616,
BgJungleRuinsGrey = 617,
BgJungleRuinsRed = 618,
BgJungleRuinsBlue = 619,
BgJungleRuinsYellow = 620,
BgJungleLight = 621,
BgJungleNormal = 622,
BgJungleDark = 623,
BgChristmas2012Yellow = 624,
BgChristmas2012Green = 625,
BgChristmas2012Blue = 626,
BgAutumn2014Yellow = 641,
BgAutumn2014Orange = 642,
BgAutumn2014Red = 643,
DecorLabel = 1000,
OneWayCyan = 1001,
OneWayRed = 1002,
OneWayYellow = 1003,
OneWayPink = 1004,
CyanDoor = 1005,
MagentaDoor = 1006,
YellowDoor = 1007,
CyanGate = 1008,
MagentaGate = 1009,
YellowGate = 1010,
DeathDoor = 1011,
DeathGate = 1012
}
}
| |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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;
using System.Collections.Generic;
using System.IO;
using SharpYaml.Events;
using SharpYaml.Tokens;
using AnchorAlias = SharpYaml.Tokens.AnchorAlias;
using DocumentEnd = SharpYaml.Tokens.DocumentEnd;
using DocumentStart = SharpYaml.Tokens.DocumentStart;
using Event = SharpYaml.Events.ParsingEvent;
using YamlStyle = SharpYaml.YamlStyle;
using Scalar = SharpYaml.Tokens.Scalar;
using StreamEnd = SharpYaml.Tokens.StreamEnd;
using StreamStart = SharpYaml.Tokens.StreamStart;
namespace SharpYaml
{
/// <summary>
/// Parses YAML streams.
/// </summary>
public class Parser : IParser
{
private readonly Stack<ParserState> states = new Stack<ParserState>();
private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection();
private ParserState state;
private readonly Scanner scanner;
private Event current;
private Token currentToken;
private Token GetCurrentToken()
{
if (currentToken == null)
{
if (scanner.InternalMoveNext())
{
currentToken = scanner.Current;
}
}
return currentToken;
}
/// <summary>
/// Initializes a new instance of the <see cref="IParser"/> class.
/// </summary>
/// <param name="input">The input where the YAML stream is to be read.</param>
public Parser(TextReader input)
{
scanner = new Scanner(input);
}
/// <summary>
/// Gets the current event.
/// </summary>
public Event Current
{
get
{
return current;
}
}
/// <summary>
/// Moves to the next event.
/// </summary>
/// <returns>Returns true if there are more events available, otherwise returns false.</returns>
public bool MoveNext()
{
// No events after the end of the stream or error.
if (state == ParserState.YAML_PARSE_END_STATE)
{
current = null;
return false;
}
else
{
// Generate the next event.
current = StateMachine();
return true;
}
}
private Event StateMachine()
{
switch (state)
{
case ParserState.YAML_PARSE_STREAM_START_STATE:
return ParseStreamStart();
case ParserState.YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE:
return ParseDocumentStart(true);
case ParserState.YAML_PARSE_DOCUMENT_START_STATE:
return ParseDocumentStart(false);
case ParserState.YAML_PARSE_DOCUMENT_CONTENT_STATE:
return ParseDocumentContent();
case ParserState.YAML_PARSE_DOCUMENT_END_STATE:
return ParseDocumentEnd();
case ParserState.YAML_PARSE_BLOCK_NODE_STATE:
return ParseNode(true, false);
case ParserState.YAML_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
return ParseNode(true, true);
case ParserState.YAML_PARSE_FLOW_NODE_STATE:
return ParseNode(false, false);
case ParserState.YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
return ParseBlockSequenceEntry(true);
case ParserState.YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
return ParseBlockSequenceEntry(false);
case ParserState.YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
return ParseIndentlessSequenceEntry();
case ParserState.YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
return ParseBlockMappingKey(true);
case ParserState.YAML_PARSE_BLOCK_MAPPING_KEY_STATE:
return ParseBlockMappingKey(false);
case ParserState.YAML_PARSE_BLOCK_MAPPING_VALUE_STATE:
return ParseBlockMappingValue();
case ParserState.YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
return ParseFlowSequenceEntry(true);
case ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
return ParseFlowSequenceEntry(false);
case ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
return ParseFlowSequenceEntryMappingKey();
case ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
return ParseFlowSequenceEntryMappingValue();
case ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
return ParseFlowSequenceEntryMappingEnd();
case ParserState.YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
return ParseFlowMappingKey(true);
case ParserState.YAML_PARSE_FLOW_MAPPING_KEY_STATE:
return ParseFlowMappingKey(false);
case ParserState.YAML_PARSE_FLOW_MAPPING_VALUE_STATE:
return ParseFlowMappingValue(false);
case ParserState.YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
return ParseFlowMappingValue(true);
default:
Debug.Assert(false, "Invalid state"); // Invalid state.
throw new InvalidOperationException();
}
}
private void Skip()
{
if (currentToken != null)
{
currentToken = null;
scanner.ConsumeCurrent();
}
}
/// <summary>
/// Parse the production:
/// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
/// ************
/// </summary>
private Event ParseStreamStart()
{
StreamStart streamStart = GetCurrentToken() as StreamStart;
if (streamStart == null)
{
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "Did not find expected <stream-start>.");
}
Skip();
state = ParserState.YAML_PARSE_IMPLICIT_DOCUMENT_START_STATE;
return new Events.StreamStart(streamStart.Start, streamStart.End);
}
/// <summary>
/// Parse the productions:
/// implicit_document ::= block_node DOCUMENT-END*
/// *
/// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
/// *************************
/// </summary>
private Event ParseDocumentStart(bool isImplicit)
{
// Parse extra document end indicators.
if (!isImplicit)
{
while (GetCurrentToken() is DocumentEnd)
{
Skip();
}
}
// Parse an isImplicit document.
if (isImplicit && !(GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is StreamEnd))
{
TagDirectiveCollection directives = new TagDirectiveCollection();
ProcessDirectives(directives);
states.Push(ParserState.YAML_PARSE_DOCUMENT_END_STATE);
state = ParserState.YAML_PARSE_BLOCK_NODE_STATE;
return new Events.DocumentStart(null, directives, true, GetCurrentToken().Start, GetCurrentToken().End);
}
// Parse an explicit document.
else if (!(GetCurrentToken() is StreamEnd))
{
Mark start = GetCurrentToken().Start;
TagDirectiveCollection directives = new TagDirectiveCollection();
VersionDirective versionDirective = ProcessDirectives(directives);
var current = GetCurrentToken();
if (!(current is DocumentStart))
{
throw new SemanticErrorException(current.Start, current.End, "Did not find expected <document start>.");
}
states.Push(ParserState.YAML_PARSE_DOCUMENT_END_STATE);
state = ParserState.YAML_PARSE_DOCUMENT_CONTENT_STATE;
Event evt = new Events.DocumentStart(versionDirective, directives, false, start, current.End);
Skip();
return evt;
}
// Parse the stream end.
else
{
state = ParserState.YAML_PARSE_END_STATE;
Event evt = new Events.StreamEnd(GetCurrentToken().Start, GetCurrentToken().End);
// Do not call skip here because that would throw an exception
if (scanner.InternalMoveNext())
{
throw new InvalidOperationException("The scanner should contain no more tokens.");
}
return evt;
}
}
/// <summary>
/// Parse directives.
/// </summary>
private VersionDirective ProcessDirectives(TagDirectiveCollection tags)
{
VersionDirective version = null;
while (true)
{
VersionDirective currentVersion;
TagDirective tag;
if ((currentVersion = GetCurrentToken() as VersionDirective) != null)
{
if (version != null)
{
throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found duplicate %YAML directive.");
}
if (currentVersion.Version.Major != Constants.MajorVersion || currentVersion.Version.Minor != Constants.MinorVersion)
{
throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found incompatible YAML document.");
}
version = currentVersion;
}
else if ((tag = GetCurrentToken() as TagDirective) != null)
{
if (tagDirectives.Contains(tag.Handle))
{
throw new SemanticErrorException(tag.Start, tag.End, "Found duplicate %TAG directive.");
}
tagDirectives.Add(tag);
if (tags != null)
{
tags.Add(tag);
}
}
else
{
break;
}
Skip();
}
if (tags != null)
{
AddDefaultTagDirectives(tags);
}
AddDefaultTagDirectives(tagDirectives);
return version;
}
private static void AddDefaultTagDirectives(TagDirectiveCollection directives)
{
foreach(var directive in Constants.DefaultTagDirectives)
{
if (!directives.Contains(directive))
{
directives.Add(directive);
}
}
}
/// <summary>
/// Parse the productions:
/// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
/// ***********
/// </summary>
private Event ParseDocumentContent()
{
if (
GetCurrentToken() is VersionDirective ||
GetCurrentToken() is TagDirective ||
GetCurrentToken() is DocumentStart ||
GetCurrentToken() is DocumentEnd ||
GetCurrentToken() is StreamEnd
)
{
state = states.Pop();
return ProcessEmptyScalar(scanner.CurrentPosition);
}
else
{
return ParseNode(true, false);
}
}
/// <summary>
/// Generate an empty scalar event.
/// </summary>
private static Event ProcessEmptyScalar(Mark position)
{
return new Events.Scalar(null, null, string.Empty, ScalarStyle.Plain, true, false, position, position);
}
/// <summary>
/// Parse the productions:
/// block_node_or_indentless_sequence ::=
/// ALIAS
/// *****
/// | properties (block_content | indentless_block_sequence)?
/// ********** *
/// | block_content | indentless_block_sequence
/// *
/// block_node ::= ALIAS
/// *****
/// | properties block_content?
/// ********** *
/// | block_content
/// *
/// flow_node ::= ALIAS
/// *****
/// | properties flow_content?
/// ********** *
/// | flow_content
/// *
/// properties ::= TAG ANCHOR? | ANCHOR TAG?
/// *************************
/// block_content ::= block_collection | flow_collection | SCALAR
/// ******
/// flow_content ::= flow_collection | SCALAR
/// ******
/// </summary>
private Event ParseNode(bool isBlock, bool isIndentlessSequence)
{
AnchorAlias alias = GetCurrentToken() as AnchorAlias;
if (alias != null)
{
state = states.Pop();
Event evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End);
Skip();
return evt;
}
Mark start = GetCurrentToken().Start;
Anchor anchor = null;
Tag tag = null;
// The anchor and the tag can be in any order. This loop repeats at most twice.
while (true)
{
if (anchor == null && (anchor = GetCurrentToken() as Anchor) != null)
{
Skip();
}
else if (tag == null && (tag = GetCurrentToken() as Tag) != null)
{
Skip();
}
else
{
break;
}
}
string tagName = null;
if (tag != null)
{
if (string.IsNullOrEmpty(tag.Handle))
{
tagName = tag.Suffix;
}
else if (tagDirectives.Contains(tag.Handle))
{
tagName = string.Concat(tagDirectives[tag.Handle].Prefix, tag.Suffix);
}
else
{
throw new SemanticErrorException(tag.Start, tag.End, "While parsing a node, find undefined tag handle.");
}
}
if (string.IsNullOrEmpty(tagName))
{
tagName = null;
}
string anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null;
bool isImplicit = string.IsNullOrEmpty(tagName);
if (isIndentlessSequence && GetCurrentToken() is BlockEntry)
{
state = ParserState.YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
return new Events.SequenceStart(
anchorName,
tagName,
isImplicit,
YamlStyle.Block,
start,
GetCurrentToken().End
);
}
else
{
Scalar scalar = GetCurrentToken() as Scalar;
if (scalar != null)
{
bool isPlainImplicit = false;
bool isQuotedImplicit = false;
if ((scalar.Style == ScalarStyle.Plain && tagName == null) || tagName == Constants.DefaultHandle)
{
isPlainImplicit = true;
}
else if (tagName == null)
{
isQuotedImplicit = true;
}
state = states.Pop();
Event evt = new Events.Scalar(anchorName, tagName, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start, scalar.End);
Skip();
return evt;
}
FlowSequenceStart flowSequenceStart = GetCurrentToken() as FlowSequenceStart;
if (flowSequenceStart != null)
{
state = ParserState.YAML_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE;
return new Events.SequenceStart(anchorName, tagName, isImplicit, YamlStyle.Flow, start, flowSequenceStart.End);
}
FlowMappingStart flowMappingStart = GetCurrentToken() as FlowMappingStart;
if (flowMappingStart != null)
{
state = ParserState.YAML_PARSE_FLOW_MAPPING_FIRST_KEY_STATE;
return new Events.MappingStart(anchorName, tagName, isImplicit, YamlStyle.Flow, start, flowMappingStart.End);
}
if (isBlock)
{
BlockSequenceStart blockSequenceStart = GetCurrentToken() as BlockSequenceStart;
if (blockSequenceStart != null)
{
state = ParserState.YAML_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE;
return new Events.SequenceStart(anchorName, tagName, isImplicit, YamlStyle.Block, start, blockSequenceStart.End);
}
BlockMappingStart blockMappingStart = GetCurrentToken() as BlockMappingStart;
if (blockMappingStart != null)
{
state = ParserState.YAML_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE;
return new Events.MappingStart(anchorName, tagName, isImplicit, YamlStyle.Block, start, GetCurrentToken().End);
}
}
if (anchorName != null || tag != null)
{
state = states.Pop();
return new Events.Scalar(anchorName, tagName, string.Empty, ScalarStyle.Plain, isImplicit, false, start, GetCurrentToken().End);
}
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "While parsing a node, did not find expected node content.");
}
}
/// <summary>
/// Parse the productions:
/// implicit_document ::= block_node DOCUMENT-END*
/// *************
/// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
/// *************
/// </summary>
private Event ParseDocumentEnd()
{
bool isImplicit = true;
Mark start = GetCurrentToken().Start;
Mark end = start;
if (GetCurrentToken() is DocumentEnd)
{
end = GetCurrentToken().End;
Skip();
isImplicit = false;
}
tagDirectives.Clear();
state = ParserState.YAML_PARSE_DOCUMENT_START_STATE;
return new Events.DocumentEnd(isImplicit, start, end);
}
/// <summary>
/// Parse the productions:
/// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
/// ******************** *********** * *********
/// </summary>
private Event ParseBlockSequenceEntry(bool isFirst)
{
if (isFirst)
{
GetCurrentToken();
Skip();
}
if (GetCurrentToken() is BlockEntry)
{
Mark mark = GetCurrentToken().End;
Skip();
if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is BlockEnd))
{
states.Push(ParserState.YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE);
return ParseNode(true, false);
}
else
{
state = ParserState.YAML_PARSE_BLOCK_SEQUENCE_ENTRY_STATE;
return ProcessEmptyScalar(mark);
}
}
else if (GetCurrentToken() is BlockEnd)
{
state = states.Pop();
Event evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End);
Skip();
return evt;
}
else
{
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "While parsing a block collection, did not find expected '-' indicator.");
}
}
/// <summary>
/// Parse the productions:
/// indentless_sequence ::= (BLOCK-ENTRY block_node?)+
/// *********** *
/// </summary>
private Event ParseIndentlessSequenceEntry()
{
if (GetCurrentToken() is BlockEntry)
{
Mark mark = GetCurrentToken().End;
Skip();
if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd))
{
states.Push(ParserState.YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE);
return ParseNode(true, false);
}
else
{
state = ParserState.YAML_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE;
return ProcessEmptyScalar(mark);
}
}
else
{
state = states.Pop();
return new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End);
}
}
/// <summary>
/// Parse the productions:
/// block_mapping ::= BLOCK-MAPPING_START
/// *******************
/// ((KEY block_node_or_indentless_sequence?)?
/// *** *
/// (VALUE block_node_or_indentless_sequence?)?)*
///
/// BLOCK-END
/// *********
/// </summary>
private Event ParseBlockMappingKey(bool isFirst)
{
if (isFirst)
{
GetCurrentToken();
Skip();
}
if (GetCurrentToken() is Key)
{
Mark mark = GetCurrentToken().End;
Skip();
if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd))
{
states.Push(ParserState.YAML_PARSE_BLOCK_MAPPING_VALUE_STATE);
return ParseNode(true, true);
}
else
{
state = ParserState.YAML_PARSE_BLOCK_MAPPING_VALUE_STATE;
return ProcessEmptyScalar(mark);
}
}
else if (GetCurrentToken() is BlockEnd)
{
state = states.Pop();
Event evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End);
Skip();
return evt;
}
else
{
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "While parsing a block mapping, did not find expected key.");
}
}
/// <summary>
/// Parse the productions:
/// block_mapping ::= BLOCK-MAPPING_START
///
/// ((KEY block_node_or_indentless_sequence?)?
///
/// (VALUE block_node_or_indentless_sequence?)?)*
/// ***** *
/// BLOCK-END
///
/// </summary>
private Event ParseBlockMappingValue()
{
if (GetCurrentToken() is Value)
{
Mark mark = GetCurrentToken().End;
Skip();
if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd))
{
states.Push(ParserState.YAML_PARSE_BLOCK_MAPPING_KEY_STATE);
return ParseNode(true, true);
}
else
{
state = ParserState.YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
return ProcessEmptyScalar(mark);
}
}
else
{
state = ParserState.YAML_PARSE_BLOCK_MAPPING_KEY_STATE;
return ProcessEmptyScalar(GetCurrentToken().Start);
}
}
/// <summary>
/// Parse the productions:
/// flow_sequence ::= FLOW-SEQUENCE-START
/// *******************
/// (flow_sequence_entry FLOW-ENTRY)*
/// * **********
/// flow_sequence_entry?
/// *
/// FLOW-SEQUENCE-END
/// *****************
/// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// *
/// </summary>
private Event ParseFlowSequenceEntry(bool isFirst)
{
if (isFirst)
{
GetCurrentToken();
Skip();
}
Event evt;
if (!(GetCurrentToken() is FlowSequenceEnd))
{
if (!isFirst)
{
if (GetCurrentToken() is FlowEntry)
{
Skip();
}
else
{
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "While parsing a flow sequence, did not find expected ',' or ']'.");
}
}
if (GetCurrentToken() is Key)
{
state = ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE;
evt = new Events.MappingStart(null, null, true, YamlStyle.Flow);
Skip();
return evt;
}
else if (!(GetCurrentToken() is FlowSequenceEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE);
return ParseNode(false, false);
}
}
state = states.Pop();
evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End);
Skip();
return evt;
}
/// <summary>
/// Parse the productions:
/// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// *** *
/// </summary>
private Event ParseFlowSequenceEntryMappingKey()
{
if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE);
return ParseNode(false, false);
}
else
{
Mark mark = GetCurrentToken().End;
Skip();
state = ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE;
return ProcessEmptyScalar(mark);
}
}
/// <summary>
/// Parse the productions:
/// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// ***** *
/// </summary>
private Event ParseFlowSequenceEntryMappingValue()
{
if (GetCurrentToken() is Value)
{
Skip();
if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE);
return ParseNode(false, false);
}
}
state = ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE;
return ProcessEmptyScalar(GetCurrentToken().Start);
}
/// <summary>
/// Parse the productions:
/// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// *
/// </summary>
private Event ParseFlowSequenceEntryMappingEnd()
{
state = ParserState.YAML_PARSE_FLOW_SEQUENCE_ENTRY_STATE;
return new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End);
}
/// <summary>
/// Parse the productions:
/// flow_mapping ::= FLOW-MAPPING-START
/// ******************
/// (flow_mapping_entry FLOW-ENTRY)*
/// * **********
/// flow_mapping_entry?
/// ******************
/// FLOW-MAPPING-END
/// ****************
/// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// * *** *
/// </summary>
private Event ParseFlowMappingKey(bool isFirst)
{
if (isFirst)
{
GetCurrentToken();
Skip();
}
if (!(GetCurrentToken() is FlowMappingEnd))
{
if (!isFirst)
{
if (GetCurrentToken() is FlowEntry)
{
Skip();
}
else
{
var current = GetCurrentToken();
throw new SemanticErrorException(current.Start, current.End, "While parsing a flow mapping, did not find expected ',' or '}'.");
}
}
if (GetCurrentToken() is Key)
{
Skip();
if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_MAPPING_VALUE_STATE);
return ParseNode(false, false);
}
else
{
state = ParserState.YAML_PARSE_FLOW_MAPPING_VALUE_STATE;
return ProcessEmptyScalar(GetCurrentToken().Start);
}
}
else if (!(GetCurrentToken() is FlowMappingEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE);
return ParseNode(false, false);
}
}
state = states.Pop();
Event evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End);
Skip();
return evt;
}
/// <summary>
/// Parse the productions:
/// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
/// * ***** *
/// </summary>
private Event ParseFlowMappingValue(bool isEmpty)
{
if (isEmpty)
{
state = ParserState.YAML_PARSE_FLOW_MAPPING_KEY_STATE;
return ProcessEmptyScalar(GetCurrentToken().Start);
}
if (GetCurrentToken() is Value)
{
Skip();
if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd))
{
states.Push(ParserState.YAML_PARSE_FLOW_MAPPING_KEY_STATE);
return ParseNode(false, false);
}
}
state = ParserState.YAML_PARSE_FLOW_MAPPING_KEY_STATE;
return ProcessEmptyScalar(GetCurrentToken().Start);
}
}
}
| |
// 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 MultiplyAddNegatedDouble()
{
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
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();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// 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();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 SimpleTernaryOpTest__MultiplyAddNegatedDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public Vector128<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddNegatedDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleTernaryOpTest__MultiplyAddNegatedDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplyAddNegated(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplyAddNegated(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddNegated), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplyAddNegated(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
fixed (Vector128<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2)),
Sse2.LoadVector128((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var op3 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplyAddNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyAddNegatedDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
fixed (Vector128<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplyAddNegated(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
fixed (Vector128<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2)),
Sse2.LoadVector128((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplyAddNegated(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2)),
Sse2.LoadVector128((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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<Double> op1, Vector128<Double> op2, Vector128<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[0] * secondOp[0]) + thirdOp[0], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[0], 9)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Round(-(firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplyAddNegated)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net>
// Copyright (c) 2006-2015 Piotr Fusik <piotr@fusik.info>
//
// 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.
//
// 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 Sooda.Caching;
using Sooda.Logging;
using Sooda.ObjectMapper;
using Sooda.QL;
using Sooda.Schema;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Xml;
namespace Sooda
{
public class SoodaObject
#if DOTNET4
: System.Dynamic.DynamicObject
#endif
{
private static readonly Logger logger = LogManager.GetLogger("Sooda.Object");
// instance fields - initialized in InitRawObject()
private byte[] _fieldIsDirty;
internal SoodaObjectFieldValues _fieldValues;
private int _dataLoadedMask;
private SoodaTransaction _transaction;
private SoodaObjectFlags _flags;
private object _primaryKeyValue;
public bool AreFieldUpdateTriggersEnabled()
{
return (_flags & SoodaObjectFlags.DisableFieldTriggers) == 0;
}
public bool EnableFieldUpdateTriggers()
{
return EnableFieldUpdateTriggers(true);
}
public bool DisableFieldUpdateTriggers()
{
return EnableFieldUpdateTriggers(false);
}
public bool EnableFieldUpdateTriggers(bool enable)
{
bool oldValue = AreFieldUpdateTriggersEnabled();
if (!enable)
_flags |= SoodaObjectFlags.DisableFieldTriggers;
else
_flags &= ~SoodaObjectFlags.DisableFieldTriggers;
return oldValue;
}
public bool AreObjectTriggersEnabled()
{
return (_flags & SoodaObjectFlags.DisableObjectTriggers) == 0;
}
public bool EnableObjectTriggers()
{
return EnableObjectTriggers(true);
}
public bool DisableObjectTriggers()
{
return EnableObjectTriggers(false);
}
public bool EnableObjectTriggers(bool enable)
{
bool oldValue = AreObjectTriggersEnabled();
if (!enable)
_flags |= SoodaObjectFlags.DisableObjectTriggers;
else
_flags &= ~SoodaObjectFlags.DisableObjectTriggers;
return oldValue;
}
private bool InsertMode
{
get
{
return (_flags & SoodaObjectFlags.InsertMode) != 0;
}
set
{
if (value)
{
_flags |= SoodaObjectFlags.InsertMode;
SetObjectDirty();
}
else
_flags &= ~SoodaObjectFlags.InsertMode;
}
}
internal bool VisitedOnCommit
{
get
{
return (_flags & SoodaObjectFlags.VisitedOnCommit) != 0;
}
set
{
if (value)
_flags |= SoodaObjectFlags.VisitedOnCommit;
else
_flags &= ~SoodaObjectFlags.VisitedOnCommit;
}
}
bool WrittenIntoDatabase
{
get
{
return (_flags & SoodaObjectFlags.WrittenIntoDatabase) != 0;
}
set
{
if (value)
_flags |= SoodaObjectFlags.WrittenIntoDatabase;
else
_flags &= ~SoodaObjectFlags.WrittenIntoDatabase;
}
}
bool PostCommitForced
{
get
{
return (_flags & SoodaObjectFlags.ForcePostCommit) != 0;
}
set
{
if (value)
_flags |= SoodaObjectFlags.ForcePostCommit;
else
_flags &= ~SoodaObjectFlags.ForcePostCommit;
}
}
public void ForcePostCommit()
{
_flags |= SoodaObjectFlags.ForcePostCommit;
}
internal bool InsertedIntoDatabase
{
get { return (_flags & SoodaObjectFlags.InsertedIntoDatabase) != 0; }
set
{
if (value)
_flags |= SoodaObjectFlags.InsertedIntoDatabase;
else
_flags &= ~SoodaObjectFlags.InsertedIntoDatabase;
}
}
bool FromCache
{
get { return (_flags & SoodaObjectFlags.FromCache) != 0; }
set
{
if (value)
_flags |= SoodaObjectFlags.FromCache;
else
_flags &= ~SoodaObjectFlags.FromCache;
}
}
SoodaCacheEntry GetCacheEntry()
{
return new SoodaCacheEntry(_dataLoadedMask, _fieldValues);
}
internal bool DeleteMarker
{
get
{
return (_flags & SoodaObjectFlags.MarkedForDeletion) != 0;
}
set
{
if (value)
_flags = _flags | SoodaObjectFlags.MarkedForDeletion;
else
_flags = (_flags & ~SoodaObjectFlags.MarkedForDeletion);
}
}
internal void SetInsertMode()
{
this.InsertMode = true;
SetAllDataLoaded();
}
public bool IsInsertMode()
{
return this.InsertMode;
}
~SoodaObject()
{
// logger.Trace("Finalizer for {0}", GetObjectKeyString());
}
protected SoodaObject(SoodaConstructor c)
{
GC.SuppressFinalize(this);
}
protected SoodaObject(SoodaTransaction tran)
{
GC.SuppressFinalize(this);
tran.Statistics.RegisterObjectInsert();
SoodaStatistics.Global.RegisterObjectInsert();
InitRawObject(tran);
InsertMode = true;
SetAllDataLoaded();
if (GetClassInfo().SubclassSelectorValue != null)
{
DisableFieldUpdateTriggers();
Sooda.Schema.FieldInfo selectorField = GetClassInfo().SubclassSelectorField;
SetPlainFieldValue(0, selectorField.Name, selectorField.ClassUnifiedOrdinal, GetClassInfo().SubclassSelectorValue, null, null);
EnableFieldUpdateTriggers();
}
}
private void PropagatePrimaryKeyToFields()
{
Sooda.Schema.FieldInfo[] primaryKeys = GetClassInfo().GetPrimaryKeyFields();
SoodaTuple tuple = _primaryKeyValue as SoodaTuple;
if (tuple != null)
{
if (tuple.Length != primaryKeys.Length)
throw new InvalidOperationException("Primary key tuple length doesn't match the expected length");
for (int i = 0; i < primaryKeys.Length; ++i)
{
_fieldValues.SetFieldValue(primaryKeys[i].ClassUnifiedOrdinal, tuple.GetValue(i));
}
}
else
{
if (primaryKeys.Length != 1)
throw new InvalidOperationException("Primary key is not a scalar.");
// scalar
_fieldValues.SetFieldValue(primaryKeys[0].ClassUnifiedOrdinal, _primaryKeyValue);
}
}
protected virtual SoodaObjectFieldValues InitFieldValues(int fieldCount, string[] fieldNames)
{
return new SoodaObjectArrayFieldValues(fieldCount);
}
private void InitFieldData(bool justLoading)
{
if (!InsertMode && GetTransaction().CachingPolicy.ShouldCacheObject(this))
{
SoodaCacheEntry cachedData = GetTransaction().Cache.Find(GetClassInfo().GetRootClass().Name, _primaryKeyValue);
if (cachedData != null)
{
GetTransaction().Statistics.RegisterCacheHit();
SoodaStatistics.Global.RegisterCacheHit();
if (logger.IsTraceEnabled)
{
logger.Trace("Initializing object {0}({1}) from cache.", this.GetType().Name, _primaryKeyValue);
}
_fieldValues = cachedData.Data;
_dataLoadedMask = cachedData.DataLoadedMask;
FromCache = true;
return;
}
// we don't register a cache miss when we're just loading
if (!justLoading)
{
GetTransaction().Statistics.RegisterCacheMiss();
SoodaStatistics.Global.RegisterCacheMiss();
if (logger.IsTraceEnabled)
{
logger.Trace("Cache miss. Object {0}({1}) not found in cache.", this.GetType().Name, _primaryKeyValue);
}
}
}
ClassInfo ci = GetClassInfo();
int fieldCount = ci.UnifiedFields.Count;
_fieldValues = InitFieldValues(fieldCount, ci.OrderedFieldNames);
GetTransaction().Statistics.RegisterFieldsInited();
SoodaStatistics.Global.RegisterFieldsInited();
// primary key was set before the fields - propagate the value
// back to the field(s)
if (_primaryKeyValue != null)
{
PropagatePrimaryKeyToFields();
}
if (InsertMode)
{
SetDefaultNotNullValues();
}
}
private void SetDefaultNotNullValues()
{
ClassInfo ci = GetClassInfo();
for (int i = 0; i < _fieldValues.Length; ++i)
{
if (ci.UnifiedFields[i].IsPrimaryKey || ci.UnifiedFields[i].ReferencedClass != null)
continue;
SoodaFieldHandler handler = GetFieldHandler(i);
if (!handler.IsNullable)
_fieldValues.SetFieldValue(i, handler.ZeroValue());
}
}
void SetUpdateMode(object primaryKeyValue)
{
InsertMode = false;
SetPrimaryKeyValue(primaryKeyValue);
SetAllDataNotLoaded();
}
public SoodaTransaction GetTransaction()
{
return _transaction;
}
protected virtual void BeforeObjectInsert() { }
protected virtual void BeforeObjectUpdate() { }
protected virtual void BeforeObjectDelete() { }
protected virtual void AfterObjectInsert() { }
protected virtual void AfterObjectUpdate() { }
protected virtual void AfterObjectDelete() { }
protected virtual void BeforeFieldUpdate(string name, object oldVal, object newVal) { }
protected virtual void AfterFieldUpdate(string name, object oldVal, object newVal) { }
public void MarkForDelete()
{
MarkForDelete(true, true);
}
public void MarkForDelete(bool delete, bool recurse)
{
try
{
int oldDeletePosition = GetTransaction().DeletedObjects.Count;
MarkForDelete(delete, recurse, true);
int newDeletePosition = GetTransaction().DeletedObjects.Count;
if (newDeletePosition != oldDeletePosition)
{
GetTransaction().SaveObjectChanges(true, null);
GetTransaction()._savingObjects = true;
foreach (SoodaDataSource source in GetTransaction()._dataSources)
{
source.BeginSaveChanges();
}
List<SoodaObject> deleted = GetTransaction().DeletedObjects;
for (int i = oldDeletePosition; i < newDeletePosition; ++i)
{
// logger.Debug("Actually deleting {0}", GetTransaction().DeletedObjects[i].GetObjectKeyString());
SoodaObject o = deleted[i];
o.CommitObjectChanges();
o.SetObjectDirty();
GetTransaction().MarkPrecommitted(o);
}
foreach (SoodaDataSource source in GetTransaction()._dataSources)
{
source.FinishSaveChanges();
}
for (int i = oldDeletePosition; i < newDeletePosition; ++i)
{
deleted[i].AfterObjectDelete();
}
}
}
finally
{
GetTransaction()._savingObjects = false;
}
}
public void MarkForDelete(bool delete, bool recurse, bool savingChanges)
{
if (DeleteMarker != delete)
{
BeforeObjectDelete();
DeleteMarker = delete;
if (recurse)
{
if (logger.IsTraceEnabled)
{
logger.Trace("Marking outer references of {0} for delete...", GetObjectKeyString());
}
for (ClassInfo ci = this.GetClassInfo(); ci != null; ci = ci.InheritsFromClass)
{
foreach (Sooda.Schema.FieldInfo fi in ci.OuterReferences)
{
logger.Trace("{0} Delete action: {1}", fi, fi.DeleteAction);
if (fi.DeleteAction == DeleteAction.Nothing)
continue;
ISoodaObjectFactory factory = GetTransaction().GetFactory(fi.ParentClass);
SoqlBooleanExpression whereExpression = Soql.FieldEquals(fi.Name, this);
SoodaWhereClause whereClause = new SoodaWhereClause(whereExpression);
// logger.Debug("loading list where: {0}", whereExpression);
IList referencingList = factory.GetList(GetTransaction(), whereClause, SoodaOrderBy.Unsorted, SoodaSnapshotOptions.KeysOnly);
switch (fi.DeleteAction)
{
case DeleteAction.Cascade:
foreach (SoodaObject o in referencingList)
{
o.MarkForDelete(delete, recurse, savingChanges);
}
break;
case DeleteAction.Nullify:
PropertyInfo pi = factory.TheType.GetProperty(fi.Name);
foreach (SoodaObject o in referencingList)
{
pi.SetValue(o, null, null);
}
break;
default:
throw new NotImplementedException(fi.DeleteAction.ToString());
}
}
}
}
GetTransaction().DeletedObjects.Add(this);
}
}
public bool IsMarkedForDelete()
{
return DeleteMarker;
}
internal object GetFieldValue(int fieldNumber)
{
return _fieldValues.GetBoxedFieldValue(fieldNumber);
}
public bool IsFieldDirty(int fieldNumber)
{
if (_fieldIsDirty == null)
return false;
int slotNumber = fieldNumber >> 3;
int bitNumber = fieldNumber & 7;
return (_fieldIsDirty[slotNumber] & (1 << bitNumber)) != 0;
}
public void SetFieldDirty(int fieldNumber, bool dirty)
{
if (_fieldIsDirty == null)
{
int fieldCount = GetClassInfo().UnifiedFields.Count;
_fieldIsDirty = new byte[(fieldCount + 7) >> 3];
}
int slotNumber = fieldNumber >> 3;
int bitNumber = fieldNumber & 7;
if (dirty)
{
_fieldIsDirty[slotNumber] |= (byte) (1 << bitNumber);
}
else
{
_fieldIsDirty[slotNumber] &= (byte) ~(1 << bitNumber);
}
}
protected virtual SoodaFieldHandler GetFieldHandler(int ordinal)
{
throw new NotImplementedException();
}
internal void CheckForNulls()
{
EnsureFieldsInited();
if (!DeleteMarker)
{
List<Sooda.Schema.FieldInfo> fields = GetClassInfo().UnifiedFields;
for (int i = 0; i < _fieldValues.Length; ++i)
{
Sooda.Schema.FieldInfo field = fields[i];
if (!field.IsNullable && IsDataLoaded(field.Table.OrdinalInClass) && _fieldValues.IsNull(i))
FieldCannotBeNull(field.Name);
}
}
}
protected internal virtual void CheckAssertions() { }
void FieldCannotBeNull(string fieldName)
{
throw new SoodaException("Field '" + fieldName + "' cannot be null on commit in " + GetObjectKeyString());
}
public bool IsObjectDirty()
{
return (_flags & SoodaObjectFlags.Dirty) != 0;
}
internal void SetObjectDirty()
{
if (!IsObjectDirty())
{
EnsureFieldsInited();
_flags |= SoodaObjectFlags.Dirty;
GetTransaction().RegisterDirtyObject(this);
}
_flags &= ~SoodaObjectFlags.WrittenIntoDatabase;
}
internal void ResetObjectDirty()
{
_flags &= ~(SoodaObjectFlags.Dirty | SoodaObjectFlags.WrittenIntoDatabase);
}
public virtual Sooda.Schema.ClassInfo GetClassInfo()
{
throw new NotImplementedException();
}
public string GetObjectKeyString()
{
return String.Format("{0}[{1}]", GetClassInfo().Name, GetPrimaryKeyValue());
}
public object GetPrimaryKeyValue()
{
return _primaryKeyValue;
}
protected void SetPrimaryKeySubValue(object keyValue, int valueOrdinal, int totalValues)
{
SoodaTuple tuple = (SoodaTuple) _primaryKeyValue;
if (tuple == null)
_primaryKeyValue = tuple = new SoodaTuple(totalValues);
tuple.SetValue(valueOrdinal, keyValue);
if (tuple.IsAllNotNull())
{
if (_fieldValues != null)
PropagatePrimaryKeyToFields();
if (IsRegisteredInTransaction())
throw new SoodaException("Cannot set primary key value more than once.");
RegisterObjectInTransaction();
}
}
protected internal void SetPrimaryKeyValue(object keyValue)
{
if (_primaryKeyValue == null)
{
_primaryKeyValue = keyValue;
if (_fieldValues != null)
PropagatePrimaryKeyToFields();
RegisterObjectInTransaction();
}
else if (IsRegisteredInTransaction())
{
throw new SoodaException("Cannot set primary key value more than once.");
}
}
protected internal virtual void AfterDeserialize() { }
protected virtual void InitNewObject() { }
#region 'Loaded' state management
bool IsAllDataLoaded()
{
// 2^N-1 has exactly N lower bits set to 1
return _dataLoadedMask == (1 << GetClassInfo().UnifiedTables.Count) - 1;
}
void SetAllDataLoaded()
{
// 2^N-1 has exactly N lower bits set to 1
_dataLoadedMask = (1 << GetClassInfo().UnifiedTables.Count) - 1;
}
void SetAllDataNotLoaded()
{
_dataLoadedMask = 0;
}
bool IsDataLoaded(int tableNumber)
{
return (_dataLoadedMask & (1 << tableNumber)) != 0;
}
void SetDataLoaded(int tableNumber)
{
_dataLoadedMask |= (1 << tableNumber);
}
#endregion
private int LoadDataFromRecord(System.Data.IDataRecord reader, int firstColumnIndex, TableInfo[] tables, int tableIndex)
{
int recordPos = firstColumnIndex;
bool first = true;
EnsureFieldsInited(true);
int i;
int oldDataLoadedMask = _dataLoadedMask;
for (i = tableIndex; i < tables.Length; ++i)
{
TableInfo table = tables[i];
// logger.Debug("Loading data from table {0}. Number of fields: {1} Record pos: {2} Table index {3}.", table.NameToken, table.Fields.Count, recordPos, tableIndex);
if (table.OrdinalInClass == 0 && !first)
{
// logger.Trace("Found table 0 of another object. Exiting.");
break;
}
foreach (Sooda.Schema.FieldInfo field in table.Fields)
{
// don't load primary keys
if (!field.IsPrimaryKey)
{
try
{
int ordinal = field.ClassUnifiedOrdinal;
if (!IsFieldDirty(ordinal))
{
object value = reader.IsDBNull(recordPos) ? null : GetFieldHandler(ordinal).RawRead(reader, recordPos);
_fieldValues.SetFieldValue(ordinal, value);
}
}
catch (Exception ex)
{
logger.Error("Error while reading field {0}.{1}: {2}", table.NameToken, field.Name, ex);
throw;
}
}
recordPos++;
}
SetDataLoaded(table.OrdinalInClass);
first = false;
}
if (!IsObjectDirty() && (!FromCache || _dataLoadedMask != oldDataLoadedMask) && GetTransaction().CachingPolicy.ShouldCacheObject(this))
{
TimeSpan expirationTimeout;
bool slidingExpiration;
if (GetTransaction().CachingPolicy.GetExpirationTimeout(this, out expirationTimeout, out slidingExpiration))
{
GetTransaction().Cache.Add(GetClassInfo().GetRootClass().Name, GetPrimaryKeyValue(), GetCacheEntry(), expirationTimeout, slidingExpiration);
FromCache = true;
}
}
// if we've started with a first table and there are more to be processed
if (tableIndex == 0 && i != tables.Length)
{
// logger.Trace("Materializing extra objects...");
for (; i < tables.Length; ++i)
{
TableInfo table = tables[i];
if (table.OrdinalInClass == 0)
{
GetTransaction().Statistics.RegisterExtraMaterialization();
SoodaStatistics.Global.RegisterExtraMaterialization();
// logger.Trace("Materializing {0} at {1}", tables[i].NameToken, recordPos);
int pkOrdinal = table.OwnerClass.GetFirstPrimaryKeyField().OrdinalInTable;
if (reader.IsDBNull(recordPos + pkOrdinal))
{
// logger.Trace("Object is null. Skipping.");
}
else
{
ISoodaObjectFactory factory = GetTransaction().GetFactory(table.OwnerClass);
SoodaObject.GetRefFromRecordHelper(GetTransaction(), factory, reader, recordPos, tables, i);
}
}
else
{
// TODO - can this be safely called?
}
recordPos += table.Fields.Count;
}
// logger.Trace("Finished materializing extra objects.");
}
return tables.Length;
}
internal void EnsureFieldsInited()
{
EnsureFieldsInited(false);
}
void EnsureFieldsInited(bool justLoading)
{
if (_fieldValues == null)
InitFieldData(justLoading);
}
internal void EnsureDataLoaded(int tableNumber)
{
if (!IsDataLoaded(tableNumber))
{
EnsureFieldsInited();
LoadData(tableNumber);
}
else if (InsertMode)
{
EnsureFieldsInited();
}
}
internal void LoadAllData()
{
// TODO - OPTIMIZE: LOAD DATA FROM ALL TABLES IN A SINGLE QUERY
for (int i = 0; i < GetClassInfo().UnifiedTables.Count; ++i)
{
if (!IsDataLoaded(i))
{
LoadData(i);
}
}
}
private void LoadData(int tableNumber)
{
LoadDataWithKey(GetPrimaryKeyValue(), tableNumber);
}
protected void LoadReadOnlyObject(object keyVal)
{
InsertMode = false;
SetPrimaryKeyValue(keyVal);
// #warning FIX ME
LoadDataWithKey(keyVal, 0);
}
protected void LoadDataWithKey(object keyVal, int tableNumber)
{
EnsureFieldsInited();
if (IsDataLoaded(tableNumber))
return;
if (logger.IsTraceEnabled)
{
// logger.Trace("Loading data for {0}({1}) from table #{2}", GetClassInfo().Name, keyVal, tableNumber);
};
try
{
SoodaDataSource ds = GetTransaction().OpenDataSource(GetClassInfo().GetDataSource());
TableInfo[] loadedTables;
using (IDataReader record = ds.LoadObjectTable(this, keyVal, tableNumber, out loadedTables))
{
if (record == null)
{
logger.Error("LoadObjectTable() failed for {0}", GetObjectKeyString());
GetTransaction().UnregisterObject(this);
throw new SoodaObjectNotFoundException(String.Format("Object {0} not found in the database", GetObjectKeyString()));
}
/*
for (int i = 0; i < loadedTables.Length; ++i)
{
logger.Trace("loadedTables[{0}] = {1}", i, loadedTables[i].NameToken);
}
*/
LoadDataFromRecord(record, 0, loadedTables, 0);
record.Close();
}
}
catch (Exception ex)
{
GetTransaction().UnregisterObject(this);
logger.Error("Exception in LoadDataWithKey({0}): {1}", GetObjectKeyString(), ex);
throw ex;
}
}
protected void RegisterObjectInTransaction()
{
GetTransaction().RegisterObject(this);
}
protected bool IsRegisteredInTransaction()
{
return GetTransaction().IsRegistered(this);
}
void SaveOuterReferences()
{
List<KeyValuePair<int, SoodaObject>> brokenReferences = null;
foreach (Sooda.Schema.FieldInfo fi in GetClassInfo().UnifiedFields)
{
if (fi.ReferencedClass == null)
continue;
object v = _fieldValues.GetBoxedFieldValue(fi.ClassUnifiedOrdinal);
if (v != null)
{
ISoodaObjectFactory factory = GetTransaction().GetFactory(fi.ReferencedClass);
SoodaObject obj = factory.TryGet(GetTransaction(), v);
if (obj != null && obj != this && obj.IsInsertMode() && !obj.InsertedIntoDatabase)
{
if (obj.VisitedOnCommit && !obj.WrittenIntoDatabase)
{
// cyclic reference
if (!fi.IsNullable)
throw new Exception("Cyclic reference between " + GetObjectKeyString() + " and " + obj.GetObjectKeyString());
if (brokenReferences == null)
{
CopyOnWrite();
brokenReferences = new List<KeyValuePair<int, SoodaObject>>();
}
brokenReferences.Add(new KeyValuePair<int, SoodaObject>(fi.ClassUnifiedOrdinal, obj));
_fieldValues.SetFieldValue(fi.ClassUnifiedOrdinal, null);
}
else
{
obj.SaveObjectChanges();
}
}
}
}
if (brokenReferences != null)
{
// insert this object without the cyclic references
CommitObjectChanges();
foreach (KeyValuePair<int, SoodaObject> pair in brokenReferences)
{
int ordinal = pair.Key;
SoodaObject obj = pair.Value;
// insert referenced object
obj.SaveObjectChanges();
// restore reference
_fieldValues.SetFieldValue(ordinal, obj.GetPrimaryKeyValue());
}
}
}
internal void SaveObjectChanges()
{
VisitedOnCommit = true;
if (WrittenIntoDatabase)
return;
if (IsObjectDirty())
{
SaveOuterReferences();
}
if ((IsObjectDirty() || IsInsertMode()) && !WrittenIntoDatabase)
{
// deletes are performed in a separate pass
if (!IsMarkedForDelete())
{
CommitObjectChanges();
}
WrittenIntoDatabase = true;
}
else if (PostCommitForced)
{
GetTransaction().AddToPostCommitQueue(this);
}
}
internal void CommitObjectChanges()
{
SoodaDataSource ds = GetTransaction().OpenDataSource(GetClassInfo().GetDataSource());
try
{
EnsureFieldsInited();
ds.SaveObjectChanges(this, GetTransaction().IsPrecommit);
}
catch (Exception e)
{
throw new SoodaDatabaseException("Cannot save object to the database " + e.Message, e);
}
//GetTransaction().AddToPostCommitQueue(this);
}
internal void InvalidateCacheAfterCommit()
{
SoodaCacheInvalidateReason reason;
if (IsMarkedForDelete())
reason = SoodaCacheInvalidateReason.Deleted;
else if (IsInsertMode())
reason = SoodaCacheInvalidateReason.Inserted;
else
reason = SoodaCacheInvalidateReason.Updated;
GetTransaction().Cache.Invalidate(GetClassInfo().GetRootClass().Name, GetPrimaryKeyValue(), reason);
}
internal void PostCommit()
{
if (IsInsertMode())
{
if (AreObjectTriggersEnabled())
AfterObjectInsert();
InsertMode = false;
}
else
{
if (AreObjectTriggersEnabled())
AfterObjectUpdate();
}
}
internal void CallBeforeCommitEvent()
{
if (AreObjectTriggersEnabled())
{
if (IsInsertMode())
BeforeObjectInsert();
else
BeforeObjectUpdate();
}
GetTransaction().AddToPostCommitQueue(this);
}
private void SerializePrimaryKey(XmlWriter xw)
{
foreach (Sooda.Schema.FieldInfo fi in GetClassInfo().GetPrimaryKeyFields())
{
int ordinal = fi.ClassUnifiedOrdinal;
xw.WriteStartElement("key");
xw.WriteAttributeString("ordinal", ordinal.ToString());
GetFieldHandler(ordinal).Serialize(_fieldValues.GetBoxedFieldValue(ordinal), xw);
xw.WriteEndElement();
}
}
// create an empty object just to make sure that the deserialization
// will find it before any references are used.
//
internal void PreSerialize(XmlWriter xw, SoodaSerializeOptions options)
{
if (!IsInsertMode() && !IsMarkedForDelete())
return;
xw.WriteStartElement("object");
xw.WriteAttributeString("mode", IsMarkedForDelete() ? "update" : "insert");
xw.WriteAttributeString("class", GetClassInfo().Name);
if (IsMarkedForDelete())
xw.WriteAttributeString("delete", "true");
SerializePrimaryKey(xw);
xw.WriteEndElement();
}
internal void Serialize(XmlWriter xw, SoodaSerializeOptions options)
{
if (IsMarkedForDelete())
return;
xw.WriteStartElement("object");
xw.WriteAttributeString("mode", "update");
xw.WriteAttributeString("class", GetClassInfo().Name);
if (!IsObjectDirty())
xw.WriteAttributeString("dirty", "false");
if (!AreObjectTriggersEnabled())
xw.WriteAttributeString("disableobjecttriggers", "true");
if (PostCommitForced)
xw.WriteAttributeString("forcepostcommit", "true");
logger.Trace("Serializing {0}...", GetObjectKeyString());
EnsureFieldsInited();
if ((options & SoodaSerializeOptions.IncludeNonDirtyFields) != 0 && !IsAllDataLoaded())
LoadAllData();
SerializePrimaryKey(xw);
foreach (Sooda.Schema.FieldInfo fi in GetClassInfo().UnifiedFields)
{
if (fi.IsPrimaryKey)
continue;
int ordinal = fi.ClassUnifiedOrdinal;
bool dirty = IsFieldDirty(ordinal);
if (dirty || (options & SoodaSerializeOptions.IncludeNonDirtyFields) != 0)
{
xw.WriteStartElement("field");
xw.WriteAttributeString("name", fi.Name);
GetFieldHandler(ordinal).Serialize(_fieldValues.GetBoxedFieldValue(ordinal), xw);
if (!dirty)
xw.WriteAttributeString("dirty", "false");
xw.WriteEndElement();
}
}
if ((options & SoodaSerializeOptions.IncludeDebugInfo) != 0)
{
xw.WriteStartElement("debug");
xw.WriteAttributeString("transaction", (_transaction != null) ? "notnull" : "null");
xw.WriteAttributeString("objectDirty", IsObjectDirty() ? "true" : "false");
xw.WriteAttributeString("dataLoaded", IsAllDataLoaded() ? "true" : "false");
xw.WriteAttributeString("disableTriggers", AreFieldUpdateTriggersEnabled() ? "false" : "true");
xw.WriteAttributeString("disableObjectTriggers", AreObjectTriggersEnabled() ? "false" : "true");
xw.WriteEndElement();
}
NameValueCollection persistentValues = GetTransaction().GetPersistentValues(this);
if (persistentValues != null)
{
foreach (string s in persistentValues.AllKeys)
{
xw.WriteStartElement("persistent");
xw.WriteAttributeString("name", s);
xw.WriteAttributeString("value", persistentValues[s]);
xw.WriteEndElement();
}
}
xw.WriteEndElement();
}
internal void DeserializePersistentField(XmlReader reader)
{
string name = reader.GetAttribute("name");
string value = reader.GetAttribute("value");
SetTransactionPersistentValue(name, value);
}
internal void DeserializeField(XmlReader reader)
{
string name = reader.GetAttribute("name");
if (reader.GetAttribute("dirty") != "false")
{
EnsureFieldsInited();
CopyOnWrite();
int fieldOrdinal = GetFieldInfo(name).ClassUnifiedOrdinal;
SoodaFieldHandler field = GetFieldHandler(fieldOrdinal);
object val = field.Deserialize(reader);
// Console.WriteLine("Deserializing field: {0}", name);
PropertyInfo pi = GetType().GetProperty(name);
if (pi.PropertyType.IsSubclassOf(typeof(SoodaObject)))
{
if (val != null)
{
ISoodaObjectFactory fact = GetTransaction().GetFactory(pi.PropertyType);
val = fact.GetRef(GetTransaction(), val);
}
pi.SetValue(this, val, null);
}
else
{
// set as raw
_fieldValues.SetFieldValue(fieldOrdinal, val);
SetFieldDirty(fieldOrdinal, true);
}
SetObjectDirty();
}
else
{
// Console.WriteLine("Not deserializing field: {0}", name);
}
}
void SetFieldValue(int fieldOrdinal, object value)
{
CopyOnWrite();
_fieldValues.SetFieldValue(fieldOrdinal, value);
SetFieldDirty(fieldOrdinal, true);
SetObjectDirty();
}
internal void SetPlainFieldValue(int tableNumber, string fieldName, int fieldOrdinal, object newValue, SoodaFieldUpdateDelegate before, SoodaFieldUpdateDelegate after)
{
EnsureFieldsInited();
EnsureDataLoaded(tableNumber);
object oldValue = _fieldValues.GetBoxedFieldValue(fieldOrdinal);
if (Object.Equals(oldValue, newValue))
return;
if (AreFieldUpdateTriggersEnabled())
{
if (before != null)
before(oldValue, newValue);
SetFieldValue(fieldOrdinal, newValue);
if (after != null)
after(oldValue, newValue);
}
else
{
SetFieldValue(fieldOrdinal, newValue);
}
}
internal void SetRefFieldValue(int tableNumber, string fieldName, int fieldOrdinal, SoodaObject newValue, SoodaObject[] refcache, int refCacheOrdinal, ISoodaObjectFactory factory)
{
if (newValue != null)
{
// transaction check
if (newValue.GetTransaction() != this.GetTransaction())
throw new SoodaException("Attempted to assign object " + newValue.GetObjectKeyString() + " from another transaction to " + this.GetObjectKeyString() + "." + fieldName);
}
EnsureFieldsInited();
EnsureDataLoaded(tableNumber);
SoodaObject oldValue = null;
SoodaObjectImpl.GetRefFieldValue(ref oldValue, this, tableNumber, fieldOrdinal, GetTransaction(), factory);
if (Object.Equals(oldValue, newValue))
return;
object[] triggerArgs = new object[] { oldValue, newValue };
if (AreFieldUpdateTriggersEnabled())
{
MethodInfo mi = this.GetType().GetMethod("BeforeFieldUpdate_" + fieldName, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public);
if (mi != null)
mi.Invoke(this, triggerArgs);
}
Sooda.Schema.FieldInfo fieldInfo = GetClassInfo().UnifiedFields[fieldOrdinal];
StringCollection backRefCollections = GetTransaction().Schema.GetBackRefCollections(fieldInfo);
if (oldValue != null && backRefCollections != null)
{
foreach (string collectionName in backRefCollections)
{
PropertyInfo coll = oldValue.GetType().GetProperty(collectionName, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (coll == null)
throw new Exception(collectionName + " not found in " + oldValue.GetType().Name + " while setting " + this.GetType().Name + "." + fieldName);
ISoodaObjectListInternal listInternal = (ISoodaObjectListInternal)coll.GetValue(oldValue, null);
listInternal.InternalRemove(this);
}
}
SetFieldValue(fieldOrdinal, newValue != null ? newValue.GetPrimaryKeyValue() : null);
refcache[refCacheOrdinal] = null;
if (newValue != null && backRefCollections != null)
{
foreach (string collectionName in backRefCollections)
{
PropertyInfo coll = newValue.GetType().GetProperty(collectionName, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (coll == null)
throw new Exception(collectionName + " not found in " + newValue.GetType().Name + " while setting " + this.GetType().Name + "." + fieldName);
ISoodaObjectListInternal listInternal = (ISoodaObjectListInternal)coll.GetValue(newValue, null);
listInternal.InternalAdd(this);
}
}
if (AreFieldUpdateTriggersEnabled())
{
MethodInfo mi = this.GetType().GetMethod("AfterFieldUpdate_" + fieldName, BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public);
if (mi != null)
mi.Invoke(this, triggerArgs);
}
}
public object Evaluate(SoqlExpression expr)
{
return Evaluate(expr, true);
}
class EvaluateContext : ISoqlEvaluateContext
{
private SoodaObject _rootObject;
public EvaluateContext(SoodaObject rootObject)
{
_rootObject = rootObject;
}
public object GetRootObject()
{
return _rootObject;
}
public object GetParameter(int position)
{
throw new Exception("No parameters allowed in evaluation.");
}
}
public object Evaluate(SoqlExpression expr, bool throwOnError)
{
try
{
EvaluateContext ec = new EvaluateContext(this);
return expr.Evaluate(ec);
}
catch
{
if (throwOnError)
throw;
else
return null;
}
}
public object Evaluate(string[] propertyAccessChain, bool throwOnError)
{
try
{
object currentObject = this;
for (int i = 0; i < propertyAccessChain.Length && currentObject != null && currentObject is SoodaObject; ++i)
{
PropertyInfo pi = currentObject.GetType().GetProperty(propertyAccessChain[i]);
currentObject = pi.GetValue(currentObject, null);
}
return currentObject;
}
catch
{
if (throwOnError)
throw;
else
return null;
}
}
public object Evaluate(string propertyAccessChain)
{
return Evaluate(propertyAccessChain, true);
}
public object Evaluate(string propertyAccessChain, bool throwOnError)
{
return Evaluate(propertyAccessChain.Split('.'), throwOnError);
}
static ISoodaObjectFactory GetFactoryFromRecord(SoodaTransaction tran, ISoodaObjectFactory factory, IDataRecord record, int firstColumnIndex, object keyValue, bool loadData)
{
ClassInfo classInfo = factory.GetClassInfo();
List<ClassInfo> subclasses = tran.Schema.GetSubclasses(classInfo);
if (subclasses.Count == 0)
return factory;
// more complex case - we have to determine the actual factory to be used for object creation
int selectorFieldOrdinal = loadData ? classInfo.SubclassSelectorField.OrdinalInTable : record.FieldCount - 1;
object selectorActualValue = factory.GetFieldHandler(selectorFieldOrdinal).RawRead(record, firstColumnIndex + selectorFieldOrdinal);
IComparer comparer = selectorActualValue is string ? (IComparer) CaseInsensitiveComparer.DefaultInvariant : Comparer.DefaultInvariant;
if (0 == comparer.Compare(selectorActualValue, classInfo.SubclassSelectorValue))
return factory;
ISoodaObjectFactory newFactory;
if (!factory.GetClassInfo().DisableTypeCache)
{
newFactory = SoodaTransaction.SoodaObjectFactoryCache.FindObjectFactory(classInfo.Name, keyValue);
if (newFactory != null)
return newFactory;
}
foreach (ClassInfo ci in subclasses)
{
if (0 == comparer.Compare(selectorActualValue, ci.SubclassSelectorValue))
{
newFactory = tran.GetFactory(ci);
SoodaTransaction.SoodaObjectFactoryCache.SetObjectFactory(classInfo.Name, keyValue, newFactory);
return newFactory;
}
}
throw new Exception("Cannot determine subclass. Selector actual value: " + selectorActualValue + " base class: " + classInfo.Name);
}
static SoodaObject GetRefFromRecordHelper(SoodaTransaction tran, ISoodaObjectFactory factory, IDataRecord record, int firstColumnIndex, TableInfo[] loadedTables, int tableIndex, bool loadData)
{
object keyValue;
Sooda.Schema.FieldInfo[] pkFields = factory.GetClassInfo().GetPrimaryKeyFields();
if (pkFields.Length == 1)
{
int pkFieldOrdinal = loadData ? firstColumnIndex + pkFields[0].OrdinalInTable : 0;
try
{
keyValue = factory.GetPrimaryKeyFieldHandler().RawRead(record, pkFieldOrdinal);
}
catch (Exception ex)
{
logger.Error("Error while reading field {0}.{1}: {2}", factory.GetClassInfo().Name, pkFieldOrdinal, ex);
throw ex;
}
}
else
{
object[] pkParts = new object[pkFields.Length];
for (int currentPkPart = 0; currentPkPart < pkFields.Length; currentPkPart++)
{
int pkFieldOrdinal = loadData ? firstColumnIndex + pkFields[currentPkPart].OrdinalInTable : currentPkPart;
SoodaFieldHandler handler = factory.GetFieldHandler(pkFieldOrdinal);
pkParts[currentPkPart] = handler.RawRead(record, pkFieldOrdinal);
}
keyValue = new SoodaTuple(pkParts);
//logger.Debug("Tuple: {0}", keyValue);
}
SoodaObject retVal = factory.TryGet(tran, keyValue);
if (retVal != null)
{
if (loadData && !retVal.IsDataLoaded(0))
retVal.LoadDataFromRecord(record, firstColumnIndex, loadedTables, tableIndex);
return retVal;
}
factory = GetFactoryFromRecord(tran, factory, record, firstColumnIndex, keyValue, loadData);
retVal = factory.GetRawObject(tran);
tran.Statistics.RegisterObjectUpdate();
SoodaStatistics.Global.RegisterObjectUpdate();
retVal.InsertMode = false;
retVal.SetPrimaryKeyValue(keyValue);
if (loadData)
retVal.LoadDataFromRecord(record, firstColumnIndex, loadedTables, tableIndex);
return retVal;
}
public static SoodaObject GetRefFromRecordHelper(SoodaTransaction tran, ISoodaObjectFactory factory, IDataRecord record, int firstColumnIndex, TableInfo[] loadedTables, int tableIndex)
{
return GetRefFromRecordHelper(tran, factory, record, firstColumnIndex, loadedTables, tableIndex, true);
}
internal static SoodaObject GetRefFromKeyRecordHelper(SoodaTransaction tran, ISoodaObjectFactory factory, IDataRecord record)
{
return GetRefFromRecordHelper(tran, factory, record, 0, null, -1, false);
}
public static SoodaObject GetRefHelper(SoodaTransaction tran, ISoodaObjectFactory factory, int keyValue)
{
return GetRefHelper(tran, factory, (object)keyValue);
}
public static SoodaObject GetRefHelper(SoodaTransaction tran, ISoodaObjectFactory factory, string keyValue)
{
return GetRefHelper(tran, factory, (object)keyValue);
}
public static SoodaObject GetRefHelper(SoodaTransaction tran, ISoodaObjectFactory factory, long keyValue)
{
return GetRefHelper(tran, factory, (object)keyValue);
}
public static SoodaObject GetRefHelper(SoodaTransaction tran, ISoodaObjectFactory factory, Guid keyValue)
{
return GetRefHelper(tran, factory, (object)keyValue);
}
public static SoodaObject GetRefHelper(SoodaTransaction tran, ISoodaObjectFactory factory, object keyValue)
{
SoodaObject retVal = factory.TryGet(tran, keyValue);
if (retVal != null)
return retVal;
ClassInfo classInfo = factory.GetClassInfo();
if (classInfo.InheritsFromClass != null && tran.ExistsObjectWithKey(classInfo.GetRootClass().Name, keyValue))
throw new SoodaObjectNotFoundException();
if (classInfo.GetSubclassesForSchema(tran.Schema).Count > 0)
{
ISoodaObjectFactory newFactory = null;
if (!classInfo.DisableTypeCache)
{
newFactory = SoodaTransaction.SoodaObjectFactoryCache.FindObjectFactory(classInfo.Name, keyValue);
}
if (newFactory != null)
{
factory = newFactory;
}
else
{
// if the class is actually inherited, we delegate the responsibility
// to the appropriate GetRefFromRecord which will be called by the snapshot
SoqlBooleanExpression where = null;
Sooda.Schema.FieldInfo[] pkFields = classInfo.GetPrimaryKeyFields();
object[] par = new object[pkFields.Length];
for (int i = 0; i < pkFields.Length; ++i)
{
par[i] = SoodaTuple.GetValue(keyValue, i);
SoqlBooleanExpression cmp = Soql.FieldEqualsParam(pkFields[i].Name, i);
where = where == null ? cmp : where.And(cmp);
}
SoodaWhereClause whereClause = new SoodaWhereClause(where, par);
IList list = factory.GetList(tran, whereClause, SoodaOrderBy.Unsorted, SoodaSnapshotOptions.NoTransaction | SoodaSnapshotOptions.NoWriteObjects | SoodaSnapshotOptions.NoCache);
if (list.Count == 1)
return (SoodaObject)list[0];
else if (list.Count == 0)
throw new SoodaObjectNotFoundException("No matching object.");
else
throw new SoodaObjectNotFoundException("More than one object found. Fatal error.");
}
}
retVal = factory.GetRawObject(tran);
tran.Statistics.RegisterObjectUpdate();
SoodaStatistics.Global.RegisterObjectUpdate();
if (factory.GetClassInfo().ReadOnly)
{
retVal.LoadReadOnlyObject(keyValue);
}
else
{
retVal.SetUpdateMode(keyValue);
}
return retVal;
}
public override string ToString()
{
object keyVal = this.GetPrimaryKeyValue();
return keyVal == null ? string.Empty : keyVal.ToString();
}
public void InitRawObject(SoodaTransaction tran)
{
_transaction = tran;
_dataLoadedMask = 0;
_flags = SoodaObjectFlags.InsertMode;
_primaryKeyValue = null;
}
internal void CopyOnWrite()
{
if (FromCache)
{
_fieldValues = _fieldValues.Clone();
FromCache = false;
}
}
protected NameValueCollection GetTransactionPersistentValues()
{
return GetTransaction().GetPersistentValues(this);
}
protected void SetTransactionPersistentValue(string name, string value)
{
SetObjectDirty();
GetTransaction().SetPersistentValue(this, name, value);
}
protected string GetTransactionPersistentValue(string name)
{
return GetTransaction().GetPersistentValue(this, name);
}
public virtual string GetLabel(bool throwOnError)
{
string labelField = GetClassInfo().GetLabel();
if (labelField == null)
return null;
object o = Evaluate(labelField, throwOnError);
if (o == null)
return String.Empty;
System.Data.SqlTypes.INullable nullable = o as System.Data.SqlTypes.INullable;
if (nullable != null && nullable.IsNull)
return String.Empty;
return Convert.ToString(o);
}
Sooda.Schema.FieldInfo GetFieldInfo(string name)
{
ClassInfo ci = GetClassInfo();
Sooda.Schema.FieldInfo fi = ci.FindFieldByName(name);
if (fi == null)
throw new Exception("Field " + name + " not found in " + ci.Name);
return fi;
}
object GetTypedFieldValue(Sooda.Schema.FieldInfo fi)
{
object value = _fieldValues.GetBoxedFieldValue(fi.ClassUnifiedOrdinal);
if (value != null && fi.References != null)
value = GetTransaction().GetFactory(fi.References).GetRef(GetTransaction(), value);
return value;
}
public object this[string fieldName]
{
get
{
Sooda.Schema.FieldInfo fi = GetFieldInfo(fieldName);
EnsureDataLoaded(fi.Table.OrdinalInClass);
return GetTypedFieldValue(fi);
}
set
{
Sooda.Schema.FieldInfo fi = GetFieldInfo(fieldName);
if (!fi.IsDynamic)
{
// Disallow because:
// - the per-field update triggers wouldn't be called
// - for references, refcache would get out-of-date
// - for references, collections would not be updated
// Alternatively we might just set the property via reflection. This wouldn't suffer from the above problems.
throw new InvalidOperationException("Cannot set non-dynamic field " + fieldName + " with an indexer");
}
if (value == null)
{
if (!fi.IsNullable)
throw new ArgumentNullException("Cannot set non-nullable " + fieldName + " to null");
}
else
{
Type type = fi.References != null
? GetTransaction().GetFactory(fi.References).TheType
: fi.GetNullableFieldHandler().GetFieldType();
if (!type.IsAssignableFrom(value.GetType()))
throw new InvalidCastException("Cannot set " + fieldName + " of type " + type + " to " + value.GetType());
}
EnsureDataLoaded(fi.Table.OrdinalInClass);
if (AreFieldUpdateTriggersEnabled())
{
object oldValue = GetTypedFieldValue(fi);
if (Object.Equals(oldValue, value))
return;
BeforeFieldUpdate(fieldName, oldValue, value);
SoodaObject so = value as SoodaObject;
SetFieldValue(fi.ClassUnifiedOrdinal, so != null ? so.GetPrimaryKeyValue() : value);
AfterFieldUpdate(fieldName, oldValue, value);
}
else
{
SoodaObject so = value as SoodaObject;
SetFieldValue(fi.ClassUnifiedOrdinal, so != null ? so.GetPrimaryKeyValue() : value);
}
}
}
#if DOTNET4
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return true;
}
public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
this[binder.Name] = value;
return true;
}
#endif
}
}
| |
using System.Collections;
using System.Collections.Generic;
using GuiLabs.Editor.Blocks;
namespace GuiLabs.Editor.CSharp
{
[BlockSerialization("using")]
public class UsingBlock :
ListBlock,
ICSharpBlock,
IEnumerable<UsingDirective>,
INamespaceLevel
{
#region ctor
public UsingBlock()
{
keyword.MyControl.Box.Margins.Top = 3;
this.MyUniversalControl.Box.Margins.Left = -1;
this.MyUniversalControl.Box.Margins.Top = -4;
MyUniversalControl.HideCurlies = true;
this.HMembers.Add(keyword);
Add("");
this.Draggable = false;
this.CanPrependBlocks = false;
this.CanMoveUpDown = false;
MyUniversalControl.Layout();
}
#endregion
#region API
#region Add
public void Add(UsingDirective usingEntry)
{
if (this.VMembers.Children.Count == 1
&& FirstUsing != null
&& FirstUsing.Text == "")
{
if (this.Root != null)
{
FirstUsing.Replace(usingEntry);
}
else
{
this.VMembers.Children.Replace(FirstUsing, usingEntry);
}
}
else
{
this.VMembers.Add(usingEntry);
}
}
public new void Add(string usingText)
{
Add(new UsingDirective(usingText));
}
#endregion
#region Exists
public bool Exists(string usingDirective)
{
foreach (UsingDirective ud in this.VMembers.Children)
{
if (ud.Text == usingDirective)
{
return true;
}
}
return false;
}
#endregion
public UsingDirective FirstUsing
{
get
{
return this.VMembers.Children.Head as UsingDirective;
}
}
public IEnumerator<UsingDirective> GetEnumerator()
{
foreach (UsingDirective u in this.VMembers.FindChildren<UsingDirective>())
{
yield return u;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region OnEvents
protected override void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.End
&& this.FirstUsing != null)
{
this.FirstUsing.SetFocus();
e.Handled = true;
}
if (!e.Handled)
{
base.OnKeyDown(sender, e);
}
}
#endregion
#region VMembers
public override VContainerBlock VMembers
{
get
{
return base.VMembers;
}
set
{
base.VMembers = value;
this.VMembers.AddAcceptableBlockTypes<UsingDirective>();
}
}
#endregion
#region Label
private KeywordLabel keyword = new KeywordLabel("using");
#endregion
#region Memento
public override void AddChildren(IEnumerable<Block> restoredChildren)
{
if (this.VMembers.Children.Count == 1
&& FirstUsing != null
&& string.IsNullOrEmpty(FirstUsing.Text))
{
this.VMembers.Children.Delete(FirstUsing);
}
foreach (Block child in restoredChildren)
{
this.VMembers.Children.Add(child);
}
}
#endregion
#region DefaultFocusableControl
public override GuiLabs.Canvas.Controls.Control DefaultFocusableControl()
{
if (FirstUsing != null)
{
return FirstUsing.MyControl;
}
else
{
return this.MyControl;
}
}
#endregion
#region GetBlocksToDelete
public override IEnumerable<Block> GetBlocksToDelete()
{
yield return this;
}
#endregion
#region Style
protected override string StyleName()
{
return "UsingBlock";
}
#endregion
#region AcceptVisitor
public override void AcceptVisitor(IVisitor Visitor)
{
Visitor.Visit(this);
}
#endregion
}
}
| |
using System;
using System.Linq;
using Jasper.Attributes;
using Jasper.Runtime.Routing;
using Jasper.Util;
using Shouldly;
using Xunit;
namespace Jasper.AzureServiceBus.Tests
{
public class topics_routing
{
[Fact]
public void route_to_topics_by_type()
{
using (var host = JasperHost.For<TopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
router.RouteByType(typeof(Topic1))
.Routes
.Single()
.Destination
.ShouldBe("asb://topic/one".ToUri());
router.RouteByType(typeof(Topic2))
.Routes
.Single()
.Destination
.ShouldBe("asb://topic/two".ToUri());
router.RouteByType(typeof(Topic3))
.Routes
.Single()
.Destination
.ShouldBe("asb://topic/three".ToUri());
}
}
[Fact]
public void route_when_topic_is_known()
{
using (var host = JasperHost.For<TopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
// Overriding the topic name here
router.RouteOutgoingByEnvelope(new Envelope(new Topic1()) {TopicName = "two"})
.Single()
.Destination
.ShouldBe("asb://topic/two".ToUri());
}
}
[Fact]
public void route_when_topic_is_known_implicit_registration()
{
using (var host = JasperHost.For<ImplicitTopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
// Overriding the topic name here
router.RouteOutgoingByEnvelope(new Envelope(new Topic1()) {TopicName = "two"})
.Single()
.Destination
.ShouldBe("asb://topic/two".ToUri());
}
}
[Theory]
[InlineData("one", "asb://topic/one")]
[InlineData("two", "asb://topic/two")]
[InlineData("three", "asb://topic/three")]
public void routing_with_topic_routed_by_topic_name_rule(string topicName, string uriString)
{
using (var host = JasperHost.For<TopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
var message = new NumberMessage
{
Topic = topicName
};
router.RouteOutgoingByMessage(message)
.Single()
.Destination
.ShouldBe(uriString.ToUri());
}
}
[Theory]
[InlineData(typeof(Topic1), "asb://topic/one")]
[InlineData(typeof(Topic2), "asb://topic/two")]
[InlineData(typeof(Topic3), "asb://topic/three")]
public void route_with_topics_by_type(Type type, string uriString)
{
using (var host = JasperHost.For<TopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
var message = Activator.CreateInstance(type);
router.RouteOutgoingByMessage(message)
.Single()
.Destination
.ShouldBe(uriString.ToUri());
}
}
[Theory]
[InlineData("one", "asb://topic/one")]
[InlineData("two", "asb://topic/two")]
[InlineData("three", "asb://topic/three")]
public void routing_with_topic_routed_by_topic_name_on_envelope(string topicName, string uriString)
{
using (var host = JasperHost.For<TopicSendingApp>())
{
var router = host.Get<IEnvelopeRouter>();
var envelope = new Envelope(new Topic1())
{
TopicName = topicName
};
router.RouteOutgoingByEnvelope(envelope)
.Single()
.Destination
.ShouldBe(uriString.ToUri());
}
}
// SAMPLE: AzureServiceBus-TopicSendingApp
public class TopicSendingApp : JasperOptions
{
public TopicSendingApp()
{
Endpoints.ConfigureAzureServiceBus(asb => { asb.ConnectionString = end_to_end.ConnectionString; });
// This directs Jasper to send all messages to
// an Azure Service Bus topic name derived from the
// message type
Endpoints.PublishAllMessages()
.ToAzureServiceBusTopics()
.OutgoingTopicNameIs<NumberMessage>(x => x.Topic);
}
}
// ENDSAMPLE
public class ImplicitTopicSendingApp : JasperOptions
{
public ImplicitTopicSendingApp()
{
Endpoints.ConfigureAzureServiceBus(asb => { asb.ConnectionString = end_to_end.ConnectionString; });
}
}
}
public class TopicHandler
{
public void Handle(Topic1 one)
{
}
public void Handle(Topic2 two)
{
}
public void Handle(Topic3 three)
{
}
public void Handle(NumberMessage message)
{
}
}
[Topic("one")]
public class Topic1
{
}
[Topic("two")]
public class Topic2
{
}
[Topic("three")]
public class Topic3
{
}
public class NumberMessage
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Topic { get; set; }
}
}
| |
/*
Copyright 2015 Shane Lillie
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 Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Util;
using Android.Views;
using Java.Interop;
// TODO: can this be replaced with something based on this: https://developer.android.com/training/animation/screen-slide.html ?
namespace EnergonSoftware.BackpackPlanner.Droid.Views
{
/// <summary>
/// https://github.com/xamarin/monodroid-samples/blob/master/ViewPagerIndicator/ViewPagerIndicator/Resources/layout/simple_circles.xml
/// </summary>
/// <remarks>
/// TODO: this needs cleaned up in a bad way
/// </remarks>
public sealed class CircleViewPagerIndicator : View, IViewPagerIndicator
{
private const int Horizontal = 0;
private const int Vertical = 1;
private float _radius;
private readonly Paint _paintPageFill;
private readonly Paint _paintStroke;
private readonly Paint _paintFill;
private Android.Support.V4.View.ViewPager _viewPager;
private Android.Support.V4.View.ViewPager.IOnPageChangeListener _listener;
private int mCurrentPage;
private int mSnapPage;
private int mCurrentOffset;
private int mScrollState;
private int mPageSize;
private int mOrientation;
private bool mCentered;
private bool mSnap;
private const int INVALID_POINTER = -1;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private bool mIsDragging;
public CircleViewPagerIndicator (Context context) : this(context, null)
{
}
public CircleViewPagerIndicator (Context context, IAttributeSet attrs) : this (context, attrs, Resource.Attribute.vpiCirclePageIndicatorStyle)
{
}
public CircleViewPagerIndicator (Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
//Load defaults from resources
var res = Resources;
int defaultPageColor = Android.Support.V4.Content.ContextCompat.GetColor (context, Resource.Color.default_circle_indicator_page_color);
int defaultFillColor = Android.Support.V4.Content.ContextCompat.GetColor (context, Resource.Color.default_circle_indicator_fill_color);
int defaultOrientation = res.GetInteger (Resource.Integer.default_circle_indicator_orientation);
int defaultStrokeColor = Android.Support.V4.Content.ContextCompat.GetColor (context, Resource.Color.default_circle_indicator_stroke_color);
float defaultStrokeWidth = res.GetDimension (Resource.Dimension.default_circle_indicator_stroke_width);
float defaultRadius = res.GetDimension (Resource.Dimension.default_circle_indicator_radius);
bool defaultCentered = res.GetBoolean (Resource.Boolean.default_circle_indicator_centered);
bool defaultSnap = res.GetBoolean (Resource.Boolean.default_circle_indicator_snap);
//Retrieve styles attributes
var a = context.ObtainStyledAttributes (attrs, Resource.Styleable.CirclePageIndicator, defStyle, Resource.Style.Widget_CirclePageIndicator);
mCentered = a.GetBoolean (Resource.Styleable.CirclePageIndicator_centered, defaultCentered);
mOrientation = a.GetInt (Resource.Styleable.CirclePageIndicator_android_orientation, defaultOrientation);
_paintPageFill = new Paint (PaintFlags.AntiAlias);
_paintPageFill.SetStyle (Paint.Style.Fill);
_paintPageFill.Color = a.GetColor (Resource.Styleable.CirclePageIndicator_pageColor, defaultPageColor);
_paintStroke = new Paint (PaintFlags.AntiAlias);
_paintStroke.SetStyle (Paint.Style.Stroke);
_paintStroke.Color = a.GetColor (Resource.Styleable.CirclePageIndicator_strokeColor, defaultStrokeColor);
_paintStroke.StrokeWidth = a.GetDimension (Resource.Styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth);
_paintFill = new Paint (PaintFlags.AntiAlias);
_paintFill.SetStyle (Paint.Style.Fill);
_paintFill.Color = a.GetColor (Resource.Styleable.CirclePageIndicator_fillColor, defaultFillColor);
_radius = a.GetDimension (Resource.Styleable.CirclePageIndicator_radius, defaultRadius);
mSnap = a.GetBoolean (Resource.Styleable.CirclePageIndicator_snap, defaultSnap);
a.Recycle ();
var configuration = ViewConfiguration.Get (context);
mTouchSlop = configuration.ScaledPagingTouchSlop;
}
public void SetCentered (bool centered)
{
mCentered = centered;
Invalidate ();
}
public bool IsCentered ()
{
return mCentered;
}
public void SetPageColor (Color pageColor)
{
_paintPageFill.Color = pageColor;
Invalidate ();
}
public int GetPageColor ()
{
return _paintPageFill.Color;
}
public void SetFillColor (Color fillColor)
{
_paintFill.Color = fillColor;
Invalidate ();
}
public int GetFillColor ()
{
return _paintFill.Color;
}
public void SetOrientation (int orientation)
{
switch (orientation)
{
case Horizontal:
case Vertical:
mOrientation = orientation;
UpdatePageSize ();
RequestLayout ();
break;
default:
throw new Java.Lang.IllegalArgumentException("Orientation must be either Horizontal or Vertical.");
}
}
public int GetOrientation ()
{
return mOrientation;
}
public void SetStrokeColor (Color strokeColor)
{
_paintStroke.Color = strokeColor;
Invalidate ();
}
public int GetStrokeColor ()
{
return _paintStroke.Color;
}
public void SetStrokeWidth (float strokeWidth)
{
_paintStroke.StrokeWidth = strokeWidth;
Invalidate ();
}
public float GetStrokeWidth ()
{
return _paintStroke.StrokeWidth;
}
public void SetRadius (float radius)
{
_radius = radius;
Invalidate ();
}
public float GetRadius ()
{
return _radius;
}
public void SetSnap (bool snap)
{
mSnap = snap;
Invalidate ();
}
public bool IsSnap ()
{
return mSnap;
}
protected override void OnDraw (Canvas canvas)
{
base.OnDraw (canvas);
if (_viewPager == null) {
return;
}
int count = _viewPager.Adapter.Count;
if (count == 0) {
return;
}
if (mCurrentPage >= count) {
SetCurrentItem (count - 1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
if (mOrientation == Horizontal) {
longSize = Width;
longPaddingBefore = PaddingLeft;
longPaddingAfter = PaddingRight;
shortPaddingBefore = PaddingTop;
} else {
longSize = Height;
longPaddingBefore = PaddingTop;
longPaddingAfter = PaddingBottom;
shortPaddingBefore = PaddingLeft;
}
float threeRadius = _radius * 3;
float shortOffset = shortPaddingBefore + _radius;
float longOffset = longPaddingBefore + _radius;
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
}
float dX;
float dY;
float pageFillRadius = _radius;
if (_paintStroke.StrokeWidth > 0) {
pageFillRadius -= _paintStroke.StrokeWidth / 2.0f;
}
//Draw stroked circles
for (int iLoop = 0; iLoop < count; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == Horizontal) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (_paintPageFill.Alpha > 0) {
canvas.DrawCircle (dX, dY, pageFillRadius, _paintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != _radius) {
canvas.DrawCircle (dX, dY, _radius, _paintStroke);
}
}
//Draw the filled circle according to the current scroll
float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
if (!mSnap && (mPageSize != 0)) {
cx += (mCurrentOffset * 1.0f / mPageSize) * threeRadius;
}
if (mOrientation == Horizontal) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
canvas.DrawCircle (dX, dY, _radius, _paintFill);
}
public override bool OnTouchEvent (MotionEvent ev)
{
if (base.OnTouchEvent (ev)) {
return true;
}
if ((_viewPager == null) || (_viewPager.Adapter.Count == 0)) {
return false;
}
var action = ev.Action;
switch ((int)action & Android.Support.V4.View.MotionEventCompat.ActionMask)
{
case (int) MotionEventActions.Down:
mActivePointerId = ev.GetPointerId (0);
mLastMotionX = ev.GetX ();
break;
case (int)MotionEventActions.Move:
{
int activePointerIndex = ev.FindPointerIndex (mActivePointerId);
float x = ev.GetX (activePointerIndex);
float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Java.Lang.Math.Abs (deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
if (!_viewPager.IsFakeDragging) {
_viewPager.BeginFakeDrag ();
}
mLastMotionX = x;
_viewPager.FakeDragBy (deltaX);
}
break;
}
case (int)MotionEventActions.Cancel:
case (int)MotionEventActions.Up:
if (!mIsDragging) {
int count = _viewPager.Adapter.Count;
int width = Width;
float halfWidth = width / 2f;
float sixthWidth = width / 6f;
if ((mCurrentPage > 0) && (ev.GetX () < halfWidth - sixthWidth)) {
_viewPager.CurrentItem = mCurrentPage - 1;
return true;
} else if ((mCurrentPage < count - 1) && (ev.GetX () > halfWidth + sixthWidth)) {
_viewPager.CurrentItem = mCurrentPage + 1;
return true;
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (_viewPager.IsFakeDragging) {
_viewPager.EndFakeDrag ();
}
break;
case Android.Support.V4.View.MotionEventCompat.ActionPointerDown: {
int index = Android.Support.V4.View.MotionEventCompat.GetActionIndex (ev);
float x = ev.GetX (index);
mLastMotionX = x;
mActivePointerId = ev.GetPointerId (index);
break;
}
case Android.Support.V4.View.MotionEventCompat.ActionPointerUp:
int pointerIndex = Android.Support.V4.View.MotionEventCompat.GetActionIndex (ev);
int pointerId = ev.GetPointerId (pointerIndex);
if (pointerId == mActivePointerId) {
int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.GetPointerId (newPointerIndex);
}
mLastMotionX = ev.GetX (ev.FindPointerIndex (mActivePointerId));
break;
}
return true;
}
public override bool PerformClick()
{
return base.PerformClick();
}
public void SetViewPager (Android.Support.V4.View.ViewPager view)
{
if (view.Adapter == null) {
throw new Java.Lang.IllegalStateException ("ViewPager does not have adapter instance.");
}
_viewPager = view;
_viewPager.AddOnPageChangeListener(this);
UpdatePageSize ();
Invalidate ();
}
private void UpdatePageSize ()
{
if (_viewPager != null) {
mPageSize = (mOrientation == Horizontal) ? _viewPager.Width : _viewPager.Height;
}
}
public void SetViewPager (Android.Support.V4.View.ViewPager view, int initialPosition)
{
SetViewPager (view);
SetCurrentItem (initialPosition);
}
public void SetCurrentItem (int item)
{
if (_viewPager == null) {
throw new Java.Lang.IllegalStateException ("ViewPager has not been bound.");
}
_viewPager.CurrentItem = item;
mCurrentPage = item;
Invalidate ();
}
public void NotifyDataSetChanged ()
{
Invalidate ();
}
public void OnPageScrollStateChanged (int state)
{
mScrollState = state;
_listener?.OnPageScrollStateChanged (state);
}
public void OnPageScrolled (int position, float positionOffset, int positionOffsetPixels)
{
mCurrentPage = position;
mCurrentOffset = positionOffsetPixels;
UpdatePageSize ();
Invalidate ();
_listener?.OnPageScrolled (position, positionOffset, positionOffsetPixels);
}
public void OnPageSelected (int position)
{
if (mSnap || mScrollState == Android.Support.V4.View.ViewPager.ScrollStateIdle) {
mCurrentPage = position;
mSnapPage = position;
Invalidate ();
}
_listener?.OnPageSelected (position);
}
public void SetOnPageChangeListener (Android.Support.V4.View.ViewPager.IOnPageChangeListener listener)
{
_listener = listener;
}
protected override void OnMeasure (int widthMeasureSpec, int heightMeasureSpec)
{
if (mOrientation == Horizontal) {
SetMeasuredDimension (MeasureLong (widthMeasureSpec), MeasureShort (heightMeasureSpec));
} else {
SetMeasuredDimension (MeasureShort (widthMeasureSpec), MeasureLong (heightMeasureSpec));
}
}
/**
* Determines the width of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int MeasureLong (int measureSpec)
{
int result;
var specMode = MeasureSpec.GetMode (measureSpec);
var specSize = MeasureSpec.GetSize (measureSpec);
if ((specMode == MeasureSpecMode.Exactly) || (_viewPager == null)) {
//We were told how big to be
result = specSize;
} else {
//Calculate the width according the views count
int count = _viewPager.Adapter.Count;
result = (int)(PaddingLeft + PaddingRight
+ (count * 2 * _radius) + (count - 1) * _radius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpecMode.AtMost) {
result = Java.Lang.Math.Min (result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The height of the view, honoring constraints from measureSpec
*/
private int MeasureShort (int measureSpec)
{
int result;
var specMode = MeasureSpec.GetMode (measureSpec);
var specSize = MeasureSpec.GetSize (measureSpec);
if (specMode == MeasureSpecMode.Exactly) {
//We were told how big to be
result = specSize;
} else {
//Measure the height
result = (int)(2 * _radius + PaddingTop + PaddingBottom + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpecMode.AtMost) {
result = Java.Lang.Math.Min (result, specSize);
}
}
return result;
}
protected override void OnRestoreInstanceState (IParcelable state)
{
try {
SavedState savedState = (SavedState)state;
base.OnRestoreInstanceState (savedState.SuperState);
mCurrentPage = savedState.CurrentPage;
mSnapPage = savedState.CurrentPage;
} catch {
base.OnRestoreInstanceState (state);
// Ignore, this needs to support IParcelable...
}
RequestLayout ();
}
protected override IParcelable OnSaveInstanceState ()
{
var superState = base.OnSaveInstanceState ();
var savedState = new SavedState(superState)
{
CurrentPage = mCurrentPage
};
return savedState;
}
public class SavedState : BaseSavedState
{
public int CurrentPage { get; set; }
public SavedState (IParcelable superState) : base(superState)
{
}
private SavedState (Parcel parcel) : base(parcel)
{
CurrentPage = parcel.ReadInt ();
}
public override void WriteToParcel (Parcel dest, ParcelableWriteFlags flags)
{
base.WriteToParcel (dest, flags);
dest.WriteInt (CurrentPage);
}
[ExportField ("CREATOR")]
static SavedStateCreator InitializeCreator ()
{
return new SavedStateCreator ();
}
class SavedStateCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel (Parcel source)
{
return new SavedState (source);
}
public Java.Lang.Object[] NewArray (int size)
{
return new SavedState[size];
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.WindowsAPICodePack.DirectX.Direct3D;
using Microsoft.WindowsAPICodePack.DirectX.Direct3D10;
using Microsoft.WindowsAPICodePack.DirectX.Direct3DX10;
using Microsoft.WindowsAPICodePack.DirectX.Graphics;
namespace Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities
{
/// <summary>
/// The format of each XMesh vertex
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct XMeshVertex
{
/// <summary>
/// The vertex location
/// </summary>
[MarshalAs(UnmanagedType.Struct)]
public Vector4F Vertex;
/// <summary>
/// The vertex normal
/// </summary>
[MarshalAs(UnmanagedType.Struct)]
public Vector4F Normal;
/// <summary>
/// The vertex color
/// </summary>
[MarshalAs(UnmanagedType.Struct)]
public Vector4F Color;
/// <summary>
/// The texture coordinates (U,V)
/// </summary>
[MarshalAs(UnmanagedType.Struct)]
public Vector2F Texture;
};
/// <summary>
/// A part is a piece of a scene
/// </summary>
internal struct Part
{
/// <summary>
/// The name of the part
/// </summary>
public string name;
/// <summary>
/// A description of the part data format
/// </summary>
public InputElementDescription[] dataDescription;
/// <summary>
/// The vertex buffer for the part
/// </summary>
public D3DBuffer vertexBuffer;
/// <summary>
/// The number of vertices in the vertex buffer
/// </summary>
public int vertexCount;
/// <summary>
/// The part texture/material
/// </summary>
public Material material;
/// <summary>
/// The parts that are sub-parts of this part
/// </summary>
public List<Part> parts;
/// <summary>
/// The transformation to be applied to this part relative to the parent
/// </summary>
public Matrix4x4F partTransform;
}
internal class Material
{
/// <summary>
/// The difuse color of the material
/// </summary>
public Vector4F materialColor;
/// <summary>
/// The exponent of the specular color
/// </summary>
public float specularPower;
/// <summary>
/// The specualr color
/// </summary>
public Vector3F specularColor;
/// <summary>
/// The emissive color
/// </summary>
public Vector3F emissiveColor;
/// <summary>
/// The part texture
/// </summary>
public ShaderResourceView textureResource;
}
/// <summary>
/// Specifies how a particular mesh should be shaded
/// </summary>
internal struct MaterialSpecification
{
/// <summary>
/// The difuse color of the material
/// </summary>
public Vector4F materialColor;
/// <summary>
/// The exponent of the specular color
/// </summary>
public float specularPower;
/// <summary>
/// The specualr color
/// </summary>
public Vector3F specularColor;
/// <summary>
/// The emissive color
/// </summary>
public Vector3F emissiveColor;
/// <summary>
/// The name of the texture file
/// </summary>
public string textureFileName;
}
/// <summary>
/// Loads a text formated .X file
/// </summary>
internal partial class XMeshTextLoader
{
#region Input element descriptions
static InputElementDescription[] description = new InputElementDescription[]
{
new InputElementDescription()
{
SemanticName = "POSITION",
SemanticIndex = 0,
Format = Format.R32G32B32A32Float,
InputSlot = 0,
AlignedByteOffset = 0,
InputSlotClass = InputClassification.PerVertexData,
InstanceDataStepRate = 0,
},
new InputElementDescription()
{
SemanticName = "NORMAL",
SemanticIndex = 0,
Format = Format.R32G32B32A32Float,
InputSlot = 0,
AlignedByteOffset = 16,
InputSlotClass = InputClassification.PerVertexData,
InstanceDataStepRate = 0,
},
new InputElementDescription()
{
SemanticName = "COLOR",
SemanticIndex = 0,
Format = Format.R32G32B32A32Float,
InputSlot = 0,
AlignedByteOffset = 32,
InputSlotClass = InputClassification.PerVertexData,
InstanceDataStepRate = 0
},
new InputElementDescription()
{
SemanticName = "TEXCOORD",
SemanticIndex = 0,
Format = Format.R32G32Float,
InputSlot = 0,
AlignedByteOffset = 48,
InputSlotClass = InputClassification.PerVertexData,
InstanceDataStepRate = 0,
}
};
#endregion // Input element descriptions
private D3DDevice device;
private string meshDirectory = "";
/// <summary>
/// Constructor that associates a device with the resulting mesh
/// </summary>
/// <param name="device"></param>
public XMeshTextLoader(D3DDevice device)
{
this.device = device;
}
/// <summary>
/// Loads the mesh from the file
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public IEnumerable<Part> XMeshFromFile(string path)
{
string meshPath = null;
if(File.Exists(path))
{
meshPath = path;
}
else
{
string sdkMediaPath = GetDXSDKMediaPath() + path;
if (File.Exists(sdkMediaPath))
meshPath = sdkMediaPath;
}
if(meshPath == null)
throw new System.IO.FileNotFoundException("Could not find mesh file.");
else
meshDirectory = Path.GetDirectoryName(meshPath);
string data = null;
using (StreamReader xFile = File.OpenText(meshPath))
{
string header = xFile.ReadLine();
ValidateHeader(header);
data = xFile.ReadToEnd();
}
return ExtractRootParts(data);
}
/// <summary>
/// Returns the path to the DX SDK dir
/// </summary>
/// <returns></returns>
private string GetDXSDKMediaPath()
{
return Environment.GetEnvironmentVariable("DXSDK_DIR");
}
/// <summary>
/// Validates the header of the .X file. Enforces the text-only requirement of this code.
/// </summary>
/// <param name="xFile"></param>
private void ValidateHeader(string fileHeader)
{
Regex headerParse = new Regex(@"xof (?<vermajor>\d\d)(?<verminor>\d\d)(?<format>\w\w\w[\w\s])(?<floatsize>\d\d\d\d)");
Match m = headerParse.Match(fileHeader);
if (!m.Success)
{
throw new System.IO.InvalidDataException("Invalid .X file.");
}
if (m.Groups.Count != 5)
{
// None of the capture groups are optional, so a successful match
// should always have 5 capture groups
throw new System.IO.InvalidDataException("Invalid .X file.");
}
if (m.Groups["vermajor"].ToString() != "03") // version 3.x supported
throw new System.IO.InvalidDataException("Unknown .X file version.");
if (m.Groups["format"].ToString() != "txt ")
throw new System.IO.InvalidDataException("Only text .X files are supported.");
}
/// <summary>
/// Parses the root scene of the .X file
/// </summary>
/// <param name="data"></param>
private IEnumerable<Part> ExtractRootParts(string data)
{
return XDataObjectFactory.ExtractDataObjects(ref data)
.Where(obj => obj.IsVisualObject)
.Select(obj => PartFromDataObject(obj))
.ToList();
}
private Part PartFromDataObject(IXDataObject dataObject)
{
Part part = new Part();
part.parts = new List<Part>();
part.name = dataObject.Name;
switch (dataObject.DataObjectType)
{
case "Frame":
// Frame data objects translate to parts with only a transform,
// and no vertices, materials, etc.
part.partTransform = ExtractFrameTransformation(dataObject);
foreach (IXDataObject childObject in dataObject.Children.Where(obj => obj.IsVisualObject))
{
part.parts.Add(PartFromDataObject(childObject));
}
break;
case "Mesh":
// Mesh data objects inherit transform from their parent,
// but do have vertices, materials, etc.
part.partTransform = Matrix4x4F.Identity;
part.dataDescription = description;
LoadMesh(ref part, dataObject);
break;
default:
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
"Object type \"{0}\" is incorrect. Only Frame or Mesh data objects can be converted to Part instances",
dataObject.DataObjectType));
}
return part;
}
/// <summary>
/// Extracts the transformation associated with the current frame
/// </summary>
/// <param name="dataFile"></param>
/// <param name="dataOffset"></param>
/// <returns></returns>
private Matrix4x4F ExtractFrameTransformation(IXDataObject dataObject)
{
IXDataObject matrixObject = GetSingleChild(dataObject, "FrameTransformMatrix");
if (matrixObject == null)
{
return Matrix4x4F.Identity;
}
string rawMatrixData = matrixObject.Body;
Regex matrixData = new Regex(@"([-\d\.,\s]+);;");
Match data = matrixData.Match(rawMatrixData);
if(!data.Success)
throw new System.IO.InvalidDataException("Error parsing frame transformation.");
string[] values = data.Groups[1].ToString().Split(new char[] { ',' });
if(values.Length != 16)
throw new System.IO.InvalidDataException("Error parsing frame transformation.");
float[] fvalues = new float[16];
for(int n = 0; n < 16; n++)
{
fvalues[n] = float.Parse(values[n], CultureInfo.InvariantCulture);
}
return new Matrix4x4F(fvalues);
}
Regex findArrayCount = new Regex(@"([\d]+);");
Regex findVector4F = new Regex(@"([-\d]+\.[\d]+);([-\d]+\.[\d]+);([-\d]+\.[\d]+);([-\d]+\.[\d]+);");
Regex findVector3F = new Regex(@"([-\d]+\.[\d]+);([-\d]+\.[\d]+);([-\d]+\.[\d]+);");
Regex findVector2F = new Regex(@"([-\d]+\.[\d]+);([-\d]+\.[\d]+);");
Regex findScalarF = new Regex(@"([-\d]+\.[\d]+);");
/// <summary>
/// Loads the first material for a mesh
/// </summary>
/// <param name="meshMAterialData"></param>
/// <returns></returns>
List<MaterialSpecification> LoadMeshMaterialList(IXDataObject dataObject)
{
var materials = from child in dataObject.Children
where child.DataObjectType == "Material"
select LoadMeshMaterial(child);
return new List<MaterialSpecification>(materials);
}
/// <summary>
/// Loads a MeshMaterial subresource
/// </summary>
/// <param name="materialData"></param>
/// <returns></returns>
MaterialSpecification LoadMeshMaterial(IXDataObject dataObject)
{
MaterialSpecification m = new MaterialSpecification();
int dataOffset = 0;
Match color = findVector4F.Match(dataObject.Body, dataOffset);
if(!color.Success)
throw new System.IO.InvalidDataException("problem reading material color");
m.materialColor.X = float.Parse(color.Groups[1].ToString(), CultureInfo.InvariantCulture);
m.materialColor.Y = float.Parse(color.Groups[2].ToString(), CultureInfo.InvariantCulture);
m.materialColor.Z = float.Parse(color.Groups[3].ToString(), CultureInfo.InvariantCulture);
m.materialColor.W = float.Parse(color.Groups[4].ToString(), CultureInfo.InvariantCulture);
dataOffset = color.Index + color.Length;
Match power = findScalarF.Match(dataObject.Body, dataOffset);
if(!power.Success)
throw new System.IO.InvalidDataException("problem reading material specular color exponent");
m.specularPower = float.Parse(power.Groups[1].ToString(), CultureInfo.InvariantCulture);
dataOffset = power.Index + power.Length;
Match specular = findVector3F.Match(dataObject.Body, dataOffset);
if(!specular.Success)
throw new System.IO.InvalidDataException("problem reading material specular color");
m.specularColor.X = float.Parse(specular.Groups[1].ToString(), CultureInfo.InvariantCulture);
m.specularColor.Y = float.Parse(specular.Groups[2].ToString(), CultureInfo.InvariantCulture);
m.specularColor.Z = float.Parse(specular.Groups[3].ToString(), CultureInfo.InvariantCulture);
dataOffset = specular.Index + specular.Length;
Match emissive = findVector3F.Match(dataObject.Body, dataOffset);
if(!emissive.Success)
throw new System.IO.InvalidDataException("problem reading material emissive color");
m.emissiveColor.X = float.Parse(emissive.Groups[1].ToString(), CultureInfo.InvariantCulture);
m.emissiveColor.Y = float.Parse(emissive.Groups[2].ToString(), CultureInfo.InvariantCulture);
m.emissiveColor.Z = float.Parse(emissive.Groups[3].ToString(), CultureInfo.InvariantCulture);
dataOffset = emissive.Index + emissive.Length;
IXDataObject filenameObject = GetSingleChild(dataObject, "TextureFilename");
if (filenameObject != null)
{
Regex findFilename = new Regex(@"[\s]+""([\\\w\.]+)"";");
Match filename = findFilename.Match(filenameObject.Body);
if (!filename.Success)
throw new System.IO.InvalidDataException("problem reading texture filename");
m.textureFileName = filename.Groups[1].ToString();
}
return m;
}
internal class IndexedMeshNormals
{
public List<Vector4F> normalVectors;
public List<Int32> normalIndexMap;
}
/// <summary>
/// Loads the indexed normal vectors for a mesh
/// </summary>
/// <param name="meshNormalData"></param>
/// <returns></returns>
IndexedMeshNormals LoadMeshNormals(IXDataObject dataObject)
{
IndexedMeshNormals indexedMeshNormals = new IndexedMeshNormals();
Match normalCount = findArrayCount.Match(dataObject.Body);
if(!normalCount.Success)
throw new System.IO.InvalidDataException("problem reading mesh normals count");
indexedMeshNormals.normalVectors = new List<Vector4F>();
int normals = int.Parse(normalCount.Groups[1].Value, CultureInfo.InvariantCulture);
int dataOffset = normalCount.Index + normalCount.Length;
for(int normalIndex = 0; normalIndex < normals; normalIndex++)
{
Match normal = findVector3F.Match(dataObject.Body, dataOffset);
if(!normal.Success)
throw new System.IO.InvalidDataException("problem reading mesh normal vector");
else
dataOffset = normal.Index + normal.Length;
indexedMeshNormals.normalVectors.Add(
new Vector4F(
float.Parse(normal.Groups[1].Value, CultureInfo.InvariantCulture),
float.Parse(normal.Groups[2].Value, CultureInfo.InvariantCulture),
float.Parse(normal.Groups[3].Value, CultureInfo.InvariantCulture),
1.0f));
}
Match faceNormalCount = findArrayCount.Match(dataObject.Body, dataOffset);
if(!faceNormalCount.Success)
throw new System.IO.InvalidDataException("problem reading mesh normals count");
indexedMeshNormals.normalIndexMap = new List<Int32>();
int faceCount = int.Parse(faceNormalCount.Groups[1].Value, CultureInfo.InvariantCulture);
dataOffset = faceNormalCount.Index + faceNormalCount.Length;
for(int faceNormalIndex = 0; faceNormalIndex < faceCount; faceNormalIndex++)
{
Match normalFace = findVertexIndex.Match(dataObject.Body, dataOffset);
if(!normalFace.Success)
throw new System.IO.InvalidDataException("problem reading mesh normal face");
else
dataOffset = normalFace.Index + normalFace.Length;
string[] vertexIndexes = normalFace.Groups[2].Value.Split(new char[] { ',' });
for(int n = 0; n <= vertexIndexes.Length - 3; n ++)
{
indexedMeshNormals.normalIndexMap.Add(int.Parse(vertexIndexes[0], CultureInfo.InvariantCulture));
indexedMeshNormals.normalIndexMap.Add(int.Parse(vertexIndexes[1 + n], CultureInfo.InvariantCulture));
indexedMeshNormals.normalIndexMap.Add(int.Parse(vertexIndexes[2 + n], CultureInfo.InvariantCulture));
}
}
return indexedMeshNormals;
}
/// <summary>
/// Loads the per vertex color for a mesh
/// </summary>
/// <param name="vertexColorData"></param>
/// <returns></returns>
Dictionary<int, Vector4F> LoadMeshColors(IXDataObject dataObject)
{
Regex findVertexColor = new Regex(@"([\d]+); ([\d]+\.[\d]+);([\d]+\.[\d]+);([\d]+\.[\d]+);([\d]+\.[\d]+);;");
Match vertexCount = findArrayCount.Match(dataObject.Body);
if(!vertexCount.Success)
throw new System.IO.InvalidDataException("problem reading vertex colors count");
Dictionary<int, Vector4F> colorDictionary = new Dictionary<int,Vector4F>();
int verticies = int.Parse(vertexCount.Groups[1].Value, CultureInfo.InvariantCulture);
int dataOffset = vertexCount.Index + vertexCount.Length;
for(int vertexIndex = 0; vertexIndex < verticies; vertexIndex++)
{
Match vertexColor = findVertexColor.Match(dataObject.Body, dataOffset);
if(!vertexColor.Success)
throw new System.IO.InvalidDataException("problem reading vertex colors");
else
dataOffset = vertexColor.Index + vertexColor.Length;
colorDictionary[int.Parse(vertexColor.Groups[1].Value, CultureInfo.InvariantCulture)] =
new Vector4F(
float.Parse(vertexColor.Groups[2].Value, CultureInfo.InvariantCulture),
float.Parse(vertexColor.Groups[3].Value, CultureInfo.InvariantCulture),
float.Parse(vertexColor.Groups[4].Value, CultureInfo.InvariantCulture),
float.Parse(vertexColor.Groups[5].Value, CultureInfo.InvariantCulture));
}
return colorDictionary;
}
/// <summary>
/// Loads the texture coordinates(U,V) for a mesh
/// </summary>
/// <param name="textureCoordinateData"></param>
/// <returns></returns>
List<Vector2F> LoadMeshTextureCoordinates(IXDataObject dataObject)
{
Match coordinateCount = findArrayCount.Match(dataObject.Body);
if(!coordinateCount.Success)
throw new System.IO.InvalidDataException("problem reading mesh texture coordinates count");
List<Vector2F> textureCoordinates = new List<Vector2F>();
int coordinates = int.Parse(coordinateCount.Groups[1].Value, CultureInfo.InvariantCulture);
int dataOffset = coordinateCount.Index + coordinateCount.Length;
for(int coordinateIndex = 0; coordinateIndex < coordinates; coordinateIndex++)
{
Match coordinate = findVector2F.Match(dataObject.Body, dataOffset);
if(!coordinate.Success)
throw new System.IO.InvalidDataException("problem reading texture coordinate count");
else
dataOffset = coordinate.Index + coordinate.Length;
textureCoordinates.Add(
new Vector2F(
float.Parse(coordinate.Groups[1].Value, CultureInfo.InvariantCulture),
float.Parse(coordinate.Groups[2].Value, CultureInfo.InvariantCulture)));
}
return textureCoordinates;
}
Regex findVertexIndex = new Regex(@"([\d]+);[\s]*([\d,]+)?;");
/// <summary>
/// Loads a mesh and creates the vertex/index buffers for the part
/// </summary>
/// <param name="part"></param>
/// <param name="meshData"></param>
void LoadMesh(ref Part part, IXDataObject dataObject)
{
// load vertex data
int dataOffset = 0;
Match vertexCount = findArrayCount.Match(dataObject.Body);
if(!vertexCount.Success)
throw new System.IO.InvalidDataException("problem reading vertex count");
List<Vector4F> vertexList = new List<Vector4F>();
int verticies = int.Parse(vertexCount.Groups[1].Value, CultureInfo.InvariantCulture);
dataOffset = vertexCount.Index + vertexCount.Length;
for(int vertexIndex = 0; vertexIndex < verticies; vertexIndex++)
{
Match vertex = findVector3F.Match(dataObject.Body, dataOffset);
if(!vertex.Success)
throw new System.IO.InvalidDataException("problem reading vertex");
else
dataOffset = vertex.Index + vertex.Length;
vertexList.Add(
new Vector4F(
float.Parse(vertex.Groups[1].Value, CultureInfo.InvariantCulture),
float.Parse(vertex.Groups[2].Value, CultureInfo.InvariantCulture),
float.Parse(vertex.Groups[3].Value, CultureInfo.InvariantCulture),
1.0f));
}
// load triangle index data
Match triangleIndexCount = findArrayCount.Match(dataObject.Body, dataOffset);
dataOffset = triangleIndexCount.Index + triangleIndexCount.Length;
if(!triangleIndexCount.Success)
throw new System.IO.InvalidDataException("problem reading index count");
List<Int32> triangleIndiciesList = new List<Int32>();
int triangleIndexListCount = int.Parse(triangleIndexCount.Groups[1].Value, CultureInfo.InvariantCulture);
dataOffset = triangleIndexCount.Index + triangleIndexCount.Length;
for(int triangleIndicyIndex = 0; triangleIndicyIndex < triangleIndexListCount; triangleIndicyIndex++)
{
Match indexEntry = findVertexIndex.Match(dataObject.Body, dataOffset);
if(!indexEntry.Success)
throw new System.IO.InvalidDataException("problem reading vertex index entry");
else
dataOffset = indexEntry.Index + indexEntry.Length;
int indexEntryCount = int.Parse(indexEntry.Groups[1].Value, CultureInfo.InvariantCulture);
string[] vertexIndexes = indexEntry.Groups[2].Value.Split(new char[] { ',' });
if(indexEntryCount != vertexIndexes.Length)
throw new System.IO.InvalidDataException("vertex index count does not equal count of indicies found");
for(int entryIndex = 0; entryIndex <= indexEntryCount - 3; entryIndex++)
{
triangleIndiciesList.Add(int.Parse(vertexIndexes[0], CultureInfo.InvariantCulture));
triangleIndiciesList.Add(int.Parse(vertexIndexes[1 + entryIndex].ToString(), CultureInfo.InvariantCulture));
triangleIndiciesList.Add(int.Parse(vertexIndexes[2 + entryIndex].ToString(), CultureInfo.InvariantCulture));
}
}
// load mesh colors
IXDataObject vertexColorData = GetSingleChild(dataObject, "MeshVertexColors");
Dictionary<int, Vector4F> colorDictionary = null;
if (vertexColorData != null)
colorDictionary = LoadMeshColors(vertexColorData);
// load mesh normals
IXDataObject meshNormalData = GetSingleChild(dataObject, "MeshNormals");
IndexedMeshNormals meshNormals = null;
if(meshNormalData != null)
{
meshNormals = LoadMeshNormals(meshNormalData);
}
// load mesh texture coordinates
IXDataObject meshTextureCoordsData = GetSingleChild(dataObject, "MeshTextureCoords");
List<Vector2F> meshTextureCoords = null;
if(meshTextureCoordsData != null)
{
meshTextureCoords = LoadMeshTextureCoordinates(meshTextureCoordsData);
}
// load mesh material
IXDataObject meshMaterialsData = GetSingleChild(dataObject, "MeshMaterialList");
List<MaterialSpecification> meshMaterials = null;
if(meshMaterialsData != null)
{
meshMaterials = LoadMeshMaterialList(meshMaterialsData);
}
// copy vertex data to HGLOBAL
int byteLength = Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count;
IntPtr nativeVertex = Marshal.AllocHGlobal(byteLength);
byte[] byteBuffer = new byte[byteLength];
XMeshVertex[] varray = new XMeshVertex[triangleIndiciesList.Count];
for(int n = 0; n < triangleIndiciesList.Count; n++)
{
XMeshVertex vertex = new XMeshVertex()
{
Vertex = vertexList[triangleIndiciesList[n]],
Normal = (meshNormals == null) ? new Vector4F(0, 0, 0, 1.0f) : meshNormals.normalVectors[meshNormals.normalIndexMap[n]],
Color = ((colorDictionary == null) ? new Vector4F(0, 0, 0, 0) : colorDictionary[triangleIndiciesList[n]]),
Texture = ((meshTextureCoords == null) ? new Vector2F(0, 0) : meshTextureCoords[triangleIndiciesList[n]])
};
byte[] vertexData = RawSerialize(vertex);
Buffer.BlockCopy(vertexData, 0, byteBuffer, vertexData.Length * n, vertexData.Length);
}
Marshal.Copy(byteBuffer, 0, nativeVertex, byteLength);
// build vertex buffer
BufferDescription bdv = new BufferDescription()
{
Usage = Usage.Default,
ByteWidth = (uint)(Marshal.SizeOf(typeof(XMeshVertex)) * triangleIndiciesList.Count),
BindingOptions = BindingOptions.VertexBuffer,
CpuAccessOptions = CpuAccessOptions.None,
MiscellaneousResourceOptions = MiscellaneousResourceOptions.None
};
SubresourceData vertexInit = new SubresourceData()
{
SystemMemory = nativeVertex
};
part.vertexBuffer = device.CreateBuffer(bdv, vertexInit);
Debug.Assert(part.vertexBuffer != null);
part.vertexCount = triangleIndiciesList.Count;
if(meshMaterials != null)
{
// only a single material is currently supported
MaterialSpecification m = meshMaterials[0];
part.material = new Material()
{
emissiveColor = m.emissiveColor,
specularColor = m.specularColor,
materialColor = m.materialColor,
specularPower = m.specularPower
};
string texturePath = "";
if(File.Exists(m.textureFileName))
texturePath = m.textureFileName;
if(File.Exists(meshDirectory + "\\" + m.textureFileName))
texturePath = meshDirectory + "\\" + m.textureFileName;
if(File.Exists(meshDirectory + "\\..\\" + m.textureFileName))
texturePath = meshDirectory + "\\..\\" + m.textureFileName;
if(texturePath.Length == 0)
{
part.material.textureResource = null;
}
else
{
part.material.textureResource =
D3D10XHelpers.CreateShaderResourceViewFromFile(
device,
texturePath);
}
}
Marshal.FreeHGlobal(nativeVertex);
}
/// <summary>
/// Copies an arbitrary structure into a byte array
/// </summary>
/// <param name="anything"></param>
/// <returns></returns>
public byte[] RawSerialize(object anything)
{
int rawsize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
try
{
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawdatas = new byte[rawsize];
Marshal.Copy(buffer, rawdatas, 0, rawsize);
return rawdatas;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.StorageGateway.Model
{
/// <summary>
/// <para>A JSON object containing the following fields:</para>
/// <ul>
/// <li> DescribeCacheOutput$CacheAllocatedInBytes </li>
/// <li> DescribeCacheOutput$CacheDirtyPercentage </li>
/// <li> DescribeCacheOutput$CacheHitPercentage </li>
/// <li> DescribeCacheOutput$CacheMissPercentage </li>
/// <li> DescribeCacheOutput$CacheUsedPercentage </li>
/// <li> DescribeCacheOutput$DiskIds </li>
/// <li> DescribeCacheOutput$GatewayARN </li>
///
/// </ul>
/// </summary>
public class DescribeCacheResult
{
private string gatewayARN;
private List<string> diskIds = new List<string>();
private long? cacheAllocatedInBytes;
private double? cacheUsedPercentage;
private double? cacheDirtyPercentage;
private double? cacheHitPercentage;
private double? cacheMissPercentage;
/// <summary>
/// In response, AWS Storage Gateway returns the ARN of the activated gateway. If you don't remember the ARN of a gateway, you can use the List
/// Gateways operations to return a list of gateways for your account and region.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>50 - 500</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string GatewayARN
{
get { return this.gatewayARN; }
set { this.gatewayARN = value; }
}
/// <summary>
/// Sets the GatewayARN property
/// </summary>
/// <param name="gatewayARN">The value to set for the GatewayARN property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithGatewayARN(string gatewayARN)
{
this.gatewayARN = gatewayARN;
return this;
}
// Check to see if GatewayARN property is set
internal bool IsSetGatewayARN()
{
return this.gatewayARN != null;
}
/// <summary>
/// An array of the gateway's local disk IDs that are configured as cache. Each local disk ID is specified as a string (minimum length of 1 and
/// maximum length of 300). If no local disks are configured as cache, then the <c>DiskIds</c> array is empty.
///
/// </summary>
public List<string> DiskIds
{
get { return this.diskIds; }
set { this.diskIds = value; }
}
/// <summary>
/// Adds elements to the DiskIds collection
/// </summary>
/// <param name="diskIds">The values to add to the DiskIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithDiskIds(params string[] diskIds)
{
foreach (string element in diskIds)
{
this.diskIds.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the DiskIds collection
/// </summary>
/// <param name="diskIds">The values to add to the DiskIds collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithDiskIds(IEnumerable<string> diskIds)
{
foreach (string element in diskIds)
{
this.diskIds.Add(element);
}
return this;
}
// Check to see if DiskIds property is set
internal bool IsSetDiskIds()
{
return this.diskIds.Count > 0;
}
/// <summary>
/// The size allocated, in bytes, for the cache. If no cache is defined for the gateway, this field returns 0.
///
/// </summary>
public long CacheAllocatedInBytes
{
get { return this.cacheAllocatedInBytes ?? default(long); }
set { this.cacheAllocatedInBytes = value; }
}
/// <summary>
/// Sets the CacheAllocatedInBytes property
/// </summary>
/// <param name="cacheAllocatedInBytes">The value to set for the CacheAllocatedInBytes property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithCacheAllocatedInBytes(long cacheAllocatedInBytes)
{
this.cacheAllocatedInBytes = cacheAllocatedInBytes;
return this;
}
// Check to see if CacheAllocatedInBytes property is set
internal bool IsSetCacheAllocatedInBytes()
{
return this.cacheAllocatedInBytes.HasValue;
}
/// <summary>
/// The percentage (0 to 100) of the cache storage in use. If no cached is defined for the gateway, this field returns 0.
///
/// </summary>
public double CacheUsedPercentage
{
get { return this.cacheUsedPercentage ?? default(double); }
set { this.cacheUsedPercentage = value; }
}
/// <summary>
/// Sets the CacheUsedPercentage property
/// </summary>
/// <param name="cacheUsedPercentage">The value to set for the CacheUsedPercentage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithCacheUsedPercentage(double cacheUsedPercentage)
{
this.cacheUsedPercentage = cacheUsedPercentage;
return this;
}
// Check to see if CacheUsedPercentage property is set
internal bool IsSetCacheUsedPercentage()
{
return this.cacheUsedPercentage.HasValue;
}
/// <summary>
/// The percentage of the cache that contains data that has not yet been persisted to Amazon S3. If no cached is defined for the gateway, this
/// field returns 0.
///
/// </summary>
public double CacheDirtyPercentage
{
get { return this.cacheDirtyPercentage ?? default(double); }
set { this.cacheDirtyPercentage = value; }
}
/// <summary>
/// Sets the CacheDirtyPercentage property
/// </summary>
/// <param name="cacheDirtyPercentage">The value to set for the CacheDirtyPercentage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithCacheDirtyPercentage(double cacheDirtyPercentage)
{
this.cacheDirtyPercentage = cacheDirtyPercentage;
return this;
}
// Check to see if CacheDirtyPercentage property is set
internal bool IsSetCacheDirtyPercentage()
{
return this.cacheDirtyPercentage.HasValue;
}
/// <summary>
/// The percentage (0 to 100) of data read from the storage volume that was read from cache. If no cached is defined for the gateway, this field
/// returns 0.
///
/// </summary>
public double CacheHitPercentage
{
get { return this.cacheHitPercentage ?? default(double); }
set { this.cacheHitPercentage = value; }
}
/// <summary>
/// Sets the CacheHitPercentage property
/// </summary>
/// <param name="cacheHitPercentage">The value to set for the CacheHitPercentage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithCacheHitPercentage(double cacheHitPercentage)
{
this.cacheHitPercentage = cacheHitPercentage;
return this;
}
// Check to see if CacheHitPercentage property is set
internal bool IsSetCacheHitPercentage()
{
return this.cacheHitPercentage.HasValue;
}
/// <summary>
/// TThe percentage (0 to 100) of data read from the storage volume that was not read from the cache, but was read from Amazon S3. If no cached
/// is defined for the gateway, this field returns 0.
///
/// </summary>
public double CacheMissPercentage
{
get { return this.cacheMissPercentage ?? default(double); }
set { this.cacheMissPercentage = value; }
}
/// <summary>
/// Sets the CacheMissPercentage property
/// </summary>
/// <param name="cacheMissPercentage">The value to set for the CacheMissPercentage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheResult WithCacheMissPercentage(double cacheMissPercentage)
{
this.cacheMissPercentage = cacheMissPercentage;
return this;
}
// Check to see if CacheMissPercentage property is set
internal bool IsSetCacheMissPercentage()
{
return this.cacheMissPercentage.HasValue;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Groups
{
public class GroupsService : GroupsServiceBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const GroupPowers DefaultEveryonePowers = GroupPowers.AllowSetHome |
GroupPowers.Accountable |
GroupPowers.JoinChat |
GroupPowers.AllowVoiceChat |
GroupPowers.ReceiveNotices |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
public const GroupPowers OwnerPowers = GroupPowers.Accountable |
GroupPowers.AllowEditLand |
GroupPowers.AllowFly |
GroupPowers.AllowLandmark |
GroupPowers.AllowRez |
GroupPowers.AllowSetHome |
GroupPowers.AllowVoiceChat |
GroupPowers.AssignMember |
GroupPowers.AssignMemberLimited |
GroupPowers.ChangeActions |
GroupPowers.ChangeIdentity |
GroupPowers.ChangeMedia |
GroupPowers.ChangeOptions |
GroupPowers.CreateRole |
GroupPowers.DeedObject |
GroupPowers.DeleteRole |
GroupPowers.Eject |
GroupPowers.FindPlaces |
GroupPowers.HostEvent |
GroupPowers.Invite |
GroupPowers.JoinChat |
GroupPowers.LandChangeIdentity |
GroupPowers.LandDeed |
GroupPowers.LandDivideJoin |
GroupPowers.LandEdit |
GroupPowers.LandEjectAndFreeze |
GroupPowers.LandGardening |
GroupPowers.LandManageAllowed |
GroupPowers.LandManageBanned |
GroupPowers.LandManagePasses |
GroupPowers.LandOptions |
GroupPowers.LandRelease |
GroupPowers.LandSetSale |
GroupPowers.ModerateChat |
GroupPowers.ObjectManipulate |
GroupPowers.ObjectSetForSale |
GroupPowers.ReceiveNotices |
GroupPowers.RemoveMember |
GroupPowers.ReturnGroupOwned |
GroupPowers.ReturnGroupSet |
GroupPowers.ReturnNonGroup |
GroupPowers.RoleProperties |
GroupPowers.SendNotices |
GroupPowers.SetLandingPoint |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
#region Daily Cleanup
private Timer m_CleanupTimer;
public GroupsService(IConfigSource config, string configName)
: base(config, configName)
{
}
public GroupsService(IConfigSource config)
: this(config, string.Empty)
{
// Once a day
m_CleanupTimer = new Timer(24 * 60 * 60 * 1000);
m_CleanupTimer.AutoReset = true;
m_CleanupTimer.Elapsed += new ElapsedEventHandler(m_CleanupTimer_Elapsed);
m_CleanupTimer.Enabled = true;
m_CleanupTimer.Start();
}
private void m_CleanupTimer_Elapsed(object sender, ElapsedEventArgs e)
{
m_Database.DeleteOldNotices();
m_Database.DeleteOldInvites();
}
#endregion
public UUID CreateGroup(string RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish, UUID founderID, out string reason)
{
reason = string.Empty;
// Check if the group already exists
if (m_Database.RetrieveGroup(name) != null)
{
reason = "A group with that name already exists";
return UUID.Zero;
}
// Create the group
GroupData data = new GroupData();
data.GroupID = UUID.Random();
data.Data = new Dictionary<string, string>();
data.Data["Name"] = name;
data.Data["Charter"] = charter;
data.Data["InsigniaID"] = insigniaID.ToString();
data.Data["FounderID"] = founderID.ToString();
data.Data["MembershipFee"] = membershipFee.ToString();
data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0";
data.Data["ShowInList"] = showInList ? "1" : "0";
data.Data["AllowPublish"] = allowPublish ? "1" : "0";
data.Data["MaturePublish"] = maturePublish ? "1" : "0";
UUID roleID = UUID.Random();
data.Data["OwnerRoleID"] = roleID.ToString();
if (!m_Database.StoreGroup(data))
return UUID.Zero;
// Create Everyone role
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, UUID.Zero, "Everyone", "Everyone in the group", "Member of " + name, (ulong)DefaultEveryonePowers, true);
// Create Owner role
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, roleID, "Owners", "Owners of the group", "Owner of " + name, (ulong)OwnerPowers, true);
// Add founder to group
_AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, roleID);
return data.GroupID;
}
public void UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
GroupData data = m_Database.RetrieveGroup(groupID);
if (data == null)
return;
// Check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at updating group {1} denied because of lack of permission", RequestingAgentID, groupID);
return;
}
data.GroupID = groupID;
data.Data["Charter"] = charter;
data.Data["ShowInList"] = showInList ? "1" : "0";
data.Data["InsigniaID"] = insigniaID.ToString();
data.Data["MembershipFee"] = membershipFee.ToString();
data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0";
data.Data["AllowPublish"] = allowPublish ? "1" : "0";
data.Data["MaturePublish"] = maturePublish ? "1" : "0";
m_Database.StoreGroup(data);
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID)
{
GroupData data = m_Database.RetrieveGroup(GroupID);
return _GroupDataToRecord(data);
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, string GroupName)
{
GroupData data = m_Database.RetrieveGroup(GroupName);
return _GroupDataToRecord(data);
}
public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{
List<DirGroupsReplyData> groups = new List<DirGroupsReplyData>();
GroupData[] data = m_Database.RetrieveGroups(search);
if (data != null && data.Length > 0)
{
foreach (GroupData d in data)
{
// Don't list group proxies
if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty)
continue;
DirGroupsReplyData g = new DirGroupsReplyData();
g.groupID = d.GroupID;
if (d.Data.ContainsKey("Name"))
g.groupName = d.Data["Name"];
else
m_log.DebugFormat("[Groups]: Key Name not found");
g.members = m_Database.MemberCount(d.GroupID);
groups.Add(g);
}
}
return groups;
}
public List<ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)
{
List<ExtendedGroupMembersData> members = new List<ExtendedGroupMembersData>();
GroupData group = m_Database.RetrieveGroup(GroupID);
if (group == null)
return members;
// Unfortunately this doesn't quite work on legacy group data because of a bug
// that's also being fixed here on CreateGroup. The OwnerRoleID sent to the DB was wrong.
// See how to find the ownerRoleID a few lines below.
UUID ownerRoleID = new UUID(group.Data["OwnerRoleID"]);
RoleData[] roles = m_Database.RetrieveRoles(GroupID);
if (roles == null)
// something wrong with this group
return members;
List<RoleData> rolesList = new List<RoleData>(roles);
// Let's find the "real" ownerRoleID
RoleData ownerRole = rolesList.Find(r => r.Data["Powers"] == ((long)OwnerPowers).ToString());
if (ownerRole != null)
ownerRoleID = ownerRole.RoleID;
// Check visibility?
// When we don't want to check visibility, we pass it "all" as the requestingAgentID
bool checkVisibility = !RequestingAgentID.Equals(UUID.Zero.ToString());
if (checkVisibility)
{
// Is the requester a member of the group?
bool isInGroup = false;
if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null)
isInGroup = true;
if (!isInGroup) // reduce the roles to the visible ones
rolesList = rolesList.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0);
}
MembershipData[] datas = m_Database.RetrieveMembers(GroupID);
if (datas == null || (datas != null && datas.Length == 0))
return members;
// OK, we have everything we need
foreach (MembershipData d in datas)
{
RoleMembershipData[] rolememberships = m_Database.RetrieveMemberRoles(GroupID, d.PrincipalID);
List<RoleMembershipData> rolemembershipsList = new List<RoleMembershipData>(rolememberships);
ExtendedGroupMembersData m = new ExtendedGroupMembersData();
// What's this person's current role in the group?
UUID selectedRole = new UUID(d.Data["SelectedRoleID"]);
RoleData selected = rolesList.Find(r => r.RoleID == selectedRole);
if (selected != null)
{
m.Title = selected.Data["Title"];
m.AgentPowers = UInt64.Parse(selected.Data["Powers"]);
}
m.AgentID = d.PrincipalID;
m.AcceptNotices = d.Data["AcceptNotices"] == "1" ? true : false;
m.Contribution = Int32.Parse(d.Data["Contribution"]);
m.ListInProfile = d.Data["ListInProfile"] == "1" ? true : false;
GridUserData gud = m_GridUserService.Get(d.PrincipalID);
if (gud != null)
{
if (bool.Parse(gud.Data["Online"]))
{
m.OnlineStatus = @"Online";
}
else
{
int unixtime = int.Parse(gud.Data["Login"]);
// The viewer is very picky about how these strings are formed. Eg. it will crash on malformed dates!
m.OnlineStatus = (unixtime == 0) ? @"unknown" : Util.ToDateTime(unixtime).ToString("MM/dd/yyyy");
}
}
// Is this person an owner of the group?
m.IsOwner = (rolemembershipsList.Find(r => r.RoleID == ownerRoleID) != null) ? true : false;
members.Add(m);
}
return members;
}
public bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason)
{
reason = string.Empty;
// check that the requesting agent has permissions to add role
if (!HasPower(RequestingAgentID, groupID, GroupPowers.CreateRole))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at creating role in group {1} denied because of lack of permission", RequestingAgentID, groupID);
reason = "Insufficient permission to create role";
return false;
}
return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, true);
}
public bool UpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers)
{
// check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at changing role in group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, false);
}
public void RemoveGroupRole(string RequestingAgentID, UUID groupID, UUID roleID)
{
// check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.DeleteRole))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at deleting role from group {1} denied because of lack of permission", RequestingAgentID, groupID);
return;
}
// Can't delete Everyone and Owners roles
if (roleID == UUID.Zero)
{
m_log.DebugFormat("[Groups]: Attempt at deleting Everyone role from group {0} denied", groupID);
return;
}
GroupData group = m_Database.RetrieveGroup(groupID);
if (group == null)
{
m_log.DebugFormat("[Groups]: Attempt at deleting role from non-existing group {0}", groupID);
return;
}
if (roleID == new UUID(group.Data["OwnerRoleID"]))
{
m_log.DebugFormat("[Groups]: Attempt at deleting Owners role from group {0} denied", groupID);
return;
}
_RemoveGroupRole(groupID, roleID);
}
public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID GroupID)
{
// TODO: check perms
return _GetGroupRoles(GroupID);
}
public List<ExtendedGroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID GroupID)
{
// TODO: check perms
// Is the requester a member of the group?
bool isInGroup = false;
if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null)
isInGroup = true;
return _GetGroupRoleMembers(GroupID, isInGroup);
}
public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason)
{
reason = string.Empty;
_AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, token);
return true;
}
public bool RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// check perms
if (RequestingAgentID != AgentID && !HasPower(RequestingAgentID, GroupID, GroupPowers.Eject))
return false;
_RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
return true;
}
public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID)
{
// Check whether the invitee is already a member of the group
MembershipData m = m_Database.RetrieveMember(groupID, agentID);
if (m != null)
return false;
// Check permission to invite
if (!HasPower(RequestingAgentID, groupID, GroupPowers.Invite))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at inviting to group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
// Check whether there are pending invitations and delete them
InvitationData invite = m_Database.RetrieveInvitation(groupID, agentID);
if (invite != null)
m_Database.DeleteInvite(invite.InviteID);
invite = new InvitationData();
invite.InviteID = inviteID;
invite.PrincipalID = agentID;
invite.GroupID = groupID;
invite.RoleID = roleID;
invite.Data = new Dictionary<string, string>();
return m_Database.StoreInvitation(invite);
}
public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
InvitationData data = m_Database.RetrieveInvitation(inviteID);
if (data == null)
return null;
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.AgentID = data.PrincipalID;
inviteInfo.GroupID = data.GroupID;
inviteInfo.InviteID = data.InviteID;
inviteInfo.RoleID = data.RoleID;
return inviteInfo;
}
public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
m_Database.DeleteInvite(inviteID);
}
public bool AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
//if (!m_Database.CheckOwnerRole(RequestingAgentID, GroupID, RoleID))
// return;
// check permissions
bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited);
bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) | IsOwner(RequestingAgentID, GroupID);
if (!limited && !unlimited)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID);
return false;
}
// AssignMemberLimited means that the person can assign another person to the same roles that she has in the group
if (!unlimited && limited)
{
// check whether person's has this role
RoleMembershipData rolemembership = m_Database.RetrieveRoleMember(GroupID, RoleID, RequestingAgentID);
if (rolemembership == null)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of limited permission", RequestingAgentID, AgentID, RoleID);
return false;
}
}
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID);
return true;
}
public bool RemoveAgentFromGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
// Don't remove from Everyone role!
if (RoleID == UUID.Zero)
return false;
// check permissions
bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited);
bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) || IsOwner(RequestingAgentID, GroupID);
if (!limited && !unlimited)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at removing {1} from role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID);
return false;
}
// AssignMemberLimited means that the person can assign another person to the same roles that she has in the group
if (!unlimited && limited)
{
// check whether person's has this role
RoleMembershipData rolemembership = m_Database.RetrieveRoleMember(GroupID, RoleID, RequestingAgentID);
if (rolemembership == null)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at removing {1} from role {2} denied because of limited permission", RequestingAgentID, AgentID, RoleID);
return false;
}
}
RoleMembershipData rolemember = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID);
if (rolemember == null)
return false;
m_Database.DeleteRoleMember(rolemember);
// Find another role for this person
UUID newRoleID = UUID.Zero; // Everyone
RoleMembershipData[] rdata = m_Database.RetrieveMemberRoles(GroupID, AgentID);
if (rdata != null)
foreach (RoleMembershipData r in rdata)
{
if (r.RoleID != UUID.Zero)
{
newRoleID = r.RoleID;
break;
}
}
MembershipData member = m_Database.RetrieveMember(GroupID, AgentID);
if (member != null)
{
member.Data["SelectedRoleID"] = newRoleID.ToString();
m_Database.StoreMember(member);
}
return true;
}
public List<GroupRolesData> GetAgentGroupRoles(string RequestingAgentID, string AgentID, UUID GroupID)
{
List<GroupRolesData> roles = new List<GroupRolesData>();
// TODO: check permissions
RoleMembershipData[] data = m_Database.RetrieveMemberRoles(GroupID, AgentID);
if (data == null || (data != null && data.Length ==0))
return roles;
foreach (RoleMembershipData d in data)
{
RoleData rdata = m_Database.RetrieveRole(GroupID, d.RoleID);
if (rdata == null) // hippos
continue;
GroupRolesData r = new GroupRolesData();
r.Name = rdata.Data["Name"];
r.Powers = UInt64.Parse(rdata.Data["Powers"]);
r.RoleID = rdata.RoleID;
r.Title = rdata.Data["Title"];
roles.Add(r);
}
return roles;
}
public ExtendedGroupMembershipData SetAgentActiveGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// TODO: check perms
PrincipalData principal = new PrincipalData();
principal.PrincipalID = AgentID;
principal.ActiveGroupID = GroupID;
m_Database.StorePrincipal(principal);
return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID);
}
public ExtendedGroupMembershipData GetAgentActiveMembership(string RequestingAgentID, string AgentID)
{
// 1. get the principal data for the active group
PrincipalData principal = m_Database.RetrievePrincipal(AgentID);
if (principal == null)
return null;
return GetAgentGroupMembership(RequestingAgentID, AgentID, principal.ActiveGroupID);
}
public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID)
{
return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID, null);
}
private ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID, MembershipData membership)
{
// 2. get the active group
GroupData group = m_Database.RetrieveGroup(GroupID);
if (group == null)
return null;
// 3. get the membership info if we don't have it already
if (membership == null)
{
membership = m_Database.RetrieveMember(group.GroupID, AgentID);
if (membership == null)
return null;
}
// 4. get the active role
UUID activeRoleID = new UUID(membership.Data["SelectedRoleID"]);
RoleData role = m_Database.RetrieveRole(group.GroupID, activeRoleID);
ExtendedGroupMembershipData data = new ExtendedGroupMembershipData();
data.AcceptNotices = membership.Data["AcceptNotices"] == "1" ? true : false;
data.AccessToken = membership.Data["AccessToken"];
data.Active = true;
data.ActiveRole = activeRoleID;
data.AllowPublish = group.Data["AllowPublish"] == "1" ? true : false;
data.Charter = group.Data["Charter"];
data.Contribution = Int32.Parse(membership.Data["Contribution"]);
data.FounderID = new UUID(group.Data["FounderID"]);
data.GroupID = new UUID(group.GroupID);
data.GroupName = group.Data["Name"];
data.GroupPicture = new UUID(group.Data["InsigniaID"]);
if (role != null)
{
data.GroupPowers = UInt64.Parse(role.Data["Powers"]);
data.GroupTitle = role.Data["Title"];
}
data.ListInProfile = membership.Data["ListInProfile"] == "1" ? true : false;
data.MaturePublish = group.Data["MaturePublish"] == "1" ? true : false;
data.MembershipFee = Int32.Parse(group.Data["MembershipFee"]);
data.OpenEnrollment = group.Data["OpenEnrollment"] == "1" ? true : false;
data.ShowInList = group.Data["ShowInList"] == "1" ? true : false;
return data;
}
public List<GroupMembershipData> GetAgentGroupMemberships(string RequestingAgentID, string AgentID)
{
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
// 1. Get all the groups that this person is a member of
MembershipData[] mdata = m_Database.RetrieveMemberships(AgentID);
if (mdata == null || (mdata != null && mdata.Length == 0))
return memberships;
foreach (MembershipData d in mdata)
{
GroupMembershipData gmember = GetAgentGroupMembership(RequestingAgentID, AgentID, d.GroupID, d);
if (gmember != null)
{
memberships.Add(gmember);
//m_log.DebugFormat("[XXX]: Member of {0} as {1}", gmember.GroupName, gmember.GroupTitle);
//Util.PrintCallStack();
}
}
return memberships;
}
public void SetAgentActiveGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
MembershipData data = m_Database.RetrieveMember(GroupID, AgentID);
if (data == null)
return;
data.Data["SelectedRoleID"] = RoleID.ToString();
m_Database.StoreMember(data);
}
public void UpdateMembership(string RequestingAgentID, string AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
// TODO: check perms
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership == null)
return;
membership.Data["AcceptNotices"] = AcceptNotices ? "1" : "0";
membership.Data["ListInProfile"] = ListInProfile ? "1" : "0";
m_Database.StoreMember(membership);
}
public bool AddGroupNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
// Check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.SendNotices))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at sending notice to group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
return _AddNotice(groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, attOwnerID);
}
public GroupNoticeInfo GetGroupNotice(string RequestingAgentID, UUID noticeID)
{
NoticeData data = m_Database.RetrieveNotice(noticeID);
if (data == null)
return null;
return _NoticeDataToInfo(data);
}
public List<ExtendedGroupNoticeData> GetGroupNotices(string RequestingAgentID, UUID groupID)
{
NoticeData[] data = m_Database.RetrieveNotices(groupID);
List<ExtendedGroupNoticeData> infos = new List<ExtendedGroupNoticeData>();
if (data == null || (data != null && data.Length == 0))
return infos;
foreach (NoticeData d in data)
{
ExtendedGroupNoticeData info = _NoticeDataToData(d);
infos.Add(info);
}
return infos;
}
public void ResetAgentGroupChatSessions(string agentID)
{
}
public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID)
{
return false;
}
public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID)
{
return false;
}
public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID)
{
}
public void AgentInvitedToGroupChatSession(string agentID, UUID groupID)
{
}
#region Actions without permission checks
protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
_AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, string.Empty);
}
protected void _RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// 1. Delete membership
m_Database.DeleteMember(GroupID, AgentID);
// 2. Remove from rolememberships
m_Database.DeleteMemberAllRoles(GroupID, AgentID);
// 3. if it was active group, inactivate it
PrincipalData principal = m_Database.RetrievePrincipal(AgentID);
if (principal != null && principal.ActiveGroupID == GroupID)
{
principal.ActiveGroupID = UUID.Zero;
m_Database.StorePrincipal(principal);
}
}
protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string accessToken)
{
// Check if it's already there
MembershipData data = m_Database.RetrieveMember(GroupID, AgentID);
if (data != null)
return;
// Add the membership
data = new MembershipData();
data.PrincipalID = AgentID;
data.GroupID = GroupID;
data.Data = new Dictionary<string, string>();
data.Data["SelectedRoleID"] = RoleID.ToString();
data.Data["Contribution"] = "0";
data.Data["ListInProfile"] = "1";
data.Data["AcceptNotices"] = "1";
data.Data["AccessToken"] = accessToken;
m_Database.StoreMember(data);
// Add principal to everyone role
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, UUID.Zero);
// Add principal to role, if different from everyone role
if (RoleID != UUID.Zero)
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID);
// Make this the active group
PrincipalData pdata = new PrincipalData();
pdata.PrincipalID = AgentID;
pdata.ActiveGroupID = GroupID;
m_Database.StorePrincipal(pdata);
}
protected bool _AddOrUpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, bool add)
{
RoleData data = m_Database.RetrieveRole(groupID, roleID);
if (add && data != null) // it already exists, can't create
{
m_log.DebugFormat("[Groups]: Group {0} already exists. Can't create it again", groupID);
return false;
}
if (!add && data == null) // it deosn't exist, can't update
{
m_log.DebugFormat("[Groups]: Group {0} doesn't exist. Can't update it", groupID);
return false;
}
if (add)
data = new RoleData();
data.GroupID = groupID;
data.RoleID = roleID;
data.Data = new Dictionary<string, string>();
data.Data["Name"] = name;
data.Data["Description"] = description;
data.Data["Title"] = title;
data.Data["Powers"] = powers.ToString();
return m_Database.StoreRole(data);
}
protected void _RemoveGroupRole(UUID groupID, UUID roleID)
{
m_Database.DeleteRole(groupID, roleID);
}
protected void _AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
RoleMembershipData data = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID);
if (data != null)
return;
data = new RoleMembershipData();
data.GroupID = GroupID;
data.PrincipalID = AgentID;
data.RoleID = RoleID;
m_Database.StoreRoleMember(data);
// Make it the SelectedRoleID
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership == null)
{
m_log.DebugFormat("[Groups]: ({0}) No such member {0} in group {1}", AgentID, GroupID);
return;
}
membership.Data["SelectedRoleID"] = RoleID.ToString();
m_Database.StoreMember(membership);
}
protected List<GroupRolesData> _GetGroupRoles(UUID groupID)
{
List<GroupRolesData> roles = new List<GroupRolesData>();
RoleData[] data = m_Database.RetrieveRoles(groupID);
if (data == null || (data != null && data.Length == 0))
return roles;
foreach (RoleData d in data)
{
GroupRolesData r = new GroupRolesData();
r.Description = d.Data["Description"];
r.Members = m_Database.RoleMemberCount(groupID, d.RoleID);
r.Name = d.Data["Name"];
r.Powers = UInt64.Parse(d.Data["Powers"]);
r.RoleID = d.RoleID;
r.Title = d.Data["Title"];
roles.Add(r);
}
return roles;
}
protected List<ExtendedGroupRoleMembersData> _GetGroupRoleMembers(UUID GroupID, bool isInGroup)
{
List<ExtendedGroupRoleMembersData> rmembers = new List<ExtendedGroupRoleMembersData>();
RoleData[] rdata = new RoleData[0];
if (!isInGroup)
{
rdata = m_Database.RetrieveRoles(GroupID);
if (rdata == null || (rdata != null && rdata.Length == 0))
return rmembers;
}
List<RoleData> rlist = new List<RoleData>(rdata);
if (!isInGroup)
rlist = rlist.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0);
RoleMembershipData[] data = m_Database.RetrieveRolesMembers(GroupID);
if (data == null || (data != null && data.Length == 0))
return rmembers;
foreach (RoleMembershipData d in data)
{
if (!isInGroup)
{
RoleData rd = rlist.Find(_r => _r.RoleID == d.RoleID); // visible role
if (rd == null)
continue;
}
ExtendedGroupRoleMembersData r = new ExtendedGroupRoleMembersData();
r.MemberID = d.PrincipalID;
r.RoleID = d.RoleID;
rmembers.Add(r);
}
return rmembers;
}
protected bool _AddNotice(UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
NoticeData data = new NoticeData();
data.GroupID = groupID;
data.NoticeID = noticeID;
data.Data = new Dictionary<string, string>();
data.Data["FromName"] = fromName;
data.Data["Subject"] = subject;
data.Data["Message"] = message;
data.Data["HasAttachment"] = hasAttachment ? "1" : "0";
if (hasAttachment)
{
data.Data["AttachmentType"] = attType.ToString();
data.Data["AttachmentName"] = attName;
data.Data["AttachmentItemID"] = attItemID.ToString();
data.Data["AttachmentOwnerID"] = attOwnerID;
}
data.Data["TMStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
return m_Database.StoreNotice(data);
}
#endregion
#region structure translations
ExtendedGroupRecord _GroupDataToRecord(GroupData data)
{
if (data == null)
return null;
ExtendedGroupRecord rec = new ExtendedGroupRecord();
rec.AllowPublish = data.Data["AllowPublish"] == "1" ? true : false;
rec.Charter = data.Data["Charter"];
rec.FounderID = new UUID(data.Data["FounderID"]);
rec.GroupID = data.GroupID;
rec.GroupName = data.Data["Name"];
rec.GroupPicture = new UUID(data.Data["InsigniaID"]);
rec.MaturePublish = data.Data["MaturePublish"] == "1" ? true : false;
rec.MembershipFee = Int32.Parse(data.Data["MembershipFee"]);
rec.OpenEnrollment = data.Data["OpenEnrollment"] == "1" ? true : false;
rec.OwnerRoleID = new UUID(data.Data["OwnerRoleID"]);
rec.ShowInList = data.Data["ShowInList"] == "1" ? true : false;
rec.ServiceLocation = data.Data["Location"];
rec.MemberCount = m_Database.MemberCount(data.GroupID);
rec.RoleCount = m_Database.RoleCount(data.GroupID);
return rec;
}
GroupNoticeInfo _NoticeDataToInfo(NoticeData data)
{
GroupNoticeInfo notice = new GroupNoticeInfo();
notice.GroupID = data.GroupID;
notice.Message = data.Data["Message"];
notice.noticeData = _NoticeDataToData(data);
return notice;
}
ExtendedGroupNoticeData _NoticeDataToData(NoticeData data)
{
ExtendedGroupNoticeData notice = new ExtendedGroupNoticeData();
notice.FromName = data.Data["FromName"];
notice.NoticeID = data.NoticeID;
notice.Subject = data.Data["Subject"];
notice.Timestamp = uint.Parse((string)data.Data["TMStamp"]);
notice.HasAttachment = data.Data["HasAttachment"] == "1" ? true : false;
if (notice.HasAttachment)
{
notice.AttachmentName = data.Data["AttachmentName"];
notice.AttachmentItemID = new UUID(data.Data["AttachmentItemID"].ToString());
notice.AttachmentType = byte.Parse(data.Data["AttachmentType"].ToString());
notice.AttachmentOwnerID = data.Data["AttachmentOwnerID"].ToString();
}
return notice;
}
#endregion
#region permissions
private bool HasPower(string agentID, UUID groupID, GroupPowers power)
{
RoleMembershipData[] rmembership = m_Database.RetrieveMemberRoles(groupID, agentID);
if (rmembership == null || (rmembership != null && rmembership.Length == 0))
return false;
foreach (RoleMembershipData rdata in rmembership)
{
RoleData role = m_Database.RetrieveRole(groupID, rdata.RoleID);
if ( (UInt64.Parse(role.Data["Powers"]) & (ulong)power) != 0 )
return true;
}
return false;
}
private bool IsOwner(string agentID, UUID groupID)
{
GroupData group = m_Database.RetrieveGroup(groupID);
if (group == null)
return false;
RoleMembershipData rmembership = m_Database.RetrieveRoleMember(groupID, new UUID(group.Data["OwnerRoleID"]), agentID);
if (rmembership == null)
return false;
return true;
}
#endregion
}
}
| |
// jQueryDataHttpRequest.cs
// Script#/Libraries/jQuery/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Xml;
namespace jQueryApi {
/// <summary>
/// Represents an XMLHttpRequest object as a deferred object.
/// </summary>
[Imported]
[IgnoreNamespace]
[ScriptName("Object")]
public sealed class jQueryDataHttpRequest<TData> : IDeferred<TData> {
private jQueryDataHttpRequest() {
}
/// <summary>
/// The ready state property of the XmlHttpRequest object.
/// </summary>
[IntrinsicProperty]
public ReadyState ReadyState {
get {
return default(ReadyState);
}
}
/// <summary>
/// The XML document for an XML response.
/// </summary>
[IntrinsicProperty]
[ScriptName("responseXML")]
public XmlDocument ResponseXml {
get {
return null;
}
}
/// <summary>
/// The text of the response.
/// </summary>
[IntrinsicProperty]
public string ResponseText {
get {
return null;
}
}
/// <summary>
/// The status code associated with the response.
/// </summary>
[IntrinsicProperty]
public int Status {
get {
return 0;
}
}
/// <summary>
/// The status text of the response.
/// </summary>
[IntrinsicProperty]
public string StatusText {
get {
return null;
}
}
/// <summary>
/// Aborts the request.
/// </summary>
public void Abort() {
}
/// <summary>
/// Add handlers to be called when the request completes or fails.
/// </summary>
/// <param name="callbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Always(params Action[] callbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request completes or fails.
/// </summary>
/// <param name="callbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Always(params Action<TData>[] callbacks) {
return null;
}
/// <summary>
/// Adds a callback to handle completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Complete(AjaxCompletedCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is successfully completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Done(params Action[] doneCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is successfully completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Done(params Action<TData>[] doneCallbacks) {
return null;
}
/// <summary>
/// Adds a callback to handle an error completing the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Error(AjaxErrorCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request errors. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="failCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Fail(params Action[] failCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request errors. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="failCallbacks">The callbacks to invoke (in order).</param>
/// <returns>The current request object.</returns>
[ExpandParams]
public jQueryDataHttpRequest<TData> Fail(params Action<TData>[] failCallbacks) {
return null;
}
/// <summary>
/// Gets the response headers associated with the request.
/// </summary>
/// <returns>The response headers.</returns>
public string GetAllResponseHeaders() {
return null;
}
/// <summary>
/// Gets a specific response header associated with the request.
/// </summary>
/// <param name="name">The name of the response header.</param>
/// <returns>The response header value.</returns>
public string GetResponseHeader(string name) {
return null;
}
/// <summary>
/// Sets the mime type on the request.
/// </summary>
/// <param name="type">The mime type to use.</param>
public void OverrideMimeType(string type) {
}
/// <summary>
/// Filters or chains the result of the request.
/// </summary>
/// <param name="successFilter">The filter to invoke when the request successfully completes.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) {
return null;
}
/// <summary>
/// Filters or chains the result of the request.
/// </summary>
/// <param name="successFilter">The filter to invoke when the request successfully completes.</param>
/// <param name="failFilter">The filter to invoke when the request fails.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) {
return null;
}
public jQueryDataHttpRequest<TTargetData> Pipe<TTargetData>(Func<TData, jQueryDataHttpRequest<TTargetData>> successChain) {
return null;
}
/// <summary>
/// Sets a request header value.
/// </summary>
/// <param name="name">The name of the request header.</param>
/// <param name="value">The value of the request header.</param>
public void SetRequestHeader(string name, string value) {
}
/// <summary>
/// Adds a callback to handle a successful completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Success(AjaxCallback<TData> callback) {
return null;
}
/// <summary>
/// Adds a callback to handle a successful completion of the request.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Success(AjaxRequestCallback<TData> callback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallback">The callback to invoke when the request completes successfully.</param>
/// <param name="failCallback">The callback to invoke when the request completes with an error.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Then(Action doneCallback, Action failCallback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallback">The callback to invoke when the request completes successfully.</param>
/// <param name="failCallback">The callback to invoke when the request completes with an error.</param>
/// <returns>The current request object.</returns>
public jQueryDataHttpRequest<TData> Then(Action<TData> doneCallback, Action<TData> failCallback) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param>
/// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param>
/// <returns>The current deferred object.</returns>
public jQueryDataHttpRequest<TData> Then(Action[] doneCallbacks, Action[] failCallbacks) {
return null;
}
/// <summary>
/// Add handlers to be called when the request is completed. If the
/// request is already completed, the handlers are still invoked.
/// </summary>
/// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param>
/// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param>
/// <returns>The current deferred object.</returns>
public jQueryDataHttpRequest<TData> Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) {
return null;
}
#region Implementation of IDeferred
void IPromise.Then(Delegate fulfilledHandler) {
}
void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler) {
}
void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler, Delegate progressHandler) {
}
IDeferred<TData> IDeferred<TData>.Always(params Action[] callbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Always(params Action<TData>[] callbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Done(params Action[] doneCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Done(params Action<TData>[] doneCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Fail(params Action[] failCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Fail(params Action<TData>[] failCallbacks) {
return null;
}
bool IDeferred<TData>.IsRejected() {
return false;
}
bool IDeferred<TData>.IsResolved() {
return false;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(Func<TData, IDeferred<TTargetData>> successFilter) {
return null;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter) {
return null;
}
IDeferred<TTargetData> IDeferred<TData>.Pipe<TTargetData>(jQueryDeferredFilter<TTargetData, TData> successFilter, jQueryDeferredFilter<TTargetData> failFilter) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action doneCallback, Action failCallback) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action<TData> doneCallback, Action<TData> failCallback) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action[] doneCallbacks, Action[] failCallbacks) {
return null;
}
IDeferred<TData> IDeferred<TData>.Then(Action<TData>[] doneCallbacks, Action<TData>[] failCallbacks) {
return null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace System.Xml
{
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable"]/*' />
/// <devdoc>
/// <para>
/// XmlNameTable implemented as a simple hash table.
/// </para>
/// </devdoc>
public class NameTable : XmlNameTable
{
//
// Private types
//
private class Entry
{
internal string str;
internal int hashCode;
internal Entry next;
internal Entry(string str, int hashCode, Entry next)
{
this.str = str;
this.hashCode = hashCode;
this.next = next;
}
}
//
// Fields
//
private Entry[] _entries;
private int _count;
private int _mask;
private int _hashCodeRandomizer;
//
// Constructor
//
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable.NameTable"]/*' />
/// <devdoc>
/// Public constructor.
/// </devdoc>
public NameTable()
{
_mask = 31;
_entries = new Entry[_mask + 1];
_hashCodeRandomizer = Environment.TickCount;
}
//
// XmlNameTable public methods
//
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable.Add"]/*' />
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(string key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
int len = key.Length;
if (len == 0)
{
return string.Empty;
}
int hashCode = len + _hashCodeRandomizer;
// use key.Length to eliminate the rangecheck
for (int i = 0; i < key.Length; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(key))
{
return e.str;
}
}
return AddEntry(key, hashCode);
}
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable.Add1"]/*' />
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
int hashCode = len + _hashCodeRandomizer;
hashCode += (hashCode << 7) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start + len;
for (int i = start + 1; i < end; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return AddEntry(new string(key, start, len), hashCode);
}
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable.Get"]/*' />
/// <devdoc>
/// Find the matching string in the NameTable.
/// </devdoc>
public override string Get(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length == 0)
{
return string.Empty;
}
int len = value.Length + _hashCodeRandomizer;
int hashCode = len;
// use value.Length to eliminate the rangecheck
for (int i = 0; i < value.Length; i++)
{
hashCode += (hashCode << 7) ^ value[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(value))
{
return e.str;
}
}
return null;
}
/// <include file='doc\NameTable.uex' path='docs/doc[@for="NameTable.Get1"]/*' />
/// <devdoc>
/// Find the matching string atom given a range of
/// characters.
/// </devdoc>
public override string Get(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
int hashCode = len + _hashCodeRandomizer;
hashCode += (hashCode << 7) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start + len;
for (int i = start + 1; i < end; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return null;
}
//
// Private methods
//
private string AddEntry(string str, int hashCode)
{
int index = hashCode & _mask;
Entry e = new Entry(str, hashCode, _entries[index]);
_entries[index] = e;
if (_count++ == _mask)
{
Grow();
}
return e.str;
}
private void Grow()
{
int newMask = _mask * 2 + 1;
Entry[] oldEntries = _entries;
Entry[] newEntries = new Entry[newMask + 1];
// use oldEntries.Length to eliminate the rangecheck
for (int i = 0; i < oldEntries.Length; i++)
{
Entry e = oldEntries[i];
while (e != null)
{
int newIndex = e.hashCode & newMask;
Entry tmp = e.next;
e.next = newEntries[newIndex];
newEntries[newIndex] = e;
e = tmp;
}
}
_entries = newEntries;
_mask = newMask;
}
private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
{
if (str1.Length != str2Length)
{
return false;
}
// use array.Length to eliminate the rangecheck
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] != str2[str2Start + i])
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Omnius.Collections
{
public class SmallList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
{
private List<T> _list;
private int? _capacity;
public SmallList()
{
_list = new List<T>();
}
public SmallList(int capacity)
{
_list = new List<T>();
_capacity = capacity;
}
public SmallList(IEnumerable<T> collection)
{
_list = new List<T>();
foreach (var item in collection)
{
this.Add(item);
}
}
protected virtual bool Filter(T item)
{
return false;
}
public T[] ToArray()
{
var array = new T[_list.Count];
_list.CopyTo(array, 0);
return array;
}
public int Capacity
{
get
{
return _capacity ?? -1;
}
set
{
_capacity = value;
}
}
public int Count
{
get
{
return _list.Count;
}
}
public T this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
public void Add(T item)
{
if (_capacity != null && _list.Count + 1 > _capacity.Value) throw new OverflowException();
if (this.Filter(item)) return;
_list.Capacity = _list.Count + 1;
_list.Add(item);
}
public void AddRange(IEnumerable<T> collection)
{
foreach (var item in collection)
{
this.Add(item);
}
}
public void Clear()
{
_list.Clear();
}
public bool Contains(T item)
{
return _list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public SmallList<T> GetRange(int index, int count)
{
return new SmallList<T>(_list.GetRange(index, count));
}
public void Sort(IComparer<T> comparer)
{
_list.Sort(comparer);
}
public void Sort(int index, int count, IComparer<T> comparer)
{
_list.Sort(index, count, comparer);
}
public void Sort(Comparison<T> comparerison)
{
_list.Sort(comparerison);
}
public void Sort()
{
_list.Sort();
}
public void Reverse()
{
_list.Reverse();
}
public void Reverse(int index, int count)
{
_list.Reverse(index, count);
}
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
_list.Insert(index, item);
}
public void InsertRange(int index, IEnumerable<T> collection)
{
_list.InsertRange(index, collection);
}
public bool Remove(T item)
{
return _list.Remove(item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public void RemoveRange(int index, int count)
{
_list.RemoveRange(index, count);
}
public int RemoveAll(Predicate<T> match)
{
return _list.RemoveAll(match);
}
public void TrimExcess()
{
_list.TrimExcess();
}
bool ICollection<T>.IsReadOnly
{
get
{
return false;
}
}
bool IList.IsFixedSize
{
get
{
return false;
}
}
bool IList.IsReadOnly
{
get
{
return false;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (T)value;
}
}
int IList.Add(object item)
{
this.Add((T)item);
return _list.Count - 1;
}
bool IList.Contains(object item)
{
return this.Contains((T)item);
}
int IList.IndexOf(object item)
{
return this.IndexOf((T)item);
}
void IList.Insert(int index, object item)
{
this.Insert(index, (T)item);
}
void IList.Remove(object item)
{
this.Remove((T)item);
}
bool ICollection.IsSynchronized
{
get
{
return true;
}
}
object ICollection.SyncRoot
{
get
{
return ((ICollection)_list).SyncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_list).CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in _list)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| |
// GZipStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// 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 (in emacs):
// Time-stamp: <2010-January-09 12:04:28>
//
// ------------------------------------------------------------------
//
// This module defines the GZipStream class, which can be used as a replacement for
// the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
// completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
// GZip header.
//
// ------------------------------------------------------------------
using System;
using System.Buffers.Binary;
using System.IO;
using System.Text;
namespace SharpCompress.Compressors.Deflate
{
public class GZipStream : Stream
{
internal static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private string? _comment;
private string? _fileName;
private DateTime? _lastModified;
internal ZlibBaseStream BaseStream;
private bool _disposed;
private bool _firstReadDone;
private int _headerByteCount;
private readonly Encoding _encoding;
public GZipStream(Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, Encoding.UTF8)
{
}
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, Encoding.UTF8)
{
}
public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, Encoding encoding)
{
BaseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, encoding);
_encoding = encoding;
}
#region Zlib properties
public virtual FlushType FlushMode
{
get => (BaseStream._flushMode);
set
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
BaseStream._flushMode = value;
}
}
public int BufferSize
{
get => BaseStream._bufferSize;
set
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
if (BaseStream._workingBuffer != null)
{
throw new ZlibException("The working buffer is already set.");
}
if (value < ZlibConstants.WorkingBufferSizeMin)
{
throw new ZlibException(
String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value,
ZlibConstants.WorkingBufferSizeMin));
}
BaseStream._bufferSize = value;
}
}
internal virtual long TotalIn => BaseStream._z.TotalBytesIn;
internal virtual long TotalOut => BaseStream._z.TotalBytesOut;
#endregion
#region Stream methods
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
return BaseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek => false;
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
return BaseStream._stream.CanWrite;
}
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length => throw new NotSupportedException();
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
{
return BaseStream._z.TotalBytesOut + _headerByteCount;
}
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
{
return BaseStream._z.TotalBytesIn + BaseStream._gzipHeaderByteCount;
}
return 0;
}
set => throw new NotSupportedException();
}
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// This may or may not result in a <c>Close()</c> call on the captive stream.
/// </remarks>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (BaseStream != null))
{
BaseStream.Dispose();
Crc32 = BaseStream.Crc32;
}
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
BaseStream.Flush();
}
/// <summary>
/// Read and decompress data from the source stream.
/// </summary>
///
/// <remarks>
/// With a <c>GZipStream</c>, decompression is done through reading.
/// </remarks>
///
/// <example>
/// <code>
/// byte[] working = new byte[WORKING_BUFFER_SIZE];
/// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
/// {
/// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
/// {
/// using (var output = System.IO.File.Create(_DecompressedFile))
/// {
/// int n;
/// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
/// {
/// output.Write(working, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
/// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</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)
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
int n = BaseStream.Read(buffer, offset, count);
// Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
// Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
if (!_firstReadDone)
{
_firstReadDone = true;
FileName = BaseStream._GzipFileName;
Comment = BaseStream._GzipComment;
LastModified = BaseStream._GzipMtime;
}
return n;
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">irrelevant; it will always throw!</param>
/// <param name="origin">irrelevant; it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">irrelevant; this method will always throw!</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
/// <para>
/// If you wish to use the <c>GZipStream</c> to compress data while writing,
/// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a
/// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>,
/// providing uncompressed data as input. The data sent to the output stream
/// will be the compressed form of the data written.
/// </para>
///
/// <para>
/// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not
/// both. Writing implies compression. Reading implies decompression.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed)
{
throw new ObjectDisposedException("GZipStream");
}
if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Undefined)
{
//Console.WriteLine("GZipStream: First write");
if (BaseStream._wantCompress)
{
// first write in compression, therefore, emit the GZIP header
_headerByteCount = EmitHeader();
}
else
{
throw new InvalidOperationException();
}
}
BaseStream.Write(buffer, offset, count);
}
#endregion Stream methods
public string? Comment
{
get => _comment;
set
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(GZipStream));
}
_comment = value;
}
}
public DateTime? LastModified
{
get => _lastModified;
set
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(GZipStream));
}
_lastModified = value;
}
}
public string? FileName
{
get => _fileName;
set
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(GZipStream));
}
_fileName = value;
if (_fileName is null)
{
return;
}
if (_fileName.Contains('/'))
{
_fileName = _fileName.Replace('/', '\\');
}
if (_fileName.EndsWith('\\'))
{
throw new InvalidOperationException("Illegal filename");
}
if (_fileName.Contains('\\'))
{
// trim any leading path
_fileName = Path.GetFileName(_fileName);
}
}
}
public int Crc32 { get; private set; }
private int EmitHeader()
{
byte[]? commentBytes = (Comment is null) ? null
: _encoding.GetBytes(Comment);
byte[]? filenameBytes = (FileName is null) ? null
: _encoding.GetBytes(FileName);
int cbLength = commentBytes?.Length + 1 ?? 0;
int fnLength = filenameBytes?.Length + 1 ?? 0;
int bufferLength = 10 + cbLength + fnLength;
var header = new byte[bufferLength];
int i = 0;
// ID
header[i++] = 0x1F;
header[i++] = 0x8B;
// compression method
header[i++] = 8;
byte flag = 0;
if (Comment != null)
{
flag ^= 0x10;
}
if (FileName != null)
{
flag ^= 0x8;
}
// flag
header[i++] = flag;
// mtime
if (LastModified is null)
{
LastModified = DateTime.Now;
}
TimeSpan delta = LastModified.Value - UNIX_EPOCH;
var timet = (int)delta.TotalSeconds;
BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(i), timet);
i += 4;
// xflg
header[i++] = 0; // this field is totally useless
// OS
header[i++] = 0xFF; // 0xFF == unspecified
// extra field length - only if FEXTRA is set, which it is not.
//header[i++]= 0;
//header[i++]= 0;
// filename
if (fnLength != 0)
{
Array.Copy(filenameBytes!, 0, header, i, fnLength - 1);
i += fnLength - 1;
header[i++] = 0; // terminate
}
// comment
if (cbLength != 0)
{
Array.Copy(commentBytes!, 0, header, i, cbLength - 1);
i += cbLength - 1;
header[i++] = 0; // terminate
}
BaseStream._stream.Write(header, 0, header.Length);
return header.Length; // bytes written
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
public class OutgoingMethodInterceptionGrain : IOutgoingMethodInterceptionGrain
{
public async Task<Dictionary<string, object>> EchoViaOtherGrain(IMethodInterceptionGrain otherGrain, string message)
{
return new Dictionary<string, object>
{
["result"] = await otherGrain.Echo(message)
};
}
public Task<string> ThrowIfGreaterThanZero(int value)
{
if (value > 0)
{
throw new ArgumentOutOfRangeException($"{value} is greater than zero!");
}
return Task.FromResult("Thanks for nothing");
}
}
public class MethodInterceptionGrain : IMethodInterceptionGrain, IIncomingGrainCallFilter
{
public Task<string> One()
{
throw new InvalidOperationException("Not allowed to actually invoke this method!");
}
[MessWithResult]
public Task<string> Echo(string someArg) => Task.FromResult(someArg);
public Task<string> NotIntercepted() => Task.FromResult("not intercepted");
public Task<string> SayHello() => Task.FromResult("Hello");
public Task<string> Throw()
{
throw new MyDomainSpecificException("Oi!");
}
public Task FilterThrows() => Task.CompletedTask;
public Task<string> IncorrectResultType() => Task.FromResult("hop scotch");
async Task IIncomingGrainCallFilter.Invoke(IIncomingGrainCallContext context)
{
var methodInfo = context.ImplementationMethod;
if (methodInfo.Name == nameof(One) && methodInfo.GetParameters().Length == 0)
{
// Short-circuit the request and return to the caller without actually invoking the grain method.
context.Result = "intercepted one with no args";
return;
}
if (methodInfo.Name == nameof(IncorrectResultType))
{
// This method has a string return type, but we are setting the result to a Guid.
// This should result in an invalid cast exception.
context.Result = Guid.NewGuid();
return;
}
if (methodInfo.Name == nameof(FilterThrows))
{
throw new MyDomainSpecificException("Filter THROW!");
}
// Invoke the request.
try
{
await context.Invoke();
}
catch (MyDomainSpecificException e)
{
context.Result = "EXCEPTION! " + e.Message;
return;
}
// To prove that the MethodInfo is from the implementation and not the interface,
// we check for this attribute which is only present on the implementation. This could be
// done in a simpler fashion, but this demonstrates a potential usage scenario.
var shouldMessWithResult = methodInfo.GetCustomAttribute<MessWithResultAttribute>();
var resultString = context.Result as string;
if (shouldMessWithResult != null && resultString != null)
{
context.Result = string.Concat(resultString.Reverse());
}
}
[Serializable]
[GenerateSerializer]
public class MyDomainSpecificException : Exception
{
public MyDomainSpecificException()
{
}
public MyDomainSpecificException(string message) : base(message)
{
}
protected MyDomainSpecificException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
[AttributeUsage(AttributeTargets.Method)]
public class MessWithResultAttribute : Attribute
{
}
}
public class GenericMethodInterceptionGrain<T> : IGenericMethodInterceptionGrain<T>, IIncomingGrainCallFilter
{
public Task<string> SayHello() => Task.FromResult("Hello");
public Task<string> GetInputAsString(T input) => Task.FromResult(input.ToString());
public async Task Invoke(IIncomingGrainCallContext context)
{
if (context.ImplementationMethod.Name == nameof(GetInputAsString))
{
context.Result = $"Hah! You wanted {context.Arguments[0]}, but you got me!";
return;
}
await context.Invoke();
}
}
public class TrickyInterceptionGrain : ITrickyMethodInterceptionGrain, IIncomingGrainCallFilter
{
public Task<string> SayHello() => Task.FromResult("Hello");
public Task<string> GetInputAsString(string input) => Task.FromResult(input);
public Task<string> GetInputAsString(bool input) => Task.FromResult(input.ToString(CultureInfo.InvariantCulture));
public Task<int> GetBestNumber() => Task.FromResult(38);
public async Task Invoke(IIncomingGrainCallContext context)
{
if (context.ImplementationMethod.Name == nameof(GetInputAsString))
{
context.Result = $"Hah! You wanted {context.Arguments[0]}, but you got me!";
return;
}
await context.Invoke();
}
}
public class GrainCallFilterTestGrain : IGrainCallFilterTestGrain, IIncomingGrainCallFilter
{
private const string Key = GrainCallFilterTestConstants.Key;
public Task<string> ThrowIfGreaterThanZero(int value)
{
if (value > 0)
{
throw new ArgumentOutOfRangeException($"{value} is greater than zero!");
}
return Task.FromResult("Thanks for nothing");
}
public Task<string> GetRequestContext() => Task.FromResult((string)RequestContext.Get(Key) + "4");
public async Task Invoke(IIncomingGrainCallContext ctx)
{
var attemptsRemaining = 2;
while (attemptsRemaining > 0)
{
try
{
var interfaceMethod = ctx.InterfaceMethod ?? throw new ArgumentException("InterfaceMethod is null!");
var implementationMethod = ctx.ImplementationMethod ?? throw new ArgumentException("ImplementationMethod is null!");
if (!string.Equals(implementationMethod.Name, interfaceMethod.Name))
{
throw new ArgumentException("InterfaceMethod.Name != ImplementationMethod.Name");
}
if (RequestContext.Get(Key) is string value) RequestContext.Set(Key, value + '3');
await ctx.Invoke();
return;
}
catch (ArgumentOutOfRangeException) when (attemptsRemaining > 1)
{
if (string.Equals(ctx.ImplementationMethod?.Name, nameof(ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value)
{
ctx.Arguments[0] = (object)(value - 1);
}
--attemptsRemaining;
}
}
}
public Task<int> SumSet(HashSet<int> numbers)
{
return Task.FromResult(numbers.Sum());
}
}
public class CaterpillarGrain : ICaterpillarGrain, IIncomingGrainCallFilter
{
Task IIncomingGrainCallFilter.Invoke(IIncomingGrainCallContext ctx)
{
if (ctx.InterfaceMethod is null) throw new Exception("InterfaceMethod is null");
if (!ctx.InterfaceMethod.DeclaringType.IsInterface) throw new Exception("InterfaceMethod is not an interface method");
if (ctx.ImplementationMethod is null) throw new Exception("ImplementationMethod is null");
if (ctx.ImplementationMethod.DeclaringType.IsInterface) throw new Exception("ImplementationMethod is an interface method");
if (RequestContext.Get("tag") is string tag)
{
var ifaceTag = ctx.InterfaceMethod.GetCustomAttribute<TestMethodTagAttribute>()?.Tag;
var implTag = ctx.ImplementationMethod.GetCustomAttribute<TestMethodTagAttribute>()?.Tag;
if (!string.Equals(tag, ifaceTag, StringComparison.Ordinal)
|| !string.Equals(tag, implTag, StringComparison.Ordinal))
{
throw new Exception($"Expected method tags to be equal to request context tag: RequestContext: {tag} Interface: {ifaceTag} Implementation: {implTag}");
}
}
return ctx.Invoke();
}
[TestMethodTag("hungry-eat")]
public Task Eat(Apple food) => Task.CompletedTask;
[TestMethodTag("omnivore-eat")]
Task IOmnivoreGrain.Eat<T>(T food) => Task.CompletedTask;
[TestMethodTag("caterpillar-eat")]
public Task Eat<T>(T food) => Task.CompletedTask;
[TestMethodTag("hungry-eatwith")]
public Task EatWith<U>(Apple food, U condiment) => Task.CompletedTask;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.Common
{
internal static partial class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
internal static Task<T> CreatedTaskWithCancellation<T>() => Task.FromCanceled<T>(new CancellationToken(true));
// this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
static partial void TraceException(string trace, Exception e)
{
Debug.Assert(e != null, "TraceException: null Exception");
if (e != null)
{
DataCommonEventSource.Log.Trace(trace, e);
}
}
internal static void TraceExceptionForCapture(Exception e)
{
Debug.Assert(IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e);
}
internal static DataException Data(string message)
{
DataException e = new DataException(message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static void CheckArgumentLength(string value, string parameterName)
{
CheckArgumentNull(value, parameterName);
if (0 == value.Length)
{
throw Argument(SR.Format(SR.ADP_EmptyString, parameterName));
}
}
internal static void CheckArgumentLength(Array value, string parameterName)
{
CheckArgumentNull(value, parameterName);
if (0 == value.Length)
{
throw Argument(SR.Format(SR.ADP_EmptyArray, parameterName));
}
}
// Invalid Enumeration
internal static ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value)
{
#if DEBUG
switch (value)
{
case AcceptRejectRule.None:
case AcceptRejectRule.Cascade:
Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(AcceptRejectRule), (int)value);
}
// DbCommandBuilder.CatalogLocation
internal static ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value)
{
#if DEBUG
switch (value)
{
case CatalogLocation.Start:
case CatalogLocation.End:
Debug.Assert(false, "valid CatalogLocation " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CatalogLocation), (int)value);
}
internal static ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value)
{
#if DEBUG
switch (value)
{
case ConflictOption.CompareAllSearchableValues:
case ConflictOption.CompareRowVersion:
case ConflictOption.OverwriteChanges:
Debug.Assert(false, "valid ConflictOption " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ConflictOption), (int)value);
}
// IDataAdapter.Update
internal static ArgumentOutOfRangeException InvalidDataRowState(DataRowState value)
{
#if DEBUG
switch (value)
{
case DataRowState.Detached:
case DataRowState.Unchanged:
case DataRowState.Added:
case DataRowState.Deleted:
case DataRowState.Modified:
Debug.Assert(false, "valid DataRowState " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowState), (int)value);
}
// KeyRestrictionBehavior
internal static ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value)
{
#if DEBUG
switch (value)
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value);
}
// IDataAdapter.FillLoadOption
internal static ArgumentOutOfRangeException InvalidLoadOption(LoadOption value)
{
#if DEBUG
switch (value)
{
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
Debug.Assert(false, "valid LoadOption " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(LoadOption), (int)value);
}
// IDataAdapter.MissingMappingAction
internal static ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value)
{
#if DEBUG
switch (value)
{
case MissingMappingAction.Passthrough:
case MissingMappingAction.Ignore:
case MissingMappingAction.Error:
Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(MissingMappingAction), (int)value);
}
// IDataAdapter.MissingSchemaAction
internal static ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value)
{
#if DEBUG
switch (value)
{
case MissingSchemaAction.Add:
case MissingSchemaAction.Ignore:
case MissingSchemaAction.Error:
case MissingSchemaAction.AddWithKey:
Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(MissingSchemaAction), (int)value);
}
internal static ArgumentOutOfRangeException InvalidRule(Rule value)
{
#if DEBUG
switch (value)
{
case Rule.None:
case Rule.Cascade:
case Rule.SetNull:
case Rule.SetDefault:
Debug.Assert(false, "valid Rule " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(Rule), (int)value);
}
// IDataAdapter.FillSchema
internal static ArgumentOutOfRangeException InvalidSchemaType(SchemaType value)
{
#if DEBUG
switch (value)
{
case SchemaType.Source:
case SchemaType.Mapped:
Debug.Assert(false, "valid SchemaType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(SchemaType), (int)value);
}
// RowUpdatingEventArgs.StatementType
internal static ArgumentOutOfRangeException InvalidStatementType(StatementType value)
{
#if DEBUG
switch (value)
{
case StatementType.Select:
case StatementType.Insert:
case StatementType.Update:
case StatementType.Delete:
case StatementType.Batch:
Debug.Assert(false, "valid StatementType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(StatementType), (int)value);
}
// RowUpdatingEventArgs.UpdateStatus
internal static ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value)
{
#if DEBUG
switch (value)
{
case UpdateStatus.Continue:
case UpdateStatus.ErrorsOccurred:
case UpdateStatus.SkipAllRemainingRows:
case UpdateStatus.SkipCurrentRow:
Debug.Assert(false, "valid UpdateStatus " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateStatus), (int)value);
}
internal static ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method)
{
return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException InvalidKeyname(string parameterName)
{
return Argument(SR.ADP_InvalidKey, parameterName);
}
internal static ArgumentException InvalidValue(string parameterName)
{
return Argument(SR.ADP_InvalidValue, parameterName);
}
//
// DataAccess
//
internal static Exception WrongType(Type got, Type expected)
{
return Argument(SR.Format(SR.SQL_WrongType, got.ToString(), expected.ToString()));
}
//
// Generic Data Provider Collection
//
internal static Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue)
{
return Argument(SR.Format(SR.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
}
// IDbDataAdapter.Fill(Schema)
internal static InvalidOperationException MissingSelectCommand(string method)
{
return Provider(SR.Format(SR.ADP_MissingSelectCommand, method));
}
//
// AdapterMappingException
//
private static InvalidOperationException DataMapping(string error)
{
return InvalidOperation(error);
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn)
{
return DataMapping(SR.Format(SR.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column)
{
return DataMapping(SR.Format(SR.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn)
{
if (string.IsNullOrEmpty(tableName))
{
return InvalidOperation(SR.Format(SR.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
}
return DataMapping(SR.Format(SR.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
}
// DataColumnMappingCollection.GetColumnMappingBySchemaAction
internal static InvalidOperationException MissingColumnMapping(string srcColumn)
{
return DataMapping(SR.Format(SR.ADP_MissingColumnMapping, srcColumn));
}
// DataTableMapping.GetDataTableBySchemaAction
internal static InvalidOperationException MissingTableSchema(string cacheTable, string srcTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableSchema, cacheTable, srcTable));
}
// DataTableMappingCollection.GetTableMappingBySchemaAction
internal static InvalidOperationException MissingTableMapping(string srcTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableMapping, srcTable));
}
// DbDataAdapter.Update
internal static InvalidOperationException MissingTableMappingDestination(string dstTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableMappingDestination, dstTable));
}
//
// DataColumnMappingCollection, DataAccess
//
internal static Exception InvalidSourceColumn(string parameter)
{
return Argument(SR.ADP_InvalidSourceColumn, parameter);
}
internal static Exception ColumnsAddNullAttempt(string parameter)
{
return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
}
internal static Exception ColumnsDataSetColumn(string cacheColumn)
{
return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
}
internal static Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ColumnsIndexSource(string srcColumn)
{
return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
}
internal static Exception ColumnsIsNotParent(ICollection collection)
{
return ParametersIsNotParent(typeof(DataColumnMapping), collection);
}
internal static Exception ColumnsIsParent(ICollection collection)
{
return ParametersIsParent(typeof(DataColumnMapping), collection);
}
internal static Exception ColumnsUniqueSourceColumn(string srcColumn)
{
return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
}
internal static Exception NotADataColumnMapping(object value)
{
return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
}
//
// DataTableMappingCollection, DataAccess
//
internal static Exception InvalidSourceTable(string parameter)
{
return Argument(SR.ADP_InvalidSourceTable, parameter);
}
internal static Exception TablesAddNullAttempt(string parameter)
{
return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
}
internal static Exception TablesDataSetTable(string cacheTable)
{
return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
}
internal static Exception TablesIndexInt32(int index, ITableMappingCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception TablesIsNotParent(ICollection collection)
{
return ParametersIsNotParent(typeof(DataTableMapping), collection);
}
internal static Exception TablesIsParent(ICollection collection)
{
return ParametersIsParent(typeof(DataTableMapping), collection);
}
internal static Exception TablesSourceIndex(string srcTable)
{
return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
}
internal static Exception TablesUniqueSourceTable(string srcTable)
{
return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
}
internal static Exception NotADataTableMapping(object value)
{
return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
}
//
// IDbCommand
//
internal static InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_ConnectionRequired_Clone;
}
else
{
switch (statementType)
{
case StatementType.Insert:
resource = SR.ADP_ConnectionRequired_Insert;
break;
case StatementType.Update:
resource = SR.ADP_ConnectionRequired_Update;
break;
case StatementType.Delete:
resource = SR.ADP_ConnectionRequired_Delete;
break;
case StatementType.Batch:
resource = SR.ADP_ConnectionRequired_Batch;
goto default;
#if DEBUG
case StatementType.Select:
Debug.Assert(false, "shouldn't be here");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(resource);
}
internal static InvalidOperationException ConnectionRequired_Res(string method) =>
InvalidOperation("ADP_ConnectionRequired_" + method);
internal static InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_OpenConnectionRequired_Clone;
}
else
{
switch (statementType)
{
case StatementType.Insert:
resource = SR.ADP_OpenConnectionRequired_Insert;
break;
case StatementType.Update:
resource = SR.ADP_OpenConnectionRequired_Update;
break;
case StatementType.Delete:
resource = SR.ADP_OpenConnectionRequired_Delete;
break;
#if DEBUG
case StatementType.Select:
Debug.Assert(false, "shouldn't be here");
goto default;
case StatementType.Batch:
Debug.Assert(false, "isRowUpdatingCommand should have been true");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(SR.Format(resource, ADP.ConnectionStateMsg(state)));
}
//
// DbDataAdapter
//
internal static ArgumentException UnwantedStatementType(StatementType statementType)
{
return Argument(SR.Format(SR.ADP_UnwantedStatementType, statementType.ToString()));
}
//
// DbDataAdapter.FillSchema
//
internal static Exception FillSchemaRequiresSourceTableName(string parameter)
{
return Argument(SR.ADP_FillSchemaRequiresSourceTableName, parameter);
}
//
// DbDataAdapter.Fill
//
internal static Exception InvalidMaxRecords(string parameter, int max)
{
return Argument(SR.Format(SR.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
}
internal static Exception InvalidStartRecord(string parameter, int start)
{
return Argument(SR.Format(SR.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
}
internal static Exception FillRequires(string parameter)
{
return ArgumentNull(parameter);
}
internal static Exception FillRequiresSourceTableName(string parameter)
{
return Argument(SR.ADP_FillRequiresSourceTableName, parameter);
}
internal static Exception FillChapterAutoIncrement()
{
return InvalidOperation(SR.ADP_FillChapterAutoIncrement);
}
internal static InvalidOperationException MissingDataReaderFieldType(int index)
{
return DataAdapter(SR.Format(SR.ADP_MissingDataReaderFieldType, index));
}
internal static InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords()
{
return DataAdapter(SR.ADP_OnlyOneTableForStartRecordOrMaxRecords);
}
//
// DbDataAdapter.Update
//
internal static ArgumentNullException UpdateRequiresNonNullDataSet(string parameter)
{
return ArgumentNull(parameter);
}
internal static InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName)
{
return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
}
internal static InvalidOperationException UpdateRequiresSourceTableName(string srcTable)
{
return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTableName, srcTable));
}
internal static ArgumentNullException UpdateRequiresDataTable(string parameter)
{
return ArgumentNull(parameter);
}
internal static Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows)
{
string resource;
switch (statementType)
{
case StatementType.Update:
resource = SR.ADP_UpdateConcurrencyViolation_Update;
break;
case StatementType.Delete:
resource = SR.ADP_UpdateConcurrencyViolation_Delete;
break;
case StatementType.Batch:
resource = SR.ADP_UpdateConcurrencyViolation_Batch;
break;
#if DEBUG
case StatementType.Select:
case StatementType.Insert:
Debug.Assert(false, "should be here");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
DBConcurrencyException exception = new DBConcurrencyException(SR.Format(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
TraceExceptionAsReturnValue(exception);
return exception;
}
internal static InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_UpdateRequiresCommandClone;
}
else
{
switch (statementType)
{
case StatementType.Select:
resource = SR.ADP_UpdateRequiresCommandSelect;
break;
case StatementType.Insert:
resource = SR.ADP_UpdateRequiresCommandInsert;
break;
case StatementType.Update:
resource = SR.ADP_UpdateRequiresCommandUpdate;
break;
case StatementType.Delete:
resource = SR.ADP_UpdateRequiresCommandDelete;
break;
#if DEBUG
case StatementType.Batch:
Debug.Assert(false, "isRowUpdatingCommand should have been true");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(resource);
}
internal static ArgumentException UpdateMismatchRowTable(int i)
{
return Argument(SR.Format(SR.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
}
internal static DataException RowUpdatedErrors()
{
return Data(SR.ADP_RowUpdatedErrors);
}
internal static DataException RowUpdatingErrors()
{
return Data(SR.ADP_RowUpdatingErrors);
}
internal static InvalidOperationException ResultsNotAllowedDuringBatch()
{
return DataAdapter(SR.ADP_ResultsNotAllowedDuringBatch);
}
//
// : DbDataAdapter
//
internal static InvalidOperationException DynamicSQLJoinUnsupported()
{
return InvalidOperation(SR.ADP_DynamicSQLJoinUnsupported);
}
internal static InvalidOperationException DynamicSQLNoTableInfo()
{
return InvalidOperation(SR.ADP_DynamicSQLNoTableInfo);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoDelete()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoDelete);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoUpdate()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoUpdate);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionDelete);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionUpdate);
}
internal static InvalidOperationException DynamicSQLNestedQuote(string name, string quote)
{
return InvalidOperation(SR.Format(SR.ADP_DynamicSQLNestedQuote, name, quote));
}
internal static InvalidOperationException NoQuoteChange()
{
return InvalidOperation(SR.ADP_NoQuoteChange);
}
internal static InvalidOperationException MissingSourceCommand()
{
return InvalidOperation(SR.ADP_MissingSourceCommand);
}
internal static InvalidOperationException MissingSourceCommandConnection()
{
return InvalidOperation(SR.ADP_MissingSourceCommandConnection);
}
// global constant strings
internal const string ConnectionString = "ConnectionString";
internal const string DataSetColumn = "DataSetColumn";
internal const string DataSetTable = "DataSetTable";
internal const string Fill = "Fill";
internal const string FillSchema = "FillSchema";
internal const string SourceColumn = "SourceColumn";
internal const string SourceTable = "SourceTable";
internal static DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted)
{
const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
// equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
int countAdded = 0, countDeleted = 0, countModifed = 0;
DataRowCollection rowCollection = dataTable.Rows;
foreach (DataRow dataRow in rowCollection)
{
switch (dataRow.RowState)
{
case DataRowState.Added:
countAdded++;
break;
case DataRowState.Deleted:
countDeleted++;
break;
case DataRowState.Modified:
countModifed++;
break;
default:
Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
break;
}
}
var dataRows = new DataRow[countAdded + countDeleted + countModifed];
if (sorted)
{
countModifed = countAdded + countDeleted;
countDeleted = countAdded;
countAdded = 0;
foreach (DataRow dataRow in rowCollection)
{
switch (dataRow.RowState)
{
case DataRowState.Added:
dataRows[countAdded++] = dataRow;
break;
case DataRowState.Deleted:
dataRows[countDeleted++] = dataRow;
break;
case DataRowState.Modified:
dataRows[countModifed++] = dataRow;
break;
default:
Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
break;
}
}
}
else
{
int index = 0;
foreach (DataRow dataRow in rowCollection)
{
if (0 != (dataRow.RowState & rowStates))
{
dataRows[index++] = dataRow;
if (index == dataRows.Length)
{
break;
}
}
}
}
return dataRows;
}
// { "a", "a", "a" } -> { "a", "a1", "a2" }
// { "a", "a", "a1" } -> { "a", "a2", "a1" }
// { "a", "A", "a" } -> { "a", "A1", "a2" }
// { "a", "A", "a1" } -> { "a", "A2", "a1" }
internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray)
{
Dictionary<string, int> hash = new Dictionary<string, int>(columnNameArray.Length);
int startIndex = columnNameArray.Length; // lowest non-unique index
for (int i = columnNameArray.Length - 1; 0 <= i; --i)
{
string columnName = columnNameArray[i];
if ((null != columnName) && (0 < columnName.Length))
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
int index;
if (hash.TryGetValue(columnName, out index))
{
startIndex = Math.Min(startIndex, index);
}
hash[columnName] = i;
}
else
{
columnNameArray[i] = string.Empty;
startIndex = i;
}
}
int uniqueIndex = 1;
for (int i = startIndex; i < columnNameArray.Length; ++i)
{
string columnName = columnNameArray[i];
if (0 == columnName.Length)
{
// generate a unique name
columnNameArray[i] = "Column";
uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
}
else
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
if (i != hash[columnName])
{
GenerateUniqueName(hash, ref columnNameArray[i], i, 1);
}
}
}
}
private static int GenerateUniqueName(Dictionary<string, int> hash, ref string columnName, int index, int uniqueIndex)
{
for (; ; ++uniqueIndex)
{
string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture);
if (hash.TryAdd(lowerName, index))
{
columnName = uniqueName;
break;
}
}
return uniqueIndex;
}
internal static int SrcCompare(string strA, string strB) => strA == strB ? 0 : 1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Diagnostics.HealthChecks
{
internal sealed partial class HealthCheckPublisherHostedService : IHostedService
{
private readonly HealthCheckService _healthCheckService;
private readonly IOptions<HealthCheckPublisherOptions> _options;
private readonly ILogger _logger;
private readonly IHealthCheckPublisher[] _publishers;
private readonly CancellationTokenSource _stopping;
private Timer? _timer;
private CancellationTokenSource? _runTokenSource;
public HealthCheckPublisherHostedService(
HealthCheckService healthCheckService,
IOptions<HealthCheckPublisherOptions> options,
ILogger<HealthCheckPublisherHostedService> logger,
IEnumerable<IHealthCheckPublisher> publishers)
{
if (healthCheckService == null)
{
throw new ArgumentNullException(nameof(healthCheckService));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (publishers == null)
{
throw new ArgumentNullException(nameof(publishers));
}
_healthCheckService = healthCheckService;
_options = options;
_logger = logger;
_publishers = publishers.ToArray();
_stopping = new CancellationTokenSource();
}
internal bool IsStopping => _stopping.IsCancellationRequested;
internal bool IsTimerRunning => _timer != null;
public Task StartAsync(CancellationToken cancellationToken = default)
{
if (_publishers.Length == 0)
{
return Task.CompletedTask;
}
// IMPORTANT - make sure this is the last thing that happens in this method. The timer can
// fire before other code runs.
_timer = NonCapturingTimer.Create(Timer_Tick, null, dueTime: _options.Value.Delay, period: _options.Value.Period);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken = default)
{
try
{
_stopping.Cancel();
}
catch
{
// Ignore exceptions thrown as a result of a cancellation.
}
if (_publishers.Length == 0)
{
return Task.CompletedTask;
}
_timer?.Dispose();
_timer = null;
return Task.CompletedTask;
}
// Yes, async void. We need to be async. We need to be void. We handle the exceptions in RunAsync
private async void Timer_Tick(object? state)
{
await RunAsync();
}
// Internal for testing
internal void CancelToken()
{
_runTokenSource!.Cancel();
}
// Internal for testing
internal async Task RunAsync()
{
var duration = ValueStopwatch.StartNew();
Logger.HealthCheckPublisherProcessingBegin(_logger);
CancellationTokenSource? cancellation = null;
try
{
var timeout = _options.Value.Timeout;
cancellation = CancellationTokenSource.CreateLinkedTokenSource(_stopping.Token);
_runTokenSource = cancellation;
cancellation.CancelAfter(timeout);
await RunAsyncCore(cancellation.Token);
Logger.HealthCheckPublisherProcessingEnd(_logger, duration.GetElapsedTime());
}
catch (OperationCanceledException) when (IsStopping)
{
// This is a cancellation - if the app is shutting down we want to ignore it. Otherwise, it's
// a timeout and we want to log it.
}
catch (Exception ex)
{
// This is an error, publishing failed.
Logger.HealthCheckPublisherProcessingEnd(_logger, duration.GetElapsedTime(), ex);
}
finally
{
cancellation?.Dispose();
}
}
private async Task RunAsyncCore(CancellationToken cancellationToken)
{
// Forcibly yield - we want to unblock the timer thread.
await Task.Yield();
// The health checks service does it's own logging, and doesn't throw exceptions.
var report = await _healthCheckService.CheckHealthAsync(_options.Value.Predicate, cancellationToken);
var publishers = _publishers;
var tasks = new Task[publishers.Length];
for (var i = 0; i < publishers.Length; i++)
{
tasks[i] = RunPublisherAsync(publishers[i], report, cancellationToken);
}
await Task.WhenAll(tasks);
}
private async Task RunPublisherAsync(IHealthCheckPublisher publisher, HealthReport report, CancellationToken cancellationToken)
{
var duration = ValueStopwatch.StartNew();
try
{
Logger.HealthCheckPublisherBegin(_logger, publisher);
await publisher.PublishAsync(report, cancellationToken);
Logger.HealthCheckPublisherEnd(_logger, publisher, duration.GetElapsedTime());
}
catch (OperationCanceledException) when (IsStopping)
{
// This is a cancellation - if the app is shutting down we want to ignore it. Otherwise, it's
// a timeout and we want to log it.
}
catch (OperationCanceledException)
{
Logger.HealthCheckPublisherTimeout(_logger, publisher, duration.GetElapsedTime());
throw;
}
catch (Exception ex)
{
Logger.HealthCheckPublisherError(_logger, publisher, duration.GetElapsedTime(), ex);
throw;
}
}
internal static class EventIds
{
public const int HealthCheckPublisherProcessingBeginId = 100;
public const int HealthCheckPublisherProcessingEndId = 101;
public const int HealthCheckPublisherBeginId = 102;
public const int HealthCheckPublisherEndId = 103;
public const int HealthCheckPublisherErrorId = 104;
public const int HealthCheckPublisherTimeoutId = 104;
// Hard code the event names to avoid breaking changes. Even if the methods are renamed, these hard-coded names shouldn't change.
public const string HealthCheckPublisherProcessingBeginName = "HealthCheckPublisherProcessingBegin";
public const string HealthCheckPublisherProcessingEndName = "HealthCheckPublisherProcessingEnd";
public const string HealthCheckPublisherBeginName = "HealthCheckPublisherBegin";
public const string HealthCheckPublisherEndName = "HealthCheckPublisherEnd";
public const string HealthCheckPublisherErrorName = "HealthCheckPublisherError";
public const string HealthCheckPublisherTimeoutName = "HealthCheckPublisherTimeout";
}
private static partial class Logger
{
[LoggerMessage(EventIds.HealthCheckPublisherProcessingBeginId, LogLevel.Debug, "Running health check publishers", EventName = EventIds.HealthCheckPublisherProcessingBeginName)]
public static partial void HealthCheckPublisherProcessingBegin(ILogger logger);
public static void HealthCheckPublisherProcessingEnd(ILogger logger, TimeSpan duration, Exception? exception = null) =>
HealthCheckPublisherProcessingEnd(logger, duration.TotalMilliseconds, exception);
[LoggerMessage(EventIds.HealthCheckPublisherProcessingEndId, LogLevel.Debug, "Health check publisher processing completed after {ElapsedMilliseconds}ms", EventName = EventIds.HealthCheckPublisherProcessingEndName)]
private static partial void HealthCheckPublisherProcessingEnd(ILogger logger, double ElapsedMilliseconds, Exception? exception = null);
[LoggerMessage(EventIds.HealthCheckPublisherBeginId, LogLevel.Debug, "Running health check publisher '{HealthCheckPublisher}'", EventName = EventIds.HealthCheckPublisherBeginName)]
public static partial void HealthCheckPublisherBegin(ILogger logger, IHealthCheckPublisher HealthCheckPublisher);
public static void HealthCheckPublisherEnd(ILogger logger, IHealthCheckPublisher HealthCheckPublisher, TimeSpan duration) =>
HealthCheckPublisherEnd(logger, HealthCheckPublisher, duration.TotalMilliseconds);
[LoggerMessage(EventIds.HealthCheckPublisherEndId, LogLevel.Debug, "Health check '{HealthCheckPublisher}' completed after {ElapsedMilliseconds}ms", EventName = EventIds.HealthCheckPublisherEndName)]
private static partial void HealthCheckPublisherEnd(ILogger logger, IHealthCheckPublisher HealthCheckPublisher, double ElapsedMilliseconds);
public static void HealthCheckPublisherError(ILogger logger, IHealthCheckPublisher publisher, TimeSpan duration, Exception exception) =>
HealthCheckPublisherError(logger, publisher, duration.TotalMilliseconds, exception);
#pragma warning disable SYSLIB1006
[LoggerMessage(EventIds.HealthCheckPublisherErrorId, LogLevel.Error, "Health check {HealthCheckPublisher} threw an unhandled exception after {ElapsedMilliseconds}ms", EventName = EventIds.HealthCheckPublisherErrorName)]
private static partial void HealthCheckPublisherError(ILogger logger, IHealthCheckPublisher HealthCheckPublisher, double ElapsedMilliseconds, Exception exception);
public static void HealthCheckPublisherTimeout(ILogger logger, IHealthCheckPublisher publisher, TimeSpan duration) =>
HealthCheckPublisherTimeout(logger, publisher, duration.TotalMilliseconds);
[LoggerMessage(EventIds.HealthCheckPublisherTimeoutId, LogLevel.Error, "Health check {HealthCheckPublisher} was canceled after {ElapsedMilliseconds}ms", EventName = EventIds.HealthCheckPublisherTimeoutName)]
private static partial void HealthCheckPublisherTimeout(ILogger logger, IHealthCheckPublisher HealthCheckPublisher, double ElapsedMilliseconds);
#pragma warning restore SYSLIB1006
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="GraphicsPathIterator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing.Drawing2D {
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Drawing;
using System.ComponentModel;
using System.Drawing.Internal;
using System.Globalization;
using System.Runtime.Versioning;
/**
* Represent a Path Iterator object
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator"]/*' />
/// <devdoc>
/// <para>
/// Provides helper functions for the <see cref='System.Drawing.Drawing2D.GraphicsPath'/> class.
/// </para>
/// </devdoc>
public sealed class GraphicsPathIterator : MarshalByRefObject, IDisposable {
/**
* Create a new path iterator object
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.GraphicsPathIterator"]/*' />
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.GraphicsPathIterator'/> class with the specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/>.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public GraphicsPathIterator(GraphicsPath path)
{
IntPtr nativeIter = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreatePathIter(out nativeIter, new HandleRef(path, (path == null) ? IntPtr.Zero : path.nativePath));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
this.nativeIter = nativeIter;
}
/**
* Dispose of resources associated with the
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.Dispose"]/*' />
/// <devdoc>
/// Cleans up Windows resources for this
/// <see cref='System.Drawing.Drawing2D.GraphicsPathIterator'/>.
/// </devdoc>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing) {
if (nativeIter != IntPtr.Zero) {
try{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDeletePathIter(new HandleRef(this, nativeIter));
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch( Exception ex ){
if( ClientUtils.IsSecurityOrCriticalException( ex ) ) {
throw;
}
Debug.Fail( "Exception thrown during Dispose: " + ex.ToString() );
}
finally{
nativeIter = IntPtr.Zero;
}
}
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.Finalize"]/*' />
/// <devdoc>
/// Cleans up Windows resources for this
/// <see cref='System.Drawing.Drawing2D.GraphicsPathIterator'/>.
/// </devdoc>
~GraphicsPathIterator() {
Dispose(false);
}
/**
* Next subpath in path
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.NextSubpath"]/*' />
/// <devdoc>
/// Returns the number of subpaths in the
/// <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. The start index and end index of the
/// next subpath are contained in out parameters.
/// </devdoc>
public int NextSubpath(out int startIndex, out int endIndex, out bool isClosed) {
int resultCount = 0;
int tempStart = 0;
int tempEnd = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterNextSubpath(new HandleRef(this, nativeIter), out resultCount,
out tempStart, out tempEnd, out isClosed);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
else {
startIndex = tempStart;
endIndex = tempEnd;
}
return resultCount;
}
/**
* Next subpath in path
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.NextSubpath1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int NextSubpath(GraphicsPath path, out bool isClosed) {
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterNextSubpathPath(new HandleRef(this, nativeIter), out resultCount,
new HandleRef(path, (path == null) ? IntPtr.Zero : path.nativePath), out isClosed);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
/**
* Next type in subpath
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.NextPathType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int NextPathType(out byte pathType, out int startIndex, out int endIndex)
{
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterNextPathType(new HandleRef(this, nativeIter), out resultCount,
out pathType, out startIndex, out endIndex);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
/**
* Next marker in subpath
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.NextMarker"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int NextMarker(out int startIndex, out int endIndex)
{
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterNextMarker(new HandleRef(this, nativeIter), out resultCount,
out startIndex, out endIndex);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
/**
* Next marker in subpath
*/
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.NextMarker1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int NextMarker(GraphicsPath path)
{
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterNextMarkerPath(new HandleRef(this, nativeIter), out resultCount,
new HandleRef(path, (path == null) ? IntPtr.Zero : path.nativePath));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.Count"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Count
{
get {
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterGetCount(new HandleRef(this, nativeIter), out resultCount);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.SubpathCount"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int SubpathCount
{
get {
int resultCount = 0;
int status = SafeNativeMethods.Gdip.GdipPathIterGetSubpathCount(new HandleRef(this, nativeIter), out resultCount);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return resultCount;
}
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.HasCurve"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool HasCurve()
{
bool hasCurve = false;
int status = SafeNativeMethods.Gdip.GdipPathIterHasCurve(new HandleRef(this, nativeIter), out hasCurve);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return hasCurve;
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.Rewind"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Rewind()
{
int status = SafeNativeMethods.Gdip.GdipPathIterRewind(new HandleRef(this, nativeIter));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.Enumerate"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Enumerate(ref PointF[] points, ref byte[] types)
{
if (points.Length != types.Length)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
int resultCount = 0;
int size = (int)Marshal.SizeOf(typeof(GPPOINTF));
int count = points.Length;
byte[] typesLocal = new byte[count];
IntPtr memoryPts = Marshal.AllocHGlobal(checked(count * size));
try {
int status = SafeNativeMethods.Gdip.GdipPathIterEnumerate(new HandleRef(this, nativeIter), out resultCount,
memoryPts, typesLocal, count);
if (status != SafeNativeMethods.Gdip.Ok) {
throw SafeNativeMethods.Gdip.StatusException(status);
}
if (resultCount < count) {
SafeNativeMethods.ZeroMemory((IntPtr)(checked((long)memoryPts + resultCount * size)), (UIntPtr)((count - resultCount) * size));
}
points = SafeNativeMethods.Gdip.ConvertGPPOINTFArrayF(memoryPts, count);
typesLocal.CopyTo(types, 0);
} finally {
Marshal.FreeHGlobal(memoryPts);
}
return resultCount;
}
/// <include file='doc\GraphicsPathIterator.uex' path='docs/doc[@for="GraphicsPathIterator.CopyData"]/*' />
/// <devdoc>
/// <para>
/// points - pointF array to copy the retrieved point data
/// types - type array to copy the retrieved type data
/// startIndex - start index of the origianl data
/// endIndex - end index of the origianl data
/// </para>
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
public int CopyData(ref PointF[] points, ref byte[] types, int startIndex, int endIndex)
{
if ((points.Length != types.Length) || (endIndex - startIndex + 1 > points.Length))
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
int resultCount = 0;
int size = (int)Marshal.SizeOf(typeof(GPPOINTF));
int count = points.Length;
byte[] typesLocal = new byte[count];
IntPtr memoryPts = Marshal.AllocHGlobal(checked(count * size));
try {
int status = SafeNativeMethods.Gdip.GdipPathIterCopyData(new HandleRef(this, nativeIter), out resultCount,
memoryPts, typesLocal, startIndex, endIndex);
if (status != SafeNativeMethods.Gdip.Ok) {
throw SafeNativeMethods.Gdip.StatusException(status);
}
if (resultCount < count) {
SafeNativeMethods.ZeroMemory((IntPtr)(checked((long)memoryPts + resultCount * size)), (UIntPtr)((count - resultCount) * size));
}
points = SafeNativeMethods.Gdip.ConvertGPPOINTFArrayF(memoryPts, count);
typesLocal.CopyTo(types, 0);
} finally {
Marshal.FreeHGlobal(memoryPts);
}
return resultCount;
}
/*
* handle to native path iterator object
*/
internal IntPtr nativeIter;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Albums.Services.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Numerics;
using System.Text;
namespace Neo.Compiler.MSIL
{
/// <summary>
/// Convert IL to NeoVM opcode
/// </summary>
public partial class ModuleConverter
{
private NeoCode Insert1(VM.OpCode code, string comment, NeoMethod to, byte[] data = null)
{
NeoCode _code = new NeoCode();
int startaddr = addr;
_code.addr = addr;
{
_code.debugcode = comment;
_code.debugline = 0;
}
addr++;
_code.code = code;
if (data != null)
{
_code.bytes = data;
addr += _code.bytes.Length;
}
to.body_Codes[startaddr] = _code;
return _code;
}
private NeoCode InsertPush(byte[] data, string comment, NeoMethod to)
{
if (data.Length == 0) return Insert1(VM.OpCode.PUSH0, comment, to);
byte prefixLen;
VM.OpCode code;
if (data.Length <= byte.MaxValue)
{
prefixLen = sizeof(byte);
code = VM.OpCode.PUSHDATA1;
}
else if (data.Length <= ushort.MaxValue)
{
prefixLen = sizeof(ushort);
code = VM.OpCode.PUSHDATA2;
}
else
{
prefixLen = sizeof(uint);
code = VM.OpCode.PUSHDATA4;
}
byte[] bytes = new byte[data.Length + prefixLen];
Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, bytes, 0, prefixLen);
Buffer.BlockCopy(data, 0, bytes, prefixLen, data.Length);
return Insert1(code, comment, to, bytes);
}
private NeoCode InsertPush(int i, string comment, NeoMethod to)
{
if (i == 0) return Insert1(VM.OpCode.PUSH0, comment, to);
if (i == -1) return Insert1(VM.OpCode.PUSHM1, comment, to);
if (i > 0 && i <= 16) return Insert1(VM.OpCode.PUSH0 + (byte)i, comment, to);
return InsertPush(((BigInteger)i).ToByteArray(), comment, to);
}
private NeoCode Convert1by1(VM.OpCode code, OpCode src, NeoMethod to, byte[] data = null)
{
NeoCode _code = new NeoCode();
int startaddr = addr;
_code.addr = addr;
if (src != null)
{
addrconv[src.addr] = addr;
_code.debugcode = src.debugcode;
_code.debugline = src.debugline;
_code.debugILAddr = src.addr;
_code.debugILCode = src.code.ToString();
_code.sequencePoint = src.sequencePoint;
}
addr++;
_code.code = code;
if (data != null)
{
_code.bytes = data;
addr += _code.bytes.Length;
}
to.body_Codes[startaddr] = _code;
return _code;
}
private void ConvertPushNumber(BigInteger i, OpCode src, NeoMethod to)
{
if (i == 0) Convert1by1(VM.OpCode.PUSH0, src, to);
else if (i == -1) Convert1by1(VM.OpCode.PUSHM1, src, to);
else if (i > 0 && i <= 16) Convert1by1(VM.OpCode.PUSH0 + (byte)i, src, to);
else
{
ConvertPushDataArray(i.ToByteArray(), src, to);
Insert1(VM.OpCode.CONVERT, "", to, new byte[] { (byte)VM.Types.StackItemType.Integer });
}
}
private void ConvertPushBoolean(bool b, OpCode src, NeoMethod to)
{
if (!b)
Convert1by1(VM.OpCode.PUSH0, src, to);
else
Convert1by1(VM.OpCode.PUSH1, src, to);
Insert1(VM.OpCode.CONVERT, "", to, new byte[] { (byte)VM.Types.StackItemType.Boolean });
}
private void ConvertPushDataArray(byte[] data, OpCode src, NeoMethod to)
{
byte prefixLen;
VM.OpCode code;
if (data.Length <= byte.MaxValue)
{
prefixLen = sizeof(byte);
code = VM.OpCode.PUSHDATA1;
}
else if (data.Length <= ushort.MaxValue)
{
prefixLen = sizeof(ushort);
code = VM.OpCode.PUSHDATA2;
}
else
{
prefixLen = sizeof(uint);
code = VM.OpCode.PUSHDATA4;
}
byte[] bytes = new byte[data.Length + prefixLen];
Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, bytes, 0, prefixLen);
Buffer.BlockCopy(data, 0, bytes, prefixLen, data.Length);
Convert1by1(code, src, to, bytes);
}
private void ConvertPushString(string str, OpCode src, NeoMethod to)
{
var data = Utility.StrictUTF8.GetBytes(str);
ConvertPushDataArray(data, src, to);
}
private void ConvertPushStringArray(string[] strArray, OpCode src, NeoMethod to)
{
for (int i = strArray.Length - 1; i >= 0; i--)
{
var str = strArray[i];
ConvertPushString(str, src, to);
}
ConvertPushNumber(strArray.Length, src, to);
Insert1(VM.OpCode.PACK, "", to);
}
private int ConvertPushI8WithConv(ILMethod from, long i, OpCode src, NeoMethod to)
{
var next = from.GetNextCodeAddr(src.addr);
var code = from.body_Codes[next].code;
BigInteger outv;
if (code == CodeEx.Conv_U || code == CodeEx.Conv_U8)
{
ulong v = (ulong)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U1)
{
byte v = (byte)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U2)
{
ushort v = (ushort)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U4)
{
uint v = (uint)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Call)
{
var call = from.body_Codes[next];
if (call.tokenMethod == "System.Numerics.BigInteger System.Numerics.BigInteger::op_Implicit(System.UInt64)")
{
// Be careful with converting ulong to biginteger
ulong v = (ulong)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
}
ConvertPushNumber(i, src, to);
return 0;
}
private int ConvertPushI4WithConv(ILMethod from, int i, OpCode src, NeoMethod to)
{
var next = from.GetNextCodeAddr(src.addr);
var code = from.body_Codes[next].code;
BigInteger outv;
if (code == CodeEx.Conv_U || code == CodeEx.Conv_U8)
{
ulong v = (uint)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U1)
{
byte v = (byte)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U2)
{
ushort v = (ushort)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else if (code == CodeEx.Conv_U4)
{
uint v = (uint)i;
outv = v;
ConvertPushNumber(outv, src, to);
return 1;
}
else
{
ConvertPushNumber(i, src, to);
return 0;
}
}
private void InsertSharedStaticVarCode(NeoMethod to)
{
//insert init constvalue part
byte count = (byte)this.outModule.mapFields.Count;
if (count > 0)
{
Insert1(VM.OpCode.INITSSLOT, "", to, new byte[] { count }); // INITSSLOT with a u8 len
}
foreach (var defvar in this.outModule.staticfieldsWithConstValue)
{
if (this.outModule.mapFields.TryGetValue(defvar.Key, out NeoField field))
{
//value
#region insertValue
//this static var had a default value.
var _src = defvar.Value;
if (_src is byte[])
{
ConvertPushDataArray((byte[])_src, null, to);
}
else if (_src is int intsrc)
{
ConvertPushNumber(intsrc, null, to);
}
else if (_src is long longsrc)
{
ConvertPushNumber(longsrc, null, to);
}
else if (_src is bool bsrc)
{
ConvertPushBoolean(bsrc, null, to);
}
else if (_src is string strsrc)
{
ConvertPushString(strsrc, null, to);
}
else if (_src is BigInteger bisrc)
{
ConvertPushNumber(bisrc, null, to);
}
else if (_src is string[] strArray)
{
ConvertPushStringArray(strArray, null, to);
}
else
{
//no need to init null
Convert1by1(VM.OpCode.PUSHNULL, null, to);
}
#endregion
if (field.index < 7)
{
Insert1(VM.OpCode.STSFLD0 + (byte)field.index, "", to);
}
else
{
var fieldIndex = (byte)field.index;
Insert1(VM.OpCode.STSFLD, "", to, new byte[] { fieldIndex });
}
}
}
//insert code part
foreach (var cctor in this.outModule.staticfieldsCctor)
{
FillMethod(cctor, to, false);
}
}
private void InsertBeginCode(ILMethod from, NeoMethod to)
{
if (from.paramtypes.Count > MAX_PARAMS_COUNT)
throw new Exception("too much params in:" + from);
if (from.body_Variables.Count > MAX_LOCAL_VARIABLES_COUNT)
throw new Exception("too much local variables in:" + from);
byte paramcount = (byte)from.paramtypes.Count;
byte varcount = (byte)from.body_Variables.Count;
if (paramcount + varcount > 0)
{
Insert1(VM.OpCode.INITSLOT, "begincode", to, new byte[] { varcount, paramcount });
}
}
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
namespace Eto.Mac.Forms.Controls
{
public class SplitterHandler : MacView<NSSplitView, Splitter, Splitter.ICallback>, Splitter.IHandler
{
double relative = double.NaN;
//TODO: RelativePosition - following is just stub, see WinForm/WPF/GTK or ThemedSplitter
public double RelativePosition
{
get
{
if (!Widget.Loaded)
return relative;
var pos = Position;
if (fixedPanel == SplitterFixedPanel.Panel1)
return pos;
var size = Orientation == Orientation.Horizontal ? Control.Bounds.Width : Control.Bounds.Height;
size -= SplitterWidth;
if (fixedPanel == SplitterFixedPanel.Panel2)
return size - pos;
return pos / (double)size;
}
set
{
relative = value;
if (Widget.Loaded)
{
SetRelative();
Control.ResizeSubviewsWithOldSize(CGSize.Empty);
}
}
}
void SetRelative()
{
if (double.IsNaN(relative))
return;
if (fixedPanel == SplitterFixedPanel.Panel1)
position = (int)Math.Round(relative);
else
{
var size = Orientation == Orientation.Horizontal ? Control.Bounds.Width : Control.Bounds.Height;
size -= SplitterWidth;
if (fixedPanel == SplitterFixedPanel.Panel2)
position = (int)Math.Round(size - relative);
else
position = (int)Math.Round(size * relative);
}
relative = double.NaN;
}
public int SplitterWidth
{
get { return (int)Math.Round(Control.DividerThickness); }
set { }
}
Control panel1;
Control panel2;
int? position;
SplitterFixedPanel fixedPanel;
bool initialPositionSet;
public bool RecurseToChildren { get { return true; } }
public override NSView ContainerControl { get { return Control; } }
public virtual Size ClientSize { get { return Size; } set { Size = value; } }
public override void AttachEvent(string id)
{
switch (id)
{
case Splitter.PositionChangedEvent:
// handled by delegate
break;
default:
base.AttachEvent(id);
break;
}
}
static void ResizeSubviews(SplitterHandler handler, CGSize oldSize)
{
var splitView = handler.Control;
var dividerThickness = splitView.DividerThickness;
var panel1Rect = splitView.Subviews[0].Frame;
var panel2Rect = splitView.Subviews[1].Frame;
var newFrame = splitView.Frame;
if (oldSize.Height <= 0 && oldSize.Width <= 0)
oldSize = newFrame.Size;
if (splitView.IsVertical)
{
panel2Rect.Y = 0;
panel2Rect.Height = panel1Rect.Height = newFrame.Height;
panel1Rect = new CGRect(CGPoint.Empty, panel1Rect.Size);
if (handler.position == null)
{
panel1Rect.Width = (nfloat)Math.Max(0, newFrame.Width / 2);
panel2Rect.Width = (nfloat)Math.Max(0, newFrame.Width - panel1Rect.Width - dividerThickness);
}
else
{
var pos = handler.position.Value;
switch (handler.fixedPanel)
{
case SplitterFixedPanel.Panel1:
panel1Rect.Width = (nfloat)Math.Max(0, Math.Min(newFrame.Width - dividerThickness, pos));
panel2Rect.Width = (nfloat)Math.Max(0, newFrame.Width - panel1Rect.Width - dividerThickness);
break;
case SplitterFixedPanel.Panel2:
panel2Rect.Width = (nfloat)Math.Max(0, Math.Min(newFrame.Width - dividerThickness, oldSize.Width - pos - dividerThickness));
panel1Rect.Width = (nfloat)Math.Max(0, newFrame.Width - panel2Rect.Width - dividerThickness);
break;
case SplitterFixedPanel.None:
var oldscale = newFrame.Width / oldSize.Width;
panel1Rect.Width = (nfloat)Math.Round(Math.Max(0, Math.Min(newFrame.Width - dividerThickness, pos * oldscale)));
panel2Rect.Width = (nfloat)Math.Max(0, newFrame.Width - panel1Rect.Width - dividerThickness);
break;
}
}
panel2Rect.X = (nfloat)Math.Min(panel1Rect.Width + dividerThickness, newFrame.Width);
}
else
{
panel2Rect.X = 0;
panel2Rect.Width = panel1Rect.Width = newFrame.Width;
panel1Rect = new CGRect(CGPoint.Empty, panel1Rect.Size);
if (handler.position == null)
{
panel1Rect.Height = (nfloat)Math.Max(0, newFrame.Height / 2);
panel2Rect.Height = (nfloat)Math.Max(0, newFrame.Height - panel1Rect.Height - dividerThickness);
}
else
{
var pos = handler.position.Value;
switch (handler.fixedPanel)
{
case SplitterFixedPanel.Panel1:
panel1Rect.Height = (nfloat)Math.Max(0, Math.Min(newFrame.Height - dividerThickness, pos));
panel2Rect.Height = (nfloat)Math.Max(0, newFrame.Height - panel1Rect.Height - dividerThickness);
break;
case SplitterFixedPanel.Panel2:
panel2Rect.Height = (nfloat)Math.Max(0, Math.Min(newFrame.Height - dividerThickness, oldSize.Height - pos - dividerThickness));
panel1Rect.Height = (nfloat)Math.Max(0, newFrame.Height - panel2Rect.Height - dividerThickness);
break;
case SplitterFixedPanel.None:
var oldscale = newFrame.Height / oldSize.Height;
panel1Rect.Height = (nfloat)Math.Round(Math.Max(0, Math.Min(newFrame.Height - dividerThickness, pos * oldscale)));
panel2Rect.Height = (nfloat)Math.Max(0, newFrame.Height - panel1Rect.Height - dividerThickness);
break;
}
}
panel2Rect.Y = (nfloat)Math.Min(panel1Rect.Height + dividerThickness, newFrame.Height);
}
splitView.Subviews[0].Frame = panel1Rect;
splitView.Subviews[1].Frame = panel2Rect;
}
class SVDelegate : NSSplitViewDelegate
{
WeakReference handler;
public SplitterHandler Handler { get { return (SplitterHandler)handler.Target; } set { handler = new WeakReference(value); } }
public override void Resize(NSSplitView splitView, CGSize oldSize)
{
SplitterHandler.ResizeSubviews(Handler, oldSize);
}
public override nfloat ConstrainSplitPosition(NSSplitView splitView, nfloat proposedPosition, nint subviewDividerIndex)
{
return Handler.Enabled ? (nfloat)Math.Round(proposedPosition) : Handler.Position;
}
public override void DidResizeSubviews(NSNotification notification)
{
var subview = Handler.Control.Subviews[0];
if (subview != null && Handler.position != null && Handler.initialPositionSet && Handler.Widget.Loaded && Handler.Widget.ParentWindow != null && Handler.Widget.ParentWindow.Loaded)
{
Handler.position = Handler.Control.IsVertical ? (int)subview.Frame.Width : (int)subview.Frame.Height;
Handler.Callback.OnPositionChanged(Handler.Widget, EventArgs.Empty);
}
}
}
// stupid hack for OSX 10.5 so that mouse down/drag/up events fire in children properly..
class EtoSplitView : NSSplitView, IMacControl
{
public WeakReference WeakHandler { get; set; }
public SplitterHandler Handler
{
get { return (SplitterHandler)WeakHandler.Target; }
set { WeakHandler = new WeakReference(value); }
}
public override void MouseDown(NSEvent theEvent)
{
var cursor = NSCursor.CurrentCursor;
if (cursor == NSCursor.ResizeLeftCursor || cursor == NSCursor.ResizeRightCursor || cursor == NSCursor.ResizeLeftRightCursor
|| cursor == NSCursor.ResizeUpCursor || cursor == NSCursor.ResizeDownCursor || cursor == NSCursor.ResizeUpDownCursor)
base.MouseDown(theEvent);
}
public override void MouseDragged(NSEvent theEvent)
{
var cursor = NSCursor.CurrentCursor;
if (cursor == NSCursor.ResizeLeftCursor || cursor == NSCursor.ResizeRightCursor || cursor == NSCursor.ResizeLeftRightCursor
|| cursor == NSCursor.ResizeUpCursor || cursor == NSCursor.ResizeDownCursor || cursor == NSCursor.ResizeUpDownCursor)
base.MouseDragged(theEvent);
}
public override void MouseUp(NSEvent theEvent)
{
var cursor = NSCursor.CurrentCursor;
if (cursor == NSCursor.ResizeLeftCursor || cursor == NSCursor.ResizeRightCursor || cursor == NSCursor.ResizeLeftRightCursor
|| cursor == NSCursor.ResizeUpCursor || cursor == NSCursor.ResizeDownCursor || cursor == NSCursor.ResizeUpDownCursor)
base.MouseUp(theEvent);
}
}
public SplitterHandler()
{
Enabled = true;
Control = new EtoSplitView { Handler = this };
Control.DividerStyle = NSSplitViewDividerStyle.Thin;
Control.AddSubview(new NSView { AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable });
Control.AddSubview(new NSView { AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable });
Control.IsVertical = true;
Control.Delegate = new SVDelegate { Handler = this };
}
public int Position
{
get { return position ?? (int)(Control.IsVertical ? Control.Subviews[0].Frame.Width : Control.Subviews[0].Frame.Height); }
set
{
position = value;
relative = double.NaN;
if (Widget.Loaded)
Control.ResizeSubviewsWithOldSize(CGSize.Empty);
}
}
public Orientation Orientation
{
get
{
return Control.IsVertical ? Orientation.Horizontal : Orientation.Vertical;
}
set
{
Control.IsVertical = value == Orientation.Horizontal;
if (Widget.Loaded)
Control.ResizeSubviewsWithOldSize(CGSize.Empty);
}
}
public override bool Enabled { get; set; }
public SplitterFixedPanel FixedPanel
{
get { return fixedPanel; }
set
{
fixedPanel = value;
if (Widget.Loaded)
Control.ResizeSubviewsWithOldSize(CGSize.Empty);
}
}
public Control Panel1
{
get { return panel1; }
set
{
if (panel1 != value)
{
var view = value.GetContainerView();
Control.ReplaceSubviewWith(Control.Subviews[0], view ?? new NSView());
panel1 = value;
}
}
}
public Control Panel2
{
get { return panel2; }
set
{
if (panel2 != value)
{
var view = value.GetContainerView();
Control.ReplaceSubviewWith(Control.Subviews[1], view ?? new NSView());
panel2 = value;
}
}
}
void SetInitialSplitPosition()
{
if (!double.IsNaN(relative))
SetRelative();
else if (position == null)
{
switch (fixedPanel)
{
case SplitterFixedPanel.None:
case SplitterFixedPanel.Panel1:
var size1 = panel1.GetPreferredSize(SizeF.MaxValue);
position = (int)(Orientation == Orientation.Horizontal ? size1.Width : size1.Height);
break;
case SplitterFixedPanel.Panel2:
var size2 = panel2.GetPreferredSize(SizeF.MaxValue);
if (Orientation == Orientation.Horizontal)
position = (int)(Control.Frame.Width - size2.Width - Control.DividerThickness);
else
position = (int)(Control.Frame.Height - size2.Height - Control.DividerThickness);
break;
}
}
else if (PreferredSize != null)
{
var preferredSize = Orientation == Orientation.Horizontal ? PreferredSize.Value.Width : PreferredSize.Value.Height;
var size = Orientation == Orientation.Horizontal ? Size.Width : Size.Height;
switch (fixedPanel)
{
case SplitterFixedPanel.Panel2:
position = size - (preferredSize - position.Value);
break;
case SplitterFixedPanel.None:
if (preferredSize > 0)
position = position.Value * size / preferredSize;
break;
}
}
}
public override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
SetInitialSplitPosition();
Control.ResizeSubviewsWithOldSize(CGSize.Empty);
initialPositionSet = true;
}
public override void OnUnLoad(EventArgs e)
{
base.OnUnLoad(e);
initialPositionSet = false;
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
var size = new SizeF();
var size1 = panel1.GetPreferredSize(availableSize);
var size2 = panel2.GetPreferredSize(availableSize);
if (Control.IsVertical)
{
if (!double.IsNaN(relative))
{
switch (FixedPanel)
{
case SplitterFixedPanel.Panel1:
size1.Width = (float)Math.Round(relative);
break;
case SplitterFixedPanel.Panel2:
size2.Width = (float)Math.Round(relative);
break;
case SplitterFixedPanel.None:
size1.Width = (float)Math.Round(Math.Max(size1.Width/relative, size2.Width/(1-relative)));
size2.Width = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
else if (position != null)
{
switch (FixedPanel)
{
case SplitterFixedPanel.None:
case SplitterFixedPanel.Panel1:
size1.Width = Math.Max(size1.Width, position.Value);
break;
case SplitterFixedPanel.Panel2:
size2.Width = Math.Max(size2.Width, Size.Width - position.Value);
break;
}
}
if (position != null)
size1.Width = position.Value;
size.Width = (float)(size1.Width + size2.Width + Control.DividerThickness);
size.Height = Math.Max(size1.Height, size2.Height);
}
else
{
if (!double.IsNaN(relative))
{
switch (FixedPanel)
{
case SplitterFixedPanel.Panel1:
size1.Height = (float)Math.Round(relative);
break;
case SplitterFixedPanel.Panel2:
size2.Height = (float)Math.Round(relative);
break;
case SplitterFixedPanel.None:
size1.Height = (float)Math.Round(Math.Max(size1.Height/relative, size2.Height/(1-relative)));
size2.Height = 0;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (position != null)
{
switch (FixedPanel)
{
case SplitterFixedPanel.None:
case SplitterFixedPanel.Panel1:
size1.Height = Math.Max(size1.Height, position.Value);
break;
case SplitterFixedPanel.Panel2:
size2.Height = Math.Max(size2.Height, Size.Height - position.Value);
break;
}
}
if (position != null)
size1.Height = position.Value;
size.Height = (float)(size1.Height + size2.Height + Control.DividerThickness);
size.Width = Math.Max(size1.Width, size2.Width);
}
return size;
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Provides functionality to use static sprites (images) to your scenes.
/// </summary>
public class OTSprite : OTObject
{
//-----------------------------------------------------------------------------
// Editor settings
//-----------------------------------------------------------------------------
/// <exclude />
public bool _flipHorizontal = false;
/// <exclude />
public bool _flipVertical = false;
/// <exclude />
public bool _transparent = true;
/// <exclude />
public bool _additive = false;
/// <exclude />
public string _materialReference = "transparent";
/// <exclude />
public Color _tintColor = Color.white;
/// <exclude />
public float _alpha = 1.0f;
/// <exclude />
public Texture _image = null;
/// <exclude />
public int _frameIndex = 0;
/// <exclude />
public OTContainer _spriteContainer;
//-----------------------------------------------------------------------------
// public attributes (get/set)
//-----------------------------------------------------------------------------
/// <summary>
/// Flips sprite image horizontally
/// </summary>
public bool flipHorizontal
{
get
{
return _flipHorizontal;
}
set
{
_flipHorizontal = value;
meshDirty = true;
_flipHorizontal_ = _flipHorizontal;
Update();
}
}
/// <summary>
/// Flips sprite image verically
/// </summary>
public bool flipVertical
{
get
{
return _flipVertical;
}
set
{
_flipVertical = value;
meshDirty = true;
_flipVertical_ = _flipVertical;
Update();
}
}
/// <summary>
/// Sprite needs transparency support
/// </summary>
public bool transparent
{
get
{
return _transparent;
}
set
{
_transparent = value;
Clean();
}
}
/// <summary>
/// Sprite needs additive transparency support
/// </summary>
public bool additive
{
get
{
return _additive;
}
set
{
_additive = value;
Clean();
}
}
/// <summary>
/// Current texture of the sprite (image or spriteContainer)
/// </summary>
public Texture texture
{
get
{
if (spriteContainer != null)
return spriteContainer.GetTexture();
else
return image;
}
}
/// <summary>
/// Default image texture for this sprite.
/// </summary>
public Texture image
{
get
{
return _image;
}
set
{
_image = value;
Clean();
}
}
/// <summary>
/// Sprite Container that will provide image information for this sprite
/// </summary>
public OTContainer spriteContainer
{
get
{
return _spriteContainer;
}
set
{
_spriteContainer = value;
Clean();
}
}
/// <summary>
/// Index of the frame that is used to get image information from the Sprite Container
/// </summary>
public int frameIndex
{
get
{
return _frameIndex;
}
set
{
_frameIndex = value;
Clean();
}
}
/// <exclude />
public Material material
{
get
{
if (Application.isPlaying)
return renderer.material;
else
return renderer.sharedMaterial;
}
set
{
assignedMaterial = true;
if (Application.isPlaying)
renderer.material = value;
else
renderer.sharedMaterial = value;
}
}
/// <summary>
/// Reference name of material for this sprite
/// </summary>
public string materialReference
{
get
{
return _materialReference;
}
set
{
_materialReference = value;
Clean();
}
}
/// <summary>
/// Tinting color of this sprite.
/// </summary>
/// <remarks>
/// This setting will only work if this sprite's materialReference can work with color tinting.
/// </remarks>
public Color tintColor
{
get
{
return _tintColor;
}
set
{
_tintColor = value;
Clean();
}
}
/// <summary>
/// Alpha channel for this sprite.
/// </summary>
/// <remarks>
/// This setting will only work if this sprite's materialReference can work with alpha channels/color.
/// </remarks>
public float alpha
{
get
{
return _alpha;
}
set
{
_alpha = value;
Clean();
}
}
[HideInInspector]
/// <exclude />
public string _containerName = "";
//-----------------------------------------------------------------------------
// protected and private fields
//-----------------------------------------------------------------------------
OTContainer _spriteContainer_ = null;
int _frameIndex_ = 0;
bool _flipHorizontal_ = false;
bool _flipVertical_ = false;
Texture _image_ = null;
bool _transparent_ = true;
Color _tintColor_ = Color.white;
float _alpha_ = 1;
bool _additive_ = false;
string _materialReference_ = "transparent";
string lastMatName = "";
Material lastMat = null;
OTMatRef mr;
bool assignedMaterial = false;
bool spriteInvalid = false;
/// <exclude />
protected bool useUV = true;
//-----------------------------------------------------------------------------
// public methods
//-----------------------------------------------------------------------------
/// <summary>
/// Retrieve frame data of the sprite's current frame. This data will include the
/// texture scale, texture offset and uv coordinates that are needed to get the
/// current frame's image.
/// </summary>
/// <returns>frame data of sprite's current frame</returns>
public OTContainer.Frame CurrentFrame()
{
if (spriteContainer != null && spriteContainer.isReady)
return spriteContainer.GetFrame(frameIndex);
else
{
if (spriteContainer == null)
throw new System.Exception("No Sprite Container available [" + name + "]");
else
throw new System.Exception("Sprite Container not ready [" + name + "]");
}
}
/// <exclude />
public override void StartUp()
{
isDirty = true;
Material mat = LookupMaterial();
if (mat != null)
{
renderer.material = mat;
HandleUV(mat);
}
base.StartUp();
}
/// <exclude />
public override void Assign(OTObject protoType)
{
base.Assign(protoType);
OTSprite pSprite = protoType as OTSprite;
tintColor = pSprite.tintColor;
alpha = pSprite.alpha;
image = pSprite.image;
spriteContainer = pSprite.spriteContainer;
frameIndex = pSprite.frameIndex;
materialReference = pSprite.materialReference;
}
//-----------------------------------------------------------------------------
// overridden subclass methods
//-----------------------------------------------------------------------------
/// <exclude />
protected override Mesh GetMesh()
{
Mesh mesh = new Mesh();
Vector2 _meshsize_ = Vector2.one;
if (objectParent)
{
_meshsize_ = size;
_pivotPoint = Vector2.Scale(_pivotPoint, size);
}
else
{
_meshsize_ = Vector2.one;
_pivotPoint = pivotPoint;
}
mesh.vertices = new Vector3[] {
new Vector3(((_meshsize_.x/2) * -1) - _pivotPoint.x, (_meshsize_.y/2) - _pivotPoint.y, 0),
new Vector3((_meshsize_.x/2) - _pivotPoint.x, (_meshsize_.y/2)- _pivotPoint.y, 0),
new Vector3((_meshsize_.x/2) - _pivotPoint.x, ((_meshsize_.y/2) * -1) - _pivotPoint.y, 0),
new Vector3(((_meshsize_.x/2) * -1) - _pivotPoint.x, ((_meshsize_.y/2) * -1) - _pivotPoint.y, 0)
};
mesh.triangles = new int[] {
0,1,2,2,3,0
};
Vector2[] meshUV = new Vector2[] {
new Vector2(0,1), new Vector2(1,1),
new Vector2(1,0), new Vector2(0,0) };
if (flipHorizontal)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[1]; meshUV[1] = v;
v = meshUV[2];
meshUV[2] = meshUV[3]; meshUV[3] = v;
}
if (flipVertical)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[3]; meshUV[3] = v;
v = meshUV[1];
meshUV[1] = meshUV[2]; meshUV[2] = v;
}
mesh.uv = meshUV;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
return mesh;
}
/// <exclude />
protected override string GetTypeName()
{
return "Sprite";
}
/// <exclude />
protected override void AfterMesh()
{
base.AfterMesh();
// reset size because mesh has been created with a size (x/y) of 1/1
size = _size;
_frameIndex_ = -1;
isDirty = true;
}
/// <exclude />
public virtual string GetMatName()
{
string matName = "";
if (spriteContainer != null)
{
if (!useUV)
matName += "spc:" + spriteContainer.name + ":" + frameIndex + ":" + materialReference;
else
matName += "spc:" + spriteContainer.name + ":" + materialReference;
}
else
if (image != null)
matName += "img:" + _image.GetInstanceID() + " : " +
materialReference;
if (matName == "") matName = materialReference;
if (mr != null)
{
if (mr.fieldColorTint != "")
matName += " : " + tintColor.ToString();
if (mr.fieldAlphaChannel != "" || mr.fieldAlphaColor != "")
matName += " : " + alpha;
}
lastMatName = matName;
return matName;
}
Material LookupMaterial()
{
return OT.LookupMaterial(GetMatName());
}
void RegisterMaterial()
{
OT.RegisterMaterial(GetMatName(), material);
}
private void SetMatReference()
{
if (transparent)
_materialReference = "transparent";
else
if (additive)
_materialReference = "additive";
else
if (_materialReference == "additive" || _materialReference == "transparent" || _materialReference == "")
_materialReference = "solid";
}
/// <exclude />
override protected void CheckDirty()
{
base.CheckDirty();
if (spriteContainer != null)
{
if (spriteContainer.isReady)
{
if (_spriteContainer_ != spriteContainer || _frameIndex_ != frameIndex)
isDirty = true;
}
}
else
if (_spriteContainer_ != null || image != _image_)
isDirty = true;
if (flipHorizontal != _flipHorizontal_ || flipVertical != _flipVertical_)
{
_flipHorizontal_ = flipHorizontal;
_flipVertical_ = flipVertical;
meshDirty = true;
}
if (!Application.isPlaying)
{
if (!isDirty && spriteContainer != null && material.mainTexture != spriteContainer.GetTexture())
isDirty = true;
}
if (transparent != _transparent_ && transparent)
{
_additive = false;
_additive_ = additive;
_transparent_ = transparent;
SetMatReference();
}
else
if (additive != _additive_ && additive)
{
_transparent = false;
_additive_ = additive;
_transparent_ = transparent;
SetMatReference();
}
else
if (!_additive && !_transparent)
{
_additive_ = additive;
_transparent_ = transparent;
if (_materialReference == "transparent" || _materialReference == "additive")
_materialReference = "solid";
}
if (materialReference != _materialReference_)
{
mr = OT.GetMatRef(materialReference);
if (_materialReference == "transparent")
{
_transparent = true;
_additive = false;
}
else
if (_materialReference == "additive")
{
_transparent = false;
_additive = true;
}
else
{
_transparent = false;
_additive = false;
}
isDirty = true;
}
if (mr != null)
{
if (_tintColor_ != tintColor)
{
if (mr.fieldColorTint != "")
isDirty = true;
else
{
_tintColor = Color.white;
_tintColor_ = _tintColor;
Debug.LogWarning("Orthello : TintColor can not be set on this materialReference!");
}
}
if (_alpha_ != alpha)
{
if (mr.fieldAlphaColor != "" || mr.fieldAlphaChannel != "")
isDirty = true;
else
{
_alpha = 1;
_alpha_ = 1;
Debug.LogWarning("Orthello : Alpha value can not be set on this materialReference!");
}
}
}
}
void HandleUV(Material mat)
{
if (useUV && spriteContainer != null && spriteContainer.isReady)
{
OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex);
mat.mainTextureScale = new Vector2(1, 1);
mat.mainTextureOffset = new Vector2(0, 0);
// adjust this sprites UV coords
if (frame.uv != null && mesh != null)
{
Vector2[] meshUV = frame.uv.Clone() as Vector2[];
if (flipHorizontal)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[1]; meshUV[1] = v;
v = meshUV[2];
meshUV[2] = meshUV[3]; meshUV[3] = v;
}
if (flipVertical)
{
Vector2 v;
v = meshUV[0];
meshUV[0] = meshUV[3]; meshUV[3] = v;
v = meshUV[1];
meshUV[1] = meshUV[2]; meshUV[2] = v;
}
mesh.uv = meshUV;
}
}
}
/// <exclude />
protected virtual Material InitMaterial()
{
if (spriteContainer != null && !spriteContainer.isReady)
{
lastMat = material;
assignedMaterial = false;
RegisterMaterial();
return lastMat;
}
Material spMat = OT.GetMaterial(_materialReference, tintColor, alpha);
if (spMat == null) spMat = OT.materialTransparent;
if (spMat == null) return null;
Material mat = new Material(spMat);
if (spriteContainer != null && spriteContainer.isReady)
{
Texture tex = spriteContainer.GetTexture();
if (mat.mainTexture != tex)
mat.mainTexture = tex;
HandleUV(mat);
}
else
if (image != null)
{
if (mat != null)
{
mat.mainTexture = image;
mat.mainTextureScale = Vector2.one;
mat.mainTextureOffset = Vector3.zero;
}
}
if (mat != null)
{
if (lastMatName != "" && lastMat != null)
OT.MatDec(lastMat, lastMatName);
if (lastMat == null && !assignedMaterial)
{
if (!isCopy)
{
if (!Application.isPlaying)
DestroyImmediate(renderer.sharedMaterial, true);
else
Destroy(renderer.material);
}
}
if (Application.isPlaying)
renderer.material = mat;
else
renderer.sharedMaterial = mat;
lastMat = mat;
assignedMaterial = false;
RegisterMaterial();
}
return mat;
}
/// <exclude />
[HideInInspector]
protected override void Clean()
{
if (!OT.isValid) return;
base.Clean();
if (_spriteContainer_ != spriteContainer ||
_frameIndex_ != frameIndex ||
_image_ != image ||
_tintColor_ != tintColor ||
_alpha_ != alpha ||
_materialReference_ != _materialReference ||
isCopy)
{
if (spriteContainer != null && spriteContainer.isReady)
{
if (frameIndex < 0) _frameIndex = 0;
if (frameIndex > spriteContainer.frameCount - 1) _frameIndex = spriteContainer.frameCount - 1;
if (spriteContainer is OTSpriteAtlas)
{
OTContainer.Frame fr = CurrentFrame();
if ((spriteContainer as OTSpriteAtlas).offsetSizing)
{
if (Vector2.Equals(oSize, Vector2.zero))
{
oSize = fr.size * OT.view.sizeFactor;
Vector2 nOffset = fr.offset * OT.view.sizeFactor;
if (_baseOffset.x != nOffset.x || _baseOffset.y != nOffset.y)
{
offset = nOffset;
position = _position;
imageSize = fr.imageSize * OT.view.sizeFactor;
}
}
if (_frameIndex_ != frameIndex || _spriteContainer_ != spriteContainer)
{
Vector2 sc = new Vector2((size.x / oSize.x) * fr.size.x * OT.view.sizeFactor, (size.y / oSize.y) * fr.size.y * OT.view.sizeFactor);
Vector3 sc3 = new Vector3(sc.x, sc.y, 1);
_size = sc;
if (!Vector3.Equals(transform.localScale, sc3))
transform.localScale = sc3;
oSize = fr.size * OT.view.sizeFactor;
imageSize = fr.imageSize * OT.view.sizeFactor;
Vector2 nOffset = fr.offset * OT.view.sizeFactor;
if (_baseOffset.x != nOffset.x || _baseOffset.y != nOffset.y)
{
offset = nOffset;
position = _position;
}
}
}
else
{
Vector3[] verts = fr.vertices.Clone() as Vector3[];
verts[0] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[1] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[2] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
verts[3] -= new Vector3(pivotPoint.x, pivotPoint.y, 0);
mesh.vertices = verts;
_size = fr.size;
Vector3 sc3 = new Vector3(_size.x, _size.y, 1);
if (!Vector3.Equals(transform.localScale, sc3))
transform.localScale = sc3;
}
}
}
Material mat = LookupMaterial();
if (mat == null)
{
mat = InitMaterial();
}
else
{
renderer.material = mat;
HandleUV(mat);
}
OT.MatInc(mat);
_spriteContainer_ = spriteContainer;
_materialReference_ = materialReference;
_frameIndex_ = frameIndex;
_image_ = image;
_tintColor_ = tintColor;
_alpha_ = alpha;
}
isDirty = false;
if (spriteContainer != null && !spriteContainer.isReady)
isDirty = true;
}
/// <exclude />
new protected void OnDestroy()
{
if (lastMatName != "" && lastMat != null)
OT.MatDec(lastMat, lastMatName);
else
DestroyImmediate(material);
base.OnDestroy();
}
/// <exclude />
protected Vector2 baseSize = Vector2.zero;
bool frameReloaded = false;
/// <exclude />
override protected void CheckSettings()
{
base.CheckSettings();
if (Application.isEditor || OT.dirtyChecks || dirtyChecks)
{
if (spriteContainer != null && spriteContainer.isReady)
{
_containerName = spriteContainer.name;
if (spriteContainer is OTSpriteAtlasImport && (spriteContainer as OTSpriteAtlasImport).reloadFrame && !frameReloaded)
{
_frameIndex_ = -1;
frameReloaded = true;
}
if (frameIndex < 0) _frameIndex = 0;
if (frameIndex > spriteContainer.frameCount - 1) _frameIndex = spriteContainer.frameCount - 1;
OTContainer.Frame fr = CurrentFrame();
if (_spriteContainer_ == null && _containerName != "")
{
// set basesize to current frame size if we just had a lookup from a prefab
baseSize = fr.size;
}
if (_spriteContainer_ != spriteContainer)
{
if (!baseSize.Equals(Vector2.zero))
size = new Vector2 (size.x * (fr.size.x / baseSize.x) , size.y * (fr.size.y / baseSize.y) ) * OT.view.sizeFactor;
else
size = fr.size * OT.view.sizeFactor;
}
baseSize = fr.size;
}
else
{
if (_image_ != image)
size = new Vector2(image.width, image.height) * OT.view.sizeFactor;
}
if (alpha < 0) _alpha = 0;
else
if (alpha > 1) _alpha = 1;
}
}
//-----------------------------------------------------------------------------
// class methods
//-----------------------------------------------------------------------------
// Use this for initialization
/// <exclude />
protected override void Awake()
{
_spriteContainer_ = spriteContainer;
_frameIndex_ = frameIndex;
_image_ = image;
_materialReference_ = materialReference;
_transparent_ = transparent;
_flipHorizontal_ = flipHorizontal;
_flipVertical_ = flipVertical;
_tintColor_ = _tintColor;
_alpha_ = _alpha;
isDirty = true;
base.Awake();
}
/// <exclude />
protected override void Start()
{
base.Start();
mr = OT.GetMatRef(materialReference);
if (Application.isPlaying)
{
if (!assignedMaterial)
{
Material mat = LookupMaterial();
if (mat != null)
{
renderer.material = mat;
HandleUV(mat);
}
else
mat = InitMaterial();
OT.MatInc(mat);
}
}
else
{
Material mat = InitMaterial();
OT.MatInc(mat);
}
if (Application.isPlaying)
_frameIndex_ = -1;
}
/// <exclude />
public void InvalidateSprite()
{
spriteInvalid = true;
renderer.enabled = false;
}
bool SpriteValid()
{
if (spriteInvalid)
{
if (!Application.isPlaying || image != null || (spriteContainer!=null && spriteContainer.isReady))
{
spriteInvalid = false;
renderer.enabled = true;
return true;
}
return false;
}
return true;
}
// Update is called once per frame
/// <exclude />
protected override void Update()
{
if (!OT.isValid) return;
SpriteValid();
if (image == null && spriteContainer == null)
{
if (_containerName!="")
{
OTContainer c = OT.ContainerByName(_containerName);
if (c!=null && c.isReady)
spriteContainer = c;
}
}
// check if no material has been assigned yet
if (!Application.isPlaying)
{
Material mat = material;
if (mat == null)
{
mat = new Material(OT.materialTransparent);
material = mat;
mat.mainTexture = texture;
}
}
base.Update();
}
}
| |
using NetSparkleUpdater.Configurations;
using NetSparkleUpdater.Enums;
using NetSparkleUpdater.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml.Linq;
namespace NetSparkleUpdater.AppCastHandlers
{
/// <summary>
/// An XML-based appcast document downloader and handler
/// </summary>
public class XMLAppCast : IAppCastHandler
{
private Configuration _config;
private string _castUrl;
private ISignatureVerifier _signatureVerifier;
private ILogger _logWriter;
private IAppCastDataDownloader _dataDownloader;
/// <summary>
/// Sparkle XML namespace
/// </summary>
public static readonly XNamespace SparkleNamespace = "http://www.andymatuschak.org/xml-namespaces/sparkle";
/// <summary>
/// App cast title (usually the name of the application)
/// </summary>
public string Title { get; set; }
/// <summary>
/// App cast language (e.g. "en")
/// </summary>
public string Language { get; set; }
/// <summary>
/// Extension (WITHOUT the "." at the start) for the signature
/// file. Defaults to "signature".
/// </summary>
public string SignatureFileExtension { get; set; }
/// <summary>
/// List of <seealso cref="AppCastItem"/> that were parsed in the app cast
/// </summary>
public readonly List<AppCastItem> Items;
/// <summary>
/// Create a new object with an empty list of <seealso cref="AppCastItem"/> items
/// </summary>
public XMLAppCast()
{
Items = new List<AppCastItem>();
SignatureFileExtension = "signature";
}
/// <summary>
/// Setup the app cast handler info for downloading and parsing app cast information
/// </summary>
/// <param name="dataDownloader">downloader that will manage the app cast download
/// (provided by <see cref="SparkleUpdater"/> via the
/// <see cref="SparkleUpdater.AppCastDataDownloader"/> property.</param>
/// <param name="castUrl">full URL to the app cast file</param>
/// <param name="config">configuration for handling update intervals/checks
/// (user skipped versions, etc.)</param>
/// <param name="signatureVerifier">Object to check signatures of app cast information</param>
/// <param name="logWriter">object that you can utilize to do any necessary logging</param>
public void SetupAppCastHandler(IAppCastDataDownloader dataDownloader, string castUrl, Configuration config, ISignatureVerifier signatureVerifier, ILogger logWriter = null)
{
_dataDownloader = dataDownloader;
_config = config;
_castUrl = castUrl;
_signatureVerifier = signatureVerifier;
_logWriter = logWriter ?? new LogWriter();
}
/// <summary>
/// Download castUrl resource and parse it
/// </summary>
public bool DownloadAndParse()
{
try
{
_logWriter.PrintMessage("Downloading app cast data...");
var appcast = _dataDownloader.DownloadAndGetAppCastData(_castUrl);
var signatureNeeded = Utilities.IsSignatureNeeded(_signatureVerifier.SecurityMode, _signatureVerifier.HasValidKeyInformation(), false);
bool isValidAppcast = true;
if (signatureNeeded)
{
_logWriter.PrintMessage("Downloading app cast signature data...");
var signature = "";
var extension = SignatureFileExtension?.TrimStart('.') ?? "signature";
try
{
signature = _dataDownloader.DownloadAndGetAppCastData(_castUrl + "." + extension);
}
catch (Exception e)
{
_logWriter.PrintMessage("Error reading app cast {0}.{2}: {1} ", _castUrl, e.Message, extension);
}
if (string.IsNullOrWhiteSpace(signature))
{
// legacy: check for .dsa file
try
{
signature = _dataDownloader.DownloadAndGetAppCastData(_castUrl + ".dsa");
}
catch (Exception e)
{
_logWriter.PrintMessage("Error reading app cast {0}.dsa: {1} ", _castUrl, e.Message);
}
}
isValidAppcast = VerifyAppCast(appcast, signature);
}
if (isValidAppcast)
{
_logWriter.PrintMessage("Appcast is valid! Parsing...");
ParseAppCast(appcast);
return true;
}
}
catch (Exception e)
{
_logWriter.PrintMessage("Error reading app cast {0}: {1} ", _castUrl, e.Message);
}
_logWriter.PrintMessage("Appcast is not valid");
return false;
}
private bool VerifyAppCast(string appCast, string signature)
{
if (string.IsNullOrWhiteSpace(appCast))
{
_logWriter.PrintMessage("Cannot read response from URL {0}", _castUrl);
return false;
}
// checking signature
var signatureNeeded = Utilities.IsSignatureNeeded(_signatureVerifier.SecurityMode, _signatureVerifier.HasValidKeyInformation(), false);
var appcastBytes = _dataDownloader.GetAppCastEncoding().GetBytes(appCast);
if (signatureNeeded && _signatureVerifier.VerifySignature(signature, appcastBytes) == ValidationResult.Invalid)
{
_logWriter.PrintMessage("Signature check of appcast failed");
return false;
}
return true;
}
/// <summary>
/// Parse the app cast XML string into a list of <see cref="AppCastItem"/> objects.
/// When complete, the Items list should contain the parsed information
/// as <see cref="AppCastItem"/> objects.
/// </summary>
/// <param name="appCast">the non-null string XML app cast</param>
protected virtual void ParseAppCast(string appCast)
{
const string itemNode = "item";
Items.Clear();
XDocument doc = XDocument.Parse(appCast);
var rss = doc?.Element("rss");
var channel = rss?.Element("channel");
Title = channel?.Element("title")?.Value ?? string.Empty;
Language = channel?.Element("language")?.Value ?? "en";
var items = doc.Descendants(itemNode);
foreach (var item in items)
{
var currentItem = AppCastItem.Parse(_config.InstalledVersion, _config.ApplicationName, _castUrl, item, _logWriter);
_logWriter.PrintMessage("Found an item in the app cast: version {0} ({1}) -- os = {2}",
currentItem?.Version, currentItem?.ShortVersion, currentItem.OperatingSystemString);
Items.Add(currentItem);
}
// sort versions in reverse order
Items.Sort((item1, item2) => -1 * item1.CompareTo(item2));
}
/// <summary>
/// Returns sorted list of updates between current installed version and latest version in <see cref="Items"/>.
/// Currently installed version is NOT included in the output.
/// </summary>
/// <returns>A list of <seealso cref="AppCastItem"/> updates that could be installed</returns>
public virtual List<AppCastItem> GetAvailableUpdates()
{
Version installed = new Version(_config.InstalledVersion);
var signatureNeeded = Utilities.IsSignatureNeeded(_signatureVerifier.SecurityMode, _signatureVerifier.HasValidKeyInformation(), false);
_logWriter.PrintMessage("Looking for available updates; our installed version is {0}; do we need a signature? {1}", installed, signatureNeeded);
return Items.Where((item) =>
{
#if NETFRAMEWORK
// don't allow non-windows updates
if (!item.IsWindowsUpdate)
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it isn't a Windows update and we're on Windows", item.Version,
item.ShortVersion, item.Title);
return false;
}
#else
// check operating system and filter out ones that don't match the current
// operating system
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !item.IsWindowsUpdate)
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it isn't a Windows update and we're on Windows", item.Version,
item.ShortVersion, item.Title);
return false;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && !item.IsMacOSUpdate)
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it isn't a macOS update and we're on macOS", item.Version,
item.ShortVersion, item.Title);
return false;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !item.IsLinuxUpdate)
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it isn't a Linux update and we're on Linux", item.Version,
item.ShortVersion, item.Title);
return false;
}
#endif
// filter smaller versions
if (new Version(item.Version).CompareTo(installed) <= 0)
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it is older than our current version of {3}", item.Version,
item.ShortVersion, item.Title, installed);
return false;
}
// filter versions without signature if we need signatures. But accept version without downloads.
if (signatureNeeded && string.IsNullOrEmpty(item.DownloadSignature) && !string.IsNullOrEmpty(item.DownloadLink))
{
_logWriter.PrintMessage("Rejecting update for {0} ({1}, {2}) because it we needed a DSA/other signature and " +
"the item has no signature yet has a download link of {3}", item.Version,
item.ShortVersion, item.Title, item.DownloadLink);
return false;
}
// accept everything else
_logWriter.PrintMessage("Item with version {0} ({1}) is a valid update! It can be downloaded at {2}", item.Version,
item.ShortVersion, item.DownloadLink);
return true;
}).ToList();
}
/// <summary>
/// Create app cast XML document as an <seealso cref="XDocument"/> object
/// </summary>
/// <param name="items">The <seealso cref="AppCastItem"/> list to include in the output file</param>
/// <param name="title">Application title/title for the app cast</param>
/// <param name="link">Link to the where the app cast is going to be downloaded</param>
/// <param name="description">Text that describes the app cast (e.g. what it provides)</param>
/// <param name="language">Language of the app cast file</param>
/// <returns>An <seealso cref="XDocument"/> xml document that describes the list of passed in update items</returns>
public static XDocument GenerateAppCastXml(List<AppCastItem> items, string title, string link = "", string description = "", string language = "en")
{
var channel = new XElement("channel");
channel.Add(new XElement("title", title));
if (!string.IsNullOrEmpty(link))
{
channel.Add(new XElement("link", link));
}
if (!string.IsNullOrEmpty(description))
{
channel.Add(new XElement("description", description));
}
channel.Add(new XElement("language", language));
foreach (var item in items)
{
channel.Add(item.GetXElement());
}
var document = new XDocument(
new XElement("rss", new XAttribute("version", "2.0"), new XAttribute(XNamespace.Xmlns + "sparkle", SparkleNamespace),
channel)
);
return document;
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 575902 $
* $LastChangedDate: 2007-09-15 04:40:19 -0600 (Sat, 15 Sep 2007) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Xml.Serialization;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities;
using IBatisNet.Common.Utilities.Objects;
using IBatisNet.Common.Utilities.Objects.Members;
using IBatisNet.DataMapper.Scope;
using IBatisNet.DataMapper.TypeHandlers;
#endregion
namespace IBatisNet.DataMapper.Configuration.ParameterMapping
{
/// <summary>
/// Summary description for ParameterProperty.
/// </summary>
[Serializable]
[XmlRoot("parameter", Namespace="http://ibatis.apache.org/mapping")]
public class ParameterProperty
{
#region Fields
[NonSerialized]
private string _nullValue = null;//string.Empty;//null;
[NonSerialized]
private string _propertyName = string.Empty;
[NonSerialized]
private ParameterDirection _direction = ParameterDirection.Input;
[NonSerialized]
private string _directionAttribute = string.Empty;
[NonSerialized]
private string _dbType = null;
[NonSerialized]
private int _size = -1;
[NonSerialized]
private byte _scale= 0;
[NonSerialized]
private byte _precision = 0;
[NonSerialized]
private string _columnName = string.Empty; // used only for store procedure
[NonSerialized]
private ITypeHandler _typeHandler = null;
[NonSerialized]
private string _clrType = string.Empty;
[NonSerialized]
private string _callBackName= string.Empty;
[NonSerialized]
private IGetAccessor _getAccessor = null;
[NonSerialized]
private bool _isComplexMemberName = false;
#endregion
#region Properties
/// <summary>
/// Indicate if we have a complex member name as [avouriteLineItem.Id]
/// </summary>
public bool IsComplexMemberName
{
get { return _isComplexMemberName; }
}
/// <summary>
/// Specify the custom type handlers to used.
/// </summary>
/// <remarks>Will be an alias to a class wchic implement ITypeHandlerCallback</remarks>
[XmlAttribute("typeHandler")]
public string CallBackName
{
get { return _callBackName; }
set { _callBackName = value; }
}
/// <summary>
/// Specify the CLR type of the parameter.
/// </summary>
/// <remarks>
/// The type attribute is used to explicitly specify the property type to be read.
/// Normally this can be derived from a property through reflection, but certain mappings such as
/// HashTable cannot provide the type to the framework.
/// </remarks>
[XmlAttribute("type")]
public string CLRType
{
get { return _clrType; }
set { _clrType = value; }
}
/// <summary>
/// The typeHandler used to work with the parameter.
/// </summary>
[XmlIgnore]
public ITypeHandler TypeHandler
{
get { return _typeHandler; }
set { _typeHandler = value; }
}
/// <summary>
/// Column Name for output parameter
/// in store proccedure.
/// </summary>
[XmlAttribute("column")]
public string ColumnName
{
get { return _columnName; }
set { _columnName = value; }
}
/// <summary>
/// Column size.
/// </summary>
[XmlAttribute("size")]
public int Size
{
get { return _size; }
set { _size = value; }
}
/// <summary>
/// Column Scale.
/// </summary>
[XmlAttribute("scale")]
public byte Scale
{
get { return _scale; }
set { _scale = value; }
}
/// <summary>
/// Column Precision.
/// </summary>
[XmlAttribute("precision")]
public byte Precision
{
get { return _precision; }
set { _precision = value; }
}
/// <summary>
/// Give an entry in the 'DbType' enumeration
/// </summary>
/// <example >
/// For Sql Server, give an entry of SqlDbType : Bit, Decimal, Money...
/// <br/>
/// For Oracle, give an OracleType Enumeration : Byte, Int16, Number...
/// </example>
[XmlAttribute("dbType")]
public string DbType
{
get { return _dbType; }
set { _dbType = value; }
}
/// <summary>
/// The direction attribute of the XML parameter.
/// </summary>
/// <example> Input, Output, InputOutput</example>
[XmlAttribute("direction")]
public string DirectionAttribute
{
get { return _directionAttribute; }
set { _directionAttribute = value; }
}
/// <summary>
/// Indicate the direction of the parameter.
/// </summary>
/// <example> Input, Output, InputOutput</example>
[XmlIgnore]
public ParameterDirection Direction
{
get { return _direction; }
set
{
_direction = value;
_directionAttribute = _direction.ToString();
}
}
/// <summary>
/// Property name used to identify the property amongst the others.
/// </summary>
/// <example>EmailAddress</example>
[XmlAttribute("property")]
public string PropertyName
{
get { return _propertyName; }
set
{
if ((value == null) || (value.Length < 1))
throw new ArgumentNullException("The property attribute is mandatory in a paremeter property.");
_propertyName = value;
if (_propertyName.IndexOf('.')<0)
{
_isComplexMemberName = false;
}
else // complex member name FavouriteLineItem.Id
{
_isComplexMemberName = true;
}
}
}
/// <summary>
/// Tell if a nullValue is defined._nullValue!=null
/// </summary>
[XmlIgnore]
public bool HasNullValue
{
get { return (_nullValue!=null); }
}
/// <summary>
/// Null value replacement.
/// </summary>
/// <example>"no_email@provided.com"</example>
[XmlAttribute("nullValue")]
public string NullValue
{
get { return _nullValue; }
set { _nullValue = value; }
}
/// <summary>
/// Defines a field/property get accessor
/// </summary>
[XmlIgnore]
public IGetAccessor GetAccessor
{
get { return _getAccessor; }
}
#endregion
#region Methods
/// <summary>
/// Initializes the parameter property
/// </summary>
/// <param name="scope">The scope.</param>
/// <param name="parameterClass">The parameter class.</param>
public void Initialize(IScope scope, Type parameterClass)
{
if(_directionAttribute.Length >0)
{
_direction = (ParameterDirection)Enum.Parse( typeof(ParameterDirection), _directionAttribute, true );
}
if (!typeof(IDictionary).IsAssignableFrom(parameterClass) // Hashtable parameter map
&& parameterClass !=null // value property
&& !scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(parameterClass) ) // value property
{
if (!_isComplexMemberName)
{
IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory;
_getAccessor = getAccessorFactory.CreateGetAccessor(parameterClass, _propertyName);
}
else // complex member name FavouriteLineItem.Id
{
string memberName = _propertyName.Substring( _propertyName.LastIndexOf('.')+1);
string parentName = _propertyName.Substring(0,_propertyName.LastIndexOf('.'));
Type parentType = ObjectProbe.GetMemberTypeForGetter(parameterClass, parentName);
IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory;
_getAccessor = getAccessorFactory.CreateGetAccessor(parentType, memberName);
}
}
scope.ErrorContext.MoreInfo = "Check the parameter mapping typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation).";
if (this.CallBackName.Length >0)
{
try
{
Type type = scope.DataExchangeFactory.TypeHandlerFactory.GetType(this.CallBackName);
ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback) Activator.CreateInstance( type );
_typeHandler = new CustomTypeHandler(typeHandlerCallback);
}
catch (Exception e)
{
throw new ConfigurationException("Error occurred during custom type handler configuration. Cause: " + e.Message, e);
}
}
else
{
if (this.CLRType.Length == 0 ) // Unknown
{
if (_getAccessor!= null &&
scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(_getAccessor.MemberType))
{
// Primitive
_typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(_getAccessor.MemberType, _dbType);
}
else
{
_typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
}
}
else // If we specify a CLR type, use it
{
Type type = TypeUtils.ResolveType(this.CLRType);
if (scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(type))
{
// Primitive
_typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType);
}
else
{
// .NET object
type = ObjectProbe.GetMemberTypeForGetter(type, this.PropertyName);
_typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType);
}
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"></see> is equal to the current <see cref="System.Object"></see>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"></see> to compare with the current <see cref="System.Object"></see>.</param>
/// <returns>
/// true if the specified <see cref="System.Object"></see> is equal to the current <see cref="System.Object"></see>; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
//Check for null and compare run-time types.
if (obj == null || GetType() != obj.GetType()) return false;
ParameterProperty p = (ParameterProperty)obj;
return (this.PropertyName == p.PropertyName);
}
/// <summary>
/// Serves as a hash function for a particular type. <see cref="System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="System.Object"></see>.
/// </returns>
public override int GetHashCode()
{
return _propertyName.GetHashCode();
}
#endregion
#region ICloneable Members
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns>An <see cref="ParameterProperty"/></returns>
public ParameterProperty Clone()
{
ParameterProperty property = new ParameterProperty();
property.CallBackName = this.CallBackName;
property.CLRType = this.CLRType;
property.ColumnName = this.ColumnName;
property.DbType = this.DbType;
property.DirectionAttribute = this.DirectionAttribute;
property.NullValue = this.NullValue;
property.PropertyName = this.PropertyName;
property.Precision = this.Precision;
property.Scale = this.Scale;
property.Size = this.Size;
return property;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Xunit;
#if false
namespace Roslyn.Services.Editor.UnitTests.CodeGeneration
{
public class ExpressionGenerationTests : AbstractCodeGenerationTests
{
[WpfFact]
public void TestFalseExpression()
{
TestExpression(
f => f.CreateFalseExpression(),
cs: "false",
vb: "False");
}
[WpfFact]
public void TestTrueExpression()
{
TestExpression(
f => f.CreateTrueExpression(),
cs: "true",
vb: "True");
}
[WpfFact]
public void TestNullExpression()
{
TestExpression(
f => f.CreateNullExpression(),
cs: "null",
vb: "Nothing");
}
[WpfFact]
public void TestThisExpression()
{
TestExpression(
f => f.CreateThisExpression(),
cs: "this",
vb: "Me");
}
[WpfFact]
public void TestBaseExpression()
{
TestExpression(
f => f.CreateBaseExpression(),
cs: "base",
vb: "MyBase");
}
[WpfFact]
public void TestInt32ConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0),
cs: "0",
vb: "0");
}
[WpfFact]
public void TestInt32ConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(1),
cs: "1",
vb: "1");
}
[WpfFact]
public void TestInt64ConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0L),
cs: "0L",
vb: "0&");
}
[WpfFact]
public void TestInt64ConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(1L),
cs: "1L",
vb: "1&");
}
[WpfFact]
public void TestSingleConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0.0f),
cs: "0F",
vb: "0!");
}
[WpfFact]
public void TestSingleConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(0.5F),
cs: "0.5F",
vb: "0.5!");
}
[WpfFact]
public void TestDoubleConstantExpression0()
{
TestExpression(
f => f.CreateConstantExpression(0.0d),
cs: "0",
vb: "0");
}
[WpfFact]
public void TestDoubleConstantExpression1()
{
TestExpression(
f => f.CreateConstantExpression(0.5D),
cs: "0.5",
vb: "0.5");
}
[WpfFact]
public void TestAddExpression1()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 + 2",
vb: "1 + 2");
}
[WpfFact]
public void TestAddExpression2()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateAddExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 + 2 + 3",
vb: "1 + 2 + 3");
}
[WpfFact]
public void TestAddExpression3()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 + 2 + 3",
vb: "1 + 2 + 3");
}
[WpfFact]
public void TestMultiplyExpression1()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 * 2",
vb: "1 * 2");
}
[WpfFact]
public void TestMultiplyExpression2()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateMultiplyExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 * 2 * 3",
vb: "1 * 2 * 3");
}
[WpfFact]
public void TestMultiplyExpression3()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 * 2 * 3",
vb: "1 * 2 * 3");
}
[WpfFact]
public void TestBinaryAndExpression1()
{
TestExpression(
f => f.CreateBinaryAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 & 2",
vb: "1 And 2");
}
[WpfFact]
public void TestBinaryOrExpression1()
{
TestExpression(
f => f.CreateBinaryOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 | 2",
vb: "1 Or 2");
}
[WpfFact]
public void TestLogicalAndExpression1()
{
TestExpression(
f => f.CreateLogicalAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 && 2",
vb: "1 AndAlso 2");
}
[WpfFact]
public void TestLogicalOrExpression1()
{
TestExpression(
f => f.CreateLogicalOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
cs: "1 || 2",
vb: "1 OrElse 2");
}
[WpfFact]
public void TestMemberAccess1()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateIdentifierName("E"),
f.CreateIdentifierName("M")),
cs: "E.M",
vb: "E.M");
}
[WpfFact]
public void TestConditionalExpression1()
{
TestExpression(
f => f.CreateConditionalExpression(
f.CreateIdentifierName("E"),
f.CreateIdentifierName("T"),
f.CreateIdentifierName("F")),
cs: "E ? T : F",
vb: "If(E, T, F)");
}
[WpfFact]
public void TestInvocation1()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E")),
cs: "E()",
vb: "E()");
}
[WpfFact]
public void TestInvocation2()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(f.CreateIdentifierName("a"))),
cs: "E(a)",
vb: "E(a)");
}
[WpfFact]
public void TestInvocation3()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n", RefKind.None, f.CreateIdentifierName("a"))),
cs: "E(n: a)",
vb: "E(n:=a)");
}
[WpfFact]
public void TestInvocation4()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(null, RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument(null, RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E(out a, ref b)",
vb: "E(a, b)");
}
[WpfFact]
public void TestInvocation5()
{
TestExpression(
f => f.CreateInvocationExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n1", RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument("n2", RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E(n1: out a, n2: ref b)",
vb: "E(n1:=a, n2:=b)");
}
[WpfFact]
public void TestElementAccess1()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E")),
cs: "E[]",
vb: "E()");
}
[WpfFact]
public void TestElementAccess2()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(f.CreateIdentifierName("a"))),
cs: "E[a]",
vb: "E(a)");
}
[WpfFact]
public void TestElementAccess3()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n", RefKind.None, f.CreateIdentifierName("a"))),
cs: "E[n: a]",
vb: "E(n:=a)");
}
[WpfFact]
public void TestElementAccess4()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument(null, RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument(null, RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E[out a, ref b]",
vb: "E(a, b)");
}
[WpfFact]
public void TestElementAccess5()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateIdentifierName("E"),
f.CreateArgument("n1", RefKind.Out, f.CreateIdentifierName("a")),
f.CreateArgument("n2", RefKind.Ref, f.CreateIdentifierName("b"))),
cs: "E[n1: out a, n2: ref b]",
vb: "E(n1:=a, n2:=b)");
}
[WpfFact]
public void TestIsExpression()
{
TestExpression(
f => f.CreateIsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
cs: "a is SomeType",
vb: "TypeOf a Is SomeType");
}
[WpfFact]
public void TestAsExpression()
{
TestExpression(
f => f.CreateAsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
cs: "a as SomeType",
vb: "TryCast(a, SomeType)");
}
[WpfFact]
public void TestNotExpression()
{
TestExpression(
f => f.CreateLogicalNotExpression(
f.CreateIdentifierName("a")),
cs: "!a",
vb: "Not a");
}
[WpfFact]
public void TestCastExpression()
{
TestExpression(
f => f.CreateCastExpression(
CreateClass("SomeType"),
f.CreateIdentifierName("a")),
cs: "(SomeType)a",
vb: "DirectCast(a, SomeType)");
}
[WpfFact]
public void TestNegateExpression()
{
TestExpression(
f => f.CreateNegateExpression(
f.CreateIdentifierName("a")),
cs: "-a",
vb: "-a");
}
}
}
#endif
| |
using System.Windows.Forms;
namespace NuGet.Options
{
partial class PackageSourcesOptionsControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PackageSourcesOptionsControl));
this.HeaderLabel = new System.Windows.Forms.Label();
this.PackageSourcesContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.CopyPackageSourceStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.removeButton = new System.Windows.Forms.Button();
this.images16px = new System.Windows.Forms.ImageList(this.components);
this.MoveUpButton = new System.Windows.Forms.Button();
this.MoveDownButton = new System.Windows.Forms.Button();
this.packageListToolTip = new System.Windows.Forms.ToolTip(this.components);
this.updateButton = new System.Windows.Forms.Button();
this.BrowseButton = new System.Windows.Forms.Button();
this.NewPackageSource = new System.Windows.Forms.TextBox();
this.NewPackageSourceLabel = new System.Windows.Forms.Label();
this.NewPackageName = new System.Windows.Forms.TextBox();
this.NewPackageNameLabel = new System.Windows.Forms.Label();
this.PackageSourcesListBox = new System.Windows.Forms.ListBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.addButton = new System.Windows.Forms.Button();
this.MachineWideSourcesLabel = new System.Windows.Forms.Label();
this.MachineWidePackageSourcesListBox = new System.Windows.Forms.ListBox();
this.images32px = new System.Windows.Forms.ImageList(this.components);
this.images64px = new System.Windows.Forms.ImageList(this.components);
this.PackageSourcesContextMenu.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// HeaderLabel
//
resources.ApplyResources(this.HeaderLabel, "HeaderLabel");
this.HeaderLabel.Name = "HeaderLabel";
//
// PackageSourcesContextMenu
//
this.PackageSourcesContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.CopyPackageSourceStripMenuItem});
this.PackageSourcesContextMenu.Name = "contextMenuStrip1";
resources.ApplyResources(this.PackageSourcesContextMenu, "PackageSourcesContextMenu");
this.PackageSourcesContextMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.PackageSourcesContextMenu_ItemClicked);
//
// CopyPackageSourceStripMenuItem
//
this.CopyPackageSourceStripMenuItem.Name = "CopyPackageSourceStripMenuItem";
resources.ApplyResources(this.CopyPackageSourceStripMenuItem, "CopyPackageSourceStripMenuItem");
//
// removeButton
//
resources.ApplyResources(this.removeButton, "removeButton");
this.removeButton.ImageList = this.images16px;
this.removeButton.Name = "removeButton";
this.removeButton.UseVisualStyleBackColor = true;
this.removeButton.Click += new System.EventHandler(this.OnRemoveButtonClick);
//
// images16px
//
this.images16px.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("images16px.ImageStream")));
this.images16px.TransparentColor = System.Drawing.Color.Transparent;
this.images16px.Images.SetKeyName(0, "up_512.png");
this.images16px.Images.SetKeyName(1, "down_512.png");
this.images16px.Images.SetKeyName(2, "cancel_512.png");
this.images16px.Images.SetKeyName(3, "add_512.png");
//
// MoveUpButton
//
resources.ApplyResources(this.MoveUpButton, "MoveUpButton");
this.MoveUpButton.ImageList = this.images16px;
this.MoveUpButton.Name = "MoveUpButton";
this.MoveUpButton.UseVisualStyleBackColor = true;
//
// MoveDownButton
//
resources.ApplyResources(this.MoveDownButton, "MoveDownButton");
this.MoveDownButton.ImageList = this.images16px;
this.MoveDownButton.Name = "MoveDownButton";
this.MoveDownButton.UseVisualStyleBackColor = true;
//
// updateButton
//
resources.ApplyResources(this.updateButton, "updateButton");
this.updateButton.Name = "updateButton";
this.updateButton.UseVisualStyleBackColor = true;
this.updateButton.Click += new System.EventHandler(this.OnUpdateButtonClick);
//
// BrowseButton
//
resources.ApplyResources(this.BrowseButton, "BrowseButton");
this.BrowseButton.Name = "BrowseButton";
this.BrowseButton.UseVisualStyleBackColor = true;
this.BrowseButton.Click += new System.EventHandler(this.OnBrowseButtonClicked);
//
// NewPackageSource
//
resources.ApplyResources(this.NewPackageSource, "NewPackageSource");
this.NewPackageSource.Name = "NewPackageSource";
//
// NewPackageSourceLabel
//
resources.ApplyResources(this.NewPackageSourceLabel, "NewPackageSourceLabel");
this.NewPackageSourceLabel.Name = "NewPackageSourceLabel";
//
// NewPackageName
//
resources.ApplyResources(this.NewPackageName, "NewPackageName");
this.NewPackageName.Name = "NewPackageName";
//
// NewPackageNameLabel
//
resources.ApplyResources(this.NewPackageNameLabel, "NewPackageNameLabel");
this.NewPackageNameLabel.Name = "NewPackageNameLabel";
//
// PackageSourcesListBox
//
resources.ApplyResources(this.PackageSourcesListBox, "PackageSourcesListBox");
this.PackageSourcesListBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tableLayoutPanel1.SetColumnSpan(this.PackageSourcesListBox, 4);
this.PackageSourcesListBox.ContextMenuStrip = this.PackageSourcesContextMenu;
this.PackageSourcesListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.PackageSourcesListBox.FormattingEnabled = true;
this.PackageSourcesListBox.Name = "PackageSourcesListBox";
this.PackageSourcesListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.PackageSourcesListBox_DrawItem);
this.PackageSourcesListBox.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.PackageSourcesListBox_MeasureItem);
this.PackageSourcesListBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.PackageSourcesListBox_KeyUp);
this.PackageSourcesListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseMove);
this.PackageSourcesListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseUp);
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.PackageSourcesListBox, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.MachineWideSourcesLabel, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.MachineWidePackageSourcesListBox, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.NewPackageNameLabel, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.NewPackageSourceLabel, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.NewPackageName, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.NewPackageSource, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.BrowseButton, 2, 5);
this.tableLayoutPanel1.Controls.Add(this.updateButton, 3, 5);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel1.SetColumnSpan(this.tableLayoutPanel2, 4);
this.tableLayoutPanel2.Controls.Add(this.HeaderLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.addButton, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.removeButton, 2, 0);
this.tableLayoutPanel2.Controls.Add(this.MoveUpButton, 3, 0);
this.tableLayoutPanel2.Controls.Add(this.MoveDownButton, 4, 0);
this.tableLayoutPanel2.GrowStyle = System.Windows.Forms.TableLayoutPanelGrowStyle.FixedSize;
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// addButton
//
resources.ApplyResources(this.addButton, "addButton");
this.addButton.ImageList = this.images16px;
this.addButton.Name = "addButton";
this.addButton.UseVisualStyleBackColor = true;
this.addButton.Click += new System.EventHandler(this.OnAddButtonClick);
//
// MachineWideSourcesLabel
//
this.tableLayoutPanel1.SetColumnSpan(this.MachineWideSourcesLabel, 4);
resources.ApplyResources(this.MachineWideSourcesLabel, "MachineWideSourcesLabel");
this.MachineWideSourcesLabel.Name = "MachineWideSourcesLabel";
//
// MachineWidePackageSourcesListBox
//
resources.ApplyResources(this.MachineWidePackageSourcesListBox, "MachineWidePackageSourcesListBox");
this.MachineWidePackageSourcesListBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tableLayoutPanel1.SetColumnSpan(this.MachineWidePackageSourcesListBox, 4);
this.MachineWidePackageSourcesListBox.ContextMenuStrip = this.PackageSourcesContextMenu;
this.MachineWidePackageSourcesListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.MachineWidePackageSourcesListBox.FormattingEnabled = true;
this.MachineWidePackageSourcesListBox.Name = "MachineWidePackageSourcesListBox";
this.MachineWidePackageSourcesListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.PackageSourcesListBox_DrawItem);
this.MachineWidePackageSourcesListBox.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.PackageSourcesListBox_MeasureItem);
this.MachineWidePackageSourcesListBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.PackageSourcesListBox_KeyUp);
this.MachineWidePackageSourcesListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseMove);
this.MachineWidePackageSourcesListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseUp);
//
// images32px
//
this.images32px.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("images32px.ImageStream")));
this.images32px.TransparentColor = System.Drawing.Color.Transparent;
this.images32px.Images.SetKeyName(0, "up_512.png");
this.images32px.Images.SetKeyName(1, "down_512.png");
this.images32px.Images.SetKeyName(2, "cancel_512.png");
this.images32px.Images.SetKeyName(3, "add_512.png");
//
// images64px
//
this.images64px.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("images64px.ImageStream")));
this.images64px.TransparentColor = System.Drawing.Color.Transparent;
this.images64px.Images.SetKeyName(0, "up_512.png");
this.images64px.Images.SetKeyName(1, "down_512.png");
this.images64px.Images.SetKeyName(2, "cancel_512.png");
this.images64px.Images.SetKeyName(3, "add_512.png");
//
// PackageSourcesOptionsControl
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "PackageSourcesOptionsControl";
this.PackageSourcesContextMenu.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label HeaderLabel;
private System.Windows.Forms.Button removeButton;
private ContextMenuStrip PackageSourcesContextMenu;
private ToolStripMenuItem CopyPackageSourceStripMenuItem;
private Button MoveUpButton;
private Button MoveDownButton;
private ToolTip packageListToolTip;
private Button updateButton;
private Button BrowseButton;
private TextBox NewPackageSource;
private Label NewPackageSourceLabel;
private TextBox NewPackageName;
private TableLayoutPanel tableLayoutPanel1;
private ListBox PackageSourcesListBox;
private Label NewPackageNameLabel;
private TableLayoutPanel tableLayoutPanel2;
private ImageList images16px;
private Button addButton;
private Label MachineWideSourcesLabel;
private ListBox MachineWidePackageSourcesListBox;
private ImageList images32px;
private ImageList images64px;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Security.Cryptography.Encryption.Aes.Tests
{
using Aes = System.Security.Cryptography.Aes;
public class AesContractTests
{
[Fact]
public static void VerifyDefaults()
{
using (Aes aes = AesFactory.Create())
{
Assert.Equal(128, aes.BlockSize);
Assert.Equal(256, aes.KeySize);
Assert.Equal(CipherMode.CBC, aes.Mode);
Assert.Equal(PaddingMode.PKCS7, aes.Padding);
}
}
[Fact]
public static void LegalBlockSizes()
{
using (Aes aes = AesFactory.Create())
{
KeySizes[] blockSizes = aes.LegalBlockSizes;
Assert.NotNull(blockSizes);
Assert.Equal(1, blockSizes.Length);
KeySizes blockSizeLimits = blockSizes[0];
Assert.Equal(128, blockSizeLimits.MinSize);
Assert.Equal(128, blockSizeLimits.MaxSize);
Assert.Equal(0, blockSizeLimits.SkipSize);
}
}
[Fact]
public static void LegalKeySizes()
{
using (Aes aes = AesFactory.Create())
{
KeySizes[] keySizes = aes.LegalKeySizes;
Assert.NotNull(keySizes);
Assert.Equal(1, keySizes.Length);
KeySizes keySizeLimits = keySizes[0];
Assert.Equal(128, keySizeLimits.MinSize);
Assert.Equal(256, keySizeLimits.MaxSize);
Assert.Equal(64, keySizeLimits.SkipSize);
}
}
[Theory]
[InlineData(64)] // too small
[InlineData(129)] // in valid range but not valid increment
[InlineData(384)] // too large
[InlineData(536870928)] // number of bits overflows and wraps around to a valid size
public static void InvalidKeySizes(int invalidKeySize)
{
using (Aes aes = AesFactory.Create())
{
// Test KeySize property
Assert.Throws<CryptographicException>(() => aes.KeySize = invalidKeySize);
// Test passing a key to CreateEncryptor and CreateDecryptor
aes.GenerateIV();
byte[] iv = aes.IV;
byte[] key;
try
{
key = new byte[invalidKeySize];
}
catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array
{
return;
}
Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {e}");
e = Record.Exception(() => aes.CreateDecryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {e}");
}
}
[Theory]
[InlineData(64)] // smaller than default BlockSize
[InlineData(129)] // larger than default BlockSize
[InlineData(536870928)] // number of bits overflows and wraps around to default BlockSize
public static void InvalidIVSizes(int invalidIvSize)
{
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
byte[] key = aes.Key;
byte[] iv;
try
{
iv = new byte[invalidIvSize];
}
catch (OutOfMemoryException) // in case there isn't enough memory at test-time to allocate the large array
{
return;
}
Exception e = Record.Exception(() => aes.CreateEncryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {e}");
e = Record.Exception(() => aes.CreateDecryptor(key, iv));
Assert.True(e is ArgumentException || e is OutOfMemoryException, $"Got {e}");
}
}
[Fact]
public static void VerifyKeyGeneration_Default()
{
using (Aes aes = AesFactory.Create())
{
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_128()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 128;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_192()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 192;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyKeyGeneration_256()
{
using (Aes aes = AesFactory.Create())
{
aes.KeySize = 256;
VerifyKeyGeneration(aes);
}
}
[Fact]
public static void VerifyIVGeneration()
{
using (Aes aes = AesFactory.Create())
{
int blockSize = aes.BlockSize;
aes.GenerateIV();
byte[] iv = aes.IV;
Assert.NotNull(iv);
Assert.Equal(blockSize, aes.BlockSize);
Assert.Equal(blockSize, iv.Length * 8);
// Standard randomness caveat: There's a very low chance that the generated IV -is-
// all zeroes. This works out to 1/2^128, which is more unlikely than 1/10^38.
Assert.NotEqual(new byte[iv.Length], iv);
}
}
[Fact]
public static void ValidateEncryptorProperties()
{
using (Aes aes = AesFactory.Create())
{
ValidateTransformProperties(aes, aes.CreateEncryptor());
}
}
[Fact]
public static void ValidateDecryptorProperties()
{
using (Aes aes = AesFactory.Create())
{
ValidateTransformProperties(aes, aes.CreateDecryptor());
}
}
[Fact]
public static void CreateTransformExceptions()
{
byte[] key;
byte[] iv;
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.GenerateIV();
key = aes.Key;
iv = aes.IV;
}
using (Aes aes = AesFactory.Create())
{
aes.Mode = CipherMode.CBC;
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null));
// CBC requires an IV.
Assert.Throws<CryptographicException>(() => aes.CreateEncryptor(key, null));
Assert.Throws<CryptographicException>(() => aes.CreateDecryptor(key, null));
}
using (Aes aes = AesFactory.Create())
{
aes.Mode = CipherMode.ECB;
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateEncryptor(null, null));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, iv));
Assert.Throws<ArgumentNullException>(() => aes.CreateDecryptor(null, null));
// ECB will accept an IV (but ignore it), and doesn't require it.
using (ICryptoTransform didNotThrow = aes.CreateEncryptor(key, null))
{
Assert.NotNull(didNotThrow);
}
using (ICryptoTransform didNotThrow = aes.CreateDecryptor(key, null))
{
Assert.NotNull(didNotThrow);
}
}
}
[Fact]
public static void ValidateOffsetAndCount()
{
using (Aes aes = AesFactory.Create())
{
aes.GenerateKey();
aes.GenerateIV();
// aes.BlockSize is in bits, new byte[] is in bytes, so we have 8 blocks.
byte[] full = new byte[aes.BlockSize];
int blockByteCount = aes.BlockSize / 8;
for (int i = 0; i < full.Length; i++)
{
full[i] = unchecked((byte)i);
}
byte[] firstBlock = new byte[blockByteCount];
byte[] middleHalf = new byte[4 * blockByteCount];
// Copy the first blockBytes of full into firstBlock.
Buffer.BlockCopy(full, 0, firstBlock, 0, blockByteCount);
// [Skip][Skip][Take][Take][Take][Take][Skip][Skip] => "middle half"
Buffer.BlockCopy(full, 2 * blockByteCount, middleHalf, 0, middleHalf.Length);
byte[] firstBlockEncrypted;
byte[] firstBlockEncryptedFromCount;
byte[] middleHalfEncrypted;
byte[] middleHalfEncryptedFromOffsetAndCount;
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
firstBlockEncrypted = encryptor.TransformFinalBlock(firstBlock, 0, firstBlock.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
firstBlockEncryptedFromCount = encryptor.TransformFinalBlock(full, 0, firstBlock.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
middleHalfEncrypted = encryptor.TransformFinalBlock(middleHalf, 0, middleHalf.Length);
}
using (ICryptoTransform encryptor = aes.CreateEncryptor())
{
middleHalfEncryptedFromOffsetAndCount = encryptor.TransformFinalBlock(full, 2 * blockByteCount, middleHalf.Length);
}
Assert.Equal(firstBlockEncrypted, firstBlockEncryptedFromCount);
Assert.Equal(middleHalfEncrypted, middleHalfEncryptedFromOffsetAndCount);
}
}
private static void ValidateTransformProperties(Aes aes, ICryptoTransform transform)
{
Assert.NotNull(transform);
Assert.Equal(aes.BlockSize, transform.InputBlockSize * 8);
Assert.Equal(aes.BlockSize, transform.OutputBlockSize * 8);
Assert.True(transform.CanTransformMultipleBlocks);
}
private static void VerifyKeyGeneration(Aes aes)
{
int keySize = aes.KeySize;
aes.GenerateKey();
byte[] key = aes.Key;
Assert.NotNull(key);
Assert.Equal(keySize, aes.KeySize);
Assert.Equal(keySize, key.Length * 8);
// Standard randomness caveat: There's a very low chance that the generated key -is-
// all zeroes. For a 128-bit key this is 1/2^128, which is more unlikely than 1/10^38.
Assert.NotEqual(new byte[key.Length], key);
}
}
}
| |
/*
Copyright (c) 2007 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Globalization;
namespace Lidgren.Library.Network
{
/// <summary>
/// A network client
/// </summary>
/// <example><code>
/// NetConfiguration config = new NetConfiguration("MyApp", 12345);
/// NetLog log = new NetLog();
///
/// NetClient myNet = new NetClient(config, log);
///
/// myNet.Connect("localhost", 12345);
/// </code></example>
public class NetClient : NetBase
{
private NetConnection m_serverConnection;
/// <summary>
/// Event fired when server is found after using DiscoverLocal() to discover servers
/// </summary>
public event EventHandler<NetServerDiscoveredEventArgs> ServerDiscovered;
/// <summary>
/// Status of the server connection
/// </summary>
public NetConnectionStatus Status { get { return (m_serverConnection == null ? NetConnectionStatus.Disconnected : m_serverConnection.Status); } }
/// <summary>
/// The connection to the server; will be null until a call to Connect() has been made.
/// </summary>
public NetConnection ServerConnection { get { return m_serverConnection; } }
public NetClient(NetAppConfiguration config, NetLog log)
{
NetBase.CurrentContext = this;
InitBase(config, log);
}
/// <summary>
/// Reads messages from network and sends unsent messages, resends etc
/// This method should be called as often as possible; maximum number
/// of seconds to spend can be specified
/// </summary>
public void Heartbeat(float maxSeconds)
{
NetBase.CurrentContext = this;
double now = NetTime.Now;
base.Heartbeat(now);
// read packets until out of time (or packets)
double exit = now + maxSeconds;
while (ReadPacket())
{
if (NetTime.Now > exit)
break;
}
if (m_serverConnection != null && m_serverConnection.Status != NetConnectionStatus.Disconnected)
m_serverConnection.Heartbeat(now);
}
/// <summary>
/// Reads messages from network and sends unsent messages, resends etc
/// This method should be called as often as possible
/// </summary>
public void Heartbeat()
{
try
{
Heartbeat(float.MaxValue);
}
finally
{
}
}
internal override void HandlePacket(NetBuffer buffer, int bytesReceived, IPEndPoint sender)
{
double now = NetTime.Now;
try
{
NetMessage msg;
if (m_serverConnection == null || m_serverConnection.Status == NetConnectionStatus.Disconnected)
{
//
// unconnected packet
//
msg = NetMessage.Decode(buffer);
if (msg == null)
{
Log.Warning("Malformed NetMessage?");
return; // malformed?
}
Log.Verbose("Received unconnected message: " + msg);
// discovery response?
if (msg.m_type == NetMessageType.Discovery)
{
NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender);
if (ServerDiscovered != null)
ServerDiscovered(this, new NetServerDiscoveredEventArgs(info));
return;
}
if (m_serverConnection != null && sender.Equals(m_serverConnection.RemoteEndpoint))
{
// we have m_serverConnection, but status is disconnected
Log.Warning("Received " + buffer.LengthBytes + " from server; but we're disconnected!");
return;
}
Log.Warning("Received " + buffer.LengthBytes + " bytes from non-server source: " + sender + "(server is " + m_serverConnection.RemoteEndpoint + ")");
return;
}
// decrypt in place
if (m_serverConnection.m_encryption.SymmetricEncryptionKeyBytes != null)
{
byte[] savedBuffer = null;
if (m_serverConnection.Status == NetConnectionStatus.Connecting)
{
// special case; save buffer in case we get unencrypted response
savedBuffer = new byte[buffer.LengthBytes];
Array.Copy(buffer.Data, 0, savedBuffer, 0, buffer.LengthBytes);
}
bool ok = m_serverConnection.m_encryption.DecryptSymmetric(buffer);
if (!ok)
{
// failed to decrypt; drop this packet UNLESS we're in a connecting state,
// in which case the server may want to tell us something
if (m_serverConnection.Status == NetConnectionStatus.Connecting)
{
// ok let this one thru unencrypted
Array.Copy(savedBuffer, buffer.Data, savedBuffer.Length);
}
else
{
Log.Warning("Failed to decrypt packet from server!");
return;
}
}
}
m_serverConnection.m_lastHeardFromRemote = now;
int messagesReceived = 0;
int usrMessagesReceived = 0;
int ackMessagesReceived = 0;
while (buffer.ReadBitsLeft > 7)
{
msg = NetMessage.Decode(buffer);
if (msg == null)
break; // done
messagesReceived++;
msg.Sender = m_serverConnection;
switch (msg.m_type)
{
case NetMessageType.Handshake:
NetHandshakeType tp = (NetHandshakeType)msg.ReadByte();
if (tp == NetHandshakeType.Connect || tp == NetHandshakeType.ConnectionEstablished)
{
Log.Warning("Client received " + tp + "?!");
}
else if (tp == NetHandshakeType.ConnectResponse)
{
if (m_serverConnection.Status != NetConnectionStatus.Connecting)
{
Log.Verbose("Received redundant ConnectResponse!");
break;
}
// Log.Debug("ConnectResponse received");
m_serverConnection.SetStatus(NetConnectionStatus.Connected, "Connected");
Log.Info("Connected to " + m_serverConnection.RemoteEndpoint);
// initialize ping to now - m_firstSentConnect
float initRoundtrip = (float)(now - m_serverConnection.m_firstSentHandshake);
m_serverConnection.m_ping.Initialize(initRoundtrip);
ushort remoteValue = msg.ReadUInt16();
m_serverConnection.RemoteClockOffset = NetTime.CalculateOffset(now, remoteValue, initRoundtrip);
Log.Verbose("Initializing remote clock offset to " + m_serverConnection.RemoteClockOffset + " ms (roundtrip " + NetUtil.SecToMil(initRoundtrip) + " ms)");
NetMessage established = new NetMessage(NetMessageType.Handshake, 3);
established.Write((byte)NetHandshakeType.ConnectionEstablished);
established.WriteSendStamp();
SendSingleMessageAtOnce(established, m_serverConnection, m_serverConnection.RemoteEndpoint);
}
else
{ // Disconnected
string reason = msg.ReadString();
m_serverConnection.SetStatus(NetConnectionStatus.Disconnected, reason);
}
break;
case NetMessageType.Acknowledge:
//Log.Debug("Received ack " + msg.SequenceChannel + "|" + msg.SequenceNumber);
m_serverConnection.ReceiveAcknowledge(msg);
ackMessagesReceived++;
break;
case NetMessageType.PingPong:
bool isPong = msg.ReadBoolean();
bool isOptimizeInfo = msg.ReadBoolean();
if (isOptimizeInfo)
{
m_serverConnection.m_ping.HandleOptimizeInfo(now, msg);
} else if (isPong)
{
if (m_serverConnection.Status == NetConnectionStatus.Connected)
m_serverConnection.m_ping.HandlePong(now, msg);
}
else
{
NetPing.ReplyPong(msg, m_serverConnection);
}
break;
case NetMessageType.User:
case NetMessageType.UserFragmented:
//Log.Debug("User message received; " + msg.m_buffer.LengthBytes + " bytes");
m_serverConnection.ReceiveMessage(now, msg);
usrMessagesReceived++;
break;
case NetMessageType.Discovery:
NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender);
if (ServerDiscovered != null)
ServerDiscovered(this, new NetServerDiscoveredEventArgs(info));
break;
default:
Log.Warning("Client received " + msg.m_type + "?!");
break;
}
}
// add statistics
NetStatistics stats = m_serverConnection.Statistics;
stats.PacketsReceived++;
stats.MessagesReceived += messagesReceived;
stats.UserMessagesReceived += usrMessagesReceived;
stats.AckMessagesReceived += ackMessagesReceived;
stats.BytesReceived += bytesReceived;
}
catch (Exception ex)
{
Log.Error("Failed to parse packet correctly; read/write mismatch? " + ex);
}
}
public void SetConnectedStatus()
{
m_serverConnection.SetStatus(NetConnectionStatus.Connected, "Connected");
}
/// <summary>
/// Reads a message, if available
/// </summary>
/// <returns>NetMessage, or null if none are available</returns>
/// <example><code>
/// bool keepGoing = true;
/// while (keepGoing)
/// {
/// myClient.Heartbeat();
///
/// NetMessage msg;
/// while ((msg = myNet.ReadMessage()) != null)
/// {
/// // handle msg
/// }
/// }
/// </code></example>
public NetMessage ReadMessage()
{
if (m_serverConnection == null)
return null;
NetBase.CurrentContext = this;
if (m_serverConnection.m_receivedMessages.Count < 1)
return null;
NetMessage msg = m_serverConnection.m_receivedMessages.Dequeue();
return msg;
}
internal override void HandleConnectionReset(IPEndPoint remote)
{
if (m_serverConnection == null)
return;
if (m_serverConnection.Status == NetConnectionStatus.Connecting)
{
Log.Info("Failed to connect");
m_serverConnection.SetStatus(NetConnectionStatus.Disconnected, "No server listening!");
}
else
{
m_serverConnection.SetStatus(NetConnectionStatus.Disconnected, "Connection reset");
}
}
/// <summary>
/// Disconnects from the server, providing specified reason
/// </summary>
public void Disconnect(string reason)
{
if (m_serverConnection != null)
{
if (m_serverConnection.Status == NetConnectionStatus.Disconnected)
{
Log.Warning("Disconnect() called altho server connection is disconnected");
}
else
{
m_serverConnection.Disconnect(reason);
}
}
else
{
Log.Warning("Disconnect() called altho no server connection");
}
}
/// <summary>
/// Send server discovery request to a remote host, not necessarily on
/// the local network
/// </summary>
public void DiscoverKnownServer(string ipOrHostName, int serverPort)
{
IPAddress ip = NetUtil.Resolve(this.Log, ipOrHostName);
NetMessage msg = NetDiscovery.EncodeRequest(this);
SendSingleMessageAtOnce(msg, null, new IPEndPoint(ip, serverPort));
}
public void DiscoverLocalServers(int serverPort)
{
IPEndPoint broadcast = new IPEndPoint(IPAddress.Broadcast, serverPort);
NetMessage msg = NetDiscovery.EncodeRequest(this);
Log.Info("Broadcasting server discovery ping...");
// special send style; can't use simulated lag due to socket options
try
{
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
m_sendBuffer.ResetWritePointer();
msg.Encode(null, m_sendBuffer);
int bytesSent = m_socket.SendTo(m_sendBuffer.Data, 0, m_sendBuffer.LengthBytes, SocketFlags.None, broadcast);
Log.Verbose(string.Format(CultureInfo.InvariantCulture, "Sent {0} bytes to {1}", bytesSent, broadcast));
return;
}
catch (SocketException sex)
{
if (sex.SocketErrorCode == SocketError.ConnectionReset ||
sex.SocketErrorCode == SocketError.ConnectionRefused ||
sex.SocketErrorCode == SocketError.ConnectionAborted)
{
Log.Warning("Remote socket forcefully closed: " + sex.SocketErrorCode);
return;
}
Log.Warning("Execute SocketException: " + sex.SocketErrorCode);
return;
}
finally
{
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
}
}
/// <summary>
/// Connects to a server
/// </summary>
public bool Connect(IPAddress address, int port)
{
return Connect(address, port, null);
}
/// <summary>
/// Connects to a server
/// </summary>
public bool Connect(IPEndPoint endPoint)
{
return Connect(endPoint.Address, endPoint.Port, null);
}
/// <summary>
/// Connects to a server
/// </summary>
public bool Connect(string host, int port)
{
IPAddress ip = NetUtil.Resolve(Log, host);
if (ip == null)
return false;
return Connect(ip, port, null);
}
/// <summary>
/// Connects to a server
/// </summary>
public bool Connect(string host, int port, byte[] customData)
{
IPAddress ip = NetUtil.Resolve(Log, host);
if (ip == null)
return false;
return Connect(ip, port, customData);
}
/// <summary>
/// Connects to a server
/// </summary>
public bool Connect(IPAddress address, int port, byte[] customData)
{
if (m_serverConnection != null && m_serverConnection.Status != NetConnectionStatus.Disconnected)
m_serverConnection.Disconnect("Reconnecting");
IPEndPoint remoteIP = new IPEndPoint(address, port);
m_serverConnection = new NetConnection(this, remoteIP);
string remoteHost = remoteIP.ToString();
Log.Info("Connecting to " + remoteHost);
m_serverConnection.m_firstSentHandshake = NetTime.Now;
m_serverConnection.m_lastSentHandshake = m_serverConnection.m_firstSentHandshake;
m_serverConnection.SetStatus(NetConnectionStatus.Connecting, "Connecting");
// save custom data for repeat connect requests
if (customData != null)
{
m_serverConnection.m_savedConnectCustomData = new byte[customData.Length];
Array.Copy(customData, m_serverConnection.m_savedConnectCustomData, customData.Length);
}
int bytesSent = NetHandshake.SendConnect(this, remoteIP, customData);
// account for connect packet
m_serverConnection.Statistics.PacketsSent++;
m_serverConnection.Statistics.MessagesSent++;
m_serverConnection.Statistics.BytesSent += bytesSent;
return true;
}
/// <summary>
/// Sends a message to the server using a specified channel
/// </summary>
public bool SendMessage(NetMessage msg, NetChannel channel)
{
if (m_serverConnection == null || m_serverConnection.Status == NetConnectionStatus.Disconnected)
{
Log.Warning("SendMessage failed - Not connected!");
return false;
}
m_serverConnection.SendMessage(msg, channel);
return true;
}
/// <summary>
/// Sends all unsent messages; may interfere with proper throttling
/// </summary>
public void FlushMessages()
{
m_serverConnection.SendUnsentMessages(true, 0.01f);
}
/// <summary>
/// Sends disconnect to server and close the connection
/// </summary>
public override void Shutdown(string reason)
{
Log.Info("Client shutdown: " + reason);
if (m_serverConnection != null)
{
/*
// some simple statistics
for (int i = 0; i < m_serverConnection.m_savedReliableMessages.Length; i++)
{
if (m_serverConnection.m_savedReliableMessages[i].Count > 0)
Log.Info("Saved reliable messages (" + ((NetChannel)i) + "): " + m_serverConnection.m_savedReliableMessages[i].Count);
}
Log.Debug(" ");
Log.Debug("Unsent acks left: " + m_serverConnection.m_unsentAcknowledges.Count);
Log.Debug("Unsent messages left: " + m_serverConnection.m_unsentMessages.Count);
Log.Debug("Withheld messages left: " + m_serverConnection.m_withheldMessages.Count);
Log.Debug("Received messages left: " + m_serverConnection.m_receivedMessages.Count);
Log.Debug("Average RTT left: " + m_serverConnection.AverageRoundtripTime);
*/
if (m_serverConnection.Status != NetConnectionStatus.Disconnected)
m_serverConnection.Disconnect(reason);
m_serverConnection.DumpStatisticsToLog(Log);
if (m_lagLoss != null)
{
Log.Debug("Artificially delayed packets still in queue: " + m_lagLoss.m_delayed.Count);
foreach (NetLogLossInducer.DelayedPacket dm in m_lagLoss.m_delayed)
Log.Debug("... " + dm);
}
}
base.Shutdown(reason);
}
public override string ToString()
{
return "[NetClient to " + this.Status + "]";
}
}
}
| |
// created on 6/21/2004
// Npgsql.NpgsqlConnecionString.cs
//
// Author:
// Glen Parker (glenebob@nwlink.com)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Resources;
namespace Npgsql
{
/// <summary>
/// Represents a connection string.
/// </summary>
internal sealed class NpgsqlConnectionString : IEnumerable
{
// Logging related values
private static readonly String CLASSNAME = "NpgsqlConnectionString";
private static System.Resources.ResourceManager resman;
private String connection_string = null;
private ListDictionary connection_string_values;
static NpgsqlConnectionString()
{
resman = new System.Resources.ResourceManager(typeof(NpgsqlConnectionString));
}
private NpgsqlConnectionString(NpgsqlConnectionString Other)
{
connection_string = Other.connection_string;
connection_string_values = new ListDictionary(CaseInsensitiveComparer.Default);
foreach (DictionaryEntry DE in Other.connection_string_values)
{
connection_string_values.Add(DE.Key, DE.Value);
}
}
private NpgsqlConnectionString(ListDictionary Values)
{
connection_string_values = Values;
}
/// <summary>
/// Return an exact copy of this NpgsqlConnectionString.
/// </summary>
public NpgsqlConnectionString Clone()
{
return new NpgsqlConnectionString(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return connection_string_values.GetEnumerator();
}
/// <summary>
/// This method parses a connection string and returns a new NpgsqlConnectionString object.
/// </summary>
public static NpgsqlConnectionString ParseConnectionString(String CS)
{
ListDictionary new_values = new ListDictionary(CaseInsensitiveComparer.Default);
String[] pairs;
String[] keyvalue;
if (CS == null)
CS = String.Empty;
// Get the key-value pairs delimited by ;
pairs = CS.Split(';');
// Now, for each pair, get its key=value.
foreach(String sraw in pairs)
{
String s = sraw.Trim();
String Key = "", Value = "";
// Just ignore these.
if (s == "")
{
continue;
}
// Split this chunk on the first CONN_ASSIGN only.
keyvalue = s.Split(new Char[] {'='}, 2);
// Keys always get trimmed and uppercased.
Key = keyvalue[0].Trim().ToUpper();
// Make sure the key is even there...
if (Key.Length == 0)
{
throw new ArgumentException(resman.GetString("Exception_WrongKeyVal"), "<BLANK>");
}
// We don't expect keys this long, and it might be about to be put
// in an error message, so makes sure it is a sane length.
if (Key.Length > 20)
{
Key = Key.Substring(0, 20);
}
// Check if there is a key-value pair.
if (keyvalue.Length != 2)
{
throw new ArgumentException(resman.GetString("Exception_WrongKeyVal"), Key);
}
// Values always get trimmed.
Value = keyvalue[1].Trim();
// Substitute the real key name if this is an alias key (ODBC stuff for example)...
String AliasKey = (string)ConnectionStringKeys.Aliases[Key];
if (AliasKey != null)
{
Key = AliasKey;
}
// Add the pair to the dictionary..
new_values.Add(Key, Value);
}
return new NpgsqlConnectionString(new_values);
}
/// <summary>
/// Case insensative accessor for indivual connection string values.
/// </summary>
public String this[String Key]
{
get
{
return (String)connection_string_values[Key];
}
set
{
connection_string_values[Key] = value;
connection_string = null;
}
}
/// <summary>
/// Report whether a value with the provided key name exists in this connection string.
/// </summary>
public Boolean Contains(String Key)
{
return connection_string_values.Contains(Key);
}
/// <summary>
/// Return a clean string representation of this connection string.
/// </summary>
public override String ToString()
{
if (connection_string == null)
{
StringBuilder S = new StringBuilder();
foreach (DictionaryEntry DE in this)
{
S.AppendFormat("{0}={1};", DE.Key, DE.Value);
}
connection_string = S.ToString();
}
return connection_string;
}
/// <summary>
/// Return a string value from the current connection string, even if the
/// given key is not in the string or if the value is null.
/// </summary>
public String ToString(String Key)
{
return ToString(Key, "");
}
/// <summary>
/// Return a string value from the current connection string, even if the
/// given key is not in the string or if the value is null.
/// </summary>
public String ToString(String Key, String Default)
{
if (! connection_string_values.Contains(Key))
{
return Default;
}
return Convert.ToString(connection_string_values[Key]);
}
/// <summary>
/// Return an integer value from the current connection string, even if the
/// given key is not in the string or if the value is null.
/// Throw an appropriate exception if the value cannot be coerced to an integer.
/// </summary>
public Int32 ToInt32(String Key)
{
return ToInt32(Key, 0);
}
/// <summary>
/// Return an integer value from the current connection string, even if the
/// given key is not in the string or if the value is null.
/// Throw an appropriate exception if the value cannot be coerced to an integer.
/// </summary>
public Int32 ToInt32(String Key, Int32 Min, Int32 Max)
{
return ToInt32(Key, Min, Max, 0);
}
/// <summary>
/// Return an integer value from the current connection string, even if the
/// given key is not in the string or if the value is null.
/// Throw an appropriate exception if the value cannot be coerced to an integer.
/// </summary>
public Int32 ToInt32(String Key, Int32 Default)
{
if (! connection_string_values.Contains(Key))
{
return Default;
}
try
{
return Convert.ToInt32(connection_string_values[Key]);
}
catch (Exception E)
{
throw new ArgumentException(String.Format(resman.GetString("Exception_InvalidIntegerKeyVal"), Key), Key, E);
}
}
/// <summary>
/// Return an integer value from the current connection string, even if the
/// given key is not in the string.
/// Throw an appropriate exception if the value cannot be coerced to an integer.
/// </summary>
public Int32 ToInt32(String Key, Int32 Min, Int32 Max, Int32 Default)
{
Int32 V;
V = ToInt32(Key, Default);
if (V < Min)
{
throw new ArgumentException(String.Format(resman.GetString("Exception_IntegerKeyValMin"), Key, Min), Key);
}
if (V > Max)
{
throw new ArgumentException(String.Format(resman.GetString("Exception_IntegerKeyValMax"), Key, Max), Key);
}
return V;
}
/// <summary>
/// Return a boolean value from the current connection string, even if the
/// given key is not in the string.
/// Throw an appropriate exception if the value is not recognized as a boolean.
/// </summary>
public Boolean ToBool(String Key)
{
return ToBool(Key, false);
}
/// <summary>
/// Return a boolean value from the current connection string, even if the
/// given key is not in the string.
/// Throw an appropriate exception if the value is not recognized as a boolean.
/// </summary>
public Boolean ToBool(String Key, Boolean Default)
{
if (! connection_string_values.Contains(Key))
{
return Default;
}
switch (connection_string_values[Key].ToString().ToLower())
{
case "t" :
case "true" :
case "y" :
case "yes" :
return true;
case "f" :
case "false" :
case "n" :
case "no" :
return false;
default :
throw new ArgumentException(String.Format(resman.GetString("Exception_InvalidBooleanKeyVal"), Key), Key);
}
}
/// <summary>
/// Return a ProtocolVersion from the current connection string, even if the
/// given key is not in the string.
/// Throw an appropriate exception if the value is not recognized as
/// integer 2 or 3.
/// </summary>
public ProtocolVersion ToProtocolVersion(String Key)
{
if (! connection_string_values.Contains(Key))
{
return ProtocolVersion.Version3;
}
switch (ToInt32(Key))
{
case 2 :
return ProtocolVersion.Version2;
case 3 :
return ProtocolVersion.Version3;
default :
throw new ArgumentException(String.Format(resman.GetString("Exception_InvalidProtocolVersionKeyVal"), Key), Key);
}
}
}
/// <summary>
/// Know connection string keys.
/// </summary>
internal abstract class ConnectionStringKeys
{
public static readonly String Host = "SERVER";
public static readonly String Port = "PORT";
public static readonly String Protocol = "PROTOCOL";
public static readonly String Database = "DATABASE";
public static readonly String UserName = "USER ID";
public static readonly String Password = "PASSWORD";
public static readonly String SSL = "SSL";
public static readonly String Encoding = "ENCODING";
public static readonly String Timeout = "TIMEOUT";
// These are for the connection pool
public static readonly String Pooling = "POOLING";
public static readonly String MinPoolSize = "MINPOOLSIZE";
public static readonly String MaxPoolSize = "MAXPOOLSIZE";
// A list of aliases for some of the above values. If one of these aliases is
// encountered when parsing a connection string, it's real key name will
// be used instead. These will be reflected if ToString() is used to inspect
// the string.
private static ListDictionary _aliases;
static ConnectionStringKeys()
{
_aliases = new ListDictionary();
// Aliases to help catch common errors.
_aliases.Add("DB", Database);
_aliases.Add("HOST", Host);
_aliases.Add("USER", UserName);
_aliases.Add("USERID", UserName);
_aliases.Add("USER NAME", UserName);
_aliases.Add("USERNAME", UserName);
_aliases.Add("PSW", Password);
// Aliases to make migration from ODBC easier.
_aliases.Add("UID", UserName);
_aliases.Add("PWD", Password);
}
public static IDictionary Aliases
{
get
{
return _aliases;
}
}
}
/// <summary>
/// Connection string default values.
/// </summary>
internal abstract class ConnectionStringDefaults
{
// Connection string defaults
public static readonly Int32 Port = 5432;
public static readonly String Encoding = "SQL_ASCII";
public static readonly Boolean Pooling = true;
public static readonly Int32 MinPoolSize = 1;
public static readonly Int32 MaxPoolSize = 20;
public static readonly Int32 Timeout = 15; // Seconds
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Streams
{
[Serializable]
internal class StreamSubscriptionHandleImpl<T> : StreamSubscriptionHandle<T>, IStreamSubscriptionHandle
{
private StreamImpl<T> streamImpl;
private readonly IStreamFilterPredicateWrapper filterWrapper;
private readonly GuidId subscriptionId;
private readonly bool isRewindable;
[NonSerialized]
private IAsyncObserver<T> observer;
[NonSerialized]
private IAsyncBatchObserver<T> batchObserver;
[NonSerialized]
private StreamHandshakeToken expectedToken;
internal bool IsValid { get { return streamImpl != null; } }
internal GuidId SubscriptionId { get { return subscriptionId; } }
internal bool IsRewindable { get { return isRewindable; } }
public override string ProviderName { get { return this.streamImpl.ProviderName; } }
public override IStreamIdentity StreamIdentity { get { return streamImpl; } }
public override Guid HandleId { get { return subscriptionId.Guid; } }
public StreamSubscriptionHandleImpl(GuidId subscriptionId, StreamImpl<T> streamImpl)
: this(subscriptionId, null, null, streamImpl, null, null)
{
}
public StreamSubscriptionHandleImpl(GuidId subscriptionId, IAsyncObserver<T> observer, IAsyncBatchObserver<T> batchObserver, StreamImpl<T> streamImpl, IStreamFilterPredicateWrapper filterWrapper, StreamSequenceToken token)
{
this.subscriptionId = subscriptionId ?? throw new ArgumentNullException("subscriptionId");
this.observer = observer;
this.batchObserver = batchObserver;
this.streamImpl = streamImpl ?? throw new ArgumentNullException("streamImpl");
this.filterWrapper = filterWrapper;
this.isRewindable = streamImpl.IsRewindable;
if (IsRewindable)
{
expectedToken = StreamHandshakeToken.CreateStartToken(token);
}
}
public void Invalidate()
{
this.streamImpl = null;
this.observer = null;
this.batchObserver = null;
}
public StreamHandshakeToken GetSequenceToken()
{
return this.expectedToken;
}
public override Task UnsubscribeAsync()
{
if (!IsValid) throw new InvalidOperationException("Handle is no longer valid. It has been used to unsubscribe or resume.");
return this.streamImpl.UnsubscribeAsync(this);
}
public override Task<StreamSubscriptionHandle<T>> ResumeAsync(IAsyncObserver<T> obs, StreamSequenceToken token = null)
{
if (!IsValid) throw new InvalidOperationException("Handle is no longer valid. It has been used to unsubscribe or resume.");
return this.streamImpl.ResumeAsync(this, obs, token);
}
public override Task<StreamSubscriptionHandle<T>> ResumeAsync(IAsyncBatchObserver<T> observer, StreamSequenceToken token = null)
{
if (!IsValid) throw new InvalidOperationException("Handle is no longer valid. It has been used to unsubscribe or resume.");
return this.streamImpl.ResumeAsync(this, observer, token);
}
public async Task<StreamHandshakeToken> DeliverBatch(IBatchContainer batch, StreamHandshakeToken handshakeToken)
{
// we validate expectedToken only for ordered (rewindable) streams
if (this.expectedToken != null)
{
if (!this.expectedToken.Equals(handshakeToken))
return this.expectedToken;
}
if (batch is IBatchContainerBatch)
{
var batchContainerBatch = batch as IBatchContainerBatch;
await NextBatch(batchContainerBatch);
}
else
{
if (this.observer != null)
{
foreach (var itemTuple in batch.GetEvents<T>())
{
await NextItem(itemTuple.Item1, itemTuple.Item2);
}
} else
{
await NextItems(batch.GetEvents<T>());
}
}
if (IsRewindable)
{
this.expectedToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken);
}
return null;
}
public async Task<StreamHandshakeToken> DeliverItem(object item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken)
{
if (this.expectedToken != null)
{
if (!this.expectedToken.Equals(handshakeToken))
return this.expectedToken;
}
T typedItem;
try
{
typedItem = (T)item;
}
catch (InvalidCastException)
{
// We got an illegal item on the stream -- close it with a Cast exception
throw new InvalidCastException("Received an item of type " + item.GetType().Name + ", expected " + typeof(T).FullName);
}
await ((this.observer != null)
? NextItem(typedItem, currentToken)
: NextItems(new[] { Tuple.Create(typedItem, currentToken) }));
// check again, in case the expectedToken was changed indiretly via ResumeAsync()
if (this.expectedToken != null)
{
if (!this.expectedToken.Equals(handshakeToken))
return this.expectedToken;
}
if (IsRewindable)
{
this.expectedToken = StreamHandshakeToken.CreateDeliveyToken(currentToken);
}
return null;
}
public async Task NextBatch(IBatchContainerBatch batchContainerBatch)
{
if (this.observer != null)
{
foreach (var batchContainer in batchContainerBatch.BatchContainers)
{
bool isRequestContextSet = batchContainer.ImportRequestContext();
foreach (var itemTuple in batchContainer.GetEvents<T>())
{
await NextItem(itemTuple.Item1, itemTuple.Item2);
}
if (isRequestContextSet)
{
RequestContext.Clear();
}
}
}
else
{
await NextItems(batchContainerBatch.BatchContainers.SelectMany(batch => batch.GetEvents<T>()));
}
}
private Task NextItem(T item, StreamSequenceToken token)
{
// This method could potentially be invoked after Dispose() has been called,
// so we have to ignore the request or we risk breaking unit tests AQ_01 - AQ_04.
if (this.observer == null || !IsValid)
return Task.CompletedTask;
if (filterWrapper != null && !filterWrapper.ShouldReceive(streamImpl, filterWrapper.FilterData, item))
return Task.CompletedTask;
return this.observer.OnNextAsync(item, token);
}
private Task NextItems(IEnumerable<Tuple<T, StreamSequenceToken>> items)
{
// This method could potentially be invoked after Dispose() has been called,
// so we have to ignore the request or we risk breaking unit tests AQ_01 - AQ_04.
if (this.batchObserver == null || !IsValid)
return Task.CompletedTask;
IList<SequentialItem<T>> batch = items
.Where(item => filterWrapper == null || !filterWrapper.ShouldReceive(streamImpl, filterWrapper.FilterData, item))
.Select(item => new SequentialItem<T>(item.Item1, item.Item2))
.ToList();
return batch.Count != 0 ? this.batchObserver.OnNextAsync(batch) : Task.CompletedTask;
}
public Task CompleteStream()
{
return this.observer is null
? this.batchObserver is null
? Task.CompletedTask
: this.batchObserver.OnCompletedAsync()
: this.observer.OnCompletedAsync();
}
public Task ErrorInStream(Exception ex)
{
return this.observer is null
? this.batchObserver is null
? Task.CompletedTask
: this.batchObserver.OnErrorAsync(ex)
: this.observer.OnErrorAsync(ex);
}
internal bool SameStreamId(StreamId streamId)
{
return IsValid && streamImpl.StreamId.Equals(streamId);
}
public override bool Equals(StreamSubscriptionHandle<T> other)
{
var o = other as StreamSubscriptionHandleImpl<T>;
return o != null && SubscriptionId.Equals(o.SubscriptionId);
}
public override bool Equals(object obj)
{
return Equals(obj as StreamSubscriptionHandle<T>);
}
public override int GetHashCode()
{
return SubscriptionId.GetHashCode();
}
public override string ToString()
{
return String.Format("StreamSubscriptionHandleImpl:Stream={0},HandleId={1}", IsValid ? streamImpl.StreamId.ToString() : "null", HandleId);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.PostEditor.Tagging
{
/// <summary>
/// Summary description for CreateTagForm.
/// </summary>
public class EditTagForm : BaseForm
{
public TagProvider Provider
{
get
{
TagProvider provider;
if (_id != null)
provider = new TagProvider(_id);
else
provider = new TagProvider();
provider.Name = textBoxName.Text;
provider.HtmlFormat = textBoxHtmlFormat.Text;
provider.Caption = textBoxCaption.Text;
provider.Separator = textBoxSeparator.Text;
return provider;
}
set
{
_id = value.Id;
textBoxName.Text = value.Name;
if (value.Name != null && value.Name != string.Empty)
Text = string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.TagsEditPattern), value.Name);
textBoxCaption.Text = value.Caption;
textBoxHtmlFormat.Text = value.HtmlFormat;
textBoxSeparator.Text = value.Separator;
if (!value.New)
_captionDirty = true;
}
}
private Button buttonOk;
private Button buttonCancel;
private Label label1;
private Label label5;
private TextBox textBoxSeparator;
private Label labelName;
private TextBox textBoxName;
private TextBox textBoxHtmlFormat;
private Label label4;
private TextBox textBoxCaption;
private TextBox textBoxPreview;
private Label label2;
private PictureBox pictureBox1;
private HelpProvider helpProviderCreateTag;
private string _id;
private Panel panelDetails;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public EditTagForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
textBoxHtmlFormat.RightToLeft = RightToLeft.No;
textBoxSeparator.RightToLeft = RightToLeft.No;
textBoxCaption.RightToLeft = RightToLeft.No;
textBoxPreview.RightToLeft = RightToLeft.No;
if (BidiHelper.IsRightToLeft)
{
textBoxHtmlFormat.TextAlign =
textBoxSeparator.TextAlign =
textBoxCaption.TextAlign = textBoxPreview.TextAlign = HorizontalAlignment.Right;
}
buttonOk.Text = Res.Get(StringId.OKButtonText);
buttonCancel.Text = Res.Get(StringId.CancelButton);
label1.Text = Res.Get(StringId.TagsHtmlTemplateLabel);
helpProviderCreateTag.SetHelpString(textBoxHtmlFormat,
string.Format(CultureInfo.InvariantCulture, Res.Get(StringId.TagsHtmlTemplateHelpString), "{tag}",
"{tag-encoded}"));
label5.Text = Res.Get(StringId.TagsHtmlDelimiterLabel);
helpProviderCreateTag.SetHelpString(textBoxSeparator, Res.Get(StringId.TagsHtmlDelimiterHelpString));
labelName.Text = Res.Get(StringId.TagsProviderNameLabel);
helpProviderCreateTag.SetHelpString(textBoxName, Res.Get(StringId.TagsProviderNameHelpString));
label4.Text = Res.Get(StringId.TagsHtmlCaptionLabel);
helpProviderCreateTag.SetHelpString(textBoxCaption,
string.Format(CultureInfo.InvariantCulture, Res.Get(StringId.TagsHtmlCaptionHelpString), "{tag-group}"));
label2.Text = Res.Get(StringId.TagsHtmlPreviewLabel);
helpProviderCreateTag.SetHelpString(textBoxPreview, Res.Get(StringId.TagsHtmlPreviewHelpString));
Text = Res.Get(StringId.TagsCreateNew);
LayoutHelper.FixupOKCancel(buttonOk, buttonCancel);
SinkEvents();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
int origHeight = panelDetails.Height;
using (new AutoGrow(panelDetails, AnchorStyles.Bottom, true))
{
LayoutHelper.NaturalizeHeightAndDistribute(8, panelDetails.Controls);
LayoutHelper.NaturalizeHeightAndDistribute(2, labelName, textBoxName);
LayoutHelper.NaturalizeHeightAndDistribute(8, textBoxName, label1);
LayoutHelper.NaturalizeHeightAndDistribute(2, label1, textBoxHtmlFormat);
LayoutHelper.NaturalizeHeightAndDistribute(8, textBoxHtmlFormat, label5);
LayoutHelper.NaturalizeHeightAndDistribute(2, label5, textBoxSeparator);
LayoutHelper.NaturalizeHeightAndDistribute(8, textBoxSeparator, label4);
LayoutHelper.NaturalizeHeightAndDistribute(2, label4, textBoxCaption);
LayoutHelper.NaturalizeHeightAndDistribute(8, textBoxCaption, label2);
LayoutHelper.NaturalizeHeightAndDistribute(2, label2, textBoxPreview);
}
Height += panelDetails.Height - origHeight;
LayoutHelper.FixupOKCancel(buttonOk, buttonCancel);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
UnSinkEvents();
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditTagForm));
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.textBoxHtmlFormat = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.textBoxSeparator = new System.Windows.Forms.TextBox();
this.labelName = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxCaption = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.textBoxPreview = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.helpProviderCreateTag = new System.Windows.Forms.HelpProvider();
this.panelDetails = new System.Windows.Forms.Panel();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panelDetails.SuspendLayout();
this.SuspendLayout();
//
// buttonOk
//
this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOk.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOk.Location = new System.Drawing.Point(232, 376);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 50;
this.buttonOk.Text = "OK";
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonCancel.Location = new System.Drawing.Point(312, 376);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 55;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// textBoxHtmlFormat
//
this.textBoxHtmlFormat.AcceptsReturn = true;
this.textBoxHtmlFormat.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpProviderCreateTag.SetHelpString(this.textBoxHtmlFormat, resources.GetString("textBoxHtmlFormat.HelpString"));
this.textBoxHtmlFormat.Location = new System.Drawing.Point(0, 64);
this.textBoxHtmlFormat.Multiline = true;
this.textBoxHtmlFormat.Name = "textBoxHtmlFormat";
this.helpProviderCreateTag.SetShowHelp(this.textBoxHtmlFormat, true);
this.textBoxHtmlFormat.Size = new System.Drawing.Size(296, 64);
this.textBoxHtmlFormat.TabIndex = 15;
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(0, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(288, 16);
this.label1.TabIndex = 10;
this.label1.Text = "&HTML template for each tag:";
//
// label5
//
this.label5.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label5.Location = new System.Drawing.Point(0, 136);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(288, 16);
this.label5.TabIndex = 20;
this.label5.Text = "&Separate the HTML for each tag using:";
//
// textBoxSeparator
//
this.textBoxSeparator.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpProviderCreateTag.SetHelpString(this.textBoxSeparator, "The separator that should appear between tag HTML. The separator will appear betw" +
"een the HTML that is generated for each tag.");
this.textBoxSeparator.Location = new System.Drawing.Point(0, 152);
this.textBoxSeparator.Name = "textBoxSeparator";
this.helpProviderCreateTag.SetShowHelp(this.textBoxSeparator, true);
this.textBoxSeparator.Size = new System.Drawing.Size(296, 23);
this.textBoxSeparator.TabIndex = 25;
//
// labelName
//
this.labelName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelName.Location = new System.Drawing.Point(0, 0);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(288, 16);
this.labelName.TabIndex = 0;
this.labelName.Text = "&Provider name:";
//
// textBoxName
//
this.textBoxName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpProviderCreateTag.SetHelpString(this.textBoxName, "The name of the tag provider. This name will be displayed when inserting tags.");
this.textBoxName.Location = new System.Drawing.Point(0, 16);
this.textBoxName.Name = "textBoxName";
this.helpProviderCreateTag.SetShowHelp(this.textBoxName, true);
this.textBoxName.Size = new System.Drawing.Size(296, 23);
this.textBoxName.TabIndex = 5;
//
// textBoxCaption
//
this.textBoxCaption.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpProviderCreateTag.SetHelpString(this.textBoxCaption, "The HTML caption that will appear with the HTML generated for the tags. Use {tag-" +
"group} where you\'d like the HTML generated from the HTML tag template to be plac" +
"ed.");
this.textBoxCaption.Location = new System.Drawing.Point(0, 200);
this.textBoxCaption.Multiline = true;
this.textBoxCaption.Name = "textBoxCaption";
this.helpProviderCreateTag.SetShowHelp(this.textBoxCaption, true);
this.textBoxCaption.Size = new System.Drawing.Size(296, 40);
this.textBoxCaption.TabIndex = 35;
//
// label4
//
this.label4.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label4.Location = new System.Drawing.Point(0, 184);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(288, 16);
this.label4.TabIndex = 30;
this.label4.Text = "HTML &caption for tag list:";
//
// textBoxPreview
//
this.textBoxPreview.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.helpProviderCreateTag.SetHelpString(this.textBoxPreview, "A preview of the literal HTML that will be generated for a set of tags.");
this.textBoxPreview.Location = new System.Drawing.Point(0, 264);
this.textBoxPreview.Multiline = true;
this.textBoxPreview.Name = "textBoxPreview";
this.textBoxPreview.ReadOnly = true;
this.textBoxPreview.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.helpProviderCreateTag.SetShowHelp(this.textBoxPreview, true);
this.textBoxPreview.Size = new System.Drawing.Size(296, 88);
this.textBoxPreview.TabIndex = 45;
this.textBoxPreview.TabStop = false;
//
// label2
//
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(0, 248);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(288, 16);
this.label2.TabIndex = 40;
this.label2.Text = "HTML preview:";
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(8, 24);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(72, 64);
this.pictureBox1.TabIndex = 46;
this.pictureBox1.TabStop = false;
//
// panelDetails
//
this.panelDetails.Controls.Add(this.label5);
this.panelDetails.Controls.Add(this.label2);
this.panelDetails.Controls.Add(this.label4);
this.panelDetails.Controls.Add(this.textBoxHtmlFormat);
this.panelDetails.Controls.Add(this.textBoxSeparator);
this.panelDetails.Controls.Add(this.label1);
this.panelDetails.Controls.Add(this.textBoxPreview);
this.panelDetails.Controls.Add(this.textBoxName);
this.panelDetails.Controls.Add(this.textBoxCaption);
this.panelDetails.Controls.Add(this.labelName);
this.panelDetails.Location = new System.Drawing.Point(88, 8);
this.panelDetails.Name = "panelDetails";
this.panelDetails.Size = new System.Drawing.Size(296, 352);
this.panelDetails.TabIndex = 0;
//
// EditTagForm
//
this.AcceptButton = this.buttonOk;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(402, 416);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.panelDetails);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "EditTagForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Create New Tag Provider";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panelDetails.ResumeLayout(false);
this.panelDetails.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private bool Valid()
{
if (textBoxName.Text.Trim() == string.Empty)
{
DisplayMessage.Show(MessageId.TagProviderNameRequired);
textBoxName.Focus();
return false;
}
if (textBoxHtmlFormat.Text == string.Empty)
{
DisplayMessage.Show(MessageId.TagFormatRequired);
textBoxHtmlFormat.Focus();
return false;
}
if (textBoxCaption.Text.IndexOf(TagProvider.TAG_GROUP_TOKEN) < 0)
{
DisplayMessage.Show(MessageId.TagMissingToken, TagProvider.TAG_GROUP_TOKEN);
textBoxCaption.Focus();
return false;
}
return true;
}
private void buttonOk_Click(object sender, EventArgs e)
{
if (Valid())
DialogResult = DialogResult.OK;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void SinkEvents()
{
textBoxCaption.TextChanged += new EventHandler(This_TextChanged);
textBoxHtmlFormat.TextChanged += new EventHandler(This_TextChanged);
textBoxName.TextChanged += new EventHandler(TextBoxName_TextChanged);
textBoxSeparator.TextChanged += new EventHandler(This_TextChanged);
textBoxCaption.KeyDown += new KeyEventHandler(textBoxCaption_KeyDown);
}
private void UnSinkEvents()
{
textBoxCaption.TextChanged -= new EventHandler(This_TextChanged);
textBoxHtmlFormat.TextChanged -= new EventHandler(This_TextChanged);
textBoxName.TextChanged -= new EventHandler(TextBoxName_TextChanged);
textBoxSeparator.TextChanged -= new EventHandler(This_TextChanged);
textBoxCaption.KeyDown -= new KeyEventHandler(textBoxCaption_KeyDown);
}
private void GeneratePreview()
{
textBoxPreview.Text =
Provider.GenerateHtmlForTags(new string[] { Res.Get(StringId.TagsTagExample1), Res.Get(StringId.TagsTagExample2) });
}
private void TextBoxName_TextChanged(object sender, EventArgs e)
{
if (!_captionDirty)
{
if (_captionText == null)
_captionText = textBoxCaption.Text;
textBoxCaption.Text = textBoxName.Text + " " + _captionText;
}
GeneratePreview();
}
private void This_TextChanged(object sender, EventArgs e)
{
GeneratePreview();
}
private bool _captionDirty = false;
private string _captionText = null;
private void textBoxCaption_KeyDown(object sender, KeyEventArgs e)
{
_captionDirty = true;
}
}
}
| |
namespace MahjongBuddy.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class Upgraded_To_V0_9 : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
AlterTableAnnotations(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_TenantFeatureSetting_MustHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_PermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
{
"DynamicFilter_RolePermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
{
"DynamicFilter_UserPermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLogin_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserRole_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_Setting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLoginAttempt_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserNotificationInfo_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AddColumn("dbo.AbpPermissions", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserLogins", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserRoles", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserNotifications", "TenantId", c => c.Int());
AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 255));
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
//Update current AbpUserRoles.TenantId values
Sql(@"UPDATE AbpUserRoles
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserRoles.UserId = AbpUsers.Id");
//Update current AbpUserLogins.TenantId values
Sql(@"UPDATE AbpUserLogins
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserLogins.UserId = AbpUsers.Id");
//Update current AbpPermissions.TenantId values
Sql(@"UPDATE AbpPermissions
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpPermissions.UserId = AbpUsers.Id");
Sql(@"UPDATE AbpPermissions
SET TenantId = AbpRoles.TenantId
FROM AbpRoles
WHERE AbpPermissions.RoleId = AbpRoles.Id");
//Update current AbpUserNotifications.TenantId values
Sql(@"UPDATE AbpUserNotifications
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserNotifications.UserId = AbpUsers.Id");
//Update current AbpSettings.TenantId values
Sql(@"UPDATE AbpSettings
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpSettings.UserId = AbpUsers.Id");
}
public override void Down()
{
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 256));
DropColumn("dbo.AbpUserNotifications", "TenantId");
DropColumn("dbo.AbpUserRoles", "TenantId");
DropColumn("dbo.AbpUserLogins", "TenantId");
DropColumn("dbo.AbpPermissions", "TenantId");
AlterTableAnnotations(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserNotificationInfo_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLoginAttempt_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_Setting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserRole_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLogin_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_PermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
{
"DynamicFilter_RolePermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
{
"DynamicFilter_UserPermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_TenantFeatureSetting_MustHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
AddForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants", "Id");
AddForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants", "Id");
AddForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants", "Id");
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.
//
namespace NLog.Internal
{
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Provides untyped IDictionary interface on top of generic IDictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
internal class DictionaryAdapter<TKey, TValue> : IDictionary
{
private readonly IDictionary<TKey, TValue> _implementation;
/// <summary>
/// Initializes a new instance of the DictionaryAdapter class.
/// </summary>
/// <param name="implementation">The implementation.</param>
public DictionaryAdapter(IDictionary<TKey, TValue> implementation)
{
_implementation = implementation;
}
/// <summary>
/// Gets an <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.ICollection"/> object containing the values in the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public ICollection Values => new List<TValue>(_implementation.Values);
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
public int Count => _implementation.Count;
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <value></value>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.
/// </returns>
public bool IsSynchronized => false;
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
public object SyncRoot => _implementation;
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object has a fixed size.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object has a fixed size; otherwise, false.
/// </returns>
public bool IsFixedSize => false;
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly => _implementation.IsReadOnly;
/// <summary>
/// Gets an <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.ICollection"/> object containing the keys of the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public ICollection Keys => new List<TKey>(_implementation.Keys);
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <param name="key">Dictionary key.</param>
/// <returns>Value corresponding to key or null if not found</returns>
public object this[object key]
{
get
{
TValue value;
if (_implementation.TryGetValue((TKey)key, out value))
{
return value;
}
else
{
return null;
}
}
set => _implementation[(TKey)key] = (TValue)value;
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="T:System.Object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="T:System.Object"/> to use as the value of the element to add.</param>
public void Add(object key, object value)
{
_implementation.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Removes all elements from the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
public void Clear()
{
_implementation.Clear();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"/> object.</param>
/// <returns>
/// True if the <see cref="T:System.Collections.IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
public bool Contains(object key)
{
return _implementation.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
public IDictionaryEnumerator GetEnumerator()
{
return new MyEnumerator(_implementation.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
public void Remove(object key)
{
_implementation.Remove((TKey)key);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Wrapper IDictionaryEnumerator.
/// </summary>
private class MyEnumerator : IDictionaryEnumerator
{
private readonly IEnumerator<KeyValuePair<TKey, TValue>> _wrapped;
/// <summary>
/// Initializes a new instance of the <see cref="MyEnumerator" /> class.
/// </summary>
/// <param name="wrapped">The wrapped.</param>
public MyEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> wrapped)
{
_wrapped = wrapped;
}
/// <summary>
/// Gets both the key and the value of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// A <see cref="T:System.Collections.DictionaryEntry"/> containing both the key and the value of the current dictionary entry.
/// </returns>
public DictionaryEntry Entry => new DictionaryEntry(_wrapped.Current.Key, _wrapped.Current.Value);
/// <summary>
/// Gets the key of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// The key of the current element of the enumeration.
/// </returns>
public object Key => _wrapped.Current.Key;
/// <summary>
/// Gets the value of the current dictionary entry.
/// </summary>
/// <value></value>
/// <returns>
/// The value of the current element of the enumeration.
/// </returns>
public object Value => _wrapped.Current.Value;
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <value></value>
/// <returns>
/// The current element in the collection.
/// </returns>
public object Current => Entry;
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// True if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
return _wrapped.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
public void Reset()
{
_wrapped.Reset();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Text;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
internal partial class HttpConnection
{
private sealed class ChunkedEncodingReadStream : HttpContentReadStream
{
/// <summary>How long a chunk indicator is allowed to be.</summary>
/// <remarks>
/// While most chunks indicators will contain no more than ulong.MaxValue.ToString("X").Length characters,
/// "chunk extensions" are allowed. We place a limit on how long a line can be to avoid OOM issues if an
/// infinite chunk length is sent. This value is arbitrary and can be changed as needed.
/// </remarks>
private const int MaxChunkBytesAllowed = 16 * 1024;
/// <summary>How long a trailing header can be. This value is arbitrary and can be changed as needed.</summary>
private const int MaxTrailingHeaderLength = 16 * 1024;
/// <summary>The number of bytes remaining in the chunk.</summary>
private ulong _chunkBytesRemaining;
/// <summary>The current state of the parsing state machine for the chunked response.</summary>
private ParsingState _state = ParsingState.ExpectChunkHeader;
private readonly HttpResponseMessage _response;
public ChunkedEncodingReadStream(HttpConnection connection, HttpResponseMessage response) : base(connection)
{
Debug.Assert(response != null, "The HttpResponseMessage cannot be null.");
_response = response;
}
public override int Read(Span<byte> buffer)
{
if (_connection == null || buffer.Length == 0)
{
// Response body fully consumed or the caller didn't ask for any data.
return 0;
}
// Try to consume from data we already have in the buffer.
int bytesRead = ReadChunksFromConnectionBuffer(buffer, cancellationRegistration: default);
if (bytesRead > 0)
{
return bytesRead;
}
// Nothing available to consume. Fall back to I/O.
while (true)
{
if (_connection == null)
{
// Fully consumed the response in ReadChunksFromConnectionBuffer.
return 0;
}
if (_state == ParsingState.ExpectChunkData &&
buffer.Length >= _connection.ReadBufferSize &&
_chunkBytesRemaining >= (ulong)_connection.ReadBufferSize)
{
// As an optimization, we skip going through the connection's read buffer if both
// the remaining chunk data and the buffer are both at least as large
// as the connection buffer. That avoids an unnecessary copy while still reading
// the maximum amount we'd otherwise read at a time.
Debug.Assert(_connection.RemainingBuffer.Length == 0);
bytesRead = _connection.Read(buffer.Slice(0, (int)Math.Min((ulong)buffer.Length, _chunkBytesRemaining)));
if (bytesRead == 0)
{
throw new IOException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _chunkBytesRemaining));
}
_chunkBytesRemaining -= (ulong)bytesRead;
if (_chunkBytesRemaining == 0)
{
_state = ParsingState.ExpectChunkTerminator;
}
return bytesRead;
}
// We're only here if we need more data to make forward progress.
_connection.Fill();
// Now that we have more, see if we can get any response data, and if
// we can we're done.
int bytesCopied = ReadChunksFromConnectionBuffer(buffer, cancellationRegistration: default);
if (bytesCopied > 0)
{
return bytesCopied;
}
}
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
// Cancellation requested.
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
if (_connection == null || buffer.Length == 0)
{
// Response body fully consumed or the caller didn't ask for any data.
return new ValueTask<int>(0);
}
// Try to consume from data we already have in the buffer.
int bytesRead = ReadChunksFromConnectionBuffer(buffer.Span, cancellationRegistration: default);
if (bytesRead > 0)
{
return new ValueTask<int>(bytesRead);
}
// We may have just consumed the remainder of the response (with no actual data
// available), so check again.
if (_connection == null)
{
Debug.Assert(_state == ParsingState.Done);
return new ValueTask<int>(0);
}
// Nothing available to consume. Fall back to I/O.
return ReadAsyncCore(buffer, cancellationToken);
}
private async ValueTask<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)
{
// Should only be called if ReadChunksFromConnectionBuffer returned 0.
Debug.Assert(_connection != null);
Debug.Assert(buffer.Length > 0);
CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken);
try
{
while (true)
{
if (_connection == null)
{
// Fully consumed the response in ReadChunksFromConnectionBuffer.
return 0;
}
if (_state == ParsingState.ExpectChunkData &&
buffer.Length >= _connection.ReadBufferSize &&
_chunkBytesRemaining >= (ulong)_connection.ReadBufferSize)
{
// As an optimization, we skip going through the connection's read buffer if both
// the remaining chunk data and the buffer are both at least as large
// as the connection buffer. That avoids an unnecessary copy while still reading
// the maximum amount we'd otherwise read at a time.
Debug.Assert(_connection.RemainingBuffer.Length == 0);
int bytesRead = await _connection.ReadAsync(buffer.Slice(0, (int)Math.Min((ulong)buffer.Length, _chunkBytesRemaining))).ConfigureAwait(false);
if (bytesRead == 0)
{
throw new IOException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _chunkBytesRemaining));
}
_chunkBytesRemaining -= (ulong)bytesRead;
if (_chunkBytesRemaining == 0)
{
_state = ParsingState.ExpectChunkTerminator;
}
return bytesRead;
}
// We're only here if we need more data to make forward progress.
await _connection.FillAsync().ConfigureAwait(false);
// Now that we have more, see if we can get any response data, and if
// we can we're done.
int bytesCopied = ReadChunksFromConnectionBuffer(buffer.Span, ctr);
if (bytesCopied > 0)
{
return bytesCopied;
}
}
}
catch (Exception exc) when (CancellationHelper.ShouldWrapInOperationCanceledException(exc, cancellationToken))
{
throw CancellationHelper.CreateOperationCanceledException(exc, cancellationToken);
}
finally
{
ctr.Dispose();
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
ValidateCopyToArgs(this, destination, bufferSize);
return
cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
_connection == null ? Task.CompletedTask :
CopyToAsyncCore(destination, cancellationToken);
}
private async Task CopyToAsyncCore(Stream destination, CancellationToken cancellationToken)
{
CancellationTokenRegistration ctr = _connection.RegisterCancellation(cancellationToken);
try
{
while (true)
{
while (true)
{
ReadOnlyMemory<byte> bytesRead = ReadChunkFromConnectionBuffer(int.MaxValue, ctr);
if (bytesRead.Length == 0)
{
break;
}
await destination.WriteAsync(bytesRead, cancellationToken).ConfigureAwait(false);
}
if (_connection == null)
{
// Fully consumed the response.
return;
}
await _connection.FillAsync().ConfigureAwait(false);
}
}
catch (Exception exc) when (CancellationHelper.ShouldWrapInOperationCanceledException(exc, cancellationToken))
{
throw CancellationHelper.CreateOperationCanceledException(exc, cancellationToken);
}
finally
{
ctr.Dispose();
}
}
private int ReadChunksFromConnectionBuffer(Span<byte> buffer, CancellationTokenRegistration cancellationRegistration)
{
int totalBytesRead = 0;
while (buffer.Length > 0)
{
ReadOnlyMemory<byte> bytesRead = ReadChunkFromConnectionBuffer(buffer.Length, cancellationRegistration);
Debug.Assert(bytesRead.Length <= buffer.Length);
if (bytesRead.Length == 0)
{
break;
}
totalBytesRead += bytesRead.Length;
bytesRead.Span.CopyTo(buffer);
buffer = buffer.Slice(bytesRead.Length);
}
return totalBytesRead;
}
private ReadOnlyMemory<byte> ReadChunkFromConnectionBuffer(int maxBytesToRead, CancellationTokenRegistration cancellationRegistration)
{
Debug.Assert(maxBytesToRead > 0);
try
{
ReadOnlySpan<byte> currentLine;
switch (_state)
{
case ParsingState.ExpectChunkHeader:
Debug.Assert(_chunkBytesRemaining == 0, $"Expected {nameof(_chunkBytesRemaining)} == 0, got {_chunkBytesRemaining}");
// Read the chunk header line.
_connection._allowedReadLineBytes = MaxChunkBytesAllowed;
if (!_connection.TryReadNextLine(out currentLine))
{
// Could not get a whole line, so we can't parse the chunk header.
return default;
}
// Parse the hex value from it.
if (!Utf8Parser.TryParse(currentLine, out ulong chunkSize, out int bytesConsumed, 'X'))
{
throw new IOException(SR.Format(SR.net_http_invalid_response_chunk_header_invalid, BitConverter.ToString(currentLine.ToArray())));
}
_chunkBytesRemaining = chunkSize;
// If there's a chunk extension after the chunk size, validate it.
if (bytesConsumed != currentLine.Length)
{
ValidateChunkExtension(currentLine.Slice(bytesConsumed));
}
// Proceed to handle the chunk. If there's data in it, go read it.
// Otherwise, finish handling the response.
if (chunkSize > 0)
{
_state = ParsingState.ExpectChunkData;
goto case ParsingState.ExpectChunkData;
}
else
{
_state = ParsingState.ConsumeTrailers;
goto case ParsingState.ConsumeTrailers;
}
case ParsingState.ExpectChunkData:
Debug.Assert(_chunkBytesRemaining > 0);
ReadOnlyMemory<byte> connectionBuffer = _connection.RemainingBuffer;
if (connectionBuffer.Length == 0)
{
return default;
}
int bytesToConsume = Math.Min(maxBytesToRead, (int)Math.Min((ulong)connectionBuffer.Length, _chunkBytesRemaining));
Debug.Assert(bytesToConsume > 0);
_connection.ConsumeFromRemainingBuffer(bytesToConsume);
_chunkBytesRemaining -= (ulong)bytesToConsume;
if (_chunkBytesRemaining == 0)
{
_state = ParsingState.ExpectChunkTerminator;
}
return connectionBuffer.Slice(0, bytesToConsume);
case ParsingState.ExpectChunkTerminator:
Debug.Assert(_chunkBytesRemaining == 0, $"Expected {nameof(_chunkBytesRemaining)} == 0, got {_chunkBytesRemaining}");
_connection._allowedReadLineBytes = MaxChunkBytesAllowed;
if (!_connection.TryReadNextLine(out currentLine))
{
return default;
}
if (currentLine.Length != 0)
{
throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_chunk_terminator_invalid, Encoding.ASCII.GetString(currentLine)));
}
_state = ParsingState.ExpectChunkHeader;
goto case ParsingState.ExpectChunkHeader;
case ParsingState.ConsumeTrailers:
Debug.Assert(_chunkBytesRemaining == 0, $"Expected {nameof(_chunkBytesRemaining)} == 0, got {_chunkBytesRemaining}");
while (true)
{
// TODO: Consider adding folded trailing header support #35769.
_connection._allowedReadLineBytes = MaxTrailingHeaderLength;
if (!_connection.TryReadNextLine(out currentLine))
{
break;
}
if (currentLine.IsEmpty)
{
// Dispose of the registration and then check whether cancellation has been
// requested. This is necessary to make determinstic a race condition between
// cancellation being requested and unregistering from the token. Otherwise,
// it's possible cancellation could be requested just before we unregister and
// we then return a connection to the pool that has been or will be disposed
// (e.g. if a timer is used and has already queued its callback but the
// callback hasn't yet run).
cancellationRegistration.Dispose();
CancellationHelper.ThrowIfCancellationRequested(cancellationRegistration.Token);
_state = ParsingState.Done;
_connection.CompleteResponse();
_connection = null;
break;
}
// Parse the trailer.
else if (!IsDisposed)
{
// Make sure that we don't inadvertently consume trailing headers
// while draining a connection that's being returned back to the pool.
HttpConnection.ParseHeaderNameValue(_connection, currentLine, _response, isFromTrailer: true);
}
}
return default;
default:
case ParsingState.Done: // shouldn't be called once we're done
Debug.Fail($"Unexpected state: {_state}");
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(this, $"Unexpected state: {_state}");
}
return default;
}
}
catch (Exception)
{
// Ensure we don't try to read from the connection again (in particular, for draining)
_connection.Dispose();
_connection = null;
throw;
}
}
private static void ValidateChunkExtension(ReadOnlySpan<byte> lineAfterChunkSize)
{
// Until we see the ';' denoting the extension, the line after the chunk size
// must contain only tabs and spaces. After the ';', anything goes.
for (int i = 0; i < lineAfterChunkSize.Length; i++)
{
byte c = lineAfterChunkSize[i];
if (c == ';')
{
break;
}
else if (c != ' ' && c != '\t') // not called out in the RFC, but WinHTTP allows it
{
throw new IOException(SR.Format(SR.net_http_invalid_response_chunk_extension_invalid, BitConverter.ToString(lineAfterChunkSize.ToArray())));
}
}
}
private enum ParsingState : byte
{
ExpectChunkHeader,
ExpectChunkData,
ExpectChunkTerminator,
ConsumeTrailers,
Done
}
public override bool NeedsDrain => (_connection != null);
public override async ValueTask<bool> DrainAsync(int maxDrainBytes)
{
Debug.Assert(_connection != null);
CancellationTokenSource cts = null;
CancellationTokenRegistration ctr = default;
try
{
int drainedBytes = 0;
while (true)
{
drainedBytes += _connection.RemainingBuffer.Length;
while (true)
{
ReadOnlyMemory<byte> bytesRead = ReadChunkFromConnectionBuffer(int.MaxValue, ctr);
if (bytesRead.Length == 0)
{
break;
}
}
// When ReadChunkFromConnectionBuffer reads the final chunk, it will clear out _connection
// and return the connection to the pool.
if (_connection == null)
{
return true;
}
if (drainedBytes >= maxDrainBytes)
{
return false;
}
if (cts == null) // only create the drain timer if we have to go async
{
TimeSpan drainTime = _connection._pool.Settings._maxResponseDrainTime;
if (drainTime != Timeout.InfiniteTimeSpan)
{
cts = new CancellationTokenSource((int)drainTime.TotalMilliseconds);
ctr = cts.Token.Register(s => ((HttpConnection)s).Dispose(), _connection);
}
}
await _connection.FillAsync().ConfigureAwait(false);
}
}
finally
{
ctr.Dispose();
cts?.Dispose();
}
}
}
}
}
| |
/*
* 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 System.Reflection;
using System.Text;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.Avatar.Attachments
{
/// <summary>
/// A module that just holds commands for inspecting avatar appearance.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SceneCommandsModule")]
public class SceneCommandsModule : ISceneCommandsModule, INonSharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
public string Name { get { return "Scene Commands Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("[SCENE COMMANDS MODULE]: INITIALIZED MODULE");
}
public void PostInitialise()
{
// m_log.DebugFormat("[SCENE COMMANDS MODULE]: POST INITIALIZED MODULE");
}
public void Close()
{
// m_log.DebugFormat("[SCENE COMMANDS MODULE]: CLOSED MODULE");
}
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName);
m_scene = scene;
m_scene.RegisterModuleInterface<ISceneCommandsModule>(this);
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName);
scene.AddCommand(
"Debug", this, "debug scene get",
"debug scene get",
"List current scene options.",
"If active is false then main scene update and maintenance loops are suspended.\n"
+ "If animations is true then extra animations debug information is logged.\n"
+ "If collisions is false then collisions with other objects are turned off.\n"
+ "If pbackup is false then periodic scene backup is turned off.\n"
+ "If physics is false then all physics objects are non-physical.\n"
+ "If scripting is false then no scripting operations happen.\n"
+ "If teleport is true then some extra teleport debug information is logged.\n"
+ "If updates is true then any frame which exceeds double the maximum desired frame time is logged.",
HandleDebugSceneGetCommand);
scene.AddCommand(
"Debug", this, "debug scene set",
"debug scene set active|collisions|pbackup|physics|scripting|teleport|updates true|false",
"Turn on scene debugging options.",
"If active is false then main scene update and maintenance loops are suspended.\n"
+ "If animations is true then extra animations debug information is logged.\n"
+ "If collisions is false then collisions with other objects are turned off.\n"
+ "If pbackup is false then periodic scene backup is turned off.\n"
+ "If physics is false then all physics objects are non-physical.\n"
+ "If scripting is false then no scripting operations happen.\n"
+ "If teleport is true then some extra teleport debug information is logged.\n"
+ "If updates is true then any frame which exceeds double the maximum desired frame time is logged.",
HandleDebugSceneSetCommand);
}
private void HandleDebugSceneGetCommand(string module, string[] args)
{
if (args.Length == 3)
{
if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null)
return;
OutputSceneDebugOptions();
}
else
{
MainConsole.Instance.Output("Usage: debug scene get");
}
}
private void OutputSceneDebugOptions()
{
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("active", m_scene.Active);
cdl.AddRow("animations", m_scene.DebugAnimations);
cdl.AddRow("pbackup", m_scene.PeriodicBackup);
cdl.AddRow("physics", m_scene.PhysicsEnabled);
cdl.AddRow("scripting", m_scene.ScriptsEnabled);
cdl.AddRow("teleport", m_scene.DebugTeleporting);
cdl.AddRow("updates", m_scene.DebugUpdates);
MainConsole.Instance.OutputFormat("Scene {0} options:", m_scene.Name);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleDebugSceneSetCommand(string module, string[] args)
{
if (args.Length == 5)
{
if (MainConsole.Instance.ConsoleScene != m_scene && MainConsole.Instance.ConsoleScene != null)
return;
string key = args[3];
string value = args[4];
SetSceneDebugOptions(new Dictionary<string, string>() { { key, value } });
MainConsole.Instance.OutputFormat("Set {0} debug scene {1} = {2}", m_scene.Name, key, value);
}
else
{
MainConsole.Instance.Output(
"Usage: debug scene set active|collisions|pbackup|physics|scripting|teleport|updates true|false");
}
}
public void SetSceneDebugOptions(Dictionary<string, string> options)
{
if (options.ContainsKey("active"))
{
bool active;
if (bool.TryParse(options["active"], out active))
m_scene.Active = active;
}
if (options.ContainsKey("animations"))
{
bool active;
if (bool.TryParse(options["animations"], out active))
m_scene.DebugAnimations = active;
}
if (options.ContainsKey("pbackup"))
{
bool active;
if (bool.TryParse(options["pbackup"], out active))
m_scene.PeriodicBackup = active;
}
if (options.ContainsKey("scripting"))
{
bool enableScripts = true;
if (bool.TryParse(options["scripting"], out enableScripts))
m_scene.ScriptsEnabled = enableScripts;
}
if (options.ContainsKey("physics"))
{
bool enablePhysics;
if (bool.TryParse(options["physics"], out enablePhysics))
m_scene.PhysicsEnabled = enablePhysics;
}
// if (options.ContainsKey("collisions"))
// {
// // TODO: Implement. If false, should stop objects colliding, though possibly should still allow
// // the avatar themselves to collide with the ground.
// }
if (options.ContainsKey("teleport"))
{
bool enableTeleportDebugging;
if (bool.TryParse(options["teleport"], out enableTeleportDebugging))
m_scene.DebugTeleporting = enableTeleportDebugging;
}
if (options.ContainsKey("updates"))
{
bool enableUpdateDebugging;
if (bool.TryParse(options["updates"], out enableUpdateDebugging))
{
m_scene.DebugUpdates = enableUpdateDebugging;
GcNotify.Enabled = enableUpdateDebugging;
}
}
}
}
}
| |
namespace DD.CBU.Compute.Api.Contracts.Server
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/server")]
[System.Xml.Serialization.XmlRootAttribute("Server", Namespace="http://oec.api.opsource.net/schemas/server", IsNullable=false)]
public partial class ServerType {
private string idField;
private string resourcePathField;
private string nameField;
private string descriptionField;
private string vlanResourcePathField;
private string imageResourcePathField;
private OperatingSystemType operatingSystemField;
private int cpuCountField;
private bool cpuCountFieldSpecified;
private int memoryField;
private bool memoryFieldSpecified;
private int osStorageField;
private bool osStorageFieldSpecified;
private int additionalLocalStorageField;
private bool additionalLocalStorageFieldSpecified;
private string machineNameField;
private string administratorPasswordField;
private string privateIPAddressField;
private bool isDeployedField;
private bool isStartedField;
private System.DateTime createdField;
private bool createdFieldSpecified;
/// <remarks/>
public string id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
public string resourcePath {
get {
return this.resourcePathField;
}
set {
this.resourcePathField = value;
}
}
/// <remarks/>
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public string description {
get {
return this.descriptionField;
}
set {
this.descriptionField = value;
}
}
/// <remarks/>
public string vlanResourcePath {
get {
return this.vlanResourcePathField;
}
set {
this.vlanResourcePathField = value;
}
}
/// <remarks/>
public string imageResourcePath {
get {
return this.imageResourcePathField;
}
set {
this.imageResourcePathField = value;
}
}
/// <remarks/>
public OperatingSystemType operatingSystem {
get {
return this.operatingSystemField;
}
set {
this.operatingSystemField = value;
}
}
/// <remarks/>
public int cpuCount {
get {
return this.cpuCountField;
}
set {
this.cpuCountField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool cpuCountSpecified {
get {
return this.cpuCountFieldSpecified;
}
set {
this.cpuCountFieldSpecified = value;
}
}
/// <remarks/>
public int memory {
get {
return this.memoryField;
}
set {
this.memoryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool memorySpecified {
get {
return this.memoryFieldSpecified;
}
set {
this.memoryFieldSpecified = value;
}
}
/// <remarks/>
public int osStorage {
get {
return this.osStorageField;
}
set {
this.osStorageField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool osStorageSpecified {
get {
return this.osStorageFieldSpecified;
}
set {
this.osStorageFieldSpecified = value;
}
}
/// <remarks/>
public int additionalLocalStorage {
get {
return this.additionalLocalStorageField;
}
set {
this.additionalLocalStorageField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool additionalLocalStorageSpecified {
get {
return this.additionalLocalStorageFieldSpecified;
}
set {
this.additionalLocalStorageFieldSpecified = value;
}
}
/// <remarks/>
public string machineName {
get {
return this.machineNameField;
}
set {
this.machineNameField = value;
}
}
/// <remarks/>
public string administratorPassword {
get {
return this.administratorPasswordField;
}
set {
this.administratorPasswordField = value;
}
}
/// <remarks/>
public string privateIPAddress {
get {
return this.privateIPAddressField;
}
set {
this.privateIPAddressField = value;
}
}
/// <remarks/>
public bool isDeployed {
get {
return this.isDeployedField;
}
set {
this.isDeployedField = value;
}
}
/// <remarks/>
public bool isStarted {
get {
return this.isStartedField;
}
set {
this.isStartedField = value;
}
}
/// <remarks/>
public System.DateTime created {
get {
return this.createdField;
}
set {
this.createdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool createdSpecified {
get {
return this.createdFieldSpecified;
}
set {
this.createdFieldSpecified = value;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBIteratorTests : CSharpPDBTestBase
{
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator1()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator2()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543490, "DevDiv")]
[Fact]
public void SimpleIterator3()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield return 1; //hidden sequence point after this.
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""0"" />
<entry offset=""0x30"" hidden=""true"" document=""0"" />
<entry offset=""0x37"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_ReleasePdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0xb3"" />
<slot startOffset=""0x6e"" endOffset=""0xb1"" />
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" />
<entry offset=""0x36"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" />
<entry offset=""0x4b"" hidden=""true"" document=""0"" />
<entry offset=""0x52"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" />
<entry offset=""0x67"" hidden=""true"" document=""0"" />
<entry offset=""0x6e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x7a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0x8f"" hidden=""true"" document=""0"" />
<entry offset=""0x96"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" />
<entry offset=""0xab"" hidden=""true"" document=""0"" />
<entry offset=""0xb2"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_DebugPdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""101"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x39"" endOffset=""0xc5"" />
<slot startOffset=""0x7e"" endOffset=""0xc3"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x39"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x3a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" />
<entry offset=""0x46"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" />
<entry offset=""0x5b"" hidden=""true"" document=""0"" />
<entry offset=""0x62"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" />
<entry offset=""0x77"" hidden=""true"" document=""0"" />
<entry offset=""0x7e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""0"" />
<entry offset=""0x7f"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x8b"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0xa0"" hidden=""true"" document=""0"" />
<entry offset=""0xa7"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" />
<entry offset=""0xbc"" hidden=""true"" document=""0"" />
<entry offset=""0xc3"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0xc4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithCapturedSyntheticVariables()
{
// this iterator captures the synthetic variable generated from the expansion of the foreach loop
var text = @"// Based on LegacyTest csharp\Source\Conformance\iterators\blocks\using001.cs
using System;
using System.Collections.Generic;
class Test<T>
{
public static IEnumerator<T> M(IEnumerable<T> items)
{
T val = default(T);
foreach (T item in items)
{
val = item;
yield return val;
}
yield return val;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test`1"" name=""M"" parameterNames=""items"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""5"" offset=""42"" />
<slot kind=""0"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""21"" endLine=""19"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""23"" endLine=""19"" endColumn=""24"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x32"" endOffset=""0xe1"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x5b"" endOffset=""0xa4"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x33"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""0"" />
<entry offset=""0x3f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""0"" />
<entry offset=""0x40"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""33"" document=""0"" />
<entry offset=""0x59"" hidden=""true"" document=""0"" />
<entry offset=""0x5b"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""0"" />
<entry offset=""0x6c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x6d"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" />
<entry offset=""0x79"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""0"" />
<entry offset=""0x90"" hidden=""true"" document=""0"" />
<entry offset=""0x98"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" />
<entry offset=""0xa5"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""0"" />
<entry offset=""0xc0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""26"" document=""0"" />
<entry offset=""0xd7"" hidden=""true"" document=""0"" />
<entry offset=""0xde"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
<entry offset=""0xe2"" hidden=""true"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(542705, "DevDiv"), WorkItem(528790, "DevDiv"), WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorBackToNextStatementAfterYieldReturn()
{
var text = @"
using System.Collections.Generic;
class C
{
IEnumerable<decimal> M()
{
const decimal d1 = 0.1M;
yield return d1;
const decimal dx = 1.23m;
yield return dx;
{
const decimal d2 = 0.2M;
yield return d2;
}
yield break;
}
static void Main()
{
foreach (var i in new C().M())
{
System.Console.WriteLine(i);
}
}
}
";
using (new CultureContext("en-US"))
{
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""21"" startColumn=""27"" endLine=""21"" endColumn=""38"" document=""0"" />
<entry offset=""0x10"" hidden=""true"" document=""0"" />
<entry offset=""0x12"" startLine=""21"" startColumn=""18"" endLine=""21"" endColumn=""23"" document=""0"" />
<entry offset=""0x18"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""41"" document=""0"" />
<entry offset=""0x1d"" startLine=""21"" startColumn=""24"" endLine=""21"" endColumn=""26"" document=""0"" />
<entry offset=""0x27"" hidden=""true"" document=""0"" />
<entry offset=""0x31"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x26"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""0"" />
<entry offset=""0x3f"" hidden=""true"" document=""0"" />
<entry offset=""0x46"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""25"" document=""0"" />
<entry offset=""0x60"" hidden=""true"" document=""0"" />
<entry offset=""0x67"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""29"" document=""0"" />
<entry offset=""0x80"" hidden=""true"" document=""0"" />
<entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x89"">
<scope startOffset=""0x26"" endOffset=""0x89"">
<constant name=""d1"" value=""0.1"" type=""Decimal"" />
<constant name=""dx"" value=""1.23"" type=""Decimal"" />
<scope startOffset=""0x67"" endOffset=""0x87"">
<constant name=""d2"" value=""0.2"" type=""Decimal"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
}
[WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorMultipleEnumerables()
{
var text = @"
using System;
using System.Collections;
using System.Collections.Generic;
public class Test<T> : IEnumerable<T> where T : class
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
foreach (var v in this.IterProp)
{
yield return v;
}
foreach (var v in IterMethod())
{
yield return v;
}
}
public IEnumerable<T> IterProp
{
get
{
yield return null;
yield return null;
}
}
public IEnumerable<T> IterMethod()
{
yield return default(T);
yield return null;
yield break;
}
}
public class Test
{
public static void Main()
{
foreach (var v in new Test<string>()) { }
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test`1"" name=""System.Collections.IEnumerable.GetEnumerator"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""32"" document=""0"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xc"">
<namespace name=""System"" />
<namespace name=""System.Collections"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1"" name=""GetEnumerator"">
<customDebugInfo>
<forwardIterator name=""<GetEnumerator>d__1"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""5"" offset=""104"" />
<slot kind=""0"" offset=""104"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""get_IterProp"">
<customDebugInfo>
<forwardIterator name=""<get_IterProp>d__3"" />
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""IterMethod"">
<customDebugInfo>
<forwardIterator name=""<IterMethod>d__4"" />
</customDebugInfo>
</method>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""45"" startColumn=""5"" endLine=""45"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""46"" startColumn=""9"" endLine=""46"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""46"" startColumn=""27"" endLine=""46"" endColumn=""45"" document=""0"" />
<entry offset=""0xd"" hidden=""true"" document=""0"" />
<entry offset=""0xf"" startLine=""46"" startColumn=""18"" endLine=""46"" endColumn=""23"" document=""0"" />
<entry offset=""0x16"" startLine=""46"" startColumn=""47"" endLine=""46"" endColumn=""48"" document=""0"" />
<entry offset=""0x17"" startLine=""46"" startColumn=""49"" endLine=""46"" endColumn=""50"" document=""0"" />
<entry offset=""0x18"" startLine=""46"" startColumn=""24"" endLine=""46"" endColumn=""26"" document=""0"" />
<entry offset=""0x22"" hidden=""true"" document=""0"" />
<entry offset=""0x2d"" startLine=""47"" startColumn=""5"" endLine=""47"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xf"" endOffset=""0x18"">
<local name=""v"" il_index=""1"" il_start=""0xf"" il_end=""0x18"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""Test`1+<GetEnumerator>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x54"" endOffset=""0x94"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0xd1"" endOffset=""0x10e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x32"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""16"" document=""0"" />
<entry offset=""0x34"" startLine=""15"" startColumn=""27"" endLine=""15"" endColumn=""40"" document=""0"" />
<entry offset=""0x52"" hidden=""true"" document=""0"" />
<entry offset=""0x54"" startLine=""15"" startColumn=""18"" endLine=""15"" endColumn=""23"" document=""0"" />
<entry offset=""0x65"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0x66"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""0"" />
<entry offset=""0x80"" hidden=""true"" document=""0"" />
<entry offset=""0x88"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""0"" />
<entry offset=""0x95"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""26"" document=""0"" />
<entry offset=""0xb0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""0"" />
<entry offset=""0xb1"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""39"" document=""0"" />
<entry offset=""0xcf"" hidden=""true"" document=""0"" />
<entry offset=""0xd1"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""0"" />
<entry offset=""0xe2"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""0"" />
<entry offset=""0xe3"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""28"" document=""0"" />
<entry offset=""0xfa"" hidden=""true"" document=""0"" />
<entry offset=""0x102"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" />
<entry offset=""0x10f"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""0"" />
<entry offset=""0x12a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""0"" />
<entry offset=""0x12e"" hidden=""true"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<get_IterProp>d__3"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""0"" />
<entry offset=""0x2b"" startLine=""29"" startColumn=""13"" endLine=""29"" endColumn=""31"" document=""0"" />
<entry offset=""0x40"" hidden=""true"" document=""0"" />
<entry offset=""0x47"" startLine=""30"" startColumn=""13"" endLine=""30"" endColumn=""31"" document=""0"" />
<entry offset=""0x5c"" hidden=""true"" document=""0"" />
<entry offset=""0x63"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""10"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<IterMethod>d__4"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""33"" document=""0"" />
<entry offset=""0x40"" hidden=""true"" document=""0"" />
<entry offset=""0x47"" startLine=""37"" startColumn=""9"" endLine=""37"" endColumn=""27"" document=""0"" />
<entry offset=""0x5c"" hidden=""true"" document=""0"" />
<entry offset=""0x63"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void VariablesWithSubstitutedType1()
{
var text = @"
using System.Collections.Generic;
class C
{
static IEnumerable<T> F<T>(T[] o)
{
int i = 0;
T t = default(T);
yield return t;
yield return o[i];
}
}
";
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"o", "<>3__o",
"<i>5__1",
"<t>5__2"
}, module.GetFieldNames("C.<F>d__0"));
});
v.VerifyPdb("C+<F>d__0`1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0x82"" />
<slot startOffset=""0x2a"" endOffset=""0x82"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""0"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""0"" />
<entry offset=""0x3e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x53"" hidden=""true"" document=""0"" />
<entry offset=""0x5a"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x7a"" hidden=""true"" document=""0"" />
<entry offset=""0x81"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x83"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithConditionalBranchDiscriminator1()
{
var text = @"
using System.Collections.Generic;
class C
{
static bool B() => false;
static IEnumerable<int> F()
{
if (B())
{
yield return 1;
}
}
}
";
// Note that conditional branch discriminator is not hoisted.
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<F>d__1"));
});
v.VerifyIL("C.<F>d__1.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 68 (0x44)
.maxstack 2
.locals init (int V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003a
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__1.<>1__state""
IL_001f: nop
IL_0020: call ""bool C.B()""
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brfalse.s IL_0042
IL_0029: nop
IL_002a: ldarg.0
IL_002b: ldc.i4.1
IL_002c: stfld ""int C.<F>d__1.<>2__current""
IL_0031: ldarg.0
IL_0032: ldc.i4.1
IL_0033: stfld ""int C.<F>d__1.<>1__state""
IL_0038: ldc.i4.1
IL_0039: ret
IL_003a: ldarg.0
IL_003b: ldc.i4.m1
IL_003c: stfld ""int C.<F>d__1.<>1__state""
IL_0041: nop
IL_0042: ldc.i4.0
IL_0043: ret
}
");
v.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""17"" document=""0"" />
<entry offset=""0x26"" hidden=""true"" document=""0"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""0"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0x3a"" hidden=""true"" document=""0"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x42"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x44"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SynthesizedVariables1()
{
var source =
@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> M(IDisposable disposable)
{
foreach (var item in new[] { 1, 2, 3 }) { lock (this) { yield return 1; } }
foreach (var item in new[] { 1, 2, 3 }) { }
lock (this) { yield return 2; }
if (disposable != null) { using (disposable) { yield return 3; } }
lock (this) { yield return 4; }
if (disposable != null) { using (disposable) { } }
lock (this) { }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>4__this",
"disposable",
"<>3__disposable",
"<>7__wrap1",
"<>7__wrap2",
"<>7__wrap3",
"<>7__wrap4",
"<>7__wrap5",
}, module.GetFieldNames("C.<M>d__0"));
});
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"disposable",
"<>3__disposable",
"<>4__this",
"<>s__1",
"<>s__2",
"<item>5__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<>s__7",
"<item>5__8",
"<>s__9",
"<>s__10",
"<>s__11",
"<>s__12",
"<>s__13",
"<>s__14",
"<>s__15",
"<>s__16"
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""disposable"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""3"" offset=""53"" />
<slot kind=""2"" offset=""53"" />
<slot kind=""6"" offset=""96"" />
<slot kind=""8"" offset=""96"" />
<slot kind=""0"" offset=""96"" />
<slot kind=""3"" offset=""149"" />
<slot kind=""2"" offset=""149"" />
<slot kind=""4"" offset=""216"" />
<slot kind=""3"" offset=""266"" />
<slot kind=""2"" offset=""266"" />
<slot kind=""4"" offset=""333"" />
<slot kind=""3"" offset=""367"" />
<slot kind=""2"" offset=""367"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_AccrossSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return x1 + x2 + x3;
yield return x1 + x2 + x3;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
// One iterator local entry for the lambda local.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x30"" endOffset=""0xea"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x30"" hidden=""true"" document=""0"" />
<entry offset=""0x3b"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x3c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x48"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x54"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x60"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x77"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""35"" document=""0"" />
<entry offset=""0xa9"" hidden=""true"" document=""0"" />
<entry offset=""0xb0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""35"" document=""0"" />
<entry offset=""0xe2"" hidden=""true"" document=""0"" />
<entry offset=""0xe9"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Release()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// TODO: Currently we don't have means neccessary to pass information about the display
// class being pushed on evaluation stack, so that EE could find the locals.
// Thus the locals are not available in EE.
var v = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 90 (0x5a)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq.s IL_0051
IL_000e: ldc.i4.0
IL_000f: ret
IL_0010: ldarg.0
IL_0011: ldc.i4.m1
IL_0012: stfld ""int C.<M>d__0.<>1__state""
IL_0017: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_001c: dup
IL_001d: ldc.i4.1
IL_001e: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0023: dup
IL_0024: ldc.i4.1
IL_0025: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_002a: dup
IL_002b: ldc.i4.1
IL_002c: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_0031: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_0037: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_003c: callvirt ""void System.Action.Invoke()""
IL_0041: ldarg.0
IL_0042: ldc.i4.1
IL_0043: stfld ""int C.<M>d__0.<>2__current""
IL_0048: ldarg.0
IL_0049: ldc.i4.1
IL_004a: stfld ""int C.<M>d__0.<>1__state""
IL_004f: ldc.i4.1
IL_0050: ret
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: stfld ""int C.<M>d__0.<>1__state""
IL_0058: ldc.i4.0
IL_0059: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" hidden=""true"" document=""0"" />
<entry offset=""0x1c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x31"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x41"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x51"" hidden=""true"" document=""0"" />
<entry offset=""0x58"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
// Possible EnC edit - add lambda:
// () => { x1 }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// We need to hoist display class variable to allow adding a new lambda after yield return
// that shares closure with the existing lambda.
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0076
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<M>d__0.<>1__state""
IL_001f: ldarg.0
IL_0020: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0025: stfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_002a: nop
IL_002b: ldarg.0
IL_002c: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0031: ldc.i4.1
IL_0032: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0037: ldarg.0
IL_0038: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_003d: ldc.i4.1
IL_003e: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_0043: ldarg.0
IL_0044: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0049: ldc.i4.1
IL_004a: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_004f: ldarg.0
IL_0050: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0055: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_005b: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0060: callvirt ""void System.Action.Invoke()""
IL_0065: nop
IL_0066: ldarg.0
IL_0067: ldc.i4.1
IL_0068: stfld ""int C.<M>d__0.<>2__current""
IL_006d: ldarg.0
IL_006e: ldc.i4.1
IL_006f: stfld ""int C.<M>d__0.<>1__state""
IL_0074: ldc.i4.1
IL_0075: ret
IL_0076: ldarg.0
IL_0077: ldc.i4.m1
IL_0078: stfld ""int C.<M>d__0.<>1__state""
IL_007d: ldc.i4.0
IL_007e: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x7e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x37"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x43"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x66"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x76"" hidden=""true"" document=""0"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DynamicLocal_AccrossSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
d.ToString();
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1"
}, module.GetFieldNames("C.<M>d__0"));
});
// CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching
// any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0xe2"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x82"" hidden=""true"" document=""0"" />
<entry offset=""0x89"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" document=""0"" />
<entry offset=""0xe1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Release()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x6d"" hidden=""true"" document=""0"" />
<entry offset=""0x74"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x76"">
<scope startOffset=""0x17"" endOffset=""0x76"">
<local name=""d"" il_index=""1"" il_start=""0x17"" il_end=""0x76"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
// Possible EnC edit:
// System.Console.WriteLine(d);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x8a"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x82"" hidden=""true"" document=""0"" />
<entry offset=""0x89"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(667579, "DevDiv")]
public void DebuggerHiddenIterator()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Diagnostics;
class C
{
static void Main(string[] args)
{
foreach (var x in F()) ;
}
[DebuggerHidden]
static IEnumerable<int> F()
{
throw new Exception();
yield break;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class ConditionalTests
{
[Fact]
public void VisitIfThenDoesNotCloneTree()
{
Expression ifTrue = ((Expression<Action>)(() => Nop())).Body;
ConditionalExpression e = Expression.IfThen(Expression.Constant(true), ifTrue);
Expression r = new Visitor().Visit(e);
Assert.Same(e, r);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void Conditional(bool useInterpreter)
{
Expression<Func<int, int, int>> f = (x, y) => x > 5 ? x : y;
Func<int, int, int> d = f.Compile(useInterpreter);
Assert.Equal(7, d(7, 4));
Assert.Equal(6, d(3, 6));
}
[Fact]
public void NullTest()
{
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.IfThen(null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.IfThenElse(null, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableTest()
{
Expression test = Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(test, Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(test, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfTrue()
{
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableIfTrue()
{
Expression ifTrue = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), ifTrue));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), ifTrue, Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfFalse()
{
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), null));
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null));
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null, typeof(void)));
}
[Fact]
public void UnreadbleIfFalse()
{
Expression ifFalse = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), ifFalse));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), ifFalse));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), ifFalse, typeof(void)));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), Expression.Empty(), null));
}
[Fact]
public void NonBooleanTest()
{
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(0), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty(), typeof(void)));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Empty(), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty(), typeof(void)));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(true, typeof(bool?)), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty(), typeof(void)));
ConstantExpression truthyConstant = Expression.Constant(new Truthiness(true));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(truthyConstant), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void IncompatibleImplicitTypes()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(new object())));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(new object()), Expression.Constant("hello")));
}
[Fact]
public void IncompatibleExplicitTypes()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(int)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(int)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(long)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(long)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant("hello"), typeof(object)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(0), typeof(object)));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AnyTypesAllowedWithExplicitVoid(bool useInterpreter)
{
Action act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(void))
).Compile(useInterpreter);
act();
act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(void))
).Compile(useInterpreter);
act();
}
[Theory, PerCompilationType(nameof(ConditionalValues))]
public void ConditionalSelectsCorrectExpression(bool test, object ifTrue, object ifFalse, object expected, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Convert(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse)
),
typeof(object)
)
).Compile(useInterpreter);
Assert.Equal(expected, func());
}
[Theory, PerCompilationType(nameof(ConditionalValuesWithTypes))]
public void ConditionalSelectsCorrectExpressionWithType(bool test, object ifTrue, object ifFalse, object expected, Type type, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse),
type
)
).Compile(useInterpreter);
Assert.Same(expected, func());
}
[Fact]
public void ByRefType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakeByRefType()));
}
[Fact]
public void PointerType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakePointerType()));
}
[Fact]
public void GenericType()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>)));
}
[Fact]
public void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>(() => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public static void ToStringTest()
{
ConditionalExpression e1 = Expression.Condition(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(int), "b"), Expression.Parameter(typeof(int), "c"));
Assert.Equal("IIF(a, b, c)", e1.ToString());
ConditionalExpression e2 = Expression.IfThen(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("IIF(a, b, default(Void))", e2.ToString());
}
private static IEnumerable<object[]> ConditionalValues()
{
yield return new object[] { true, "yes", "no", "yes" };
yield return new object[] { false, "yes", "no", "no" };
yield return new object[] { true, 42, 12, 42 };
yield return new object[] { false, 42L, 12L, 12L };
}
private static IEnumerable<object[]> ConditionalValuesWithTypes()
{
ConstantExpression ce = Expression.Constant(98);
BinaryExpression be = Expression.And(Expression.Constant(2), Expression.Constant(3));
yield return new object[] { true, ce, be, ce, typeof(Expression) };
yield return new object[] { false, ce, be, be, typeof(Expression) };
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
private static void Nop()
{
}
private class Visitor : ExpressionVisitor
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using UnityTest.IntegrationTests;
#if UNITY_5_3_OR_NEWER
using UnityEditor.SceneManagement;
#endif
namespace UnityTest
{
public static partial class Batch
{
const string k_ResultFilePathParam = "-resultFilePath=";
private const string k_TestScenesParam = "-testscenes=";
private const string k_OtherBuildScenesParam = "-includeBuildScenes=";
const string k_TargetPlatformParam = "-targetPlatform=";
const string k_ResultFileDirParam = "-resultsFileDirectory=";
public static int returnCodeTestsOk = 0;
public static int returnCodeTestsFailed = 2;
public static int returnCodeRunError = 3;
public static void RunIntegrationTests()
{
var targetPlatform = GetTargetPlatform();
var otherBuildScenes = GetSceneListFromParam (k_OtherBuildScenesParam);
var testScenes = GetSceneListFromParam(k_TestScenesParam);
if (testScenes.Count == 0)
testScenes = FindTestScenesInProject();
RunIntegrationTests(targetPlatform, testScenes, otherBuildScenes);
}
public static void RunIntegrationTests(BuildTarget ? targetPlatform)
{
var sceneList = FindTestScenesInProject();
RunIntegrationTests(targetPlatform, sceneList, new List<string>());
}
public static void RunIntegrationTests(BuildTarget? targetPlatform, List<string> testScenes, List<string> otherBuildScenes)
{
if (targetPlatform.HasValue)
BuildAndRun(targetPlatform.Value, testScenes, otherBuildScenes);
else
RunInEditor(testScenes, otherBuildScenes);
}
private static void BuildAndRun(BuildTarget target, List<string> testScenes, List<string> otherBuildScenes)
{
var resultFilePath = GetParameterArgument(k_ResultFileDirParam);
const int port = 0;
var ipList = TestRunnerConfigurator.GetAvailableNetworkIPs();
var config = new PlatformRunnerConfiguration
{
buildTarget = target,
buildScenes = otherBuildScenes,
testScenes = testScenes,
projectName = "IntegrationTests",
resultsDir = resultFilePath,
sendResultsOverNetwork = InternalEditorUtility.inBatchMode,
ipList = ipList,
port = port
};
if (Application.isWebPlayer)
{
config.sendResultsOverNetwork = false;
Debug.Log("You can't use WebPlayer as active platform for running integration tests. Switching to Standalone");
EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.StandaloneWindows);
}
PlatformRunner.BuildAndRunInPlayer(config);
}
private static void RunInEditor(List<string> testScenes, List<string> otherBuildScenes)
{
CheckActiveBuildTarget();
NetworkResultsReceiver.StopReceiver();
if (testScenes == null || testScenes.Count == 0)
{
Debug.Log("No test scenes on the list");
EditorApplication.Exit(returnCodeRunError);
return;
}
string previousScenesXml = "";
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(EditorBuildSettingsScene[]));
using(StringWriter textWriter = new StringWriter())
{
serializer.Serialize(textWriter, EditorBuildSettings.scenes);
previousScenesXml = textWriter.ToString();
}
EditorBuildSettings.scenes = (testScenes.Concat(otherBuildScenes).ToList()).Select(s => new EditorBuildSettingsScene(s, true)).ToArray();
#if UNITY_5_3_OR_NEWER
EditorSceneManager.OpenScene(testScenes.First());
#else
EditorApplication.LoadLevelInPlayMode(testScenes.First());
#endif
GuiHelper.SetConsoleErrorPause(false);
var config = new PlatformRunnerConfiguration
{
resultsDir = GetParameterArgument(k_ResultFileDirParam),
ipList = TestRunnerConfigurator.GetAvailableNetworkIPs(),
port = PlatformRunnerConfiguration.TryToGetFreePort(),
runInEditor = true
};
var settings = new PlayerSettingConfigurator(true);
settings.AddConfigurationFile(TestRunnerConfigurator.integrationTestsNetwork, string.Join("\n", config.GetConnectionIPs()));
settings.AddConfigurationFile(TestRunnerConfigurator.testScenesToRun, string.Join ("\n", testScenes.ToArray()));
settings.AddConfigurationFile(TestRunnerConfigurator.previousScenes, previousScenesXml);
NetworkResultsReceiver.StartReceiver(config);
EditorApplication.isPlaying = true;
}
private static string GetParameterArgument(string parameterName)
{
foreach (var arg in Environment.GetCommandLineArgs())
{
if (arg.ToLower().StartsWith(parameterName.ToLower()))
{
return arg.Substring(parameterName.Length);
}
}
return null;
}
static void CheckActiveBuildTarget()
{
var notSupportedPlatforms = new[] { "MetroPlayer", "WebPlayer", "WebPlayerStreamed" };
if (notSupportedPlatforms.Contains(EditorUserBuildSettings.activeBuildTarget.ToString()))
{
Debug.Log("activeBuildTarget can not be "
+ EditorUserBuildSettings.activeBuildTarget +
" use buildTarget parameter to open Unity.");
}
}
private static BuildTarget ? GetTargetPlatform()
{
string platformString = null;
BuildTarget buildTarget;
foreach (var arg in Environment.GetCommandLineArgs())
{
if (arg.ToLower().StartsWith(k_TargetPlatformParam.ToLower()))
{
platformString = arg.Substring(k_ResultFilePathParam.Length);
break;
}
}
try
{
if (platformString == null) return null;
buildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), platformString);
}
catch
{
return null;
}
return buildTarget;
}
private static List<string> FindTestScenesInProject()
{
var integrationTestScenePattern = "*Test?.unity";
return Directory.GetFiles("Assets", integrationTestScenePattern, SearchOption.AllDirectories).ToList();
}
private static List<string> GetSceneListFromParam(string param)
{
var sceneList = new List<string>();
foreach (var arg in Environment.GetCommandLineArgs())
{
if (arg.ToLower().StartsWith(param.ToLower()))
{
var scenesFromParam = arg.Substring(param.Length).Split(',');
foreach (var scene in scenesFromParam)
{
var sceneName = scene;
if (!sceneName.EndsWith(".unity"))
sceneName += ".unity";
var foundScenes = Directory.GetFiles(Directory.GetCurrentDirectory(), sceneName, SearchOption.AllDirectories);
if (foundScenes.Length == 1)
sceneList.Add(foundScenes[0].Substring(Directory.GetCurrentDirectory().Length + 1));
else
Debug.Log(sceneName + " not found or multiple entries found");
}
}
}
return sceneList.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
}
}
}
| |
using System;
using System.Collections.Generic;
using JenkinsConsoleUtility.Util;
public interface ICommand
{
string[] CommandKeys { get; }
string[] MandatoryArgKeys { get; }
int Execute(Dictionary<string, string> argsLc, Dictionary<string, string> argsCased);
}
namespace JenkinsConsoleUtility
{
public static class JenkinsConsoleUtility
{
public static int Main(string[] args)
{
var commandLookup = FindICommands();
List<string> orderedCommands;
Dictionary<string, string> lcArgsByName, casedArgsByName;
ICommand tempCommand;
try
{
ExtractArgs(args, out orderedCommands, out lcArgsByName, out casedArgsByName);
var success = true;
foreach (var key in orderedCommands)
{
if (!commandLookup.TryGetValue(key, out tempCommand))
{
success = false;
JcuUtil.FancyWriteToConsole(ConsoleColor.Red, "Unexpected command: " + key);
}
}
if (orderedCommands.Count == 0)
JcuUtil.FancyWriteToConsole(ConsoleColor.DarkYellow, "No commands given, no work will be done");
if (!success || orderedCommands.Count == 0)
throw new Exception("Commands not input correctly");
}
catch (Exception)
{
JcuUtil.FancyWriteToConsole(ConsoleColor.Yellow, "Run a sequence of ordered commands --<command> [--<command> ...] [-<argKey> <argValue> ...]\nValid commands:", ConsoleColor.Gray, commandLookup.Keys);
JcuUtil.FancyWriteToConsole(ConsoleColor.Yellow, "argValues can have spaces. Dashes in argValues can cause problems, and are not recommended.");
JcuUtil.FancyWriteToConsole(ConsoleColor.Yellow, "Quotes are considered part of the argKey or argValue, and are not parsed as tokens.");
// TODO: Report list of available commands and valid/required args for commands
return Pause(1);
}
var returnCode = 0;
foreach (var key in orderedCommands)
{
if (returnCode == 0 && commandLookup.TryGetValue(key, out tempCommand))
{
returnCode = VerifyKeys(tempCommand, lcArgsByName);
if (returnCode == 0)
{
try
{
returnCode = tempCommand.Execute(lcArgsByName, casedArgsByName);
}
catch (Exception e)
{
JcuUtil.FancyWriteToConsole(ConsoleColor.Red, key + " command threw exception: " + e.ToString());
returnCode = 1;
}
}
}
if (returnCode != 0)
{
JcuUtil.FancyWriteToConsole(ConsoleColor.Yellow, key + " command returned error code: " + returnCode);
return Pause(returnCode);
}
}
return Pause(0);
}
/// <summary>
/// Try to find the given (lowercased) key in the command line arguments, or the environment variables.
/// If it is present, return it
/// Else getDefault (if defined), else throw an exception
/// Defined as empty string is considered a successful result
/// </summary>
/// <returns>The string associated with this key</returns>
public static string GetArgVar(Dictionary<string, string> args, string key, string getDefault = null)
{
string output = "";
if (TryGetArgVar(out output, args, key, getDefault))
{
return output;
}
if (getDefault != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
{
JcuUtil.FancyWriteToConsole(ConsoleColor.DarkYellow, "GetArgVar: " + key + " not defined, reverting to: " + getDefault);
return getDefault;
}
var msg = "ERROR: Required parameter: " + key + " not found";
JcuUtil.FancyWriteToConsole(ConsoleColor.Red, msg);
throw new Exception(msg);
}
/// <summary>
/// Try to find the given key in the command line arguments, or the environment variables.
/// If it is present, return it.
/// Defined as empty string returns true
/// Falling through to getDefault always returns false
/// </summary>
/// <returns>True if the key is found</returns>
public static bool TryGetArgVar(out string output, Dictionary<string, string> args, string key, string getDefault = null)
{
var lcKey = key.ToLower();
// Check in args (not guaranteed to be lc-keys)
output = null;
if (args != null)
foreach (var eachArgKey in args.Keys)
if (eachArgKey.ToLower() == lcKey)
output = args[eachArgKey];
if (output != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
return true;
// Check in env-vars - Definitely not lc-keys
var allEnvVars = Environment.GetEnvironmentVariables();
foreach (string eachEnvKey in allEnvVars.Keys)
if (eachEnvKey.ToLower() == lcKey)
output = allEnvVars[eachEnvKey] as string;
if (output != null) // Don't use string.IsNullOrEmpty() here, because there's a distinction between "undefined" and "empty"
return true;
output = getDefault;
return false;
}
private static int VerifyKeys(ICommand cmd, Dictionary<string, string> argsByName)
{
if (cmd.MandatoryArgKeys == null || cmd.MandatoryArgKeys.Length == 0)
return 0;
var allEnvVars = Environment.GetEnvironmentVariables();
List<string> missingArgKeys = new List<string>();
foreach (var eachCmdKey in cmd.MandatoryArgKeys)
{
var expectedKey = eachCmdKey.ToLower();
var found = argsByName.ContainsKey(expectedKey);
if (!found)
foreach (string envKey in allEnvVars.Keys)
if (envKey.ToLower() == expectedKey)
found = true;
if (!found)
missingArgKeys.Add(expectedKey);
}
foreach (var eachCmdKey in missingArgKeys)
JcuUtil.FancyWriteToConsole(ConsoleColor.Yellow, cmd.CommandKeys[0] + " - Missing argument: " + eachCmdKey);
return missingArgKeys.Count;
}
private static int Pause(int code)
{
JcuUtil.FancyWriteToConsole(code == 0 ? ConsoleColor.Green : ConsoleColor.DarkRed, "Done! Press any key to close");
try
{
Console.ReadKey();
}
catch (InvalidOperationException)
{
// ReadKey fails when run from inside of Jenkins, so just ignore it.
}
return code;
}
private static Dictionary<string, ICommand> FindICommands()
{
// Just hard code the list for now
var commandLookup = new Dictionary<string, ICommand>();
var iCommands = typeof(ICommand);
var cmdTypes = new List<Type>();
foreach (var eachAssembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var eachType in eachAssembly.GetTypes())
if (iCommands.IsAssignableFrom(eachType) && eachType.Name != iCommands.Name)
cmdTypes.Add(eachType);
foreach (var eachPkgType in cmdTypes)
{
var eachInstance = (ICommand)Activator.CreateInstance(eachPkgType);
foreach (var eachCmdKey in eachInstance.CommandKeys)
commandLookup.Add(eachCmdKey.ToLower(), eachInstance);
}
return commandLookup;
}
/// <summary>
/// Extract command line arguments into target information
/// </summary>
private static void ExtractArgs(string[] args, out List<string> orderedCommands, out Dictionary<string, string> lcArgsByName, out Dictionary<string, string> casedArgsByName)
{
orderedCommands = new List<string>();
lcArgsByName = new Dictionary<string, string>();
casedArgsByName = new Dictionary<string, string>();
string activeKeyLc = null;
string activeKeyCased = null;
foreach (var eachArgCased in args)
{
var eachArgLc = eachArgCased.ToLower();
if (eachArgLc.StartsWith("--"))
{
activeKeyLc = eachArgLc.Substring(2);
activeKeyCased = eachArgCased.Substring(2);
orderedCommands.Add(activeKeyLc);
}
else if (eachArgLc.StartsWith("-"))
{
activeKeyLc = eachArgLc.Substring(1);
activeKeyCased = eachArgCased.Substring(1);
lcArgsByName[activeKeyLc] = "";
casedArgsByName[activeKeyCased] = "";
}
else if (activeKeyCased == null)
{
throw new Exception("Unexpected token: " + eachArgCased);
}
else
{
lcArgsByName[activeKeyLc] = (lcArgsByName[activeKeyLc] + " " + eachArgLc).Trim();
casedArgsByName[activeKeyCased] = (casedArgsByName[activeKeyCased] + " " + eachArgCased).Trim();
}
}
}
}
}
| |
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.NetApp.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace NetApp.Tests.Helpers
{
public class ResourceUtils
{
public const long gibibyte = 1024L * 1024L * 1024L;
private const string remoteSuffix = "-R";
public const string vnet = "sdknettestqa2vnet464";
public const string backupVnet = "sdknettestqa2vnet464euap";
public const string repVnet = "sdktestqa2vnet464";
//public const string remoteVnet = repVnet + remoteSuffix;
public const string remoteVnet = "sdktestqa2vnet464east-R";
//public const string subsId = "8f38cfec-0ecd-413a-892e-2494f77a3b56";
//public const string subsId = "0661B131-4A11-479B-96BF-2F95ACCA2F73";
public const string subsId = "69a75bda-882e-44d5-8431-63421204132a";
public const string location = "westus2";
//public const string location = "eastus2euap";
//public const string remoteLocation = "southcentralus";
public const string remoteLocation = "eastus";
//public const string backupLocation = "westus2";
//public const string backupLocation = "westus2"; //"westusstage";
public const string backupLocation = "eastus2euap"; //"westusstage";
public const string resourceGroup = "sdk-net-test-qa2";
//public const string resourceGroup = "ab_sdk_test_rg";
public const string repResourceGroup = "sdk-test-qa2";
public const string remoteResourceGroup = repResourceGroup + remoteSuffix;
public const string accountName1 = "sdk-net-tests-acc-208";
public const string accountName1Repl = "sdk-net-tests-acc-20b";
public const string remoteAccountName1 = accountName1Repl + remoteSuffix;
public const string accountName2 = "sdk-net-tests-acc-21";
public const string poolName1 = "sdk-net-tests-pool-201";
public const string poolName1Repl = "sdk-net-tests-pool-10b";
public const string remotePoolName1 = poolName1Repl + remoteSuffix;
public const string poolName2 = "sdk-net-tests-pool-211";
public const string volumeName1 = "sdk-net-tests-vol-2101";
public const string volumeBackupAccountName1 = "sdk-net-tests-acc-211v";
public const string backupVolumeName1 = "sdk-net-tests-vol-2108";
public const string volumeName1Repl = "sdk-net-tests-vol-1000b";
public const string remoteVolumeName1 = volumeName1Repl + remoteSuffix;
public const string volumeName2 = "sdk-net-tests-vol-1001";
public const string snapshotName1 = "sdk-net-tests-snap-11";
public const string snapshotName2 = "sdk-net-tests-snap-12";
public const string snapshotPolicyName1 = "sdk-net-tests-snapshotPolicy-1";
public const string snapshotPolicyName2 = "sdk-net-tests-snapshotPolicy-2";
public const string backupPolicyName1 = "sdk-net-tests-backupPolicy-105a";
public const string backupPolicyName2 = "sdk-net-tests-backupPolicy-105b";
//public const string backupVaultId = "cbsvault";
public static ActiveDirectory activeDirectory = new ActiveDirectory()
{
Username = "sdkuser",
Password = "sdkpass",
Domain = "sdkdomain",
Dns = "192.0.2.2",
SmbServerName = "SDKSMBSeNa",
};
public static ActiveDirectory activeDirectory2 = new ActiveDirectory()
{
Username = "sdkuser1",
Password = "sdkpass1",
Domain = "sdkdomain",
Dns = "192.0.2.1",
SmbServerName = "SDKSMBSeNa",
};
public static ExportPolicyRule defaultExportPolicyRule = new ExportPolicyRule()
{
RuleIndex = 1,
UnixReadOnly = false,
UnixReadWrite = true,
Cifs = false,
Nfsv3 = true,
Nfsv41 = false,
AllowedClients = "0.0.0.0/0"
};
public static IList<ExportPolicyRule> defaultExportPolicyRuleList = new List<ExportPolicyRule>()
{
defaultExportPolicyRule
};
public static VolumePropertiesExportPolicy defaultExportPolicy = new VolumePropertiesExportPolicy()
{
Rules = defaultExportPolicyRuleList
};
private const int delay = 5000;
private const int retryAttempts = 4;
public static NetAppAccount CreateAccount(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, IDictionary<string, string> tags = default(IDictionary<string, string>), ActiveDirectory activeDirectory = null)
{
// request reference example
// az netappfiles account update -g --account-name cli-lf-acc2 --active-directories '[{"username": "aduser", "password": "aduser", "smbservername": "SMBSERVER", "dns": "1.2.3.4", "domain": "westcentralus"}]' -l westus2
var activeDirectories = activeDirectory != null ? new List <ActiveDirectory> { activeDirectory } : new List<ActiveDirectory>();
var netAppAccount = new NetAppAccount()
{
Location = location,
Tags = tags,
ActiveDirectories = activeDirectories
};
var resource = netAppMgmtClient.Accounts.CreateOrUpdate(netAppAccount, resourceGroup, accountName);
Assert.Equal(resource.Name, accountName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static CapacityPool CreatePool(AzureNetAppFilesManagementClient netAppMgmtClient, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, IDictionary<string, string> tags = default(IDictionary<string, string>), bool poolOnly = false, string serviceLevel = "Premium")
{
if (!poolOnly)
{
CreateAccount(netAppMgmtClient, accountName, resourceGroup: resourceGroup, location: location, tags: tags);
}
var pool = new CapacityPool
{
Location = location,
Size = 4398046511104,
ServiceLevel = serviceLevel,
Tags = tags
};
CapacityPool resource;
try
{
resource = netAppMgmtClient.Pools.CreateOrUpdate(pool, resourceGroup, accountName, poolName);
}
catch
{
// try one more time
resource = netAppMgmtClient.Pools.CreateOrUpdate(pool, resourceGroup, accountName, poolName);
}
Assert.Equal(resource.Name, accountName + '/' + poolName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, string vnet = vnet, bool volumeOnly = false, string snapshotId = null, string snapshotPolicyId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: location);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var volume = new Volume
{
Location = location,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + vnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
SnapshotId = snapshotId,
};
if (snapshotPolicyId != null)
{
var volumDataProtection = new VolumePropertiesDataProtection
{
Snapshot = new VolumeSnapshotProperties(snapshotPolicyId)
};
volume.DataProtection = volumDataProtection;
}
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateDpVolume(AzureNetAppFilesManagementClient netAppMgmtClient, Volume sourceVolume, string volumeName = remoteVolumeName1, string poolName = remotePoolName1, string accountName = remoteAccountName1, string resourceGroup = remoteResourceGroup, string location = location, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, bool volumeOnly = false, string snapshotId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: remoteLocation);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var replication = new ReplicationObject
{
EndpointType = "dst",
RemoteVolumeResourceId = sourceVolume.Id,
ReplicationSchedule = "_10minutely"
};
var dataProtection = new VolumePropertiesDataProtection
{
Replication = replication
};
var volume = new Volume
{
Location = remoteLocation,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
//SubnetId = "/subscriptions/" + subsId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + remoteVnet + "/subnets/default",
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + remoteVnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
SnapshotId = snapshotId,
VolumeType = "DataProtection",
DataProtection = dataProtection
};
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static Volume CreateBackedupVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = volumeBackupAccountName1, string resourceGroup = resourceGroup, string location = backupLocation, List<string> protocolTypes = null, IDictionary<string, string> tags = default(IDictionary<string, string>), VolumePropertiesExportPolicy exportPolicy = null, bool volumeOnly = false, string vnet = backupVnet, string backupPolicyId = null, string backupVaultId = null)
{
if (!volumeOnly)
{
CreatePool(netAppMgmtClient, poolName, accountName, resourceGroup: resourceGroup, location: location);
}
var defaultProtocolType = new List<string>() { "NFSv3" };
var volumeProtocolTypes = protocolTypes == null ? defaultProtocolType : protocolTypes;
var dataProtection = new VolumePropertiesDataProtection
{
Backup = new VolumeBackupProperties {BackupEnabled = true, BackupPolicyId = backupPolicyId, VaultId = backupVaultId }
};
var volume = new Volume
{
Location = location,
UsageThreshold = 100 * gibibyte,
ProtocolTypes = volumeProtocolTypes,
CreationToken = volumeName,
SubnetId = "/subscriptions/" + netAppMgmtClient.SubscriptionId + "/resourceGroups/" + resourceGroup + "/providers/Microsoft.Network/virtualNetworks/" + backupVnet + "/subnets/default",
Tags = tags,
ExportPolicy = exportPolicy,
VolumeType = "DataProtection",
DataProtection = dataProtection
};
var resource = netAppMgmtClient.Volumes.CreateOrUpdate(volume, resourceGroup, accountName, poolName, volumeName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
return resource;
}
public static void CreateSnapshot(AzureNetAppFilesManagementClient netAppMgmtClient, string snapshotName = snapshotName1, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool snapshotOnly = false)
{
Volume volume = null;
var snapshot = new Snapshot();
if (!snapshotOnly)
{
volume = CreateVolume(netAppMgmtClient, volumeName, poolName, accountName);
snapshot = new Snapshot
{
Location = location,
};
}
else
{
// for those tests where snapshotOnly is true, no filesystem id will be available
// use this opportunity to test snapshot creation with no filesystem id provided
// for these cases it should use the name in the resource id
snapshot = new Snapshot
{
Location = location,
};
}
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
var resource = netAppMgmtClient.Snapshots.Create(snapshot, resourceGroup, accountName, poolName, volumeName, snapshotName);
Assert.Equal(resource.Name, accountName + '/' + poolName + '/' + volumeName + '/' + snapshotName);
}
public static void DeleteAccount(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = accountName1, string resourceGroup = resourceGroup, bool deep = false)
{
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the account
netAppMgmtClient.Accounts.Delete(resourceGroup, accountName);
}
public static void DeletePool(AzureNetAppFilesManagementClient netAppMgmtClient, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the pool - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might not be complete and therefore pool has child resource
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Pools.Delete(resourceGroup, accountName, poolName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
public static void DeleteVolume(AzureNetAppFilesManagementClient netAppMgmtClient, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the volume - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might not be complete and therefore volume has child resource
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Volumes.Delete(resourceGroup, accountName, poolName, volumeName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
public static void DeleteSnapshot(AzureNetAppFilesManagementClient netAppMgmtClient, string snapshotName = snapshotName1, string volumeName = volumeName1, string poolName = poolName1, string accountName = accountName1, string resourceGroup = resourceGroup, string location = location, bool deep = false)
{
bool retry = true;
int co = 0;
if (deep)
{
// find and delete all nested resources - not implemented
}
// now delete the snapshot - with retry for test robustness due to
// - ARM caching (ARM continues to tidy up even after the awaited async op
// has returned)
// - other async actions in RP/SDE/NRP
// e.g. snapshot deletion might fail if the actual creation is not complete at
// all levels
while (retry == true)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
try
{
netAppMgmtClient.Snapshots.Delete(resourceGroup, accountName, poolName, volumeName, snapshotName);
retry = false;
}
catch
{
co++;
if (co > retryAttempts)
{
retry = false;
}
}
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
namespace Revit.SDK.Samples.AutoTagRooms.CS
{
/// <summary>
/// The graphic user interface of auto tag rooms
/// </summary>
public partial class AutoTagRoomsForm : System.Windows.Forms.Form
{
/// <summary>
/// Default constructor of AutoTagRoomsForm
/// </summary>
private AutoTagRoomsForm()
{
InitializeComponent();
}
/// <summary>
/// Constructor of AutoTagRoomsForm
/// </summary>
/// <param name="roomsData">The data source of AutoTagRoomsForm</param>
public AutoTagRoomsForm(RoomsData roomsData) : this()
{
m_roomsData = roomsData;
InitRoomListView();
}
/// <summary>
/// When the AutoTagRoomsForm is loading, initialize the levelsComboBox and tagTypesComboBox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AutoTagRoomsForm_Load(object sender, EventArgs e)
{
// levelsComboBox
this.levelsComboBox.DataSource = m_roomsData.Levels;
this.levelsComboBox.DisplayMember = "Name";
this.levelsComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
this.levelsComboBox.Sorted = true;
this.levelsComboBox.DropDown += new EventHandler(levelsComboBox_DropDown);
// tagTypesComboBox
this.tagTypesComboBox.DataSource = m_roomsData.RoomTagTypes;
this.tagTypesComboBox.DisplayMember = "Name";
this.tagTypesComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
this.tagTypesComboBox.DropDown += new EventHandler(tagTypesComboBox_DropDown);
}
/// <summary>
/// When the tagTypesComboBox drop down, adjust its width
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void tagTypesComboBox_DropDown(object sender, EventArgs e)
{
AdjustWidthComboBox_DropDown(sender, e);
}
/// <summary>
/// When the levelsComboBox drop down, adjust its width
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void levelsComboBox_DropDown(object sender, EventArgs e)
{
AdjustWidthComboBox_DropDown(sender, e);
}
/// <summary>
/// Initialize the roomsListView
/// </summary>
private void InitRoomListView()
{
this.roomsListView.Columns.Clear();
// Create the columns of the roomsListView
this.roomsListView.Columns.Add("Room Name");
foreach (RoomTagType type in m_roomsData.RoomTagTypes)
{
this.roomsListView.Columns.Add(type.Name);
}
this.roomsListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
this.roomsListView.FullRowSelect = true;
}
/// <summary>
/// Update the rooms information in the specified level
/// </summary>
private void UpdateRoomsList()
{
// when update the RoomsListView, clear all the items first
this.roomsListView.Items.Clear();
foreach (Room tmpRoom in m_roomsData.Rooms)
{
Level level = this.levelsComboBox.SelectedItem as Level;
if (tmpRoom.Level.Id.IntegerValue == level.Id.IntegerValue)
{
ListViewItem item = new ListViewItem(tmpRoom.Name);
// Shows the number of each type of RoomTags that the room has
foreach (RoomTagType type in m_roomsData.RoomTagTypes)
{
int count = m_roomsData.GetTagNumber(tmpRoom, type);
string str = count.ToString();
item.SubItems.Add(str);
}
this.roomsListView.Items.Add(item);
}
}
}
/// <summary>
/// When clicked the autoTag button, then tag all rooms in the specified level.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void autoTagButton_Click(object sender, EventArgs e)
{
Level level = this.levelsComboBox.SelectedItem as Level;
RoomTagType tagType = this.tagTypesComboBox.SelectedItem as RoomTagType;
if (level != null && tagType != null)
{
m_roomsData.AutoTagRooms(level, tagType);
}
UpdateRoomsList();
}
/// <summary>
/// When selected different level, then update the roomsListView.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void levelsComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateRoomsList();
}
/// <summary>
/// Adjust combo box drop down list width to longest string width
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int vertScrollBarWidth =
(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (Autodesk.Revit.DB.Element element in ((ComboBox)sender).Items)
{
string s = element.Name;
newWidth = (int)g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth)
{
width = newWidth;
}
}
senderComboBox.DropDownWidth = width;
}
}
}
| |
//
// assembly: System
// namespace: System.Text.RegularExpressions
// file: debug.cs
//
// author: Dan Lewis (dlewis@gmx.co.uk)
// (c) 2002
//
// 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;
namespace System.Text.RegularExpressions {
class Disassembler {
public static void DisassemblePattern (ushort[] image) {
DisassembleBlock (image, 0, 0);
}
public static void DisassembleBlock (ushort[] image, int pc, int depth) {
OpCode op;
OpFlags flags;
for (;;) {
if (pc >= image.Length)
return;
PatternCompiler.DecodeOp (image[pc], out op, out flags);
Console.Write (FormatAddress (pc) + ": "); // address
Console.Write (new string (' ', depth * 2)); // indent
Console.Write (DisassembleOp (image, pc)); // instruction
Console.WriteLine ();
int skip;
switch (op) {
case OpCode.False: case OpCode.True: case OpCode.Until:
skip = 1;
break;
case OpCode.Character: case OpCode.Category: case OpCode.Position:
case OpCode.Open: case OpCode.Close: case OpCode.Reference:
case OpCode.Sub: case OpCode.Branch: case OpCode.Jump: case OpCode.In:
skip = 2;
break;
case OpCode.Balance: case OpCode.IfDefined: case OpCode.Range:
case OpCode.Test: case OpCode.Anchor:
skip = 3;
break;
case OpCode.Repeat: case OpCode.FastRepeat: case OpCode.Info:
skip = 4;
break;
case OpCode.String: skip = image[pc + 1] + 2; break;
case OpCode.Set: skip = image[pc + 2] + 3; break;
default:
skip = 1;
break;
}
pc += skip;
}
}
public static string DisassembleOp (ushort[] image, int pc) {
OpCode op;
OpFlags flags;
PatternCompiler.DecodeOp (image[pc], out op, out flags);
string str = op.ToString ();
if (flags != 0)
str += "[" + flags.ToString ("f") + "]";
switch (op) {
case OpCode.False: case OpCode.True: case OpCode.Until:
default:
break;
case OpCode.Info:
str += " " + image[pc + 1];
str += " (" + image[pc + 2] + ", " + image[pc + 3] + ")";
break;
case OpCode.Character:
str += " '" + FormatChar ((char)image[pc + 1]) + "'";
break;
case OpCode.Category:
str += " /" + (Category)image[pc + 1];
break;
case OpCode.Range:
str += " '" + FormatChar ((char)image[pc + 1]) + "', ";
str += " '" + FormatChar ((char)image[pc + 2]) + "'";
break;
case OpCode.Set:
str += " " + FormatSet (image, pc + 1);
break;
case OpCode.String:
str += " '" + ReadString (image, pc + 1) + "'";
break;
case OpCode.Position:
str += " /" + (Position)image[pc + 1];
break;
case OpCode.Open: case OpCode.Close: case OpCode.Reference:
str += " " + image[pc + 1];
break;
case OpCode.Balance:
str += " " + image[pc + 1] + " " + image[pc + 2];
break;
case OpCode.IfDefined: case OpCode.Anchor:
str += " :" + FormatAddress (pc + image[pc + 1]);
str += " " + image[pc + 2];
break;
case OpCode.Sub: case OpCode.Branch: case OpCode.Jump:
case OpCode.In:
str += " :" + FormatAddress (pc + image[pc + 1]);
break;
case OpCode.Test:
str += " :" + FormatAddress (pc + image[pc + 1]);
str += ", :" + FormatAddress (pc + image[pc + 2]);
break;
case OpCode.Repeat: case OpCode.FastRepeat:
str += " :" + FormatAddress (pc + image[pc + 1]);
str += " (" + image[pc + 2] + ", ";
if (image[pc + 3] == 0xffff)
str += "Inf";
else
str += image[pc + 3];
str += ")";
break;
}
return str;
}
// private static members
private static string ReadString (ushort[] image, int pc) {
int len = image[pc];
char[] chars = new char[len];
for (int i = 0; i < len; ++ i)
chars[i] = (char)image[pc + i + 1];
return new string (chars);
}
private static string FormatAddress (int pc) {
return pc.ToString ("x4");
}
private static string FormatSet (ushort[] image, int pc) {
int lo = image[pc ++];
int hi = (image[pc ++] << 4) - 1;
string str = "[";
bool hot = false;
char a = (char)0, b;
for (int i = 0; i <= hi; ++ i) {
bool m = (image[pc + (i >> 4)] & (1 << (i & 0xf))) != 0;
if (m & !hot) { // start of range
a = (char)(lo + i);
hot = true;
}
else if (hot & (!m || i == hi)) { // end of range
b = (char)(lo + i - 1);
str += FormatChar (a);
if (b != a)
str += "-" + FormatChar (b);
hot = false;
}
}
str += "]";
return str;
}
private static string FormatChar (char c) {
if (c == '-' || c == ']')
return "\\" + c;
if (Char.IsLetterOrDigit (c) || Char.IsSymbol (c))
return c.ToString ();
if (Char.IsControl (c)) {
return "^" + (char)('@' + c);
}
return "\\u" + ((int)c).ToString ("x4");
}
}
}
| |
namespace KabMan.Client
{
partial class NewCoordinate
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.LookUpRoom = new DevExpress.XtraEditors.LookUpEdit();
this.simpleButton4 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton3 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
this.txtCoordinateName = new DevExpress.XtraEditors.TextEdit();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.LookUpRoom.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtCoordinateName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.LookUpRoom);
this.layoutControl1.Controls.Add(this.simpleButton4);
this.layoutControl1.Controls.Add(this.simpleButton3);
this.layoutControl1.Controls.Add(this.simpleButton2);
this.layoutControl1.Controls.Add(this.txtCoordinateName);
this.layoutControl1.Controls.Add(this.simpleButton1);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.HiddenItems.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem2,
this.layoutControlItem3});
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(400, 97);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// LookUpRoom
//
this.LookUpRoom.Location = new System.Drawing.Point(102, 7);
this.LookUpRoom.Name = "LookUpRoom";
this.LookUpRoom.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.LookUpRoom.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("RoomName", "Name", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
this.LookUpRoom.Properties.NullText = "Select to Data Center!";
this.LookUpRoom.Size = new System.Drawing.Size(292, 20);
this.LookUpRoom.StyleController = this.layoutControl1;
this.LookUpRoom.TabIndex = 1;
//
// simpleButton4
//
this.simpleButton4.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.simpleButton4.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.simpleButton4.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.simpleButton4.Appearance.Options.UseBackColor = true;
this.simpleButton4.Appearance.Options.UseBorderColor = true;
this.simpleButton4.Appearance.Options.UseForeColor = true;
this.simpleButton4.Location = new System.Drawing.Point(310, 69);
this.simpleButton4.Name = "simpleButton4";
this.simpleButton4.Size = new System.Drawing.Size(84, 22);
this.simpleButton4.StyleController = this.layoutControl1;
this.simpleButton4.TabIndex = 1;
this.simpleButton4.Text = "Cancel";
this.simpleButton4.Click += new System.EventHandler(this.simpleButton4_Click);
//
// simpleButton3
//
this.simpleButton3.Appearance.BackColor = System.Drawing.SystemColors.ButtonFace;
this.simpleButton3.Appearance.BackColor2 = System.Drawing.SystemColors.ButtonHighlight;
this.simpleButton3.Appearance.BorderColor = System.Drawing.Color.DimGray;
this.simpleButton3.Appearance.Options.UseBackColor = true;
this.simpleButton3.Appearance.Options.UseBorderColor = true;
this.simpleButton3.Appearance.Options.UseForeColor = true;
this.simpleButton3.Location = new System.Drawing.Point(215, 69);
this.simpleButton3.Name = "simpleButton3";
this.simpleButton3.Size = new System.Drawing.Size(84, 22);
this.simpleButton3.StyleController = this.layoutControl1;
this.simpleButton3.TabIndex = 1;
this.simpleButton3.Text = "Save";
this.simpleButton3.Click += new System.EventHandler(this.simpleButton3_Click);
//
// simpleButton2
//
this.simpleButton2.Location = new System.Drawing.Point(106, 38);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(288, 22);
this.simpleButton2.StyleController = this.layoutControl1;
this.simpleButton2.TabIndex = 1;
this.simpleButton2.Text = "simpleButton2";
//
// txtCoordinateName
//
this.txtCoordinateName.Location = new System.Drawing.Point(102, 38);
this.txtCoordinateName.Name = "txtCoordinateName";
this.txtCoordinateName.Size = new System.Drawing.Size(292, 20);
this.txtCoordinateName.StyleController = this.layoutControl1;
this.txtCoordinateName.TabIndex = 4;
//
// simpleButton1
//
this.simpleButton1.Location = new System.Drawing.Point(106, 38);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(89, 22);
this.simpleButton1.StyleController = this.layoutControl1;
this.simpleButton1.TabIndex = 1;
this.simpleButton1.Text = "simpleButton1";
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.simpleButton1;
this.layoutControlItem2.CustomizationFormText = "layoutControlItem2";
this.layoutControlItem2.Location = new System.Drawing.Point(99, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(100, 93);
this.layoutControlItem2.Text = "layoutControlItem2";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextToControlDistance = 0;
this.layoutControlItem2.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.simpleButton2;
this.layoutControlItem3.CustomizationFormText = "layoutControlItem3";
this.layoutControlItem3.Location = new System.Drawing.Point(99, 31);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(299, 93);
this.layoutControlItem3.Text = "layoutControlItem3";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.emptySpaceItem1,
this.layoutControlItem4,
this.layoutControlItem5,
this.layoutControlItem6});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "Root";
this.layoutControlGroup1.Size = new System.Drawing.Size(400, 97);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "Root";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.txtCoordinateName;
this.layoutControlItem1.CustomizationFormText = "Coordinate Name :";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(398, 31);
this.layoutControlItem1.Text = "Coordinate Name :";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(90, 20);
//
// emptySpaceItem1
//
this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1";
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 62);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(208, 33);
this.emptySpaceItem1.Text = "emptySpaceItem1";
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.simpleButton3;
this.layoutControlItem4.CustomizationFormText = "layoutControlItem4";
this.layoutControlItem4.Location = new System.Drawing.Point(208, 62);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(95, 33);
this.layoutControlItem4.Text = "layoutControlItem4";
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem4.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem4.TextToControlDistance = 0;
this.layoutControlItem4.TextVisible = false;
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.simpleButton4;
this.layoutControlItem5.CustomizationFormText = "layoutControlItem5";
this.layoutControlItem5.Location = new System.Drawing.Point(303, 62);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(95, 33);
this.layoutControlItem5.Text = "layoutControlItem5";
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem5.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem5.TextToControlDistance = 0;
this.layoutControlItem5.TextVisible = false;
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.LookUpRoom;
this.layoutControlItem6.CustomizationFormText = "Room :";
this.layoutControlItem6.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(398, 31);
this.layoutControlItem6.Text = "Data Center :";
this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem6.TextSize = new System.Drawing.Size(90, 20);
//
// NewCoordinate
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(400, 97);
this.Controls.Add(this.layoutControl1);
this.Name = "NewCoordinate";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "NewCoordinate";
this.Load += new System.EventHandler(this.NewCoordinate_Load);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.LookUpRoom.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtCoordinateName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.SimpleButton simpleButton4;
private DevExpress.XtraEditors.SimpleButton simpleButton3;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
private DevExpress.XtraEditors.TextEdit txtCoordinateName;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraEditors.LookUpEdit LookUpRoom;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using SlackAPI.RPCMessages;
namespace SlackAPI
{
/// <summary>
/// SlackClient is intended to solely handle RPC (HTTP-based) functionality. Does not handle WebSocket connectivity.
///
/// For WebSocket connectivity, refer to <see cref="SlackAPI.SlackSocketClient"/>
/// </summary>
public class SlackClient : SlackClientBase
{
private readonly string APIToken;
public Self MySelf;
public User MyData;
public Team MyTeam;
public List<string> starredChannels;
public List<User> Users;
public List<Bot> Bots;
public List<Channel> Channels;
public List<Channel> Groups;
public List<DirectMessageConversation> DirectMessages;
public Dictionary<string, User> UserLookup;
public Dictionary<string, Channel> ChannelLookup;
public Dictionary<string, Channel> GroupLookup;
public Dictionary<string, DirectMessageConversation> DirectMessageLookup;
public Dictionary<string, Conversation> ConversationLookup;
public SlackClient(string token)
{
APIToken = token;
}
public SlackClient(string token, IWebProxy proxySettings)
: base(proxySettings)
{
APIToken = token;
}
public virtual void Connect(Action<LoginResponse> onConnected = null, Action onSocketConnected = null)
{
EmitLogin((loginDetails) =>
{
if (loginDetails.ok)
Connected(loginDetails);
if (onConnected != null)
onConnected(loginDetails);
});
}
protected virtual void Connected(LoginResponse loginDetails)
{
MySelf = loginDetails.self;
MyData = loginDetails.users.First((c) => c.id == MySelf.id);
MyTeam = loginDetails.team;
Users = new List<User>(loginDetails.users.Where((c) => !c.deleted));
Bots = new List<Bot>(loginDetails.bots.Where((c) => !c.deleted));
Channels = new List<Channel>(loginDetails.channels);
Groups = new List<Channel>(loginDetails.groups);
DirectMessages = new List<DirectMessageConversation>(loginDetails.ims.Where((c) => Users.Exists((a) => a.id == c.user) && c.id != MySelf.id));
starredChannels =
Groups.Where((c) => c.is_starred).Select((c) => c.id)
.Union(
DirectMessages.Where((c) => c.is_starred).Select((c) => c.user)
).Union(
Channels.Where((c) => c.is_starred).Select((c) => c.id)
).ToList();
UserLookup = new Dictionary<string, User>();
foreach (User u in Users) UserLookup.Add(u.id, u);
ChannelLookup = new Dictionary<string, Channel>();
ConversationLookup = new Dictionary<string, Conversation>();
foreach (Channel c in Channels)
{
ChannelLookup.Add(c.id, c);
ConversationLookup.Add(c.id, c);
}
GroupLookup = new Dictionary<string, Channel>();
foreach (Channel g in Groups)
{
GroupLookup.Add(g.id, g);
ConversationLookup.Add(g.id, g);
}
DirectMessageLookup = new Dictionary<string, DirectMessageConversation>();
foreach (DirectMessageConversation im in DirectMessages)
{
DirectMessageLookup.Add(im.id, im);
ConversationLookup.Add(im.id, im);
}
}
public void APIRequestWithToken<K>(Action<K> callback, params Tuple<string, string>[] getParameters)
where K : Response
{
APIRequest(callback, getParameters, new Tuple<string, string>[0], APIToken);
}
public void TestAuth(Action<AuthTestResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetUserList(Action<UserListResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetUserByEmail(Action<UserEmailLookupResponse> callback, string email)
{
APIRequestWithToken(callback, new Tuple<string, string>("email", email));
}
public void ChannelsCreate(Action<ChannelCreateResponse> callback, string name) {
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void ChannelsInvite(Action<ChannelInviteResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GetConversationsList(Action<ConversationsListResponse> callback, string cursor = "", bool ExcludeArchived = true, int limit = 100, string[] types = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>()
{
Tuple.Create("exclude_archived", ExcludeArchived ? "1" : "0")
};
if (limit > 0)
parameters.Add(Tuple.Create("limit", limit.ToString()));
if ((types != null) && types.Any())
parameters.Add(Tuple.Create("types", string.Join(",", types)));
if (!string.IsNullOrEmpty(cursor))
parameters.Add(Tuple.Create("cursor", cursor));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GetChannelList(Action<ChannelListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetGroupsList(Action<GroupListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetDirectMessageList(Action<DirectMessageConversationListResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetFiles(Action<FileListResponse> callback, string userId = null, DateTime? from = null, DateTime? to = null, int? count = null, int? page = null, FileTypes types = FileTypes.all, string channel = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if (from.HasValue)
parameters.Add(new Tuple<string, string>("ts_from", from.Value.ToProperTimeStamp()));
if (to.HasValue)
parameters.Add(new Tuple<string, string>("ts_to", to.Value.ToProperTimeStamp()));
if (!types.HasFlag(FileTypes.all))
{
FileTypes[] values = (FileTypes[])Enum.GetValues(typeof(FileTypes));
StringBuilder building = new StringBuilder();
bool first = true;
for (int i = 0; i < values.Length; ++i)
{
if (types.HasFlag(values[i]))
{
if (!first) building.Append(",");
building.Append(values[i].ToString());
first = false;
}
}
if (building.Length > 0)
parameters.Add(new Tuple<string, string>("types", building.ToString()));
}
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
if (!string.IsNullOrEmpty(channel))
parameters.Add(new Tuple<string, string>("channel", channel));
APIRequestWithToken(callback, parameters.ToArray());
}
void GetHistory<K>(Action<K> historyCallback, string channel, DateTime? latest = null, DateTime? oldest = null, int? count = null, bool? unreads = false)
where K : MessageHistory
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string, string>("channel", channel));
if(latest.HasValue)
parameters.Add(new Tuple<string, string>("latest", latest.Value.ToProperTimeStamp()));
if(oldest.HasValue)
parameters.Add(new Tuple<string, string>("oldest", oldest.Value.ToProperTimeStamp()));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if (unreads.HasValue)
parameters.Add(new Tuple<string, string>("unreads", unreads.Value ? "1" : "0"));
APIRequestWithToken(historyCallback, parameters.ToArray());
}
public void GetChannelHistory(Action<ChannelMessageHistory> callback, Channel channelInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null, bool? unreads = false)
{
GetHistory(callback, channelInfo.id, latest, oldest, count, unreads);
}
public void GetDirectMessageHistory(Action<MessageHistory> callback, DirectMessageConversation conversationInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null, bool? unreads = false)
{
GetHistory(callback, conversationInfo.id, latest, oldest, count, unreads);
}
public void GetGroupHistory(Action<GroupMessageHistory> callback, Channel groupInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null, bool? unreads = false)
{
GetHistory(callback, groupInfo.id, latest, oldest, count, unreads);
}
public void GetConversationsHistory(Action<ConversationsMessageHistory> callback, Channel conversationInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null, bool? unreads = false)
{
GetHistory(callback, conversationInfo.id, latest, oldest, count, unreads);
}
public void MarkChannel(Action<MarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback,
new Tuple<string, string>("channel", channelId),
new Tuple<string, string>("ts", ts.ToProperTimeStamp())
);
}
public void GetFileInfo(Action<FileInfoResponse> callback, string fileId, int? page = null, int? count = null)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("file", fileId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
#region Groups
public void GroupsArchive(Action<GroupArchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsClose(Action<GroupCloseResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsCreate(Action<GroupCreateResponse> callback, string name)
{
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void GroupsCreateChild(Action<GroupCreateChildResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsInvite(Action<GroupInviteResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsKick(Action<GroupKickResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsLeave(Action<GroupLeaveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsMark(Action<GroupMarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId), new Tuple<string, string>("ts", ts.ToProperTimeStamp()));
}
public void GroupsOpen(Action<GroupOpenResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsRename(Action<GroupRenameResponse> callback, string channelId, string name)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("name", name));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetPurpose(Action<GroupSetPurposeResponse> callback, string channelId, string purpose)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("purpose", purpose));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetTopic(Action<GroupSetPurposeResponse> callback, string channelId, string topic)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("topic", topic));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsUnarchive(Action<GroupUnarchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
#endregion
#region Conversations
public void ConversationsArchive(Action<ConversationsArchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void ConversationsClose(Action<ConversationsCloseResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void ConversationsCreate(Action<ConversationsCreateResponse> callback, string name)
{
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void ConversationsInvite(Action<ConversationsInviteResponse> callback, string channelId, string[] userIds)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("users", string.Join(",", userIds)));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsKick(Action<ConversationsKickResponse> callback, string channelId, string userId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsLeave(Action<ConversationsLeaveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void ConversationsMark(Action<ConversationsMarkResponse> callback, string channelId, DateTime ts)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("ts", ts.ToProperTimeStamp()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsOpen(Action<ConversationsOpenResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void ConversationsRename(Action<ConversationsRenameResponse> callback, string channelId, string name)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("name", name));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsSetPurpose(Action<ConversationsSetPurposeResponse> callback, string channelId, string purpose)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("purpose", purpose));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsSetTopic(Action<ConversationsSetPurposeResponse> callback, string channelId, string topic)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("topic", topic));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ConversationsUnarchive(Action<ConversationsUnarchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
#endregion
public void SearchAll(Action<SearchResponseAll> callback, string query, string sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting != null)
parameters.Add(new Tuple<string, string>("sort", sorting));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchMessages(Action<SearchResponseMessages> callback, string query, string sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting != null)
parameters.Add(new Tuple<string, string>("sort", sorting));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchFiles(Action<SearchResponseFiles> callback, string query, string sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting != null)
parameters.Add(new Tuple<string, string>("sort", sorting));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GetStars(Action<StarListResponse> callback, string userId = null, int? count = null, int? page = null){
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
if(!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if(page.HasValue)
parameters.Add(new Tuple<string,string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void DeleteMessage(Action<DeletedResponse> callback, string channelId, DateTime ts)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>()
{
new Tuple<string,string>("ts", ts.ToProperTimeStamp()),
new Tuple<string,string>("channel", channelId)
};
APIRequestWithToken(callback, parameters.ToArray());
}
public void EmitPresence(Action<PresenceResponse> callback, Presence status)
{
APIRequestWithToken(callback, new Tuple<string, string>("presence", status.ToString()));
}
public void GetPreferences(Action<UserPreferencesResponse> callback)
{
APIRequestWithToken(callback);
}
#region Users
public void GetCounts(Action<UserCountsResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetPresence(Action<UserGetPresenceResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
public void GetInfo(Action<UserInfoResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
#endregion
public void EmitLogin(Action<LoginResponse> callback, string agent = "Inumedia.SlackAPI")
{
APIRequestWithToken(callback, new Tuple<string, string>("agent", agent));
}
public void Update(
Action<UpdateResponse> callback,
string ts,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
IBlock[] blocks = null,
Attachment[] attachments = null,
bool as_user = false)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("ts", ts));
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("text", text));
if (!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string, string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (blocks != null && blocks.Length > 0)
parameters.Add(new Tuple<string, string>("blocks",
JsonConvert.SerializeObject(blocks, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
})));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments",
JsonConvert.SerializeObject(attachments, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
})));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void JoinDirectMessageChannel(Action<JoinDirectMessageChannelResponse> callback, string user)
{
var param = new Tuple<string, string>("users", user);
APIRequestWithToken(callback, param);
}
public void PostMessage(
Action<PostMessageResponse> callback,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
IBlock[] blocks = null,
Attachment[] attachments = null,
bool? unfurl_links = null,
string icon_url = null,
string icon_emoji = null,
bool? as_user = null,
string thread_ts = null)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("channel", channelId));
parameters.Add(new Tuple<string,string>("text", text));
if(!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string,string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (blocks != null && blocks.Length > 0)
parameters.Add(new Tuple<string, string>("blocks",
JsonConvert.SerializeObject(blocks, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments",
JsonConvert.SerializeObject(attachments, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (unfurl_links.HasValue)
parameters.Add(new Tuple<string, string>("unfurl_links", unfurl_links.Value ? "true" : "false"));
if (!string.IsNullOrEmpty(icon_url))
parameters.Add(new Tuple<string, string>("icon_url", icon_url));
if (!string.IsNullOrEmpty(icon_emoji))
parameters.Add(new Tuple<string, string>("icon_emoji", icon_emoji));
if (as_user.HasValue)
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
if (!string.IsNullOrEmpty(thread_ts))
parameters.Add(new Tuple<string, string>("thread_ts", thread_ts));
APIRequestWithToken(callback, parameters.ToArray());
}
public void PostEphemeralMessage(
Action<PostEphemeralResponse> callback,
string channelId,
string text,
string targetuser,
string parse = null,
bool linkNames = false,
Block[] blocks = null,
Attachment[] attachments = null,
bool as_user = false,
string thread_ts = null)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("channel", channelId));
parameters.Add(new Tuple<string,string>("text", text));
parameters.Add(new Tuple<string,string>("user", targetuser));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (blocks != null && blocks.Length > 0)
parameters.Add(new Tuple<string, string>("blocks",
JsonConvert.SerializeObject(blocks, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments",
JsonConvert.SerializeObject(attachments, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void ScheduleMessage(
Action<ScheduleMessageResponse> callback,
string channelId,
string text,
DateTime post_at,
string botName = null,
string parse = null,
bool linkNames = false,
IBlock[] blocks = null,
Attachment[] attachments = null,
bool? unfurl_links = null,
string icon_url = null,
string icon_emoji = null,
bool? as_user = null,
string thread_ts = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("text", text));
parameters.Add(new Tuple<string, string>("post_at", (post_at - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds.ToString()));
if (!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string, string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (blocks != null && blocks.Length > 0)
parameters.Add(new Tuple<string, string>("blocks",
JsonConvert.SerializeObject(blocks, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments",
JsonConvert.SerializeObject(attachments, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (unfurl_links.HasValue)
parameters.Add(new Tuple<string, string>("unfurl_links", unfurl_links.Value ? "true" : "false"));
if (!string.IsNullOrEmpty(icon_url))
parameters.Add(new Tuple<string, string>("icon_url", icon_url));
if (!string.IsNullOrEmpty(icon_emoji))
parameters.Add(new Tuple<string, string>("icon_emoji", icon_emoji));
if (as_user.HasValue)
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
if (!string.IsNullOrEmpty(thread_ts))
parameters.Add(new Tuple<string, string>("thread_ts", thread_ts));
APIRequestWithToken(callback, parameters.ToArray());
}
public void DialogOpen(
Action<DialogOpenResponse> callback,
string triggerId,
Dialog dialog)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("trigger_id", triggerId));
parameters.Add(new Tuple<string, string>("dialog",
JsonConvert.SerializeObject(dialog,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
})));
APIRequestWithToken(callback, parameters.ToArray());
}
public void AddReaction(
Action<ReactionAddedResponse> callback,
string name = null,
string channel = null,
string timestamp = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(name))
parameters.Add(new Tuple<string, string>("name", name));
if (!string.IsNullOrEmpty(channel))
parameters.Add(new Tuple<string, string>("channel", channel));
if (!string.IsNullOrEmpty(timestamp))
parameters.Add(new Tuple<string, string>("timestamp", timestamp));
APIRequestWithToken(callback, parameters.ToArray());
}
public void UploadFile(Action<FileUploadResponse> callback, byte[] fileData, string fileName, string[] channelIds, string title = null, string initialComment = null, bool useAsync = false, string fileType = null)
{
Uri target = new Uri(Path.Combine(APIBaseLocation, useAsync ? "files.uploadAsync" : "files.upload"));
List<string> parameters = new List<string>();
//File/Content
if (!string.IsNullOrEmpty(fileType))
parameters.Add(string.Format("{0}={1}", "filetype", fileType));
if (!string.IsNullOrEmpty(fileName))
parameters.Add(string.Format("{0}={1}", "filename", fileName));
if (!string.IsNullOrEmpty(title))
parameters.Add(string.Format("{0}={1}", "title", title));
if (!string.IsNullOrEmpty(initialComment))
parameters.Add(string.Format("{0}={1}", "initial_comment", initialComment));
parameters.Add(string.Format("{0}={1}", "channels", string.Join(",", channelIds)));
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new ByteArrayContent(fileData), "file", fileName);
HttpResponseMessage response = PostRequestAsync(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form, APIToken).Result;
string result = response.Content.ReadAsStringAsync().Result;
callback(result.Deserialize<FileUploadResponse>());
}
}
public void DeleteFile(Action<FileDeleteResponse> callback, string file = null)
{
if (string.IsNullOrEmpty(file))
return;
APIRequestWithToken(callback, new Tuple<string, string>("file", file));
}
public void PublishAppHomeTab(
Action<AppHomeTabResponse> callback,
string userId,
View view)
{
view.type = ViewTypes.Home;
var parameters = new List<Tuple<string, string>>
{
new Tuple<string, string>("user_id", userId),
new Tuple<string, string>("view", JsonConvert.SerializeObject(view, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
}))
};
APIRequestWithToken(callback, parameters.ToArray());
}
}
}
| |
/*
* 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.Specialized;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Net;
using System.Text;
using System.Web;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Simulation
{
public class AgentHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
public AgentHandler() { }
public AgentHandler(ISimulationService sim)
{
m_SimulationService = sim;
}
public Hashtable Handler(Hashtable request)
{
// m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
//
// m_log.Debug("---------------------------");
// m_log.Debug(" >> uri=" + request["uri"]);
// m_log.Debug(" >> content-type=" + request["content-type"]);
// m_log.Debug(" >> http-method=" + request["http-method"]);
// m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
UUID agentID;
UUID regionID;
string action;
if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
{
m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("DELETE"))
{
string auth_token = string.Empty;
if (request.ContainsKey("auth"))
auth_token = request["auth"].ToString();
DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token);
return responsedata;
}
else if (method.Equals("QUERYACCESS"))
{
DoQueryAccess(request, responsedata, agentID, regionID);
return responsedata;
}
else
{
m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request));
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
{
if (m_SimulationService == null)
{
m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
responsedata["str_response_string"] = string.Empty;
return;
}
// m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
OSDMap args = Utils.GetOSDMap((string)request["body"]);
Vector3 position = Vector3.Zero;
if (args.ContainsKey("position"))
position = Vector3.Parse(args["position"].AsString());
GridRegion destination = new GridRegion();
destination.RegionID = regionID;
string reason;
string version;
bool result = m_SimulationService.QueryAccess(destination, id, position, out version, out reason);
responsedata["int_response_code"] = HttpStatusCode.OK;
OSDMap resp = new OSDMap(3);
resp["success"] = OSD.FromBoolean(result);
resp["reason"] = OSD.FromString(reason);
resp["version"] = OSD.FromString(version);
// We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
// Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
}
protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token)
{
if (string.IsNullOrEmpty(action))
m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token);
else
m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID);
GridRegion destination = new GridRegion();
destination.RegionID = regionID;
if (action.Equals("release"))
ReleaseAgent(regionID, id);
else
Util.FireAndForget(delegate { m_SimulationService.CloseAgent(destination, id, auth_token); });
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
//m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID);
}
protected virtual void ReleaseAgent(UUID regionID, UUID id)
{
m_SimulationService.ReleaseAgent(regionID, id, "");
}
}
public class AgentPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
protected bool m_Proxy = false;
public AgentPostHandler(ISimulationService service) :
base("POST", "/agent")
{
m_SimulationService = service;
}
public AgentPostHandler(string path) :
base("POST", path)
{
m_SimulationService = null;
}
protected override byte[] ProcessRequest(string path, Stream request,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// m_log.DebugFormat("[SIMULATION]: Stream handler called");
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
string[] querystringkeys = httpRequest.QueryString.AllKeys;
string[] rHeaders = httpRequest.Headers.AllKeys;
keysvals.Add("uri", httpRequest.RawUrl);
keysvals.Add("content-type", httpRequest.ContentType);
keysvals.Add("http-method", httpRequest.HttpMethod);
foreach (string queryname in querystringkeys)
keysvals.Add(queryname, httpRequest.QueryString[queryname]);
foreach (string headername in rHeaders)
headervals[headername] = httpRequest.Headers[headername];
keysvals.Add("headers", headervals);
keysvals.Add("querystringkeys", querystringkeys);
httpResponse.StatusCode = 200;
httpResponse.ContentType = "text/html";
httpResponse.KeepAlive = false;
Encoding encoding = Encoding.UTF8;
Stream inputStream = null;
if (httpRequest.ContentType == "application/x-gzip")
inputStream = new GZipStream(request, CompressionMode.Decompress);
else if (httpRequest.ContentType == "application/json")
inputStream = request;
else // no go
{
httpResponse.StatusCode = 406;
return encoding.GetBytes("false");
}
StreamReader reader = new StreamReader(inputStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
keysvals.Add("body", requestBody);
Hashtable responsedata = new Hashtable();
UUID agentID;
UUID regionID;
string action;
if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
{
m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
httpResponse.StatusCode = 404;
return encoding.GetBytes("false");
}
DoAgentPost(keysvals, responsedata, agentID);
httpResponse.StatusCode = (int)responsedata["int_response_code"];
return encoding.GetBytes((string)responsedata["str_response_string"]);
}
protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
AgentDestinationData data = CreateAgentDestinationData();
UnpackData(args, data, request);
GridRegion destination = new GridRegion();
destination.RegionID = data.uuid;
destination.RegionLocX = data.x;
destination.RegionLocY = data.y;
destination.RegionName = data.name;
GridRegion gatekeeper = ExtractGatekeeper(data);
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
OSDMap resp = new OSDMap(2);
string reason = String.Empty;
// This is the meaning of POST agent
//m_regionClient.AdjustUserInformation(aCircuit);
//bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
bool result = CreateAgent(gatekeeper, destination, aCircuit, data.flags, data.fromLogin, out reason);
resp["reason"] = OSD.FromString(reason);
resp["success"] = OSD.FromBoolean(result);
// Let's also send out the IP address of the caller back to the caller (HG 1.5)
resp["your_ip"] = OSD.FromString(GetCallerIP(request));
// TODO: add reason if not String.Empty?
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
protected virtual AgentDestinationData CreateAgentDestinationData()
{
return new AgentDestinationData();
}
protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request)
{
// retrieve the input arguments
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out data.x);
else
m_log.WarnFormat(" -- request didn't have destination_x");
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out data.y);
else
m_log.WarnFormat(" -- request didn't have destination_y");
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
data.name = args["destination_name"].ToString();
if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
data.flags = args["teleport_flags"].AsUInteger();
}
protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data)
{
return null;
}
protected string GetCallerIP(Hashtable request)
{
if (!m_Proxy)
return Util.GetCallerIP(request);
// We're behind a proxy
Hashtable headers = (Hashtable)request["headers"];
//// DEBUG
//foreach (object o in headers.Keys)
// m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString()));
string xff = "X-Forwarded-For";
if (headers.ContainsKey(xff.ToLower()))
xff = xff.ToLower();
if (!headers.ContainsKey(xff) || headers[xff] == null)
{
m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
return Util.GetCallerIP(request);
}
m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
if (ep != null)
return ep.Address.ToString();
// Oops
return Util.GetCallerIP(request);
}
// subclasses can override this
protected virtual bool CreateAgent(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason)
{
return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
}
}
public class AgentPutHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
protected bool m_Proxy = false;
public AgentPutHandler(ISimulationService service) :
base("PUT", "/agent")
{
m_SimulationService = service;
}
public AgentPutHandler(string path) :
base("PUT", path)
{
m_SimulationService = null;
}
protected override byte[] ProcessRequest(string path, Stream request,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
// m_log.DebugFormat("[SIMULATION]: Stream handler called");
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
string[] querystringkeys = httpRequest.QueryString.AllKeys;
string[] rHeaders = httpRequest.Headers.AllKeys;
keysvals.Add("uri", httpRequest.RawUrl);
keysvals.Add("content-type", httpRequest.ContentType);
keysvals.Add("http-method", httpRequest.HttpMethod);
foreach (string queryname in querystringkeys)
keysvals.Add(queryname, httpRequest.QueryString[queryname]);
foreach (string headername in rHeaders)
headervals[headername] = httpRequest.Headers[headername];
keysvals.Add("headers", headervals);
keysvals.Add("querystringkeys", querystringkeys);
Stream inputStream;
if (httpRequest.ContentType == "application/x-gzip")
inputStream = new GZipStream(request, CompressionMode.Decompress);
else
inputStream = request;
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(inputStream, encoding);
string requestBody = reader.ReadToEnd();
reader.Close();
keysvals.Add("body", requestBody);
httpResponse.StatusCode = 200;
httpResponse.ContentType = "text/html";
httpResponse.KeepAlive = false;
Hashtable responsedata = new Hashtable();
UUID agentID;
UUID regionID;
string action;
if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
{
m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
httpResponse.StatusCode = 404;
return encoding.GetBytes("false");
}
DoAgentPut(keysvals, responsedata);
httpResponse.StatusCode = (int)responsedata["int_response_code"];
return encoding.GetBytes((string)responsedata["str_response_string"]);
}
protected void DoAgentPut(Hashtable request, Hashtable responsedata)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
string messageType;
if (args["message_type"] != null)
messageType = args["message_type"].AsString();
else
{
m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
messageType = "AgentData";
}
bool result = true;
if ("AgentData".Equals(messageType))
{
AgentData agent = new AgentData();
try
{
agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = UpdateAgent(destination, agent);
}
else if ("AgentPosition".Equals(messageType))
{
AgentPosition agent = new AgentPosition();
try
{
agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
}
catch (Exception ex)
{
m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = m_SimulationService.UpdateAgent(destination, agent);
}
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = result.ToString();
//responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
}
// subclasses can override this
protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
{
return m_SimulationService.UpdateAgent(destination, agent);
}
}
public class AgentDestinationData
{
public int x;
public int y;
public string name;
public UUID uuid;
public uint flags;
public bool fromLogin;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/language/v1/language_service.proto
// Original file comments:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Language.V1 {
/// <summary>
/// Provides text analysis operations such as sentiment analysis and entity
/// recognition.
/// </summary>
public static partial class LanguageService
{
static readonly string __ServiceName = "google.cloud.language.v1.LanguageService";
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest> __Marshaller_AnalyzeSentimentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Marshaller_AnalyzeSentimentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest> __Marshaller_AnalyzeEntitiesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Marshaller_AnalyzeEntitiesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest> __Marshaller_AnalyzeEntitySentimentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> __Marshaller_AnalyzeEntitySentimentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest> __Marshaller_AnalyzeSyntaxRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Marshaller_AnalyzeSyntaxResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.ClassifyTextRequest> __Marshaller_ClassifyTextRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.ClassifyTextRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.ClassifyTextResponse> __Marshaller_ClassifyTextResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.ClassifyTextResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnnotateTextRequest> __Marshaller_AnnotateTextRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnnotateTextResponse> __Marshaller_AnnotateTextResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Method_AnalyzeSentiment = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AnalyzeSentiment",
__Marshaller_AnalyzeSentimentRequest,
__Marshaller_AnalyzeSentimentResponse);
static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Method_AnalyzeEntities = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AnalyzeEntities",
__Marshaller_AnalyzeEntitiesRequest,
__Marshaller_AnalyzeEntitiesResponse);
static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest, global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> __Method_AnalyzeEntitySentiment = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest, global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AnalyzeEntitySentiment",
__Marshaller_AnalyzeEntitySentimentRequest,
__Marshaller_AnalyzeEntitySentimentResponse);
static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Method_AnalyzeSyntax = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AnalyzeSyntax",
__Marshaller_AnalyzeSyntaxRequest,
__Marshaller_AnalyzeSyntaxResponse);
static readonly grpc::Method<global::Google.Cloud.Language.V1.ClassifyTextRequest, global::Google.Cloud.Language.V1.ClassifyTextResponse> __Method_ClassifyText = new grpc::Method<global::Google.Cloud.Language.V1.ClassifyTextRequest, global::Google.Cloud.Language.V1.ClassifyTextResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ClassifyText",
__Marshaller_ClassifyTextRequest,
__Marshaller_ClassifyTextResponse);
static readonly grpc::Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse> __Method_AnnotateText = new grpc::Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AnnotateText",
__Marshaller_AnnotateTextRequest,
__Marshaller_AnnotateTextResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Language.V1.LanguageServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of LanguageService</summary>
public abstract partial class LanguageServiceBase
{
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Classifies a document into categories.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.ClassifyTextResponse> ClassifyText(global::Google.Cloud.Language.V1.ClassifyTextRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for LanguageService</summary>
public partial class LanguageServiceClient : grpc::ClientBase<LanguageServiceClient>
{
/// <summary>Creates a new client for LanguageService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public LanguageServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for LanguageService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public LanguageServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected LanguageServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected LanguageServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentiment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentimentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntities(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntitiesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently proper names and common nouns) in the text
/// along with entity types, salience, mentions for each entity, and
/// other properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntitySentiment(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntitySentiment, null, options, request);
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntitySentimentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] in the text and analyzes
/// sentiment associated with each entity and its mentions.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntitySentiment, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntax(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntaxAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// Classifies a document into categories.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.ClassifyTextResponse ClassifyText(global::Google.Cloud.Language.V1.ClassifyTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ClassifyText(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Classifies a document into categories.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.ClassifyTextResponse ClassifyText(global::Google.Cloud.Language.V1.ClassifyTextRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ClassifyText, null, options, request);
}
/// <summary>
/// Classifies a document into categories.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.ClassifyTextResponse> ClassifyTextAsync(global::Google.Cloud.Language.V1.ClassifyTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ClassifyTextAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Classifies a document into categories.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.ClassifyTextResponse> ClassifyTextAsync(global::Google.Cloud.Language.V1.ClassifyTextRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ClassifyText, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateText(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnnotateText, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateTextAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnnotateText, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override LanguageServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new LanguageServiceClient(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(LanguageServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_AnalyzeSentiment, serviceImpl.AnalyzeSentiment)
.AddMethod(__Method_AnalyzeEntities, serviceImpl.AnalyzeEntities)
.AddMethod(__Method_AnalyzeEntitySentiment, serviceImpl.AnalyzeEntitySentiment)
.AddMethod(__Method_AnalyzeSyntax, serviceImpl.AnalyzeSyntax)
.AddMethod(__Method_ClassifyText, serviceImpl.ClassifyText)
.AddMethod(__Method_AnnotateText, serviceImpl.AnnotateText).Build();
}
}
}
#endregion
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at given moments in time, defined with Unix 'cron-like' definitions.
/// </summary>
/// <remarks>
/// <para>
/// For those unfamiliar with "cron", this means being able to create a firing
/// schedule such as: "At 8:00am every Monday through Friday" or "At 1:30am
/// every last Friday of the month".
/// </para>
///
/// <para>
/// The format of a "Cron-Expression" string is documented on the
/// <see cref="CronExpression" /> class.
/// </para>
///
/// <para>
/// Here are some full examples: <br />
/// <table cellspacing="8">
/// <tr>
/// <th align="left">Expression</th>
/// <th align="left"> </th>
/// <th align="left">Meaning</th>
/// </tr>
/// <tr>
/// <td align="left">"0 0 12 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 12pm (noon) every day" /></td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * *"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am every day" /></td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am every day" /></td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 * * ? *"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am every day" /></td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 * * ? 2005"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am every day during the year 2005" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 * 14 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire every minute starting at 2pm and ending at 2:59pm, every day" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 0/5 14 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 0/5 14,18 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 0-5 14 * * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire every minute starting at 2pm and ending at 2:05pm, every day" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 10,44 14 ? 3 WED"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 2:10pm and at 2:44pm every Wednesday in the month of March." />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * MON-FRI"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 15 * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on the 15th day of every month" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 L * ?"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on the last day of every month" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * 6L"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on the last Friday of every month" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * 6L"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on the last Friday of every month" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * 6L 2002-2005"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on every last Friday of every month during the years 2002, 2003, 2004 and 2005" />
/// </td>
/// </tr>
/// <tr>
/// <td align="left">"0 15 10 ? * 6#3"" /></td>
/// <td align="left"> </td>
/// <td align="left">Fire at 10:15am on the third Friday of every month" />
/// </td>
/// </tr>
/// </table>
/// </para>
///
/// <para>
/// Pay attention to the effects of '?' and '*' in the day-of-week and
/// day-of-month fields!
/// </para>
///
/// <para>
/// <b>NOTES:</b>
/// <ul>
/// <li>Support for specifying both a day-of-week and a day-of-month value is
/// not complete (you'll need to use the '?' character in on of these fields).
/// </li>
/// <li>Be careful when setting fire times between mid-night and 1:00 AM -
/// "daylight savings" can cause a skip or a repeat depending on whether the
/// time moves back or jumps forward.</li>
/// </ul>
/// </para>
/// </remarks>
/// <seealso cref="ITrigger"/>
/// <seealso cref="ISimpleTrigger"/>
/// <author>Sharada Jambula</author>
/// <author>James House</author>
/// <author>Contributions from Mads Henderson</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class CronTriggerImpl : AbstractTrigger, ICronTrigger
{
protected const int YearToGiveupSchedulingAt = 2299;
private CronExpression cronEx;
private DateTimeOffset startTimeUtc = DateTimeOffset.MinValue;
private DateTimeOffset? endTimeUtc;
private DateTimeOffset? nextFireTimeUtc;
private DateTimeOffset? previousFireTimeUtc;
[NonSerialized] private TimeZoneInfo timeZone;
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with no settings.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
public CronTriggerImpl()
{
StartTimeUtc = SystemTime.UtcNow();
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with the given name and default group.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
public CronTriggerImpl(string name) : this(name, null)
{
}
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with the given name and group.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
public CronTriggerImpl(string name, string group) : base(name, group)
{
StartTimeUtc = SystemTime.UtcNow();
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with the given name, group and
/// expression.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="cronExpression"> A cron expression dictating the firing sequence of the <see cref="ITrigger" /></param>
public CronTriggerImpl(string name, string group, string cronExpression) : base(name, group)
{
CronExpressionString = cronExpression;
StartTimeUtc = SystemTime.UtcNow();
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with the given name and group, and
/// associated with the identified <see cref="IJobDetail" />.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
/// <param name="name">The name of the <see cref="ITrigger" />.</param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="jobName">name of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="jobGroup">Group of the <see cref="IJobDetail" /> executed on firetime</param>
public CronTriggerImpl(string name, string group, string jobName,
string jobGroup) : base(name, group, jobName, jobGroup)
{
StartTimeUtc = SystemTime.UtcNow();
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Create a <see cref="ICronTrigger" /> with the given name and group,
/// associated with the identified <see cref="IJobDetail" />,
/// and with the given "cron" expression.
/// </summary>
/// <remarks>
/// The start-time will also be set to the current time, and the time zone
/// will be set the the system's default time zone.
/// </remarks>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="jobName">name of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="jobGroup">Group of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="cronExpression"> A cron expression dictating the firing sequence of the <see cref="ITrigger" /></param>
public CronTriggerImpl(string name, string group, string jobName,
string jobGroup, string cronExpression)
: this(name, group, jobName, jobGroup, SystemTime.UtcNow(), null, cronExpression, TimeZoneInfo.Local)
{
}
/// <summary>
/// Create a <see cref="ICronTrigger" /> with the given name and group,
/// associated with the identified <see cref="IJobDetail" />,
/// and with the given "cron" expression resolved with respect to the <see cref="TimeZone" />.
/// </summary>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="jobName">name of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="jobGroup">Group of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="cronExpression"> A cron expression dictating the firing sequence of the <see cref="ITrigger" /></param>
/// <param name="timeZone">
/// Specifies for which time zone the cronExpression should be interpreted,
/// i.e. the expression 0 0 10 * * ?, is resolved to 10:00 am in this time zone.
/// </param>
public CronTriggerImpl(string name, string group, string jobName,
string jobGroup, string cronExpression, TimeZoneInfo timeZone)
: this(name, group, jobName, jobGroup, SystemTime.UtcNow(), null, cronExpression,
timeZone)
{
}
/// <summary>
/// Create a <see cref="ICronTrigger" /> that will occur at the given time,
/// until the given end time.
/// <para>
/// If null, the start-time will also be set to the current time, the time
/// zone will be set the the system's default.
/// </para>
/// </summary>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="jobName">name of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="jobGroup">Group of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the earliest time for the <see cref="ITrigger" /> to start firing.</param>
/// <param name="endTime">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param>
/// <param name="cronExpression"> A cron expression dictating the firing sequence of the <see cref="ITrigger" /></param>
public CronTriggerImpl(string name, string group, string jobName,
string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTime,
string cronExpression)
: base(name, group, jobName, jobGroup)
{
CronExpressionString = cronExpression;
if (startTimeUtc == DateTimeOffset.MinValue)
{
startTimeUtc = SystemTime.UtcNow();
}
StartTimeUtc = startTimeUtc;
if (endTime.HasValue)
{
EndTimeUtc = endTime;
}
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Create a <see cref="CronTriggerImpl" /> with fire time dictated by the
/// <param name="cronExpression" /> resolved with respect to the specified
/// <param name="timeZone" /> occurring from the <see cref="startTimeUtc" /> until
/// the given <paran name="endTimeUtc" />.
/// </summary>
/// <param name="name">The name of the <see cref="ITrigger" /></param>
/// <param name="group">The group of the <see cref="ITrigger" /></param>
/// <param name="jobName">name of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="jobGroup">Group of the <see cref="IJobDetail" /> executed on firetime</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the earliest time for the <see cref="ITrigger" /> to start firing.</param>
/// <param name="endTime">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to quit repeat firing.</param>
public CronTriggerImpl(string name, string group, string jobName,
string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTime,
string cronExpression,
TimeZoneInfo timeZone) : base(name, group, jobName, jobGroup)
{
CronExpressionString = cronExpression;
if (startTimeUtc == DateTimeOffset.MinValue)
{
startTimeUtc = SystemTime.UtcNow();
}
StartTimeUtc = startTimeUtc;
if (endTime.HasValue)
{
EndTimeUtc = endTime;
}
if (timeZone == null)
{
timeZone = TimeZoneInfo.Local;
}
else
{
TimeZone = timeZone;
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public override object Clone()
{
CronTriggerImpl copy = (CronTriggerImpl) MemberwiseClone();
if (cronEx != null)
{
copy.CronExpression = (CronExpression) cronEx.Clone();
}
return copy;
}
/// <summary>
/// Gets or sets the cron expression string.
/// </summary>
/// <value>The cron expression string.</value>
public string CronExpressionString
{
set
{
TimeZoneInfo orginalTimeZone = TimeZone;
cronEx = new CronExpression(value);
cronEx.TimeZone = orginalTimeZone;
}
get { return cronEx == null ? null : cronEx.CronExpressionString; }
}
/// <summary>
/// Set the CronExpression to the given one. The TimeZone on the passed-in
/// CronExpression over-rides any that was already set on the Trigger.
/// </summary>
/// <value>The cron expression.</value>
public CronExpression CronExpression
{
set
{
cronEx = value;
timeZone = value.TimeZone;
}
}
/// <summary>
/// Returns the date/time on which the trigger may begin firing. This
/// defines the initial boundary for trigger firings the trigger
/// will not fire prior to this date and time.
/// </summary>
/// <value></value>
public override DateTimeOffset StartTimeUtc
{
get { return startTimeUtc; }
set
{
DateTimeOffset? eTime = EndTimeUtc;
if (eTime.HasValue && eTime.Value < value)
{
throw new ArgumentException("End time cannot be before start time");
}
// round off millisecond...
DateTimeOffset dt = new DateTimeOffset(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Offset);
startTimeUtc = dt;
}
}
/// <summary>
/// Get or sets the time at which the <c>CronTrigger</c> should quit
/// repeating - even if repeastCount isn't yet satisfied.
/// </summary>
public override DateTimeOffset? EndTimeUtc
{
get { return endTimeUtc; }
set
{
DateTimeOffset sTime = StartTimeUtc;
if (value.HasValue && sTime > value.Value)
{
throw new ArgumentException("End time cannot be before start time");
}
endTimeUtc = value;
}
}
/// <summary>
/// Returns the next time at which the <see cref="ITrigger" /> is scheduled to fire. If
/// the trigger will not fire again, <see langword="null" /> will be returned. Note that
/// the time returned can possibly be in the past, if the time that was computed
/// for the trigger to next fire has already arrived, but the scheduler has not yet
/// been able to fire the trigger (which would likely be due to lack of resources
/// e.g. threads).
/// </summary>
///<remarks>
/// The value returned is not guaranteed to be valid until after the <see cref="ITrigger" />
/// has been added to the scheduler.
/// </remarks>
/// <returns></returns>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
/// <summary>
/// Returns the previous time at which the <see cref="ITrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be returned.
/// </summary>
/// <returns></returns>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Sets the next fire time.
/// <para>
/// <b>This method should not be invoked by client code.</b>
/// </para>
/// </summary>
/// <param name="fireTime">The fire time.</param>
public override void SetNextFireTimeUtc(DateTimeOffset? fireTime)
{
nextFireTimeUtc = fireTime;
}
/// <summary>
/// Sets the previous fire time.
/// <para>
/// <b>This method should not be invoked by client code.</b>
/// </para>
/// </summary>
/// <param name="fireTime">The fire time.</param>
public override void SetPreviousFireTimeUtc(DateTimeOffset? fireTime)
{
previousFireTimeUtc = fireTime;
}
/// <summary>
/// Sets the time zone for which the <see cref="ICronTrigger.CronExpressionString" /> of this
/// <see cref="ICronTrigger" /> will be resolved.
/// </summary>
/// <remarks>
/// If <see cref="ICronTrigger.CronExpressionString" /> is set after this
/// property, the TimeZone setting on the CronExpression will "win". However
/// if <see cref="CronExpressionString" /> is set after this property, the
/// time zone applied by this method will remain in effect, since the
/// string cron expression does not carry a time zone!
/// </remarks>
/// <value>The time zone.</value>
public TimeZoneInfo TimeZone
{
get
{
if (cronEx != null)
{
return cronEx.TimeZone;
}
if (timeZone == null)
{
timeZone = TimeZoneInfo.Local;
}
return timeZone;
}
set
{
if (cronEx != null)
{
cronEx.TimeZone = value;
}
timeZone = value;
}
}
/// <summary>
/// Returns the next time at which the <see cref="ITrigger" /> will fire,
/// after the given time. If the trigger will not fire after the given time,
/// <see langword="null" /> will be returned.
/// </summary>
/// <param name="afterTimeUtc"></param>
/// <returns></returns>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (StartTimeUtc > afterTimeUtc.Value)
{
afterTimeUtc = startTimeUtc.AddSeconds(-1);
}
if (EndTimeUtc.HasValue && (afterTimeUtc.Value.CompareTo(EndTimeUtc.Value) >= 0))
{
return null;
}
DateTimeOffset? pot = GetTimeAfter(afterTimeUtc.Value);
if (EndTimeUtc.HasValue && pot.HasValue && pot.Value > EndTimeUtc.Value)
{
return null;
}
return pot;
}
public override IScheduleBuilder GetScheduleBuilder()
{
CronScheduleBuilder cb = CronScheduleBuilder.CronSchedule(CronExpressionString).InTimeZone(TimeZone);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.CronTrigger.DoNothing: cb.WithMisfireHandlingInstructionDoNothing();
break;
case Quartz.MisfireInstruction.CronTrigger.FireOnceNow: cb.WithMisfireHandlingInstructionFireAndProceed();
break;
}
return cb;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ITrigger" /> will fire, if
/// the Trigger will repeat indefinitely, null will be returned.
/// <para>
/// Note that the return time *may* be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
DateTimeOffset? resultTime;
if (EndTimeUtc.HasValue)
{
resultTime = GetTimeBefore(EndTimeUtc.Value.AddSeconds(1));
}
else
{
resultTime = (cronEx == null) ? null : cronEx.GetFinalFireTime();
}
if (resultTime.HasValue && resultTime.Value < StartTimeUtc)
{
return null;
}
return resultTime;
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision
{
get { return false; }
}
/// <summary>
/// Used by the <see cref="IScheduler" /> to determine whether or not
/// it is possible for this <see cref="ITrigger" /> to fire again.
/// <para>
/// If the returned value is <see langword="false" /> then the <see cref="IScheduler" />
/// may remove the <see cref="ITrigger" /> from the <see cref="IJobStore" />.
/// </para>
/// </summary>
/// <returns></returns>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.CronTrigger.DoNothing)
{
return false;
}
return true;
}
/// <summary>
/// This method should not be used by the Quartz client.
/// <para>
/// To be implemented by the concrete classes that extend this class.
/// </para>
/// <para>
/// The implementation should update the <see cref="ITrigger" />'s state
/// based on the MISFIRE_INSTRUCTION_XXX that was selected when the <see cref="ITrigger" />
/// was created.
/// </para>
/// </summary>
/// <param name="cal"></param>
public override void UpdateAfterMisfire(ICalendar cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
instr = Quartz.MisfireInstruction.CronTrigger.FireOnceNow;
}
if (instr == Quartz.MisfireInstruction.CronTrigger.DoNothing)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null
&& !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
}
SetNextFireTimeUtc(newFireTime);
}
else if (instr == Quartz.MisfireInstruction.CronTrigger.FireOnceNow)
{
SetNextFireTimeUtc(SystemTime.UtcNow());
}
}
/// <summary>
/// <para>
/// Determines whether the date and (optionally) time of the given Calendar
/// instance falls on a scheduled fire-time of this trigger.
/// </para>
///
/// <para>
/// Equivalent to calling <see cref="WillFireOn(DateTimeOffset, bool)" />.
/// </para>
/// </summary>
/// <param name="test">The date to compare.</param>
/// <returns></returns>
public bool WillFireOn(DateTimeOffset test)
{
return WillFireOn(test, false);
}
/// <summary>
/// Determines whether the date and (optionally) time of the given Calendar
/// instance falls on a scheduled fire-time of this trigger.
/// <para>
/// Note that the value returned is NOT validated against the related
/// ICalendar (if any).
/// </para>
/// </summary>
/// <param name="test">The date to compare</param>
/// <param name="dayOnly">If set to true, the method will only determine if the
/// trigger will fire during the day represented by the given Calendar
/// (hours, minutes and seconds will be ignored).</param>
/// <returns></returns>
public bool WillFireOn(DateTimeOffset test, bool dayOnly)
{
test = new DateTime(test.Year, test.Month, test.Day, test.Hour, test.Minute, test.Second);
if (dayOnly)
{
test = new DateTime(test.Year, test.Month, test.Day, 0, 0, 0);
}
DateTimeOffset? fta = GetFireTimeAfter(test.AddMilliseconds(-1 * 1000));
if (fta == null)
{
return false;
}
DateTimeOffset p = TimeZoneUtil.ConvertTime(fta.Value, TimeZone);
if (dayOnly)
{
return (p.Year == test.Year
&& p.Month == test.Month
&& p.Day == test.Day);
}
while (fta.Value < test)
{
fta = GetFireTimeAfter(fta);
}
if (fta.Equals(test))
{
return true;
}
return false;
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <param name="cal"></param>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar cal)
{
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null
&& !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
/// <summary>
/// Updates the trigger with new calendar.
/// </summary>
/// <param name="calendar">The calendar to update with.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (!nextFireTimeUtc.HasValue || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
// avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc.HasValue && nextFireTimeUtc.Value < (now))
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
continue;
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <param name="cal"></param>
/// <returns>
/// the first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar cal)
{
nextFireTimeUtc = GetFireTimeAfter(startTimeUtc.AddSeconds(-1));
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
return nextFireTimeUtc;
}
/// <summary>
/// Gets the expression summary.
/// </summary>
/// <returns></returns>
public string GetExpressionSummary()
{
return cronEx == null ? null : cronEx.GetExpressionSummary();
}
public TriggerBuilder GetTriggerBuilder()
{
throw new NotImplementedException();
}
////////////////////////////////////////////////////////////////////////////
//
// Computation Functions
//
////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the next time to fire after the given time.
/// </summary>
/// <param name="afterTime">The time to compute from.</param>
/// <returns></returns>
protected DateTimeOffset? GetTimeAfter(DateTimeOffset afterTime)
{
if (cronEx != null)
{
return cronEx.GetTimeAfter(afterTime);
}
return null;
}
/// <summary>
/// NOT YET IMPLEMENTED: Returns the time before the given time
/// that this <see cref="ICronTrigger" /> will fire.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
protected DateTimeOffset? GetTimeBefore(DateTimeOffset? date)
{
return (cronEx == null) ? null : cronEx.GetTimeBefore(endTimeUtc);
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : ProxyCredentials.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 11/24/2007
// Note : Copyright 2007, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class that is used to specify credentials for a proxy
// server.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.2.0 09/13/2007 EFW Created the code
//=============================================================================
using System;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This class is used to specify credentials for a proxy server.
/// </summary>
public class ProxyCredentials
{
#region Private data members
//=====================================================================
// Private data members
private bool useProxyServer;
private Uri proxyServer;
private UserCredentials credentials;
#endregion
#region Properties
//=====================================================================
// Properties
/// <summary>
/// This is used to set or get the flag indicating whether or not to
/// use the proxy server.
/// </summary>
/// <value>By default, this is false and <see cref="ProxyServer"/> and
/// <see cref="Credentials"/> will be ignored.</value>
public bool UseProxyServer
{
get { return useProxyServer; }
set { useProxyServer = value; }
}
/// <summary>
/// Get or set the proxy server name
/// </summary>
/// <value>If <see cref="UseProxyServer"/> is false, this will be
/// ignored.</value>
public Uri ProxyServer
{
get { return proxyServer; }
set { proxyServer = value; }
}
/// <summary>
/// Get the user credentials
/// </summary>
/// <value>If <see cref="UseProxyServer"/> is false, this will be
/// ignored.</value>
public UserCredentials Credentials
{
get { return credentials; }
}
#endregion
//=====================================================================
// Methods, etc.
/// <summary>
/// Constructor
/// </summary>
/// <overloads>There are two overloads for the constructor.</overloads>
public ProxyCredentials()
{
credentials = new UserCredentials();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="useProxy">True to use default the proxy server, false
/// to not use it.</param>
/// <param name="server">The server name to use.</param>
/// <param name="proxyUser">The user credentials to use for the proxy
/// server.</param>
public ProxyCredentials(bool useProxy, Uri server,
UserCredentials proxyUser)
{
useProxyServer = useProxy;
proxyServer = server;
if(proxyUser == null)
credentials = new UserCredentials();
else
credentials = proxyUser;
}
/// <summary>
/// Create a proxy credentials instance from an XPath navigator
/// containing the settings.
/// </summary>
/// <param name="navigator">The XPath navigator from which to
/// obtain the settings.</param>
/// <returns>A <see cref="ProxyCredentials"/> object containing the
/// settings from the XPath navigator.</returns>
/// <remarks>It should contain an element called <b>proxyCredentials</b>
/// with two attributes (<b>useProxy</b> and <b>proxyServer</b>) and a
/// nested <b>userCredentials</b> element.</remarks>
public static ProxyCredentials FromXPathNavigator(
XPathNavigator navigator)
{
ProxyCredentials credentials = new ProxyCredentials();
UserCredentials user;
string server;
if(navigator != null)
{
navigator = navigator.SelectSingleNode("proxyCredentials");
if(navigator != null)
{
credentials.UseProxyServer = Convert.ToBoolean(
navigator.GetAttribute("useProxy", String.Empty),
CultureInfo.InvariantCulture);
server = navigator.GetAttribute("proxyServer",
String.Empty).Trim();
if(server.Length != 0)
credentials.ProxyServer = new Uri(server,
UriKind.RelativeOrAbsolute);
user = UserCredentials.FromXPathNavigator(navigator);
credentials.Credentials.UseDefaultCredentials =
user.UseDefaultCredentials;
credentials.Credentials.UserName = user.UserName;
credentials.Credentials.Password = user.Password;
}
}
return credentials;
}
/// <summary>
/// Store the credentials as a node in the given XML document
/// </summary>
/// <param name="config">The XML document</param>
/// <param name="root">The node in which to store the element</param>
/// <returns>Returns the node that was added or the one that
/// already existed in the document.</returns>
/// <remarks>The credentials are stored in an element called
/// <b>proxyCredentials</b> with two attributes (<b>useProxy</b> and
/// <b>proxyServer</b>) and a nested <b>userCredentials</b> element.
/// It is created if it does not already exist.</remarks>
public XmlNode ToXml(XmlDocument config, XmlNode root)
{
XmlNode node;
XmlAttribute attr;
if(root == null)
throw new ArgumentNullException("root");
node = root.SelectSingleNode("proxyCredentials");
if(node == null)
{
node = config.CreateNode(XmlNodeType.Element,
"proxyCredentials", null);
root.AppendChild(node);
attr = config.CreateAttribute("useProxy");
node.Attributes.Append(attr);
attr = config.CreateAttribute("proxyServer");
node.Attributes.Append(attr);
}
node.Attributes["useProxy"].Value =
useProxyServer.ToString().ToLower(
CultureInfo.InvariantCulture);
node.Attributes["proxyServer"].Value = (proxyServer == null) ?
String.Empty : proxyServer.OriginalString;
credentials.ToXml(config, node);
return node;
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game {public class World : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
Spheres = (
(Enumerable.Range(-1,(1) + ((1) - (-1))).ToList<System.Int32>()).Select(__ContextSymbol2 => new { ___x00 = __ContextSymbol2 })
.SelectMany(__ContextSymbol3=> (Enumerable.Range(-1,(1) + ((1) - (-1))).ToList<System.Int32>()).Select(__ContextSymbol4 => new { ___y00 = __ContextSymbol4,
prev = __ContextSymbol3 })
.Select(__ContextSymbol5 => new Sphere(new UnityEngine.Vector3((__ContextSymbol5.prev.___x00) * (20f),(__ContextSymbol5.___y00) * (20f),0f)))
.ToList<Sphere>())).ToList<Sphere>();
Boids = (
(Enumerable.Range(1,(1) + ((40) - (1))).ToList<System.Int32>()).Select(__ContextSymbol0 => new { ___a00 = __ContextSymbol0 })
.Select(__ContextSymbol1 => new Boid(new UnityEngine.Vector3(UnityEngine.Random.Range(-10,10),UnityEngine.Random.Range(-10,10),0f)))
.ToList<Boid>()).ToList<Boid>();
BoidBoss = new BoidLeader(new UnityEngine.Vector3(-10f,0f,0f));
}
public BoidLeader BoidBoss;
public List<Boid> Boids;
public List<Sphere> Spheres;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world) {
var t = System.DateTime.Now;
BoidBoss.Update(dt, world);
for(int x0 = 0; x0 < Boids.Count; x0++) {
Boids[x0].Update(dt, world);
}
for(int x0 = 0; x0 < Spheres.Count; x0++) {
Spheres[x0].Update(dt, world);
}
}
}
public class Boid{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 pos;
public int ID;
public Boid(UnityEngine.Vector3 pos)
{JustEntered = false;
frame = World.frame;
Velocity = new UnityEngine.Vector3(0f,0f,0f);
UnityBoid = UnityBoid.Instantiate(pos);
SeparationImpulse = 20f;
SeparationFactor = 100000f;
Separation = Vector3.zero;
SeekImpulse = 5f;
Seek = Vector3.zero;
MaxVelocity = 8f;
MaxDist = (Scale.x) * (2f);
FrictionFactor = 0.4f;
Friction = Vector3.zero;
Force = Vector3.zero;
CohesionMaxDist = 30f;
CohesionImpulse = 0.9f;
Cohesion = Vector3.zero;
Acceleration = Vector3.zero;
}
public UnityEngine.Vector3 Acceleration;
public UnityEngine.Vector3 Cohesion;
public System.Single CohesionImpulse;
public System.Single CohesionMaxDist;
public UnityEngine.Vector3 Force;
public UnityEngine.Vector3 Friction;
public System.Single FrictionFactor;
public System.Single MaxDist;
public System.Single MaxVelocity;
public UnityEngine.Vector3 Position{ get { return UnityBoid.Position; }
set{UnityBoid.Position = value; }
}
public UnityEngine.Vector3 Scale{ get { return UnityBoid.Scale; }
}
public UnityEngine.Vector3 Seek;
public System.Single SeekImpulse;
public UnityEngine.Vector3 Separation;
public System.Single SeparationFactor;
public System.Single SeparationImpulse;
public UnityBoid UnityBoid;
public UnityEngine.Vector3 Velocity;
public System.Boolean enabled{ get { return UnityBoid.enabled; }
set{UnityBoid.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityBoid.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityBoid.hideFlags; }
set{UnityBoid.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityBoid.isActiveAndEnabled; }
}
public System.String name{ get { return UnityBoid.name; }
set{UnityBoid.name = value; }
}
public System.String tag{ get { return UnityBoid.tag; }
set{UnityBoid.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityBoid.transform; }
}
public System.Boolean useGUILayout{ get { return UnityBoid.useGUILayout; }
set{UnityBoid.useGUILayout = value; }
}
public UnityEngine.Vector3 ___friction30;
public List<Casanova.Prelude.Tuple<UnityEngine.Vector3, System.Single>> ___close_boids_positions40;
public UnityEngine.Vector3 ___close_boids_sum40;
public System.Single ___boss_dist40;
public System.Boolean ___is_boss_close40;
public UnityEngine.Vector3 ___close_boids_sum41;
public UnityEngine.Vector3 ___diff41;
public System.Int32 ___total_count40;
public UnityEngine.Vector3 ___avg40;
public UnityEngine.Vector3 ___steer40;
public System.Single ___boss_dist51;
public System.Boolean ___is_boss_close51;
public UnityEngine.Vector3 ___desired50;
public UnityEngine.Vector3 ___steer51;
public UnityEngine.Vector3 ___close_neighbors60;
public List<Boid> ___counter60;
public UnityEngine.Vector3 ___desired61;
public UnityEngine.Vector3 ___steer62;
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
this.Rule5(dt, world);
this.Rule6(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
Acceleration = ((((((Seek) + (Cohesion))) + (Friction))) + (Separation));
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
Velocity = ((Velocity) + (((Acceleration) * (dt))));
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
Position = ((Position) + (((Velocity) * (dt))));
s2 = -1;
return;
default: return;}}
int s3=-1;
public void Rule3(float dt, World world){
switch (s3)
{
case -1:
___friction30 = Velocity.normalized;
Friction = ((((___friction30) * (-1f))) * (FrictionFactor));
s3 = -1;
return;
default: return;}}
int s4=-1;
public void Rule4(float dt, World world){
switch (s4)
{
case -1:
___close_boids_positions40 = (
(world.Boids).Select(__ContextSymbol6 => new { ___boid40 = __ContextSymbol6 })
.Select(__ContextSymbol7 => new {___d40 = UnityEngine.Vector3.Distance(Position,__ContextSymbol7.___boid40.Position), prev = __ContextSymbol7 })
.Where(__ContextSymbol8 => ((((((__ContextSymbol8.___d40) > (0))) && (((MaxDist) > (__ContextSymbol8.___d40))))) && (!(((this) == (__ContextSymbol8.prev.___boid40))))))
.Select(__ContextSymbol9 => new Casanova.Prelude.Tuple<UnityEngine.Vector3, System.Single>((Position) - (__ContextSymbol9.prev.___boid40.Position),__ContextSymbol9.___d40))
.ToList<Casanova.Prelude.Tuple<UnityEngine.Vector3, System.Single>>()).ToList<Casanova.Prelude.Tuple<UnityEngine.Vector3, System.Single>>();
___close_boids_sum40 = (
(___close_boids_positions40).Select(__ContextSymbol10 => new { ___item40 = __ContextSymbol10 })
.Select(__ContextSymbol11 => new {___d41 = __ContextSymbol11.___item40.Item2, prev = __ContextSymbol11 })
.Select(__ContextSymbol12 => new {___diff40 = __ContextSymbol12.prev.___item40.Item1, prev = __ContextSymbol12 })
.Select(__ContextSymbol13 => (__ContextSymbol13.___diff40.normalized) / ((__ContextSymbol13.prev.___d41) / (SeparationFactor)))
.Aggregate(default(UnityEngine.Vector3), (acc, __x) => acc + __x));
___boss_dist40 = UnityEngine.Vector3.Distance(Position,world.BoidBoss.Position);
___is_boss_close40 = ((((___boss_dist40) > (0))) && (((world.BoidBoss.MaxDist) > (___boss_dist40))));
if(___is_boss_close40)
{
___diff41 = ((Position) - (world.BoidBoss.Position));
___close_boids_sum41 = ((((___diff41.normalized) / (((___boss_dist40) / (SeparationFactor))))) + (___close_boids_sum40)); }else
{
___close_boids_sum41 = ___close_boids_sum40; }
if(((((___close_boids_positions40.Count) > (0))) || (___is_boss_close40)))
{
goto case 2; }else
{
goto case 3; }
case 2:
if(___is_boss_close40)
{
___total_count40 = ((1) + (___close_boids_positions40.Count)); }else
{
___total_count40 = ___close_boids_positions40.Count; }
___avg40 = new UnityEngine.Vector3((___close_boids_sum41.x) / (___total_count40),(___close_boids_sum41.y) / (___total_count40),0f);
___steer40 = ((___avg40.normalized) * (MaxVelocity));
Separation = ((((___steer40) - (Velocity))) * (SeparationImpulse));
s4 = -1;
return;
case 3:
Separation = Vector3.zero;
s4 = -1;
return;
default: return;}}
int s5=-1;
public void Rule5(float dt, World world){
switch (s5)
{
case -1:
___boss_dist51 = UnityEngine.Vector3.Distance(Position,world.BoidBoss.Position);
___is_boss_close51 = ((((___boss_dist51) > (0))) && (((world.BoidBoss.MaxDist) > (___boss_dist51))));
if(!(___is_boss_close51))
{
goto case 15; }else
{
goto case 16; }
case 15:
___desired50 = ((world.BoidBoss.Position) - (Position));
___steer51 = ((___desired50.normalized) * (MaxVelocity));
Seek = ((((___steer51) - (Velocity))) * (SeekImpulse));
s5 = -1;
return;
case 16:
Seek = Vector3.zero;
s5 = -1;
return;
default: return;}}
int s6=-1;
public void Rule6(float dt, World world){
switch (s6)
{
case -1:
___close_neighbors60 = (
(world.Boids).Select(__ContextSymbol15 => new { ___boid61 = __ContextSymbol15 })
.Select(__ContextSymbol16 => new {___d62 = UnityEngine.Vector3.Distance(Position,__ContextSymbol16.___boid61.Position), prev = __ContextSymbol16 })
.Where(__ContextSymbol17 => ((((CohesionMaxDist) > (__ContextSymbol17.___d62))) && (!(((this) == (__ContextSymbol17.prev.___boid61))))))
.Select(__ContextSymbol18 => __ContextSymbol18.prev.___boid61.Position)
.Aggregate(default(UnityEngine.Vector3), (acc, __x) => acc + __x));
___counter60 = (
(world.Boids).Select(__ContextSymbol20 => new { ___boid62 = __ContextSymbol20 })
.Select(__ContextSymbol21 => new {___d63 = UnityEngine.Vector3.Distance(Position,__ContextSymbol21.___boid62.Position), prev = __ContextSymbol21 })
.Where(__ContextSymbol22 => (((((MaxDist) * (CohesionMaxDist)) > (__ContextSymbol22.___d63))) && (!(((this) == (__ContextSymbol22.prev.___boid62))))))
.Select(__ContextSymbol23 => __ContextSymbol23.prev.___boid62)
.ToList<Boid>()).ToList<Boid>();
if(((___counter60.Count) > (0)))
{
goto case 24; }else
{
goto case 25; }
case 24:
___desired61 = new UnityEngine.Vector3((___close_neighbors60.x) / (___counter60.Count),(___close_neighbors60.y) / (___counter60.Count),0f);
___steer62 = ((___desired61.normalized) * (MaxVelocity));
Cohesion = ((((___steer62) - (Velocity))) * (CohesionImpulse));
s6 = -1;
return;
case 25:
Cohesion = Vector3.zero;
s6 = -1;
return;
default: return;}}
}
public class BoidLeader{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 position;
public int ID;
public BoidLeader(UnityEngine.Vector3 position)
{JustEntered = false;
frame = World.frame;
UnityBoidLeader = UnityBoidLeader.Instantiate(position);
Start = true;
MaxVelocity = 5f;
MaxDist = (Scale.x) * (3f);
Camera = UnityCamera.Find();
}
public UnityEngine.Vector3 Backward{ get { return UnityBoidLeader.Backward; }
}
public UnityCamera Camera;
public UnityEngine.Vector3 Down{ get { return UnityBoidLeader.Down; }
}
public UnityEngine.Vector3 Forward{ get { return UnityBoidLeader.Forward; }
}
public UnityEngine.Vector3 Left{ get { return UnityBoidLeader.Left; }
}
public System.Single MaxDist;
public System.Single MaxVelocity;
public UnityEngine.Vector3 Position{ get { return UnityBoidLeader.Position; }
set{UnityBoidLeader.Position = value; }
}
public UnityEngine.Vector3 Right{ get { return UnityBoidLeader.Right; }
}
public UnityEngine.Quaternion Rotation{ get { return UnityBoidLeader.Rotation; }
set{UnityBoidLeader.Rotation = value; }
}
public UnityEngine.Vector3 Scale{ get { return UnityBoidLeader.Scale; }
}
public System.Boolean Start;
public UnityBoidLeader UnityBoidLeader;
public UnityEngine.Vector3 Up{ get { return UnityBoidLeader.Up; }
}
public System.Boolean enabled{ get { return UnityBoidLeader.enabled; }
set{UnityBoidLeader.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityBoidLeader.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityBoidLeader.hideFlags; }
set{UnityBoidLeader.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityBoidLeader.isActiveAndEnabled; }
}
public System.String name{ get { return UnityBoidLeader.name; }
set{UnityBoidLeader.name = value; }
}
public System.String tag{ get { return UnityBoidLeader.tag; }
set{UnityBoidLeader.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityBoidLeader.transform; }
}
public System.Boolean useGUILayout{ get { return UnityBoidLeader.useGUILayout; }
set{UnityBoidLeader.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.S)))
{
s0 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Down) * (dt))) * (MaxVelocity))));
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.W)))
{
s1 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Up) * (dt))) * (MaxVelocity))));
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.D)))
{
s2 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Right) * (dt))) * (MaxVelocity))));
s2 = -1;
return;
default: return;}}
int s3=-1;
public void Rule3(float dt, World world){
switch (s3)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.A)))
{
s3 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Left) * (dt))) * (MaxVelocity))));
s3 = -1;
return;
default: return;}}
int s4=-1;
public void Rule4(float dt, World world){
switch (s4)
{
case -1:
Camera.Position = ((Position) + (new UnityEngine.Vector3(0f,1f,-200f)));
s4 = -1;
return;
default: return;}}
}
public class Sphere{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 position;
public int ID;
public Sphere(UnityEngine.Vector3 position)
{JustEntered = false;
frame = World.frame;
UnitySphere = UnitySphere.Instantiate(position);
Speed = UnityEngine.Random.Range(15f,45f);
RotationZ = UnityEngine.Random.Range(-50f,50f);
}
public UnityEngine.Vector3 Position{ get { return UnitySphere.Position; }
set{UnitySphere.Position = value; }
}
public UnityEngine.Quaternion Rotation{ get { return UnitySphere.Rotation; }
set{UnitySphere.Rotation = value; }
}
public System.Single RotationZ;
public System.Single Speed;
public UnitySphere UnitySphere;
public System.Boolean enabled{ get { return UnitySphere.enabled; }
set{UnitySphere.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnitySphere.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnitySphere.hideFlags; }
set{UnitySphere.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnitySphere.isActiveAndEnabled; }
}
public System.String name{ get { return UnitySphere.name; }
set{UnitySphere.name = value; }
}
public System.String tag{ get { return UnitySphere.tag; }
set{UnitySphere.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnitySphere.transform; }
}
public System.Boolean useGUILayout{ get { return UnitySphere.useGUILayout; }
set{UnitySphere.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame; this.Rule0(dt, world);
this.Rule1(dt, world);
}
public void Rule0(float dt, World world)
{
Rotation = ((UnityEngine.Quaternion.Euler(0f,0f,0f)) * (UnityEngine.Quaternion.Euler(0f,0f,0f))) * (UnityEngine.Quaternion.Euler(0f,0f,RotationZ));
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
RotationZ = ((RotationZ) + (((Speed) * (dt))));
s1 = -1;
return;
default: return;}}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security.Cryptography.Asn1
{
public partial class AsnReader
{
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, returning the contents as an unprocessed <see cref="ReadOnlyMemory{T}"/>
/// over the original data.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="contents">
/// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data
/// corresponding to the contents of the character string.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if the value had a primitive encoding,
/// <c>false</c> and does not advance the reader if it had a constructed encoding.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/>
public bool TryReadPrimitiveCharacterStringBytes(
UniversalTagNumber encodingType,
out ReadOnlyMemory<byte> contents)
{
return TryReadPrimitiveCharacterStringBytes(
new Asn1Tag(encodingType),
encodingType,
out contents);
}
/// <summary>
/// Reads the next value as a character with a specified tag, returning the contents
/// as an unprocessed <see cref="ReadOnlyMemory{T}"/> over the original data.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="contents">
/// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data
/// corresponding to the value of the OCTET STRING.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if the OCTET STRING value had a primitive encoding,
/// <c>false</c> and does not advance the reader if it had a constructed encoding.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/>
public bool TryReadPrimitiveCharacterStringBytes(
Asn1Tag expectedTag,
UniversalTagNumber encodingType,
out ReadOnlyMemory<byte> contents)
{
CheckCharacterStringEncodingType(encodingType);
// T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings.
return TryReadPrimitiveOctetStringBytes(expectedTag, encodingType, out contents);
}
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, copying the value into a provided destination buffer.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/>
public bool TryCopyCharacterStringBytes(
UniversalTagNumber encodingType,
Span<byte> destination,
out int bytesWritten)
{
return TryCopyCharacterStringBytes(
new Asn1Tag(encodingType),
encodingType,
destination,
out bytesWritten);
}
/// <summary>
/// Reads the next value as character string with the specified tag and
/// encoding type, copying the value into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/>
public bool TryCopyCharacterStringBytes(
Asn1Tag expectedTag,
UniversalTagNumber encodingType,
Span<byte> destination,
out int bytesWritten)
{
CheckCharacterStringEncodingType(encodingType);
bool copied = TryCopyCharacterStringBytes(
expectedTag,
encodingType,
destination,
out int bytesRead,
out bytesWritten);
if (copied)
{
_data = _data.Slice(bytesRead);
}
return copied;
}
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, copying the value into a provided destination buffer.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/>
public bool TryCopyCharacterStringBytes(
UniversalTagNumber encodingType,
ArraySegment<byte> destination,
out int bytesWritten)
{
return TryCopyCharacterStringBytes(
new Asn1Tag(encodingType),
encodingType,
destination.AsSpan(),
out bytesWritten);
}
/// <summary>
/// Reads the next value as character string with the specified tag and
/// encoding type, copying the value into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <remarks>
/// This method does not determine if the string used only characters defined by the encoding.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/>
public bool TryCopyCharacterStringBytes(
Asn1Tag expectedTag,
UniversalTagNumber encodingType,
ArraySegment<byte> destination,
out int bytesWritten)
{
return TryCopyCharacterStringBytes(
expectedTag,
encodingType,
destination.AsSpan(),
out bytesWritten);
}
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, copying the decoded value into a provided destination buffer.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="charsWritten">
/// On success, receives the number of chars written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/>
public bool TryCopyCharacterString(
UniversalTagNumber encodingType,
Span<char> destination,
out int charsWritten)
{
return TryCopyCharacterString(
new Asn1Tag(encodingType),
encodingType,
destination,
out charsWritten);
}
/// <summary>
/// Reads the next value as character string with the specified tag and
/// encoding type, copying the decoded value into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="charsWritten">
/// On success, receives the number of chars written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/>
/// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/>
public bool TryCopyCharacterString(
Asn1Tag expectedTag,
UniversalTagNumber encodingType,
Span<char> destination,
out int charsWritten)
{
Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType);
return TryCopyCharacterString(expectedTag, encodingType, encoding, destination, out charsWritten);
}
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, copying the decoded value into a provided destination buffer.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="charsWritten">
/// On success, receives the number of chars written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="ReadCharacterString(UniversalTagNumber)"/>
/// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,ArraySegment{byte},out int)"/>
/// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,ArraySegment{char},out int)"/>
public bool TryCopyCharacterString(
UniversalTagNumber encodingType,
ArraySegment<char> destination,
out int charsWritten)
{
return TryCopyCharacterString(
new Asn1Tag(encodingType),
encodingType,
destination.AsSpan(),
out charsWritten);
}
/// <summary>
/// Reads the next value as character string with the specified tag and
/// encoding type, copying the decoded value into a provided destination buffer.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <param name="destination">The buffer in which to write.</param>
/// <param name="charsWritten">
/// On success, receives the number of chars written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient
/// length to receive the value, otherwise
/// <c>false</c> and the reader does not advance.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,ArraySegment{byte},out int)"/>
/// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/>
public bool TryCopyCharacterString(
Asn1Tag expectedTag,
UniversalTagNumber encodingType,
ArraySegment<char> destination,
out int charsWritten)
{
return TryCopyCharacterString(
expectedTag,
encodingType,
destination.AsSpan(),
out charsWritten);
}
/// <summary>
/// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified
/// encoding type, returning the decoded value as a <see cref="string"/>.
/// </summary>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <returns>
/// the decoded value as a <see cref="string"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/>
/// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/>
/// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/>
public string ReadCharacterString(UniversalTagNumber encodingType) =>
ReadCharacterString(new Asn1Tag(encodingType), encodingType);
/// <summary>
/// Reads the next value as character string with the specified tag and
/// encoding type, returning the decoded value as a <see cref="string"/>.
/// </summary>
/// <param name="expectedTag">The tag to check for before reading.</param>
/// <param name="encodingType">
/// A <see cref="UniversalTagNumber"/> corresponding to the value type to process.
/// </param>
/// <returns>
/// the decoded value as a <see cref="string"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="encodingType"/> is not a known character string type.
/// </exception>
/// <exception cref="CryptographicException">
/// the next value does not have the correct tag --OR--
/// the length encoding is not valid under the current encoding rules --OR--
/// the contents are not valid under the current encoding rules --OR--
/// the string did not successfully decode
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as
/// <paramref name="encodingType"/>.
/// </exception>
/// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/>
/// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/>
/// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/>
public string ReadCharacterString(Asn1Tag expectedTag, UniversalTagNumber encodingType)
{
Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType);
return ReadCharacterString(expectedTag, encodingType, encoding);
}
// T-REC-X.690-201508 sec 8.23
private bool TryCopyCharacterStringBytes(
Asn1Tag expectedTag,
UniversalTagNumber universalTagNumber,
Span<byte> destination,
out int bytesRead,
out int bytesWritten)
{
// T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings.
if (TryReadPrimitiveOctetStringBytes(
expectedTag,
out Asn1Tag actualTag,
out int? contentLength,
out int headerLength,
out ReadOnlyMemory<byte> contents,
universalTagNumber))
{
bytesWritten = contents.Length;
if (destination.Length < bytesWritten)
{
bytesWritten = 0;
bytesRead = 0;
return false;
}
contents.Span.CopyTo(destination);
bytesRead = headerLength + bytesWritten;
return true;
}
Debug.Assert(actualTag.IsConstructed);
bool copied = TryCopyConstructedOctetStringContents(
Slice(_data, headerLength, contentLength),
destination,
contentLength == null,
out int contentBytesRead,
out bytesWritten);
if (copied)
{
bytesRead = headerLength + contentBytesRead;
}
else
{
bytesRead = 0;
}
return copied;
}
private static unsafe bool TryCopyCharacterString(
ReadOnlySpan<byte> source,
Span<char> destination,
Text.Encoding encoding,
out int charsWritten)
{
if (source.Length == 0)
{
charsWritten = 0;
return true;
}
fixed (byte* bytePtr = &MemoryMarshal.GetReference(source))
fixed (char* charPtr = &MemoryMarshal.GetReference(destination))
{
try
{
int charCount = encoding.GetCharCount(bytePtr, source.Length);
if (charCount > destination.Length)
{
charsWritten = 0;
return false;
}
charsWritten = encoding.GetChars(bytePtr, source.Length, charPtr, destination.Length);
Debug.Assert(charCount == charsWritten);
}
catch (DecoderFallbackException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
return true;
}
}
private string ReadCharacterString(
Asn1Tag expectedTag,
UniversalTagNumber universalTagNumber,
Text.Encoding encoding)
{
byte[] rented = null;
// T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings.
ReadOnlySpan<byte> contents = GetOctetStringContents(
expectedTag,
universalTagNumber,
out int bytesRead,
ref rented);
try
{
string str;
if (contents.Length == 0)
{
str = string.Empty;
}
else
{
unsafe
{
fixed (byte* bytePtr = &MemoryMarshal.GetReference(contents))
{
try
{
str = encoding.GetString(bytePtr, contents.Length);
}
catch (DecoderFallbackException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
}
}
_data = _data.Slice(bytesRead);
return str;
}
finally
{
if (rented != null)
{
Array.Clear(rented, 0, contents.Length);
ArrayPool<byte>.Shared.Return(rented);
}
}
}
private bool TryCopyCharacterString(
Asn1Tag expectedTag,
UniversalTagNumber universalTagNumber,
Text.Encoding encoding,
Span<char> destination,
out int charsWritten)
{
byte[] rented = null;
// T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings.
ReadOnlySpan<byte> contents = GetOctetStringContents(
expectedTag,
universalTagNumber,
out int bytesRead,
ref rented);
try
{
bool copied = TryCopyCharacterString(
contents,
destination,
encoding,
out charsWritten);
if (copied)
{
_data = _data.Slice(bytesRead);
}
return copied;
}
finally
{
if (rented != null)
{
Array.Clear(rented, 0, contents.Length);
ArrayPool<byte>.Shared.Return(rented);
}
}
}
private static void CheckCharacterStringEncodingType(UniversalTagNumber encodingType)
{
// T-REC-X.680-201508 sec 41
switch (encodingType)
{
case UniversalTagNumber.BMPString:
case UniversalTagNumber.GeneralString:
case UniversalTagNumber.GraphicString:
case UniversalTagNumber.IA5String:
case UniversalTagNumber.ISO646String:
case UniversalTagNumber.NumericString:
case UniversalTagNumber.PrintableString:
case UniversalTagNumber.TeletexString:
// T61String is an alias for TeletexString (already listed)
case UniversalTagNumber.UniversalString:
case UniversalTagNumber.UTF8String:
case UniversalTagNumber.VideotexString:
// VisibleString is an alias for ISO646String (already listed)
return;
}
throw new ArgumentOutOfRangeException(nameof(encodingType));
}
}
}
| |
/*
* 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 OpenSim.Framework;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using log4net;
using Nini.Config;
using OpenMetaverse;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Services.InventoryService
{
/// <summary>
/// Basically a hack to give us a Inventory library while we don't have a inventory server
/// once the server is fully implemented then should read the data from that
/// </summary>
public class LibraryService : ServiceBase, ILibraryService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private InventoryFolderImpl m_LibraryRootFolder;
public InventoryFolderImpl LibraryRootFolder
{
get { return m_LibraryRootFolder; }
}
private UUID libOwner = new UUID("11111111-1111-0000-0000-000100bba000");
/// <summary>
/// Holds the root library folder and all its descendents. This is really only used during inventory
/// setup so that we don't have to repeatedly search the tree of library folders.
/// </summary>
protected Dictionary<UUID, InventoryFolderImpl> libraryFolders
= new Dictionary<UUID, InventoryFolderImpl>();
public LibraryService(IConfigSource config)
: base(config)
{
string pLibrariesLocation = Path.Combine("inventory", "Libraries.xml");
string pLibName = "OpenSim Library";
IConfig libConfig = config.Configs["LibraryService"];
if (libConfig != null)
{
pLibrariesLocation = libConfig.GetString("DefaultLibrary", pLibrariesLocation);
pLibName = libConfig.GetString("LibraryName", pLibName);
}
m_log.Debug("[LIBRARY]: Starting library service...");
m_LibraryRootFolder = new InventoryFolderImpl();
m_LibraryRootFolder.Owner = libOwner;
m_LibraryRootFolder.ID = new UUID("00000112-000f-0000-0000-000100bba000");
m_LibraryRootFolder.Name = pLibName;
m_LibraryRootFolder.ParentID = UUID.Zero;
m_LibraryRootFolder.Type = (short)8;
m_LibraryRootFolder.Version = (ushort)1;
libraryFolders.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder);
LoadLibraries(pLibrariesLocation);
}
public InventoryItemBase CreateItem(UUID inventoryID, UUID assetID, string name, string description,
int assetType, int invType, UUID parentFolderID)
{
InventoryItemBase item = new InventoryItemBase();
item.Owner = libOwner;
item.CreatorId = libOwner.ToString();
item.ID = inventoryID;
item.AssetID = assetID;
item.Description = description;
item.Name = name;
item.AssetType = assetType;
item.InvType = invType;
item.Folder = parentFolderID;
item.BasePermissions = 0x7FFFFFFF;
item.EveryOnePermissions = 0x7FFFFFFF;
item.CurrentPermissions = 0x7FFFFFFF;
item.NextPermissions = 0x7FFFFFFF;
return item;
}
/// <summary>
/// Use the asset set information at path to load assets
/// </summary>
/// <param name="path"></param>
/// <param name="assets"></param>
protected void LoadLibraries(string librariesControlPath)
{
m_log.InfoFormat("[LIBRARY INVENTORY]: Loading library control file {0}", librariesControlPath);
LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig);
}
/// <summary>
/// Read a library set from config
/// </summary>
/// <param name="config"></param>
protected void ReadLibraryFromConfig(IConfig config, string path)
{
string basePath = Path.GetDirectoryName(path);
string foldersPath
= Path.Combine(
basePath, config.GetString("foldersFile", String.Empty));
LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig);
string itemsPath
= Path.Combine(
basePath, config.GetString("itemsFile", String.Empty));
LoadFromFile(itemsPath, "Library items", ReadItemFromConfig);
}
/// <summary>
/// Read a library inventory folder from a loaded configuration
/// </summary>
/// <param name="source"></param>
private void ReadFolderFromConfig(IConfig config, string path)
{
InventoryFolderImpl folderInfo = new InventoryFolderImpl();
folderInfo.ID = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString()));
folderInfo.Name = config.GetString("name", "unknown");
folderInfo.ParentID = new UUID(config.GetString("parentFolderID", m_LibraryRootFolder.ID.ToString()));
folderInfo.Type = (short)config.GetInt("type", 8);
folderInfo.Owner = libOwner;
folderInfo.Version = 1;
if (libraryFolders.ContainsKey(folderInfo.ParentID))
{
InventoryFolderImpl parentFolder = libraryFolders[folderInfo.ParentID];
libraryFolders.Add(folderInfo.ID, folderInfo);
parentFolder.AddChildFolder(folderInfo);
// m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
}
else
{
m_log.WarnFormat(
"[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
folderInfo.Name, folderInfo.ID, folderInfo.ParentID);
}
}
/// <summary>
/// Read a library inventory item metadata from a loaded configuration
/// </summary>
/// <param name="source"></param>
private void ReadItemFromConfig(IConfig config, string path)
{
InventoryItemBase item = new InventoryItemBase();
item.Owner = libOwner;
item.CreatorId = libOwner.ToString();
item.ID = new UUID(config.GetString("inventoryID", m_LibraryRootFolder.ID.ToString()));
item.AssetID = new UUID(config.GetString("assetID", item.ID.ToString()));
item.Folder = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString()));
item.Name = config.GetString("name", String.Empty);
item.Description = config.GetString("description", item.Name);
item.InvType = config.GetInt("inventoryType", 0);
item.AssetType = config.GetInt("assetType", item.InvType);
item.CurrentPermissions = (uint)config.GetLong("currentPermissions", (uint)PermissionMask.All);
item.NextPermissions = (uint)config.GetLong("nextPermissions", (uint)PermissionMask.All);
item.EveryOnePermissions
= (uint)config.GetLong("everyonePermissions", (uint)PermissionMask.All - (uint)PermissionMask.Modify);
item.BasePermissions = (uint)config.GetLong("basePermissions", (uint)PermissionMask.All);
item.Flags = (uint)config.GetInt("flags", 0);
if (libraryFolders.ContainsKey(item.Folder))
{
InventoryFolderImpl parentFolder = libraryFolders[item.Folder];
try
{
parentFolder.Items.Add(item.ID, item);
}
catch (Exception)
{
m_log.WarnFormat("[LIBRARY INVENTORY] Item {1} [{0}] not added, duplicate item", item.ID, item.Name);
}
}
else
{
m_log.WarnFormat(
"[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
item.Name, item.ID, item.Folder);
}
}
private delegate void ConfigAction(IConfig config, string path);
/// <summary>
/// Load the given configuration at a path and perform an action on each Config contained within it
/// </summary>
/// <param name="path"></param>
/// <param name="fileDescription"></param>
/// <param name="action"></param>
private static void LoadFromFile(string path, string fileDescription, ConfigAction action)
{
if (File.Exists(path))
{
try
{
XmlConfigSource source = new XmlConfigSource(path);
for (int i = 0; i < source.Configs.Count; i++)
{
action(source.Configs[i], path);
}
}
catch (XmlException e)
{
m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e);
}
}
else
{
m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path);
}
}
/// <summary>
/// Looks like a simple getter, but is written like this for some consistency with the other Request
/// methods in the superclass
/// </summary>
/// <returns></returns>
public Dictionary<UUID, InventoryFolderImpl> GetAllFolders()
{
Dictionary<UUID, InventoryFolderImpl> fs = new Dictionary<UUID, InventoryFolderImpl>();
fs.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder);
List<InventoryFolderImpl> fis = TraverseFolder(m_LibraryRootFolder);
foreach (InventoryFolderImpl f in fis)
{
fs.Add(f.ID, f);
}
//return libraryFolders;
return fs;
}
private List<InventoryFolderImpl> TraverseFolder(InventoryFolderImpl node)
{
List<InventoryFolderImpl> folders = node.RequestListOfFolderImpls();
List<InventoryFolderImpl> subs = new List<InventoryFolderImpl>();
foreach (InventoryFolderImpl f in folders)
subs.AddRange(TraverseFolder(f));
folders.AddRange(subs);
return folders;
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* Wrap keys according to RFC 3217 - RC2 mechanism
*/
public class RC2WrapEngine
: IWrapper
{
/** Field engine */
private CbcBlockCipher engine;
/** Field param */
private ICipherParameters parameters;
/** Field paramPlusIV */
private ParametersWithIV paramPlusIV;
/** Field iv */
private byte[] iv;
/** Field forWrapping */
private bool forWrapping;
private SecureRandom sr;
/** Field IV2 */
private static readonly byte[] IV2 =
{
(byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
(byte) 0x2c, (byte) 0x79, (byte) 0xe8,
(byte) 0x21, (byte) 0x05
};
//
// checksum digest
//
IDigest sha1 = new Sha1Digest();
byte[] digest = new byte[20];
/**
* Method init
*
* @param forWrapping
* @param param
*/
public void Init(
bool forWrapping,
ICipherParameters parameters)
{
this.forWrapping = forWrapping;
this.engine = new CbcBlockCipher(new RC2Engine());
if (parameters is ParametersWithRandom)
{
ParametersWithRandom pWithR = (ParametersWithRandom)parameters;
sr = pWithR.Random;
parameters = pWithR.Parameters;
}
else
{
sr = new SecureRandom();
}
if (parameters is ParametersWithIV)
{
if (!forWrapping)
throw new ArgumentException("You should not supply an IV for unwrapping");
this.paramPlusIV = (ParametersWithIV)parameters;
this.iv = this.paramPlusIV.GetIV();
this.parameters = this.paramPlusIV.Parameters;
if (this.iv.Length != 8)
throw new ArgumentException("IV is not 8 octets");
}
else
{
this.parameters = parameters;
if (this.forWrapping)
{
// Hm, we have no IV but we want to wrap ?!?
// well, then we have to create our own IV.
this.iv = new byte[8];
sr.NextBytes(iv);
this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
}
}
}
/**
* Method GetAlgorithmName
*
* @return
*/
public string AlgorithmName
{
get { return "RC2"; }
}
/**
* Method wrap
*
* @param in
* @param inOff
* @param inLen
* @return
*/
public byte[] Wrap(
byte[] input,
int inOff,
int length)
{
if (!forWrapping)
{
throw new InvalidOperationException("Not initialized for wrapping");
}
int len = length + 1;
if ((len % 8) != 0)
{
len += 8 - (len % 8);
}
byte [] keyToBeWrapped = new byte[len];
keyToBeWrapped[0] = (byte)length;
Array.Copy(input, inOff, keyToBeWrapped, 1, length);
byte[] pad = new byte[keyToBeWrapped.Length - length - 1];
if (pad.Length > 0)
{
sr.NextBytes(pad);
Array.Copy(pad, 0, keyToBeWrapped, length + 1, pad.Length);
}
// Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped);
// Let WKCKS = WK || CKS where || is concatenation.
byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length];
Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length);
Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length);
// Encrypt WKCKS in CBC mode using KEK as the key and IV as the
// initialization vector. Call the results TEMP1.
byte [] TEMP1 = new byte[WKCKS.Length];
Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length);
int noOfBlocks = WKCKS.Length / engine.GetBlockSize();
int extraBytes = WKCKS.Length % engine.GetBlockSize();
if (extraBytes != 0)
{
throw new InvalidOperationException("Not multiple of block length");
}
engine.Init(true, paramPlusIV);
for (int i = 0; i < noOfBlocks; i++)
{
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
}
// Left TEMP2 = IV || TEMP1.
byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length];
Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length);
Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length);
// Reverse the order of the octets in TEMP2 and call the result TEMP3.
byte[] TEMP3 = new byte[TEMP2.Length];
for (int i = 0; i < TEMP2.Length; i++)
{
TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)];
}
// Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
// of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
// result. It is 40 octets long if a 168 bit key is being wrapped.
ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
this.engine.Init(true, param2);
for (int i = 0; i < noOfBlocks + 1; i++)
{
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
return TEMP3;
}
/**
* Method unwrap
*
* @param in
* @param inOff
* @param inLen
* @return
* @throws InvalidCipherTextException
*/
public byte[] Unwrap(
byte[] input,
int inOff,
int length)
{
if (forWrapping)
{
throw new InvalidOperationException("Not set for unwrapping");
}
if (input == null)
{
throw new InvalidCipherTextException("Null pointer as ciphertext");
}
if (length % engine.GetBlockSize() != 0)
{
throw new InvalidCipherTextException("Ciphertext not multiple of "
+ engine.GetBlockSize());
}
/*
// Check if the length of the cipher text is reasonable given the key
// type. It must be 40 bytes for a 168 bit key and either 32, 40, or
// 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
// or inconsistent with the algorithm for which the key is intended,
// return error.
//
// we do not accept 168 bit keys. it has to be 192 bit.
int lengthA = (estimatedKeyLengthInBit / 8) + 16;
int lengthB = estimatedKeyLengthInBit % 8;
if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) {
throw new XMLSecurityException("empty");
}
*/
// Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
// and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
this.engine.Init(false, param2);
byte [] TEMP3 = new byte[length];
Array.Copy(input, inOff, TEMP3, 0, length);
for (int i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++)
{
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
// Reverse the order of the octets in TEMP3 and call the result TEMP2.
byte[] TEMP2 = new byte[TEMP3.Length];
for (int i = 0; i < TEMP3.Length; i++)
{
TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)];
}
// Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
this.iv = new byte[8];
byte[] TEMP1 = new byte[TEMP2.Length - 8];
Array.Copy(TEMP2, 0, this.iv, 0, 8);
Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8);
// Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
// found in the previous step. Call the result WKCKS.
this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
this.engine.Init(false, this.paramPlusIV);
byte[] LCEKPADICV = new byte[TEMP1.Length];
Array.Copy(TEMP1, 0, LCEKPADICV, 0, TEMP1.Length);
for (int i = 0; i < (LCEKPADICV.Length / engine.GetBlockSize()); i++)
{
int currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(LCEKPADICV, currentBytePos, LCEKPADICV, currentBytePos);
}
// Decompose LCEKPADICV. CKS is the last 8 octets and WK, the wrapped key, are
// those octets before the CKS.
byte[] result = new byte[LCEKPADICV.Length - 8];
byte[] CKStoBeVerified = new byte[8];
Array.Copy(LCEKPADICV, 0, result, 0, LCEKPADICV.Length - 8);
Array.Copy(LCEKPADICV, LCEKPADICV.Length - 8, CKStoBeVerified, 0, 8);
// Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
// with the CKS extracted in the above step. If they are not equal, return error.
if (!CheckCmsKeyChecksum(result, CKStoBeVerified))
{
throw new InvalidCipherTextException(
"Checksum inside ciphertext is corrupted");
}
if ((result.Length - ((result[0] & 0xff) + 1)) > 7)
{
throw new InvalidCipherTextException(
"too many pad bytes (" + (result.Length - ((result[0] & 0xff) + 1)) + ")");
}
// CEK is the wrapped key, now extracted for use in data decryption.
byte[] CEK = new byte[result[0]];
Array.Copy(result, 1, CEK, 0, CEK.Length);
return CEK;
}
/**
* Some key wrap algorithms make use of the Key Checksum defined
* in CMS [CMS-Algorithms]. This is used to provide an integrity
* check value for the key being wrapped. The algorithm is
*
* - Compute the 20 octet SHA-1 hash on the key being wrapped.
* - Use the first 8 octets of this hash as the checksum value.
*
* @param key
* @return
* @throws Exception
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private byte[] CalculateCmsKeyChecksum(
byte[] key)
{
sha1.BlockUpdate(key, 0, key.Length);
sha1.DoFinal(digest, 0);
byte[] result = new byte[8];
Array.Copy(digest, 0, result, 0, 8);
return result;
}
/**
* @param key
* @param checksum
* @return
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private bool CheckCmsKeyChecksum(
byte[] key,
byte[] checksum)
{
return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Jasily.Core;
using Jasily.Extensions.System.Linq;
using Jasily.Extensions.System.Text;
using JetBrains.Annotations;
namespace Jasily.Extensions.System
{
/// <summary>
/// useful extension methods for string.
/// </summary>
public static class StringExtensions
{
#region encoding & decoding
/// <summary>
/// use utf-8 encoding convert string to byte[].
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
[PublicAPI]
[NotNull]
public static byte[] GetBytes([NotNull] this string s)
{
if (s == null) throw new ArgumentNullException(nameof(s));
return Encoding.UTF8.GetBytes(s);
}
/// <summary>
/// use <paramref name="encoding"/> encoding convert string to byte[].
/// </summary>
/// <param name="s"></param>
/// <param name="encoding"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
[PublicAPI]
[NotNull]
public static byte[] GetBytes([NotNull] this string s, [NotNull] Encoding encoding)
{
if (s == null) throw new ArgumentNullException(nameof(s));
if (encoding == null) throw new ArgumentNullException(nameof(encoding));
return encoding.GetBytes(s);
}
#endregion
public static string Repeat([CanBeNull] this string str, int count)
{
// make sure raise Exception whatever str is null or not.
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
return str == null ? null : (count == 0 ? string.Empty : string.Concat(Enumerable.Repeat(str, count)));
}
#region between
[NotNull]
public static string Between([NotNull] this string str, int leftIndex, int rightIndex)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (rightIndex == leftIndex) return string.Empty;
if (rightIndex < leftIndex) throw new ArgumentException();
return str.Substring(leftIndex, rightIndex - leftIndex);
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
/// <exception cref="T:System.ArgumentNullException"></exception>
[NotNull]
public static string Between([NotNull] this string str, char left, char right) => Between(str, 0, left, right);
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="startIndex"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
/// <exception cref="T:System.ArgumentNullException"></exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"></exception>
[NotNull]
public static string Between([NotNull] this string str, int startIndex, char left, char right)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var leftIndex = str.IndexOf(left, startIndex);
if (leftIndex < 0) return string.Empty;
startIndex = leftIndex + 1;
if (startIndex == str.Length) return string.Empty;
var rightIndex = str.IndexOf(right, startIndex);
if (rightIndex < 0) return string.Empty;
return str.Substring(startIndex, rightIndex - startIndex);
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
/// <exception cref="T:System.ArgumentNullException"></exception>
/// <exception cref="T:System.ArgumentException"></exception>
[NotNull]
public static string Between([NotNull] this string str, [NotNull] string left, [NotNull] string right,
StringComparison comparisonType = StringComparison.Ordinal) => Between(str, 0, left, right, comparisonType);
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="startIndex"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
/// <exception cref="T:System.ArgumentNullException"></exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"></exception>
/// <exception cref="T:System.ArgumentException"></exception>
[NotNull]
public static string Between([NotNull] this string str, int startIndex, [NotNull] string left, [NotNull] string right,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var leftIndex = str.IndexOf(left, startIndex, comparisonType);
if (leftIndex < 0) return string.Empty;
startIndex = leftIndex + left.Length;
if (startIndex == str.Length) return string.Empty;
var rightIndex = str.IndexOf(right, startIndex, comparisonType);
if (rightIndex < 0) return string.Empty;
return str.Substring(startIndex, rightIndex - startIndex);
}
#endregion
#region ensure
/// <summary>
/// ensure length of string large or equals the <paramref name="length"/>.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
/// <param name="paddingChar"></param>
/// <param name="position"></param>
/// <returns></returns>
[PublicAPI]
[NotNull]
public static string EnsureLength([NotNull] this string str, int length, char paddingChar, Position position)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (length < 0) throw new ArgumentOutOfRangeException();
if (str.Length >= length) return str;
var padding = new string(paddingChar, length - str.Length);
switch (position)
{
case Position.Begin:
return padding + str;
case Position.End:
return str + padding;
default:
throw new ArgumentOutOfRangeException(nameof(position), position, null);
}
}
/// <summary>
/// ensure string startswith <paramref name="value"/>. if NOT, insert it.
/// </summary>
/// <param name="str"></param>
/// <param name="value"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
[PublicAPI]
[NotNull]
public static string EnsureStart([NotNull] this string str, string value, StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.StartsWith(value, comparisonType) ? str : value + str;
}
/// <summary>
/// ensure string endswith <paramref name="value"/>. if NOT, append it.
/// </summary>
/// <param name="str"></param>
/// <param name="value"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
[PublicAPI]
[NotNull]
public static string EnsureEnd([NotNull] this string str, string value, StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.EndsWith(value, comparisonType) ? str : str + value;
}
#endregion
#region substring
[NotNull]
public static string Take([NotNull] this string str, int count)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (count > str.Length) return str;
return str.Substring(0, count);
}
#endregion
#region replace
public static string Replace([NotNull] this string str, [NotNull] string oldValue, [NotNull] string newValue,
StringComparison comparisonType, int maxCount = int.MaxValue)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (oldValue == null) throw new ArgumentNullException(nameof(oldValue));
if (oldValue.Length == 0) throw new ArgumentException("Argument is empty", nameof(oldValue));
if (newValue == null) throw new ArgumentNullException(nameof(newValue));
if (maxCount < 1) throw new ArgumentOutOfRangeException(nameof(maxCount));
if (str.Length < oldValue.Length) return str;
if (comparisonType == StringComparison.Ordinal) return str.Replace(oldValue, newValue);
var sb = new StringBuilder();
var ptr = 0;
for (int index, count = 0; count < maxCount && (index = str.IndexOf(oldValue, ptr, comparisonType)) > 0; count++)
{
sb.Append(str, ptr, index - ptr);
sb.Append(newValue);
ptr = index + oldValue.Length;
count++;
}
return sb.Append(str, ptr).ToString();
}
public static string ReplaceFirst([NotNull] this string str, [NotNull] string oldValue,
[NotNull] string newValue, StringComparison comparisonType)
=> Replace(str, oldValue, newValue, comparisonType, 1);
public static string ReplaceStart([NotNull] this string str, [NotNull] string oldValue,
[NotNull] string newValue,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (oldValue == null) throw new ArgumentNullException(nameof(oldValue));
if (oldValue.Length == 0) throw new ArgumentException("Argument is empty", nameof(oldValue));
if (newValue == null) throw new ArgumentNullException(nameof(newValue));
if (str.Length < oldValue.Length) return str;
var count = 0;
for (; str.StartsWith(oldValue.Length * count, oldValue, comparisonType); count++)
{
}
switch (count)
{
case 0:
return str;
case 1:
return newValue + str.Substring(oldValue.Length);
default:
return string.Concat(Enumerable.Repeat(newValue, count)
.Append(str.Substring(oldValue.Length * count)));
}
}
/// <summary>
/// replace char by index.
/// </summary>
/// <param name="str"></param>
/// <param name="value"></param>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static string ReplaceChar([NotNull] this string str, char value, int index)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (index < 0 || index > str.Length) throw new ArgumentOutOfRangeException(nameof(index));
var array = str.ToCharArray();
array[index] = value;
return new string(array);
}
#endregion
#region start or end
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="startIndex"></param>
/// <param name="value"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static bool StartsWith([NotNull] this string str, int startIndex, [NotNull] string value,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length == 0) return true;
return string.Compare(str, startIndex, value, 0, value.Length, comparisonType) == 0;
}
#endregion
#region contains
public static bool Contains([NotNull] this string str, char value)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value) > -1;
}
public static bool Contains([NotNull] this string str, char value, int startIndex)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value, startIndex) > -1;
}
public static bool Contains([NotNull] this string str, char value, int startIndex, int count)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value, startIndex, count) > -1;
}
public static bool Contains([NotNull] this string str, [NotNull] string value,
StringComparison comparisonType)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value, comparisonType) > -1;
}
public static bool Contains([NotNull] this string str, [NotNull] string value, int startIndex,
StringComparison comparisonType)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value, startIndex, comparisonType) > -1;
}
public static bool Contains([NotNull] this string str, [NotNull] string value, int startIndex, int count,
StringComparison comparisonType)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.IndexOf(value, startIndex, count, comparisonType) > -1;
}
#endregion
#region split & join
public static string[] Split([NotNull] this string str, [NotNull] string separator,
StringSplitOptions options = StringSplitOptions.None)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (separator == null) throw new ArgumentNullException(nameof(separator));
return str.Split(new[] { separator }, options);
}
public static string[] Split([NotNull] this string str, [NotNull] string separator, int count,
StringSplitOptions options = StringSplitOptions.None)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (separator == null) throw new ArgumentNullException(nameof(separator));
return str.Split(new[] { separator }, count, options);
}
/// <summary>
/// if set includeSeparator = true, return [ block, separator, block, separator, ... ].
/// </summary>
/// <param name="str"></param>
/// <param name="separator"></param>
/// <param name="comparisonType"></param>
/// <param name="options"></param>
/// <param name="includeSeparator"></param>
/// <returns></returns>
public static string[] Split([NotNull] this string str, [NotNull] string separator, StringComparison comparisonType,
StringSplitOptions options = StringSplitOptions.None, bool includeSeparator = false)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (separator == null) throw new ArgumentNullException(nameof(separator));
if (separator.Length == 0) throw new ArgumentException(nameof(separator));
var rets = new List<string>();
var ptr = 0;
while (true)
{
var index = str.IndexOf(separator, ptr, comparisonType);
if (index < 0)
{
rets.Add(str.Substring(ptr));
break;
}
rets.Add(str.Substring(ptr, index - ptr));
if (includeSeparator)
{
rets.Add(str.Substring(index, separator.Length));
}
ptr = index + separator.Length;
}
return options == StringSplitOptions.None ? rets.ToArray() : rets.Where(z => !string.IsNullOrEmpty(z)).ToArray();
}
public static string[] SplitWhen([NotNull] this string text, [NotNull] Func<char, bool> separator,
StringSplitOptions options = StringSplitOptions.None)
{
if (text == null) throw new ArgumentNullException(nameof(text));
if (separator == null) throw new ArgumentNullException(nameof(separator));
return SplitWhen(text, (c, i) => separator(c), options);
}
public static string[] SplitWhen([NotNull] this string text, [NotNull] Func<char, int, bool> separator,
StringSplitOptions options = StringSplitOptions.None)
{
if (text == null) throw new ArgumentNullException(nameof(text));
if (separator == null) throw new ArgumentNullException(nameof(separator));
var rets = new List<string>();
var start = 0;
var ptr = 0;
for (; ptr < text.Length; ptr++)
{
if (separator(text[ptr], ptr))
{
if (ptr == start)
{
rets.Add(string.Empty);
}
else
{
rets.Add(text.Substring(start, ptr - start));
start = ptr;
}
}
}
if (ptr > start + 1)
{
rets.Add(text.Substring(start, ptr - start));
}
return options == StringSplitOptions.None ? rets.ToArray() : rets.Where(z => z.Length > 0).ToArray();
}
/// <summary>
/// use '\r\n' or '\n' to split text.
/// </summary>
/// <param name="str"></param>
/// <param name="options"></param>
/// <returns></returns>
public static string[] SplitLines([NotNull] this string str, StringSplitOptions options = StringSplitOptions.None)
{
if (str == null) throw new ArgumentNullException(nameof(str));
return str.Split(new[] { "\r\n", "\n" }, options);
}
/// <summary>
/// return first line from text
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FirstLine([NotNull] this string str)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var index = str.IndexOf('\n');
return index == -1
? str
: str.Substring(0, index > 0 && str[index - 1] == '\r' ? index - 1 : index);
}
/// <summary>
/// use Environment.NewLine to join texts.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static string JoinLines([NotNull] this IEnumerable<string> values)
=> string.Join(Environment.NewLine, values);
#endregion
#region trim
public static string TrimStart([NotNull] this string str, params string[] trimStrings)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (trimStrings == null || trimStrings.Length == 0)
return str;
if (trimStrings.Any(z => z.IsNullOrEmpty()))
throw new ArgumentException();
var startIndex = 0;
for (string start; (start = trimStrings.FirstOrDefault(z => str.StartsWith(startIndex, z))) != null;)
{
startIndex += start.Length;
}
return str.Substring(startIndex);
}
#endregion
#region common part
public static string CommonStart(this string[] source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source.Length == 0) return string.Empty;
if (source.Length == 1) return source[0];
var exp = source[0];
var end = source.Min(z => z.Length); // length
foreach (var item in source.Skip(1))
{
for (var i = 0; i < end; i++)
{
if (item[i] != exp[i])
{
end = i;
break;
}
}
}
return exp.Substring(0, end);
}
public static string CommonEnd(this string[] source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source.Length == 0) return string.Empty;
if (source.Length == 1) return source[0];
var exp = source[0];
var len = source.Select(z => z.Length).Min();
foreach (var item in source.Skip(1))
{
for (var i = 0; i < len; i++)
{
if (exp[exp.Length - i - 1] != item[item.Length - i - 1])
{
len = i;
break;
}
}
}
return exp.Substring(exp.Length - len);
}
#endregion
#region after/before first and last
public static string AfterFirst([NotNull] this string str, [NotNull] string spliter,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (string.IsNullOrEmpty(spliter)) throw new ArgumentException(nameof(spliter));
var index = str.IndexOf(spliter, comparisonType);
return index < 1 ? str : str.Substring(index + 1);
}
public static string AfterFirst([NotNull] this string str, char spliter)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var index = str.IndexOf(spliter);
return index < 1 ? str : str.Substring(index + 1);
}
public static string AfterFirst([NotNull] this string str, params char[] spliter)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var index = str.LastIndexOfAny(spliter);
return index < 1 ? str : str.Substring(index + 1);
}
public static string AfterLast([NotNull] this string str, [NotNull] string spliter,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (string.IsNullOrEmpty(spliter)) throw new ArgumentException(nameof(spliter));
var index = str.LastIndexOf(spliter, comparisonType);
return index < 1 ? str : str.Substring(index + 1);
}
public static string AfterLast([NotNull] this string str, char spliter)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var index = str.LastIndexOf(spliter);
return index < 1 ? str : str.Substring(index + 1);
}
public static string AfterLast([NotNull] this string str, params char[] spliter)
{
if (str == null) throw new ArgumentNullException(nameof(str));
var index = str.LastIndexOfAny(spliter);
return index < 1 ? str : str.Substring(index + 1);
}
public static string BeforeFirst([NotNull] this string str, [NotNull] string spliter,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (string.IsNullOrEmpty(spliter)) throw new ArgumentException(nameof(spliter));
var index = str.IndexOf(spliter, comparisonType);
if (index < 0) return str;
return index == 0 ? string.Empty : str.Substring(0, index);
}
public static string BeforeFirst([NotNull] this string str, [NotNull] string[] spliters,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (spliters == null) throw new ArgumentNullException(nameof(spliters));
if (spliters.Length == 0 || spliters.Any(string.IsNullOrEmpty)) throw new ArgumentException(nameof(spliters));
var indexs = spliters.Select(z => str.IndexOf(z, comparisonType)).Where(z => z >= 0).ToArray();
if (indexs.Length == 0) return str;
var index = indexs.Min();
return index == 0 ? string.Empty : str.Substring(0, index);
}
public static string BeforeLast([NotNull] this string str, [NotNull] string spliter,
StringComparison comparisonType = StringComparison.Ordinal)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (spliter == null) throw new ArgumentNullException(nameof(spliter));
var index = str.LastIndexOf(spliter, comparisonType);
return index <= 0 ? string.Empty : str.Substring(0, index);
}
#endregion
#region static method to extension method
/// <summary>
/// return String.IsNullOrEmpty(text)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNullOrEmpty([CanBeNull] this string value) => string.IsNullOrEmpty(value);
/// <summary>
/// return String.IsNullOrWhiteSpace(text)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNullOrWhiteSpace([CanBeNull] this string value) => string.IsNullOrWhiteSpace(value);
/// <summary>
/// return String.Concat(texts)
/// </summary>
/// <param name="texts"></param>
/// <param name="spliter"></param>
/// <returns></returns>
public static string ConcatAsString([NotNull] this IEnumerable<string> texts)
=> string.Concat(texts);
/// <summary>
/// return String.Join(spliter, texts)
/// </summary>
/// <param name="texts"></param>
/// <param name="spliter"></param>
/// <returns></returns>
public static string JoinAsString([NotNull] this IEnumerable<string> texts, string spliter)
=> string.Join(spliter, texts);
#endregion
#region null <=> empty
[NotNull]
public static string EmptyIfNull([CanBeNull] this string str) => str ?? string.Empty;
[CanBeNull]
public static string NullIfEmpty<T>([CanBeNull] this string str) => string.IsNullOrEmpty(str) ? null : str;
#endregion
/// <summary>
/// since unicode code point can large then char.MaxValue, we need int to save it.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int[] ToUnicodeChars([NotNull] this string str)
{
var indexs = StringInfo.ParseCombiningCharacters(str);
if (indexs.Length == 0) return Empty<int>.Array;
var chars = new int[indexs.Length];
for (var i = 0; i < indexs.Length; i++)
{
chars[i] = char.ConvertToUtf32(str, indexs[i]);
}
return chars;
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Cassandra.IntegrationTests.Core
{
[TestFixture, Category("long")]
public class StressTests : TestGlobals
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;
//For different threads
Trace.AutoFlush = true;
}
/// <summary>
/// Insert and select records in parallel them using Session.Execute sync methods.
/// </summary>
[Test]
public void Parallel_Insert_And_Select_Sync()
{
var originalTraceLevel = Diagnostics.CassandraTraceSwitch.Level;
ITestCluster testCluster = TestClusterManager.GetTestCluster(3);
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Warning;
testCluster.Builder = Cluster.Builder().WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance);
testCluster.InitClient();
ISession session = testCluster.Session;
string uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10);
session.Execute(@"CREATE KEYSPACE " + uniqueKsName +
" WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};");
TestUtils.WaitForSchemaAgreement(testCluster.Cluster);
session.ChangeKeyspace(uniqueKsName);
string tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
session.Execute(String.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName));
TestUtils.WaitForSchemaAgreement(testCluster.Cluster);
var insertQuery = String.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
var insertQueryPrepared = session.Prepare(insertQuery);
var selectQuery = String.Format("SELECT * FROM {0} LIMIT 10000", tableName);
const int rowsPerId = 1000;
object insertQueryStatement = new SimpleStatement(insertQuery);
if (CassandraVersion.Major < 2)
{
//Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2
insertQueryStatement = session.Prepare(insertQuery);
}
var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId);
var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);
//Execute insert sync to have some records
actionInsert();
//Execute select sync to assert that everything is going OK
actionSelect();
var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
//Add 10 actions to execute
actions.AddRange(new[] {actionInsert, actionSelect, actionInsertPrepared});
actions.AddRange(new[] {actionSelect, actionInsert, actionInsertPrepared, actionInsert});
actions.AddRange(new[] {actionInsertPrepared, actionInsertPrepared, actionSelect});
}
//Execute in parallel the 100 actions
var parallelOptions = new ParallelOptions();
parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
parallelOptions.MaxDegreeOfParallelism = 300;
Parallel.Invoke(parallelOptions, actions.ToArray());
Parallel.Invoke(actions.ToArray());
Diagnostics.CassandraTraceSwitch.Level = originalTraceLevel;
}
/// <summary>
/// In parallel it inserts some records and selects them using Session.Execute sync methods.
/// </summary>
[Test]
[TestCassandraVersion(2, 0), Category(TestCategories.CcmOnly)]
public void Parallel_Insert_And_Select_Sync_With_Nodes_Failing()
{
var originalTraceLevel = Diagnostics.CassandraTraceSwitch.Level;
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Warning;
Cluster.Builder()
.WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance);
CcmCluster ccmCluster = (CcmCluster)TestClusterManager.GetTestCluster(3);
var session = ccmCluster.Session;
string uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10);
session.Execute(@"CREATE KEYSPACE " + uniqueKsName +
" WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};");
TestUtils.WaitForSchemaAgreement(ccmCluster.Cluster);
session.ChangeKeyspace(uniqueKsName);
string tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
session.Execute(String.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName));
TestUtils.WaitForSchemaAgreement(ccmCluster.Cluster);
var insertQuery = String.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
var insertQueryPrepared = session.Prepare(insertQuery);
var selectQuery = String.Format("SELECT * FROM {0} LIMIT 10000", tableName);
const int rowsPerId = 100;
object insertQueryStatement = new SimpleStatement(insertQuery);
if (CassandraVersion.Major < 2)
{
//Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2
insertQueryStatement = session.Prepare(insertQuery);
}
var actionInsert = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId);
var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
var actionSelect = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);
//Execute insert sync to have some records
actionInsert();
//Execute select sync to assert that everything is going OK
actionSelect();
var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
//Add 10 actions to execute
actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared });
actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert });
actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect });
}
actions.Insert(8, () =>
{
Thread.Sleep(300);
ccmCluster.CcmBridge.StopForce(2);
});
//Execute in parallel more than 100 actions
var parallelOptions = new ParallelOptions();
parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
parallelOptions.MaxDegreeOfParallelism = 1000;
Parallel.Invoke(parallelOptions, actions.ToArray());
Diagnostics.CassandraTraceSwitch.Level = originalTraceLevel;
}
/// <summary>
/// Creates thousands of Session instances and checks memory consumption before and after Dispose and dereferencing
/// </summary>
[Test]
public void Memory_Consumption_After_Cluster_Dispose()
{
var testCluster = TestClusterManager.GetTestCluster(2, DefaultMaxClusterCreateRetries, true, false);
//Only warning as tracing through console slows it down.
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Warning;
var start = GC.GetTotalMemory(false);
long diff = 0;
Trace.TraceInformation("--Initial memory: {0}", start / 1024);
Action multipleConnect = () =>
{
var cluster = Cluster.Builder().AddContactPoint(testCluster.InitialContactPoint).Build();
for (var i = 0; i < 200; i++)
{
var session = cluster.Connect();
TestHelper.ParallelInvoke(() => session.Execute("select * from system.local"), 20);
}
Trace.TraceInformation("--Before disposing: {0}", GC.GetTotalMemory(false) / 1024);
cluster.Dispose();
Trace.TraceInformation("--After disposing: {0}", GC.GetTotalMemory(false) / 1024);
};
multipleConnect();
var handle = new AutoResetEvent(false);
//Collect all generations
GC.Collect();
//Wait 5 seconds for all the connections resources to be freed
var timer = new Timer(s =>
{
GC.Collect();
handle.Set();
diff = GC.GetTotalMemory(false) - start;
Trace.TraceInformation("--End, diff memory: {0}", diff / 1024);
});
timer.Change(5000, Timeout.Infinite);
handle.WaitOne();
//the end memory usage can not be greater than double the start memory
//If there is a memory leak, it should be an order of magnitude greater...
Assert.Less(diff, start / 2);
}
public Action GetInsertAction(ISession session, object bindableStatement, ConsistencyLevel consistency, int rowsPerId)
{
Action action = () =>
{
Trace.TraceInformation("Starting inserting from thread {0}", Thread.CurrentThread.ManagedThreadId);
var id = Guid.NewGuid();
for (var i = 0; i < rowsPerId; i++)
{
var paramsArray = new object[] { id, DateTime.Now, DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) };
IStatement statement;
if (bindableStatement is SimpleStatement)
{
statement = new SimpleStatement(((SimpleStatement)bindableStatement).QueryString, paramsArray).SetConsistencyLevel(consistency);
}
else if (bindableStatement is PreparedStatement)
{
statement = ((PreparedStatement)bindableStatement).Bind(paramsArray).SetConsistencyLevel(consistency);
}
else
{
throw new Exception("Can not bind a statement of type " + bindableStatement.GetType().FullName);
}
session.Execute(statement);
}
Trace.TraceInformation("Finished inserting from thread {0}", Thread.CurrentThread.ManagedThreadId);
};
return action;
}
public Action GetSelectAction(ISession session, string query, ConsistencyLevel consistency, int executeLength)
{
Action action = () =>
{
for (var i = 0; i < executeLength; i++)
{
session.Execute(new SimpleStatement(query).SetPageSize(500).SetConsistencyLevel(consistency).SetRetryPolicy(DowngradingConsistencyRetryPolicy.Instance));
//Count will iterate through the result set and it will likely to page results
//Assert.True(rs.Count() > 0);
}
};
return action;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function TruckToy::create( %this )
{
TruckToy.ObstacleFriction = 1.5;
TruckToy.CameraWidth = 20;
TruckToy.CameraHeight = 15;
TruckToy.WorldWidth = TruckToy.CameraWidth * 10;
TruckToy.WorldLeft = TruckToy.WorldWidth * -0.5;
TruckToy.WorldRight = TruckToy.WorldWidth * 0.5;
TruckToy.FloorLevel = -4.5;
TruckToy.BackdropDomain = 31;
TruckToy.BackgroundDomain = 25;
TruckToy.TruckDomain = 20;
TruckToy.GroundDomain = 18;
TruckToy.ObstacleDomain = 15;
TruckToy.ProjectileDomain = 16;
TruckToy.ForegroundDomain = 10;
TruckToy.WheelSpeed = 400;
TruckToy.WheelFriction = 1;
TruckToy.FrontWheelDensity = 6;
TruckToy.RearWheelDensity = 3;
TruckToy.FrontWheelDrive = true;
TruckToy.RearWheelDrive = true;
TruckToy.ProjectileRate = 3000;
TruckToy.ExplosionScale = 1;
TruckToy.RotateCamera = true;
// Add the custom controls.
addNumericOption( "Wheel Speed", 100, 1000, 50, "setWheelSpeed", TruckToy.WheelSpeed, false, "Sets the rotational speed of the wheel when it is put into drive." );
addNumericOption( "Wheel Friction", 0, 10, 1, "setWheelFriction", TruckToy.WheelFriction, true, "Sets the friction for the surface of each wheel." );
addNumericOption( "Front Wheel Density", 1, 20, 1, "setFrontWheelDensity", TruckToy.FrontWheelDensity, true, "Sets the density of the front wheel." );
addNumericOption( "Rear Wheel Density", 1, 20, 1, "setFrontWheelDensity", TruckToy.RearWheelDensity, true, "Sets the density of the rear wheel." );
addNumericOption( "Projectile Rate (ms)", 100, 60000, 100, "setProjectileRate", TruckToy.ProjectileRate, false, "Sets the time interval in-between projectiles appearing." );
addNumericOption( "Explosion Scale", 1, 11, 1, "setExplosionScale", TruckToy.ExplosionScale, false, "Sets the size scale of the explosions caused by a projectile landing." );
addFlagOption("Front Wheel Drive", "setFrontWheelDrive", TruckToy.FrontWheelDrive, false, "Whether the motor on the front wheel is active or not." );
addFlagOption("Rear Wheel Drive", "setRearWheelDrive", TruckToy.RearWheelDrive, false, "Whether the motor on the rear wheel is active or not." );
addFlagOption("Rotate Camera", "setRotateCamera", TruckToy.RotateCamera, true, "Whether the rotate the camera that is mounted to the truck or not." );
// Reset the toy.
%this.reset();
}
//-----------------------------------------------------------------------------
function TruckToy::destroy( %this )
{
// Deactivate the package.
deactivatePackage( TruckToyPackage );
}
//-----------------------------------------------------------------------------
function TruckToy::reset( %this )
{
// Clear the scene.
SandboxScene.clear();
// Set a typical Earth gravity.
SandboxScene.setGravity( 0, -9.8 );
// Camera Configuration
SandboxWindow.setCameraPosition( TruckToy.WorldLeft + (TruckToy.CameraWidth/2) - 10, 0 );
SandboxWindow.setCameraAngle( 0 );
SandboxWindow.setCameraSize( TruckToy.CameraWidth, TruckToy.CameraHeight );
SandboxWindow.setViewLimitOn( TruckToy.WorldLeft, TruckToy.CameraHeight/-2, TruckToy.WorldRight, TruckToy.CameraHeight/2 );
// Create the scene contents in a roughly left to right order.
// Background.
%this.createBackground();
// Floor.
%this.createFloor();
// Wrecked cars at start.
%this.createWreckedCar( 1, -90, TruckToy.FloorLevel + 0.75, 0, true );
%this.createWreckedCar( 2, -85, TruckToy.FloorLevel + 0.75, 0, true );
%this.createWreckedCar( 3, -82, TruckToy.FloorLevel + 0.75, 0, true );
%this.createWreckedCar( 1, -87.123, -2.478, 2.537, true );
%this.createBrick( 3, -87.5, TruckToy.FloorLevel + 0.25, true );
%this.createBrick( 4, -87.5, TruckToy.FloorLevel + 0.75, true );
%this.createBrick( 2, -79, TruckToy.FloorLevel + 0.25, true );
%this.createBonfire( -91.5, TruckToy.FloorLevel + 0.5, 1, TruckToy.BackgroundDomain-1 );
// Building with chains.
%this.createForegroundWall( 2, -99, -5 );
%this.createForegroundWall( 1, -75.5, -6.5 );
%this.createBrokenCementWall( -78, -1.5 );
%this.createWreckedBuilding( -71.5, -1 );
%this.createWoodPile( -65, -2.5 );
%this.createBrickPile( -67, TruckToy.FloorLevel + 0.45 );
%this.createForegroundBrickWall( 1, -61, -6 );
%this.createBonfire( -82, TruckToy.FloorLevel + 0.5, 1.5, TruckToy.ObstacleDomain+1 );
// Start of bridge.
%this.createPlank( 1, -53, TruckToy.FloorLevel + 0.5, 0, true );
%this.createPlank( 1, -50.1522, -2.3, 21.267, true );
%this.createWreckedCar( 2, -47, TruckToy.FloorLevel + 1.9, -100, true );
%this.createWreckedCar( 3, -45.5, TruckToy.FloorLevel + 1.9, 100, true );
%this.createPlank( 2, -44, TruckToy.FloorLevel + 2, -90, true );
%this.createPlank( 1, -43, TruckToy.FloorLevel + 2, -90, true );
%this.createPlank( 2, -42, TruckToy.FloorLevel + 2, -90, true );
%this.createPlank( 1, -41, TruckToy.FloorLevel + 2, -90, true );
%this.createForegroundWall( 2, -42, -4.5 );
%this.createBridge( -41, TruckToy.FloorLevel + 4, 40 );
for ( %n = 0; %n < 10; %n++ )
{
%brick = %this.createBrickStack( getRandom(1,5), -39 + getRandomF(0,16), TruckToy.FloorLevel + 5, false );
%brick.setAwake(true);
}
%this.createPlank( 1, -20.5, TruckToy.FloorLevel + 1.5, -90, true );
%this.createPlank( 3, -19, TruckToy.FloorLevel + 4, 0, true );
%this.createPlank( 1, -16.5, TruckToy.FloorLevel + 1.5, -90, true );
%this.createForegroundBrickWall( 2, -19, -6 );
%this.createBonfire( -46.5, TruckToy.FloorLevel, 3, TruckToy.BackgroundDomain-1 );
%this.createBonfire( -18.7, TruckToy.FloorLevel + 1, 2, TruckToy.BackgroundDomain-1 );
// More wrecked cars.
%this.createWreckedCar( 1, -12, TruckToy.FloorLevel + 0.75, 0, true );
%this.createWreckedCar( 2, -7, TruckToy.FloorLevel + 0.75, 0, true );
%this.createWreckedCar( 3, -4, TruckToy.FloorLevel + 0.75, 0, true );
%this.createBonfire( -5, TruckToy.FloorLevel + 0.5, 1, TruckToy.BackgroundDomain-1 );
// ************************************************************************
// Start of pyramid.
// ************************************************************************
%this.createPyramid( 2, TruckToy.FloorLevel + 0.25, 19, true );
%this.createForegroundWall( 1, 9, -6 );
%this.createPyramid( 2+21, TruckToy.FloorLevel + 0.25, 13, true );
%this.createForegroundBrickWall( 1, 9, -7 );
%this.createBonfire( 21, TruckToy.FloorLevel, 3, TruckToy.BackgroundDomain-1 );
// ************************************************************************
// Start of brick stacks.
// ************************************************************************
%this.createBrickStack( 45, TruckToy.FloorLevel + 0.25, 10, false );
%this.createBrickStack( 47, TruckToy.FloorLevel + 0.25, 1, true );
%this.createBrickStack( 49, TruckToy.FloorLevel + 0.25, 10, false );
%this.createBrickStack( 72, TruckToy.FloorLevel + 0.25, 1, true );
%this.createBrickStack( 74, TruckToy.FloorLevel + 0.25, 10, false );
%this.createBrickStack( 76, TruckToy.FloorLevel + 0.25, 1, true );
%this.createBrickStack( 78, TruckToy.FloorLevel + 0.25, 10, false );
%this.createBonfire( 71, TruckToy.FloorLevel, 1, TruckToy.BackgroundDomain-1 );
%this.createBonfire( 85, TruckToy.FloorLevel, 1.5, TruckToy.BackgroundDomain-1 );
// Truck.
%truckStartX = TruckToy.WorldLeft + (TruckToy.CameraWidth/6);
%truckStartY = 3;
%this.createTruck( %truckStartX, %truckStartY );
// Start the timer.
TruckToy.startTimer( "createProjectile", TruckToy.ProjectileRate );
}
// -----------------------------------------------------------------------------
function TruckToy::createBackground(%this)
{
// Atmosphere
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( "ToyAssets:highlightBackground" );
%obj.BlendColor = DarkGray;
%obj.setSize( TruckToy.WorldWidth * (TruckToy.CameraWidth*2), 75 );
%obj.setSceneLayer( TruckToy.BackdropDomain );
%obj.setSceneGroup( TruckToy.BackdropDomain );
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
// Industrial Background
%obj = new Scroller();
%obj.setBodyType( "static" );
%obj.setImage( "TruckToy:industrial_02" );
%obj.setPosition( 0, -1 );
%obj.setSize( TruckToy.WorldWidth, 8 );
%obj.setRepeatX( TruckToy.WorldWidth / 8 );
%obj.setSceneLayer( TruckToy.BackgroundDomain);
%obj.setSceneGroup( TruckToy.BackgroundDomain);
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
}
// -----------------------------------------------------------------------------
function TruckToy::createFloor(%this)
{
// Ground
%obj = new Scroller();
%obj.setBodyType( "static" );
%obj.setImage( "ToyAssets:woodGround" );
%obj.setSize( TruckToy.WorldWidth, 3 );
%obj.setPosition( 0, TruckToy.FloorLevel - (%obj.getSizeY()/2) );
%obj.setRepeatX( TruckToy.WorldWidth / 12 );
%obj.setSceneLayer( TruckToy.ObstacleDomain );
%obj.setSceneGroup( TruckToy.GroundDomain );
%obj.setDefaultFriction( TruckToy.ObstacleFriction );
%obj.setCollisionGroups( none );
%obj.createEdgeCollisionShape( TruckToy.WorldWidth/-2, 1.5, TruckToy.WorldWidth/2, 1.5 );
%obj.createEdgeCollisionShape( TruckToy.WorldWidth/-2, 3, TruckToy.WorldWidth/-2, 50 );
%obj.createEdgeCollisionShape( TruckToy.WorldWidth/2, 3, TruckToy.WorldWidth/2, 50 );
%obj.CollisionCallback = true;
%obj.setAwake( false );
SandboxScene.add( %obj );
}
// -----------------------------------------------------------------------------
function TruckToy::createBrokenCementWall( %this, %posX, %posY )
{
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( "TruckToy:brokenCementWall" );
%obj.setPosition( %posX, %posY );
%obj.setSize( 6, 6 );
%obj.setSceneLayer( TruckToy.BackgroundDomain-2 );
%obj.setSceneGroup( TruckToy.BackgroundDomain);
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createWoodPile( %this, %posX, %posY )
{
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( "TruckToy:woodPile" );
%obj.setPosition( %posX, %posY );
%obj.setSize( 8, 5 );
%obj.setSceneLayer( TruckToy.BackgroundDomain-2 );
%obj.setSceneGroup( TruckToy.BackgroundDomain);
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createBrickStack( %this, %posX, %posY, %brickCount, %static )
{
for ( %n = 0; %n < %brickCount; %n++ )
{
%this.createBrick( getRandom(1,5), %posX, %posY + (%n*0.5), %static );
}
}
// -----------------------------------------------------------------------------
function TruckToy::createPyramid( %this, %posX, %posY, %brickBaseCount, %static )
{
if ( %brickBaseCount < 2 )
{
echo( "Invalid pyramid brick base count of" SPC %brickBaseCount );
return;
}
for( %stack = 0; %stack < %brickBaseCount; %stack++ )
{
%stackIndexCount = %brickBaseCount - (%stack*2);
%stackX = %posX + ( %stack * 1.0 ) + getRandomF(-0.3, 0.3 );
%stackY = %posY + ( %stack * 0.5 );
for ( %stackIndex = 0; %stackIndex < %stackIndexCount; %stackIndex++ )
{
%this.createBrick( getRandom(1, 5), %stackX + %stackIndex, %stackY, %static );
}
}
}
// -----------------------------------------------------------------------------
function TruckToy::createBridge( %this, %posX, %posY, %linkCount )
{
%linkWidth = 0.5;
%linkHeight = %linkWidth * 0.5;
%halfLinkWidth = %linkWidth * 0.5;
%rootObj = new Sprite();
%rootObj.setBodyType( "static" );
%rootObj.setImage( "ToyAssets:cable" );
%rootObj.setPosition( %posX, %posY );
%rootObj.setSize( %linkWidth, %linkHeight );
%rootObj.setSceneLayer( TruckToy.BackgroundDomain-3 );
%rootObj.setSceneGroup( TruckToy.ObstacleDomain );
%rootObj.setCollisionSuppress();
SandboxScene.add( %rootObj );
%lastLinkObj = %rootObj;
for ( %n = 1; %n <= %linkCount; %n++ )
{
%obj = new Sprite();
%obj.setImage( "ToyAssets:cable" );
%obj.setPosition( %posX + (%n*%linkWidth), %posY );
%obj.setSize( %linkWidth, %linkHeight );
%obj.setSceneLayer( TruckToy.BackgroundDomain-3 );
%obj.setSceneGroup( TruckToy.ObstacleDomain );
if ( %n == %linkCount )
{
%obj.setBodyType( "static" );
%obj.setCollisionSuppress();
}
else
{
%obj.setCollisionGroups( none );
%obj.setDefaultDensity( 1 );
%obj.setDefaultFriction( TruckToy.ObstacleFriction );
%obj.createPolygonBoxCollisionShape( %linkWidth, %linkHeight );
%obj.setAngularDamping( 1.0 );
%obj.setLinearDamping( 1.0 );
}
//%obj.setDebugOn( 5 );
SandboxScene.add( %obj );
SandboxScene.createRevoluteJoint( %lastLinkObj, %obj, %halfLinkWidth, 0, -%halfLinkWidth, 0 );
%joint = SandboxScene.createMotorJoint( %lastLinkObj, %obj );
SandboxScene.setMotorJointMaxForce( %joint, 1000 );
%obj.setAwake( false );
%lastLinkObj.setAwake( false );
//%obj.setDebugOn( 5 );
%lastLinkObj = %obj;
}
return %lastLinkObj;
}
// -----------------------------------------------------------------------------
function TruckToy::createChain( %this, %posX, %posY, %linkCount )
{
%linkWidth = 0.25;
%linkHeight = %linkWidth * 2;
%halfLinkHeight = %linkHeight * 0.5;
%rootObj = new Sprite();
%rootObj.setBodyType( "static" );
%rootObj.setImage( "ToyAssets:chain" );
%rootObj.setPosition( %posX, %posY );
%rootObj.setSize( %linkWidth, %linkHeight );
%rootObj.setSceneLayer( TruckToy.BackgroundDomain-1 );
%rootObj.setSceneGroup( TruckToy.ObstacleDomain );
%rootObj.setCollisionSuppress();
SandboxScene.add( %rootObj );
%lastLinkObj = %rootObj;
for ( %n = 1; %n <= %linkCount; %n++ )
{
if ( %n < %linkCount )
{
%obj = new Sprite();
%obj.setImage( "ToyAssets:chain" );
%obj.setPosition( %posX, %posY - (%n*%linkHeight) );
%obj.setSize( %linkWidth, %linkHeight );
SandboxScene.add( %obj );
}
else
{
%obj = %this.createBonfire( %posX, %posY - (%n*%linkHeight), 0.5, TruckToy.BackgroundDomain-1 );
%obj.BodyType = dynamic;
}
%obj.setSceneLayer( TruckToy.BackgroundDomain-1 );
%obj.setSceneGroup( TruckToy.ObstacleDomain );
%obj.setCollisionGroups( none );
%obj.setDefaultDensity( 1 );
%obj.setDefaultFriction( 0.2 );
%obj.createPolygonBoxCollisionShape( %linkWidth, %linkHeight );
%obj.setAngularDamping( 1.0 );
%obj.setLinearDamping( 0.5 );
SandboxScene.createRevoluteJoint( %lastLinkObj, %obj, 0, -%halfLinkHeight, 0, %halfLinkHeight, false );
%lastLinkObj = %obj;
}
%lastLinkObj.setAwake(false);
return %lastLinkObj;
}
// -----------------------------------------------------------------------------
function TruckToy::createWreckedBuilding( %this, %posX, %posY )
{
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( "TruckToy:wreckedBuilding" );
%obj.setPosition( %posX, %posY );
%obj.setSize( 9, 8 );
%obj.setSceneLayer( TruckToy.BackgroundDomain-1 );
%obj.setSceneGroup( TruckToy.BackgroundDomain);
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
%this.createChain( %posX - 3, %posY + 3.4, 10 );
%this.createChain( %posX - 1, %posY + 3.2, 10 );
%this.createChain( %posX + 1, %posY + 3.0, 10 );
%this.createChain( %posX + 3, %posY + 2.8, 10 );
}
// -----------------------------------------------------------------------------
function TruckToy::createForegroundBrickWall( %this, %wallNumber, %posX, %posY )
{
if ( %wallNumber < 1 || %wallNumber > 2 )
{
echo( "Invalid foreground wall no of" SPC %wallNumber );
return;
}
%image = "TruckToy:brickWall_0" @ %wallNumber;
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( %image );
%obj.setPosition( %posX, %posY );
%obj.setSize( 10, 5 );
%obj.setSceneLayer( TruckToy.ForegroundDomain-1 );
%obj.setSceneGroup( TruckToy.ForegroundDomain );
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createForegroundWall( %this, %wallNumber, %posX, %posY )
{
if ( %wallNumber < 1 || %wallNumber > 2 )
{
echo( "Invalid foreground wall no of" SPC %wallNumber );
return;
}
%image = "TruckToy:foregroundWall_0" @ %wallNumber;
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( %image );
%obj.setPosition( %posX, %posY );
%obj.setSize( 6, 6 );
%obj.setSceneLayer( TruckToy.ForegroundDomain-1 );
%obj.setSceneGroup( TruckToy.ForegroundDomain );
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createBrick( %this, %brickNumber, %posX, %posY, %static )
{
if ( %brickNumber < 1 || %brickNumber > 5 )
{
echo( "Invalid brick no of" SPC %brickNumber );
return;
}
%image = "ToyAssets:brick_0" @ %brickNumber;
%obj = new Sprite();
if ( %static ) %obj.setBodyType( "static" );
%obj.setImage( %image );
%obj.setPosition( %posX, %posY );
%obj.setSize( 1, 0.5 );
%obj.setSceneLayer( TruckToy.ObstacleDomain );
%obj.setSceneGroup( TruckToy.ObstacleDomain );
%obj.setCollisionGroups( TruckToy.GroundDomain, TruckToy.ObstacleDomain );
%obj.setDefaultFriction( TruckToy.ObstacleFriction );
%obj.createPolygonBoxCollisionShape( 1, 0.5 );
%obj.setAwake( false );
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createBrickPile( %this, %posX, %posY )
{
%obj = new Sprite();
%obj.setBodyType( "static" );
%obj.setImage( "TruckToy:brickPile" );
%obj.setPosition( %posX, %posY );
%obj.setSize( 4, 1 );
%obj.setSceneLayer( TruckToy.BackgroundDomain-3 );
%obj.setSceneGroup( TruckToy.BackgroundDomain);
%obj.setCollisionSuppress();
%obj.setAwake( false );
%obj.setActive( false );
SandboxScene.add( %obj );
}
// -----------------------------------------------------------------------------
function TruckToy::createPlank( %this, %plankNumber, %posX, %posY, %angle, %static )
{
if ( %plankNumber < 1 || %plankNumber > 3 )
{
echo( "Invalid plank no of" SPC %plankNumber );
return;
}
%image = "TruckToy:plank_0" @ %plankNumber;
%obj = new Sprite();
if ( %static ) %obj.setBodyType( "static" );
%obj.setImage( %image );
%obj.setAngle( %angle );
%obj.setPosition( %posX, %posY );
%obj.setSize( 5, 1 );
%obj.setSceneLayer( TruckToy.ObstacleDomain );
%obj.setSceneGroup( TruckToy.ObstacleDomain );
%obj.setDefaultFriction( TruckToy.ObstacleFriction );
%obj.setCollisionGroups( TruckToy.GroundDomain, TruckToy.ObstacleDomain );
%obj.setAwake( false );
%obj.setDefaultFriction( 1.0 );
switch$( %plankNumber )
{
case 1:
%obj.createPolygonCollisionShape( "-2.5 -0.5 2.5 -0.5 2.5 -0.2 2.0 0.5 -2.5 -0.2" );
case 2:
%obj.createPolygonCollisionShape( "-2.5 -0.4 2.4 -0.5 2.4 0.5 0 0.5 -2.1 0.1 -2.5 -0.2" );
case 3:
%obj.createPolygonCollisionShape( "-2.5 -0.4 2.5 -0.5 1.9 0.5 -1.8 0.5 -2.5 0" );
}
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createWreckedCar( %this, %carNumber, %posX, %posY, %angle, %static )
{
if ( %carNumber < 1 || %carNumber > 3 )
{
echo( "Invalid brick no of" SPC %brickNumber );
return;
}
%image = "TruckToy:wreckedCar_0" @ %carNumber;
%obj = new Sprite();
if ( %static ) %obj.setBodyType( "static" );
%obj.setImage( %image );
%obj.setAngle( %angle );
%obj.setPosition( %posX, %posY );
%obj.setSize( 4, 1.5 );
%obj.setSceneLayer( TruckToy.ObstacleDomain );
%obj.setSceneGroup( TruckToy.ObstacleDomain );
%obj.setCollisionGroups( TruckToy.GroundDomain, TruckToy.ObstacleDomain );
%obj.setAwake( false );
%obj.setDefaultFriction( TruckToy.ObstacleFriction );
switch$( %carNumber )
{
case 1:
%obj.createPolygonCollisionShape( "-2 -0.65 0.5 -0.75 2 -0.45 1.9 0.2 0.5 0.65 -0.5 0.6 -2 -0.3" );
case 2:
%obj.createPolygonCollisionShape( "-2 -0.75 2 -0.75 2 -0.2 0.4 0.65 -0.9 0.7 -2 0.0" );
case 3:
%obj.createPolygonCollisionShape( "-2 -0.65 0 -0.75 2 -0.55 1.8 0.3 0.5 0.75 -0.5 0.75 -2 0.1" );
}
SandboxScene.add( %obj );
return %obj;
}
// -----------------------------------------------------------------------------
function TruckToy::createBonfire(%this, %x, %y, %scale, %layer)
{
// Create an impact explosion at the projectiles position.
%particlePlayer = new ParticlePlayer();
%particlePlayer.BodyType = static;
%particlePlayer.SetPosition( %x, %y );
%particlePlayer.SceneLayer = %layer;
%particlePlayer.ParticleInterpolation = true;
%particlePlayer.Particle = "ToyAssets:bonfire";
%particlePlayer.SizeScale = %scale;
%particlePlayer.CameraIdleDistance = TruckToy.CameraWidth * 0.8;
SandboxScene.add( %particlePlayer );
return %particlePlayer;
}
// -----------------------------------------------------------------------------
function TruckToy::createProjectile(%this)
{
// Fetch the truck position.
%truckPositionX = TruckToy.TruckBody.Position.x;
%projectile = new Sprite() { class = "TruckProjectile"; };
%projectile.Animation = "ToyAssets:Projectile_FireballAnim";
%projectile.setPosition( getRandom( %truckPositionX - (TruckToy.CameraWidth * 0.2), %truckPositionX + (TruckToy.CameraWidth * 0.5) ), 12 );
%projectile.setSceneLayer( TruckToy.BackgroundDomain-2 );
%projectile.setSceneGroup( TruckToy.ProjectileDomain );
%projectile.FlipY = true;
%projectile.Size = getRandom(0.5, 2);
%projectile.Lifetime = 2.5;
%projectile.createCircleCollisionShape( 0.2 );
%projectile.setCollisionGroups( TruckToy.GroundDomain );
%projectile.CollisionCallback = true;
SandboxScene.add( %projectile );
}
// -----------------------------------------------------------------------------
function TruckProjectile::onCollision(%this, %object, %collisionDetails)
{
// Create an impact explosion at the projectiles position.
%particlePlayer = new ParticlePlayer();
%particlePlayer.BodyType = Static;
%particlePlayer.Position = %this.Position;
%particlePlayer.Size = 10;
%particlePlayer.SceneLayer = TruckToy.BackgroundDomain-1;
%particlePlayer.ParticleInterpolation = true;
%particlePlayer.Particle = "ToyAssets:ImpactExplosion";
%particlePlayer.SizeScale = getRandom(TruckToy.ExplosionScale, TruckToy.ExplosionScale * 1.5);
SandboxScene.add( %particlePlayer );
// Start the camera shaking.
SandboxWindow.startCameraShake( 10 + (3 * TruckToy.ExplosionScale), 1 );
// Delete the projectile.
%this.safeDelete();
}
// -----------------------------------------------------------------------------
function TruckToy::createTruck( %this, %posX, %posY )
{
// Truck Body.
%exhaustParticles = new ParticlePlayer();
%exhaustParticles.setPosition( %posX-3, %posY );
%exhaustParticles.setSceneLayer( TruckToy.TruckDomain );
%exhaustParticles.Particle = "TruckToy:exhaust";
%exhaustParticles.SizeScale = 0.1;
%exhaustParticles.ForceScale = 0.4;
%exhaustParticles.EmissionRateScale = 4;
SandboxScene.add( %exhaustParticles );
%exhaustParticles.play();
TruckToy.TruckExhaust = %exhaustParticles;
TruckToy.TruckBody = new Sprite();
TruckToy.TruckBody.setPosition( %posX, %posY );
TruckToy.TruckBody.setImage( "TruckToy:truckBody" );
TruckToy.TruckBody.setSize( 5, 2.5 );
TruckToy.TruckBody.setSceneLayer( TruckToy.TruckDomain );
TruckToy.TruckBody.setSceneGroup( TruckToy.ObstacleDomain);
TruckToy.TruckBody.setCollisionGroups( TruckToy.ObstacleDomain, TruckToy.ObstacleDomain-1, TruckToy.GroundDomain );
TruckToy.TruckBody.createPolygonCollisionShape( "-2 0.2 -2 -0.5 0 -.95 2 -0.5 2 0.0 0 0.7 -1.5 0.7" );
//TruckToy.TruckBody.setDebugOn( 5 );
SandboxScene.add( TruckToy.TruckBody );
// Attach the exhaust output to the truck body.
%joint = SandboxScene.createRevoluteJoint( TruckToy.TruckBody, TruckToy.TruckExhaust, "-2.3 -0.6", "0 0" );
SandboxScene.setRevoluteJointLimit( %joint, 0, 0 );
// Mount camera to truck body.
SandboxWindow.mount( TruckToy.TruckBody, "0 0", 3, true, TruckToy.RotateCamera );
// Tires.
// Suspension = -1.0 : -1.5
// Rear tire.
%tireRear = new Sprite();
%tireRear.setPosition( %posX-1.4, %posY-1.0 );
%tireRear.setImage( "ToyAssets:tires" );
%tireRear.setSize( 1.7, 1.7 );
%tireRear.setSceneLayer( TruckToy.TruckDomain-1 );
%tireRear.setSceneGroup( TruckToy.ObstacleDomain );
%tireRear.setCollisionGroups( TruckToy.ObstacleDomain, TruckToy.GroundDomain );
%tireRear.setDefaultFriction( TruckToy.WheelFriction );
%tireRear.setDefaultDensity( TruckToy.RearWheelDensity );
%tireRear.createCircleCollisionShape( 0.8 );
SandboxScene.add( %tireRear );
TruckToy.RearWheel = %tireRear;
// Front tire.
%tireFront = new Sprite();
%tireFront.setPosition( %posX+1.7, %posY-1.0 );
%tireFront.setImage( "ToyAssets:tires" );
%tireFront.setSize( 1.7, 1.7 );
%tireFront.setSceneLayer( TruckToy.TruckDomain-1 );
%tireFront.setSceneGroup( TruckToy.ObstacleDomain );
%tireFront.setCollisionGroups( TruckToy.ObstacleDomain, TruckToy.GroundDomain );
%tireFront.setDefaultFriction( TruckToy.WheelFriction );
%tireFront.setDefaultDensity( TruckToy.FrontWheelDensity );
%tireFront.createCircleCollisionShape( 0.8 );
SandboxScene.add( %tireFront );
TruckToy.FrontWheel = %tireFront;
// Suspension joints.
TruckToy.RearMotorJoint = SandboxScene.createWheelJoint( TruckToy.TruckBody, %tireRear, "-1.4 -1.25", "0 0", "0 1" );
TruckToy.FrontMotorJoint = SandboxScene.createWheelJoint( TruckToy.TruckBody, %tireFront, "1.7 -1.25", "0 0", "0 1" );
}
// -----------------------------------------------------------------------------
function truckForward(%val)
{
if(%val)
{
if ( !TruckToy.TruckMoving )
{
%driveActive = false;
if ( TruckToy.FrontWheelDrive )
{
SandboxScene.setWheelJointMotor( TruckToy.FrontMotorJoint, true, -TruckToy.WheelSpeed, 10000 );
%driveActive = true;
}
else
{
SandboxScene.setWheelJointMotor( TruckToy.FrontMotorJoint, false );
}
if ( TruckToy.RearWheelDrive )
{
SandboxScene.setWheelJointMotor( TruckToy.RearMotorJoint, true, -TruckToy.WheelSpeed, 10000 );
%driveActive = true;
}
else
{
SandboxScene.setWheelJointMotor( TruckToy.RearMotorJoint, false );
}
if ( %driveActive )
{
TruckToy.TruckExhaust.SizeScale *= 4;
TruckToy.TruckExhaust.ForceScale /= 2;
}
}
TruckToy.TruckMoving = true;
}
else
{
truckStop();
}
}
// -----------------------------------------------------------------------------
function truckReverse(%val)
{
if(%val)
{
if ( !TruckToy.TruckMoving )
{
%driveActive = false;
if ( TruckToy.FrontWheelDrive )
{
SandboxScene.setWheelJointMotor( TruckToy.FrontMotorJoint, true, TruckToy.WheelSpeed, 10000 );
%driveActive = true;
}
else
{
SandboxScene.setWheelJointMotor( TruckToy.FrontMotorJoint, false );
}
if ( TruckToy.RearWheelDrive )
{
SandboxScene.setWheelJointMotor( TruckToy.RearMotorJoint, true, TruckToy.WheelSpeed, 10000 );
%driveActive = true;
}
else
{
SandboxScene.setWheelJointMotor( TruckToy.RearMotorJoint, false );
}
if ( %driveActive )
{
TruckToy.TruckExhaust.SizeScale *= 4;
TruckToy.TruckExhaust.ForceScale /= 2;
}
}
TruckToy.TruckMoving = true;
}
else
{
truckStop();
}
}
//-----------------------------------------------------------------------------
function TruckToy::truckStop(%this)
{
// Finish if truck is not moving.
if ( !TruckToy.TruckMoving )
return;
// Stop truck moving.
SandboxScene.setWheelJointMotor( TruckToy.RearMotorJoint, true, 0, 10000 );
SandboxScene.setWheelJointMotor( TruckToy.FrontMotorJoint, true, 0, 10000 );
TruckToy.TruckExhaust.SizeScale /= 4;
TruckToy.TruckExhaust.ForceScale *= 2;
// Flag truck as not moving.
TruckToy.TruckMoving = false;
}
//-----------------------------------------------------------------------------
function TruckToy::setWheelSpeed( %this, %value )
{
%this.WheelSpeed = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setWheelFriction( %this, %value )
{
%this.WheelFriction = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setFrontWheelDensity( %this, %value )
{
%this.FrontWheelDensity = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setRearWheelDensity( %this, %value )
{
%this.RearWheelDensity = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setFrontWheelDrive( %this, %value )
{
%this.FrontWheelDrive = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setRearWheelDrive( %this, %value )
{
%this.RearWheelDrive = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setProjectileRate( %this, %value )
{
%this.ProjectileRate = %value;
// Start the timer.
TruckToy.startTimer( "createProjectile", TruckToy.ProjectileRate );
}
//-----------------------------------------------------------------------------
function TruckToy::setExplosionScale( %this, %value )
{
%this.ExplosionScale = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::setRotateCamera( %this, %value )
{
%this.RotateCamera = %value;
}
//-----------------------------------------------------------------------------
function TruckToy::onTouchDown(%this, %touchID, %worldPosition)
{
// Finish if truck is already moving.
if ( TruckToy.TruckMoving )
return;
// If we touch in-front of the truck then move forward else reverse.
if ( %worldPosition.x >= TruckToy.TruckBody.Position.x )
{
truckForward( true );
}
else
{
truckReverse( true );
}
}
//-----------------------------------------------------------------------------
function TruckToy::onTouchUp(%this, %touchID, %worldPosition)
{
// Stop the truck.
TruckToy.truckStop();
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Hammock.Model;
using Newtonsoft.Json;
namespace TweetSharp
{
#if !SILVERLIGHT
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterSearchUser
{
[DataMember]
public virtual string Name { get; set; }
[DataMember]
public virtual string IdStr { get; set; }
[JsonProperty("screen_name")]
[DataMember]
public virtual string ScreenName { get; set; }
[JsonProperty("profile_image_url")]
[DataMember]
public virtual string ProfileImageUrl { get; set; }
/*
"created_at": "Mon Apr 26 06:01:55 +0000 2010",
"location": "LA, CA",
"follow_request_sent": null,
"profile_link_color": "0084B4",
"is_translator": false,
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "",
"indices": [
0,
0
]
}
]
},
"description": {
"urls": [
]
}
},
"default_profile": true,
"contributors_enabled": false,
"favourites_count": 0,
"url": null,
"profile_image_url_https": "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg",
"utc_offset": -28800,
"id": 137238150,
"profile_use_background_image": true,
"listed_count": 2,
"profile_text_color": "333333",
"lang": "en",
"followers_count": 70,
"protected": false,
"notifications": null,
"profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png",
"profile_background_color": "C0DEED",
"verified": false,
"geo_enabled": true,
"time_zone": "Pacific Time (US & Canada)",
"description": "Born 330 Live 310",
"default_profile_image": false,
"profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png",
"statuses_count": 579,
"friends_count": 110,
"following": null,
"show_all_inline_media": false,
"screen_name": "sean_cummings"
*/
}
#if !SILVERLIGHT
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
[DebuggerDisplay("{FromUserScreenName}: {Text}")]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterSearchStatus : PropertyChangedBase,
IComparable<TwitterSearchStatus>,
IEquatable<TwitterSearchStatus>
{
private int _fromUserId;
private string _fromUserName;
private string _fromUserScreenName;
private long _id;
private string _isoLanguageCode;
private string _profileImageUrl;
private long _sinceId;
private string _source;
private string _text;
private int? _toUserId;
private string _toUserScreenName;
private string _location;
private TwitterGeoLocation _geoLocation;
private TwitterEntities _entities;
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string Text
{
get { return _text; }
set
{
if (_text == value)
{
return;
}
_text = value;
OnPropertyChanged("Text");
}
}
private string _textAsHtml;
public virtual string TextAsHtml
{
get
{
if (string.IsNullOrEmpty(Text))
{
return Text;
}
return _textAsHtml ?? (_textAsHtml = Text.ParseTwitterageToHtml());
}
set
{
_textAsHtml = value;
}
}
[JsonProperty("created_at")]
#if !Smartphone && !NET20
[DataMember]
#endif
public string CreatedDateStr { get; set; }
public virtual DateTime CreatedDate
{
get
{
var m = Regex.Match(CreatedDateStr, @"\w+ (\w+) (\d+) (\d+):(\d+):(\d+) \+(\d+) (\d+)");
string dateStr = m.Groups[7].Value + " " + m.Groups[1].Value + " " + m.Groups[2].Value + " " + m.Groups[3].Value + ":" + m.Groups[4].Value + ":" + m.Groups[5].Value + " +" + m.Groups[6].Value;
var dt = DateTime.Parse(dateStr, DateTimeFormatInfo.InvariantInfo);
return dt;
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public string IsoLanguageCode
{
get { return _isoLanguageCode; }
set
{
if (_isoLanguageCode == value)
{
return;
}
_isoLanguageCode = value;
OnPropertyChanged("IsoLanguageCode");
}
}
[JsonProperty("geo")]
#if !Smartphone && !NET20
[DataMember]
#endif
public TwitterGeoLocation GeoLocation
{
get { return _geoLocation; }
set
{
if (_geoLocation == value)
{
return;
}
_geoLocation = value;
OnPropertyChanged("TwitterGeoLocation");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual TwitterEntities Entities
{
get { return _entities; }
set
{
if (_entities == value)
{
return;
}
_entities = value;
OnPropertyChanged("Entities");
}
}
[JsonProperty("user")]
public virtual TwitterSearchUser User { get; set; }
[JsonProperty("retweet_count")]
public int RetweetCount { get; set; }
#region IComparable<TwitterSearchStatus> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(TwitterSearchStatus other)
{
return other.Id == Id ? 0 : other.Id > Id ? -1 : 1;
}
#endregion
#region IEquatable<TwitterSearchStatus> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="status">The status.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="status"/> parameter; otherwise, false.
/// </returns>
public bool Equals(TwitterSearchStatus status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.Id == Id;
}
#endregion
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="status">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object status)
{
if (ReferenceEquals(null, status))
{
return false;
}
if (ReferenceEquals(this, status))
{
return true;
}
return status.GetType() == typeof (TwitterSearchStatus) && Equals((TwitterSearchStatus) status);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return Id.GetHashCode();
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(TwitterSearchStatus left, TwitterSearchStatus right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(TwitterSearchStatus left, TwitterSearchStatus right)
{
return !Equals(left, right);
}
///<summary>
/// This implicit conversion supports treating a search status as if it were a
/// regular <see cref="TwitterStatus" />. This is useful if you need to combine search
/// results and regular results in the same UI context.
///</summary>
///<param name="searchStatus"></param>
///<returns></returns>
public static implicit operator TwitterStatus(TwitterSearchStatus searchStatus)
{
var user = new TwitterUser
{
};
var status = new TwitterStatus
{
CreatedDate = searchStatus.CreatedDate,
Id = searchStatus.Id,
RawSource = searchStatus.RawSource,
Text = searchStatus.Text,
User = user
};
return status;
}
#if !Smartphone && !NET20
/// <summary>
/// The source content used to deserialize the model entity instance.
/// Can be XML or JSON, depending on the endpoint used.
/// </summary>
[DataMember]
#endif
public virtual string RawSource { get; set; }
}
}
| |
/* Copyright (C) 2014 Newcastle University
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Android.Views;
using Android.Widget;
using Bootleg.API;
using Android.Support.V7.Widget;
using Square.Picasso;
using Android.Content;
using Bootleg.Droid.UI;
using Android.Graphics;
using Bootleg.API.Model;
namespace Bootleg.Droid
{
public class EventAdapter : RecyclerView.Adapter
{
public enum TileType : int { NEWSHOOT = 0x01, ENTERCODE = 0x02, EVENT = 0x00, MORESHOOTS = 0x03, EMPTY = 0x04, MYEVENTSTITLE=0x05, EVENT_FEATURED=0x06 };
public class HeaderEventItem
{
public Shoot Event { get; set; }
internal TileType Tiletype { get; set; }
}
public enum EventViewType { MYEVENT, FEATURED_LIST, FEATURED, LIST, NEARBY, NEARBY_SINGLE };
public class ViewHolder : RecyclerView.ViewHolder
{
// each data item is just a string in this case
private View view;
EventViewType buttons;
Action<Shoot> capture;
Action<Shoot> edit;
Action<Shoot> share;
Action<string> entercode;
Action showmore;
EventAdapter adpt;
Shoot currentevent;
public ViewHolder(View itemView, Action<Shoot> capture, Action<Shoot> edit, Action showmore, Action<Shoot> share, Action<string> entercode, EventViewType buttons, EventAdapter adpt, int tiletype) : base(itemView)
{
this.capture = capture;
this.edit = edit;
view = itemView;
this.buttons = buttons;
this.showmore = showmore;
this.adpt = adpt;
this.share = share;
this.entercode = entercode;
if (tiletype == (int)TileType.MYEVENTSTITLE)
{
//do nothing -- its the title
}
else
{
if (buttons == EventViewType.MYEVENT)
{
view.Click += (sender, e) =>
{
if (currentevent != null)
edit(currentevent);
};
//view.FindViewById<ImageButton>(Resource.Id.capturebtn).Click += (sender, e) =>
//{
// if (currentevent != null)
// capture(currentevent);
//};
//view.FindViewById<ImageButton>(Resource.Id.editbtn).Click += (sender, e) =>
//{
// if (currentevent != null)
// edit(currentevent);
//};
}
else
{
view.Click += View_Click;
}
if (view.FindViewById<ImageButton>(Resource.Id.sharebtn) != null)
{
if (WhiteLabelConfig.EXTERNAL_LINKS)
{
view.FindViewById<ImageButton>(Resource.Id.sharebtn).Click += ViewHolder_Click;
}
else
{
view.FindViewById<ImageButton>(Resource.Id.sharebtn).Visibility = ViewStates.Gone;
}
}
if (view.FindViewById<EditText>(Resource.Id.code) != null)
{
view.FindViewById<EditText>(Resource.Id.code).TextChanged += ViewHolder_TextChanged;
}
}
}
private void ViewHolder_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
{
if (e.Text.Count() == 4)
{
entercode?.Invoke(e.Text.ToString());
view.FindViewById<EditText>(Resource.Id.code).Text = "";
}
}
private void ViewHolder_Click(object sender, EventArgs e)
{
//share:
share?.Invoke(currentevent);
}
private void View_Click(object sender, EventArgs e)
{
if (currentevent != null)
capture(currentevent);
else
showmore?.Invoke();
}
internal void SetItem(HeaderEventItem item)
{
currentevent = item.Event;
if (item.Tiletype == TileType.EVENT || item.Tiletype == TileType.EVENT_FEATURED)
{
if (view.FindViewById<TextView>(Resource.Id.joincode) != null)
{
if (string.IsNullOrEmpty(item.Event.joincode) || WhiteLabelConfig.LOCAL_SERVER || item.Event.ispublic)
{
view.FindViewById<TextView>(Resource.Id.joincode).Visibility = ViewStates.Gone;
}
else
{
view.FindViewById<TextView>(Resource.Id.joincode).Visibility = ViewStates.Visible;
view.FindViewById<TextView>(Resource.Id.joincode).Text = item.Event.joincode;
}
}
if (view.FindViewById<ImageButton>(Resource.Id.sharebtn) != null)
{
if (currentevent.ispublic && WhiteLabelConfig.EXTERNAL_LINKS)
view.FindViewById<ImageButton>(Resource.Id.sharebtn).Visibility = ViewStates.Visible;
else
view.FindViewById<ImageButton>(Resource.Id.sharebtn).Visibility = ViewStates.Gone;
}
//view.FindViewById<ImageView>(Resource.Id.event_icon).SetImageResource(Resource.Drawable.ic_event_white_48dp);
string msg = "";
if (buttons == EventViewType.MYEVENT)
{
if (currentevent.myclips > 0)
{
view.FindViewById<TextView>(Resource.Id.clipcount).Text = Java.Lang.String.Format("%d", currentevent.myclips);
view.FindViewById<TextView>(Resource.Id.clipcount).Visibility = ViewStates.Visible;
view.FindViewById<ImageView>(Resource.Id.myclipsimg).Visibility = ViewStates.Visible;
}
else
{
view.FindViewById<TextView>(Resource.Id.clipcount).Visibility = ViewStates.Invisible;
view.FindViewById<ImageView>(Resource.Id.myclipsimg).Visibility = ViewStates.Invisible;
}
var ups = Bootlegger.BootleggerClient.GetNumUploadsForShoot(currentevent);
if (ups > 0)
{
msg = Java.Lang.String.Format("%d", ups);
}
if (msg != "")
{
view.FindViewById<TextView>(Resource.Id.uploadcount).Visibility = ViewStates.Visible;
view.FindViewById<TextView>(Resource.Id.uploadcount).Text = msg;
view.FindViewById<View>(Resource.Id.uploadimg).Visibility = ViewStates.Visible;
}
else
{
view.FindViewById<TextView>(Resource.Id.uploadcount).Visibility = ViewStates.Gone;
view.FindViewById<View>(Resource.Id.uploadimg).Visibility = ViewStates.Gone;
}
var imgs = Bootlegger.BootleggerClient.GetSampleMediaForEvent(currentevent).ToList().OrderBy(x => x.CreatedAt);
if (imgs.Count() > 0)
Picasso.With(view.Context).Load(imgs.First().Thumb + "?s=" + WhiteLabelConfig.THUMBNAIL_SIZE).CenterCrop().Fit().Into(view.FindViewById<ImageView>(Resource.Id.event_background));
else
{
if (!string.IsNullOrEmpty(currentevent.iconbackground))
//Picasso.With(view.Context).Load(Resource.Drawable.event_back).CenterCrop().Fit().Tag(adpt).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
//else
Picasso.With(view.Context).Load(currentevent.iconbackground).CenterCrop().Fit().Tag(adpt).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
//Picasso.With(view.Context).Load("https://ifrc.bootlegger.tv/backgrounds/ifrc.jpg").CenterCrop().Fit().Tag(adpt).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
}
}
if (!string.IsNullOrEmpty(currentevent.group) && buttons != EventViewType.MYEVENT)
{
view.FindViewById<TextView>(Resource.Id.organiser).Text = adpt.context.Resources.GetQuantityString(Resource.Plurals.shootcount, currentevent.events.Count, currentevent.events.Count);
view.FindViewById<TextView>(Resource.Id.firstLine).Text = currentevent.group;
//view.FindViewById<TextView>(Resource.Id.secondLine).Text = adpt.context.Resources.GetQuantityString(Resource.Plurals.shootcount, currentevent.events.Count, currentevent.events.Count);
//view.FindViewById<TextView>(Resource.Id.secondLine).Visibility = ViewStates.Visible;
Picasso.With(view.Context).Load(currentevent.icon).CenterCrop().Fit().Tag(adpt).Config(Bitmap.Config.Argb4444).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
Picasso.With(view.Context).Load(Resource.Drawable.ic_video_library_black_24dp).Fit().Tag(adpt).Transform(new CircleTransform()).Into(view.FindViewById<ImageView>(Resource.Id.organisericon));
}
else
{
if (buttons != EventViewType.MYEVENT)
{
if (!string.IsNullOrEmpty(currentevent.iconbackground))
//Picasso.With(view.Context).Load(Resource.Drawable.event_back).CenterCrop().Fit().Tag(adpt).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
//else
Picasso.With(view.Context).Load(currentevent.iconbackground).CenterCrop().Fit().Tag(adpt).Into(view.FindViewById<ImageView>(Resource.Id.event_background));
}
view.FindViewById<TextView>(Resource.Id.organiser).Text = currentevent.organisedby;
view.FindViewById<TextView>(Resource.Id.firstLine).Text = currentevent.name;
}
//if (!string.IsNullOrEmpty(currentevent.icon) && view.FindViewById<ImageView>(Resource.Id.event_icon) != null)
//{
// Picasso.With(view.Context).Load(currentevent.icon).Fit().Tag(adpt).Config(Bitmap.Config.Argb4444).Transform(new CircleTransform()).Into(view.FindViewById<ImageView>(Resource.Id.event_icon));
//}
Picasso.With(view.Context).Load(currentevent.organiserprofile).Fit().Tag(adpt).Transform(new CircleTransform()).Into(view.FindViewById<ImageView>(Resource.Id.organisericon));
}
else
{
}
}
}
List<HeaderEventItem> allitems;
public List<HeaderEventItem> Visibleitems {
get; set; }
Context context;
public event EventHandler<Shoot> Capture;
public event EventHandler<Shoot> Edit;
public event Action GoToUploads;
public EventViewType ViewType { get; private set; }
public void UpdateData(List<Shoot> data, EventViewType viewtype)
{
ViewType = viewtype;
allitems = new List<HeaderEventItem>();
allitems.Clear();
//if (viewtype == EventViewType.FEATURED && WhiteLabelConfig.ALLOW_CODE_JOIN)
// allitems.Add(new HeaderEventItem() { Tiletype = TileType.ENTERCODE });
if (viewtype == EventViewType.MYEVENT)
allitems.Add(new HeaderEventItem() { Tiletype = TileType.MYEVENTSTITLE });
//if ((context.ApplicationContext as BootleggerApp).Comms.CurrentUser!=null && (viewtype == EventViewType.MYEVENT) && WhiteLabelConfig.ALLOW_CREATE_OWN)
// allitems.Add(new HeaderEventItem() { Tiletype = TileType.NEWSHOOT });
if (data?.Count==0)
allitems.Add(new HeaderEventItem() { Tiletype = TileType.EMPTY });
if (viewtype == EventViewType.FEATURED)
data = data.Take(3).ToList();
if (viewtype == EventViewType.FEATURED)
{
if (data != null)
foreach (var r in data)
allitems.Add(new HeaderEventItem() { Event = r, Tiletype = TileType.EVENT_FEATURED });
}
else
{
if (data != null)
foreach (var r in data)
allitems.Add(new HeaderEventItem() { Event = r });
}
Visibleitems = allitems;
NotifyDataSetChanged();
}
public EventAdapter():base()
{
Visibleitems = new List<HeaderEventItem>();
}
public override long GetItemId(int position)
{
return allitems[position].Event?.id?.GetHashCode() ?? 99;
}
public EventAdapter(Context context)
: base()
{
this.context = context;
Visibleitems = new List<HeaderEventItem>();
}
public void FlushFilter()
{
Visibleitems = new List<HeaderEventItem>();
Visibleitems.AddRange(allitems);
NotifyDataSetChanged();
}
public void SetFilter(string queryText)
{
Visibleitems = new List<HeaderEventItem>();
var results = from ev in allitems where
ev.Tiletype == TileType.EVENT &&
(
(ev.Event.name!=null && (ev.Event.name.ToLower().Contains(queryText.ToLower()) || ev.Event.description.ToLower().Contains(queryText.ToLower())))
|| (ev.Event.@group!=null && ev.Event.@group.ToLower().Contains(queryText.ToLower()) || (ev.Event.@group != null && EventContains(queryText.ToLower(),ev.Event.events)))) select ev;
Visibleitems.AddRange(results.ToList());
NotifyDataSetChanged();
}
private static bool EventContains(string queryText, IEnumerable<Shoot> events)
{
return (from ev in events where (ev.name != null && (ev.name.ToLower().Contains(queryText.ToLower()) || ev.description.ToLower().Contains(queryText.ToLower()))) select ev).ToList().Count > 0;
}
public override int ItemCount
{
get
{
return Visibleitems.Count();
}
}
void OnCapture(Shoot position)
{
Capture?.Invoke(this, position);
}
void OnEdit(Shoot position)
{
Edit?.Invoke(this, position);
}
public event Action ShowMore;
public event Action MakeShoot;
public event Action<Shoot> Share;
public event Action<string> OnEnterCode;
void OnShowMore()
{
ShowMore?.Invoke();
}
void OnMakeShoot()
{
MakeShoot?.Invoke();
}
void OnShowUploads()
{
GoToUploads?.Invoke();
}
void OnShare(Shoot e)
{
Share(e);
}
public override int GetItemViewType(int position)
{
return (int)allitems[position].Tiletype;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var item = Visibleitems[position];
ViewHolder view = holder as ViewHolder;
view.SetItem(item);
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
ViewHolder vh;
switch (viewType)
{
//case (int)TileType.NEWSHOOT:
//itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.makeshoot, parent, false);
//vh = new ViewHolder(itemView, null, null, OnMakeShoot, null,null, ViewType, this, viewType);
//return vh;
case (int)TileType.EMPTY:
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.emptyshoots, parent, false);
vh = new ViewHolder(itemView, null, null, null, null, null, ViewType, this, viewType);
return vh;
case (int)TileType.MORESHOOTS:
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.moreshoots, parent, false);
vh = new ViewHolder(itemView, null, null, OnShowMore, null, null, ViewType, this, viewType);
return vh;
case (int)TileType.ENTERCODE:
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.enter_code, parent, false);
vh = new ViewHolder(itemView, null, null, null, null, OnEnterCode, ViewType, this, viewType);
return vh;
case (int)TileType.MYEVENTSTITLE:
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.myeventstitle, parent, false);
vh = new ViewHolder(itemView, null, null, null, null, null, ViewType, this, viewType);
return vh;
case (int)TileType.EVENT:
case (int)TileType.EVENT_FEATURED:
default:
if (ViewType == EventViewType.MYEVENT)
{
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.eventitem_small, parent, false);
vh = new ViewHolder(itemView, OnCapture, OnEdit, null, OnShare,null, ViewType, this, viewType);
return vh;
}
else
{
//make less than 100% width when displaying as featured...
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.eventitem, parent, false);
if (viewType == (int)TileType.EVENT_FEATURED)
{
if (context.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
{
itemView.LayoutParameters.Width = (parent.Width - Utils.dp2px(context, (34 * 2))) / 2;
itemView.LayoutParameters = new FrameLayout.LayoutParams(itemView.LayoutParameters) { MarginStart = Utils.dp2px(context, 4), MarginEnd = Utils.dp2px(context, 4), TopMargin = Utils.dp2px(context, 4) };
}
else
{
itemView.LayoutParameters.Width = parent.Width - Utils.dp2px(context, (34 * 2));
itemView.LayoutParameters = new FrameLayout.LayoutParams(itemView.LayoutParameters) { MarginStart = Utils.dp2px(context, 4), MarginEnd = Utils.dp2px(context, 4), TopMargin = Utils.dp2px(context, 4) };
}
}
vh = new ViewHolder(itemView, OnCapture, OnEdit, null, OnShare,null, ViewType, this, viewType);
return vh;
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// The Azure SQL Database Management API includes operations for getting
/// Azure SQL Database Server quotas. Specifically, using the APIs you can
/// get a specific quota or list all of the quotas for the Azure SQL
/// Database Server.
/// </summary>
internal partial class QuotaOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IQuotaOperations
{
/// <summary>
/// Initializes a new instance of the QuotaOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal QuotaOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieves the specified quota from the server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server from which to
/// retrieve the quota.
/// </param>
/// <param name='quotaName'>
/// Required. The name of the quota to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response structure for the Quota Get operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.QuotaGetResponse> GetAsync(string serverName, string quotaName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (quotaName == null)
{
throw new ArgumentNullException("quotaName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("quotaName", quotaName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/serverquotas/" + Uri.EscapeDataString(quotaName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
QuotaGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new QuotaGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
XElement serviceResourceElement2 = serviceResourceElement.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement2 != null)
{
Quota serviceResourceInstance = new Quota();
result.Quota = serviceResourceInstance;
XElement valueElement = serviceResourceElement2.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure"));
if (valueElement != null)
{
string valueInstance = valueElement.Value;
serviceResourceInstance.Value = valueInstance;
}
XElement nameElement = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns a list of quotas from the server.
/// </summary>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server from which to
/// get the quotas.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response structure for the Quota List operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.QuotaListResponse> ListAsync(string serverName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId) + "/services/sqlservers/servers/" + Uri.EscapeDataString(serverName) + "/serverquotas";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
QuotaListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new QuotaListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourcesSequenceElement != null)
{
foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
Quota serviceResourceInstance = new Quota();
result.Quotas.Add(serviceResourceInstance);
XElement valueElement = serviceResourcesElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure"));
if (valueElement != null)
{
string valueInstance = valueElement.Value;
serviceResourceInstance.Value = valueInstance;
}
XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
if (typeElement != null)
{
string typeInstance = typeElement.Value;
serviceResourceInstance.Type = typeInstance;
}
XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
string stateInstance = stateElement.Value;
serviceResourceInstance.State = stateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Globalization;
using TestLibrary;
// ToString_str.cs
// Tests TimeSpan.ToString(str)
// The desktop changes 2009/04/21 KatyK are ported 2009/06/08 DidemG
public class TimeSpanTest
{
static bool verbose = false;
static int iCountTestcases = 0;
static int iCountErrors = 0;
public static int Main(String[] args)
{
try
{
// for SL, String.ToLower(InvariantCulture)
if ((args.Length > 0) && args[0].ToLower() == "true")
verbose = true;
Logging.WriteLine("CurrentCulture: " + Utilities.CurrentCulture.Name);
Logging.WriteLine("CurrentUICulture: " + Utilities.CurrentCulture.Name);
RunTests();
}
catch (Exception e)
{
iCountErrors++;
Logging.WriteLine("Unexpected exception!! " + e.ToString());
}
if (iCountErrors == 0)
{
Logging.WriteLine("Pass. iCountTestcases=="+iCountTestcases);
return 100;
}
else
{
Logging.WriteLine("FAIL! iCountTestcases=="+iCountTestcases+", iCountErrors=="+iCountErrors);
return 1;
}
}
public static void RunTests()
{
// The current implementation uses the same character as the default NumberDecimalSeparator
// for a culture, but this is an implementation detail and could change. No user overrides
// are respected.
String GDecimalSeparator = Utilities.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Standard formats
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat); // no regressions
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, GDecimalSeparator));
VerifyToString(ts, "G", Support.GFormat(ts, GDecimalSeparator));
}
// Custom formats
TimeSpan ts1 = new TimeSpan(1, 2, 3, 4, 56);
VerifyToString(ts1, "d'-'", "1-");
VerifyToString(ts1, "%d", "1");
VerifyToString(ts1, "dd", "01");
VerifyToString(ts1, "ddd", "001");
VerifyToString(ts1, "dddd", "0001");
VerifyToString(ts1, "ddddd", "00001");
VerifyToString(ts1, "dddddd", "000001");
VerifyToString(ts1, "ddddddd", "0000001");
VerifyToString(ts1, "dddddddd", "00000001");
VerifyToString(ts1, "h'-'", "2-");
VerifyToString(ts1, "%h", "2");
VerifyToString(ts1, "hh", "02");
VerifyToString(ts1, "m'-'", "3-");
VerifyToString(ts1, "%m", "3");
VerifyToString(ts1, "mm", "03");
VerifyToString(ts1, "s'-'", "4-");
VerifyToString(ts1, "%s", "4");
VerifyToString(ts1, "ss", "04");
VerifyToString(ts1, "f'-'", "0-");
VerifyToString(ts1, "ff", "05");
VerifyToString(ts1, "fff", "056");
VerifyToString(ts1, "ffff", "0560");
VerifyToString(ts1, "fffff", "05600");
VerifyToString(ts1, "ffffff", "056000");
VerifyToString(ts1, "fffffff", "0560000");
VerifyToString(ts1, "F'-'", "-");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056");
VerifyToString(ts1, "FFFFFFF", "056");
VerifyToString(ts1, "hhmmss", "020304");
ts1 = new TimeSpan(-1, -2, -3, -4, -56);
VerifyToString(ts1, "d'-'", "1-");
VerifyToString(ts1, "%d", "1");
VerifyToString(ts1, "dd", "01");
VerifyToString(ts1, "ddd", "001");
VerifyToString(ts1, "dddd", "0001");
VerifyToString(ts1, "ddddd", "00001");
VerifyToString(ts1, "dddddd", "000001");
VerifyToString(ts1, "ddddddd", "0000001");
VerifyToString(ts1, "dddddddd", "00000001");
VerifyToString(ts1, "h'-'", "2-");
VerifyToString(ts1, "%h", "2");
VerifyToString(ts1, "hh", "02");
VerifyToString(ts1, "m'-'", "3-");
VerifyToString(ts1, "%m", "3");
VerifyToString(ts1, "mm", "03");
VerifyToString(ts1, "s'-'", "4-");
VerifyToString(ts1, "%s", "4");
VerifyToString(ts1, "ss", "04");
VerifyToString(ts1, "f'-'", "0-");
VerifyToString(ts1, "ff", "05");
VerifyToString(ts1, "fff", "056");
VerifyToString(ts1, "ffff", "0560");
VerifyToString(ts1, "fffff", "05600");
VerifyToString(ts1, "ffffff", "056000");
VerifyToString(ts1, "fffffff", "0560000");
VerifyToString(ts1, "F'-'", "-");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056");
VerifyToString(ts1, "FFFFFFF", "056");
VerifyToString(ts1, "hhmmss", "020304");
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToString(ts1, "'.'F", ".");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056007");
VerifyToString(ts1, "FFFFFFF", "0560078");
ts1 = new TimeSpan(1, 2, 3, 4).Add(new TimeSpan(789));
VerifyToString(ts1, "'.'F", ".");
VerifyToString(ts1, "FF", "");
VerifyToString(ts1, "FFF", "");
VerifyToString(ts1, "FFFF", "");
VerifyToString(ts1, "FFFFF", "00007");
VerifyToString(ts1, "FFFFFF", "000078");
VerifyToString(ts1, "FFFFFFF", "0000789");
// Literals
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToString(ts1, "d'd'", "1d");
VerifyToString(ts1, "d' days'", "1 days");
VerifyToString(ts1, "d' days, 'h' hours, 'm' minutes, 's'.'FFFF' seconds'", "1 days, 2 hours, 3 minutes, 4.056 seconds");
// Error formats
foreach (String errorFormat in Support.ErrorFormats)
{
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToStringException<FormatException>(ts1, errorFormat);
}
// Vary current culture
Utilities.CurrentCulture = CultureInfo.InvariantCulture;
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, "."));
VerifyToString(ts, "G", Support.GFormat(ts, "."));
}
Utilities.CurrentCulture = new CultureInfo("en-US");
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, "."));
VerifyToString(ts, "G", Support.GFormat(ts, "."));
}
Utilities.CurrentCulture = new CultureInfo("de-DE");
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, ","));
VerifyToString(ts, "G", Support.GFormat(ts, ","));
}
}
public static void VerifyToString(TimeSpan timeSpan, String expectedResult)
{
iCountTestcases++;
try
{
String result = timeSpan.ToString();
if (verbose)
Logging.WriteLine("{0} ({1}) ==> {2}", Support.PrintTimeSpan(timeSpan), "default", result);
if (result != expectedResult)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Return: '{2}', Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), "default", expectedResult, result);
}
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), "default", ex);
}
}
public static void VerifyToString(TimeSpan timeSpan, String format, String expectedResult)
{
iCountTestcases++;
try
{
String result = timeSpan.ToString(format);
if (verbose)
Logging.WriteLine("{0} ('{1}') ==> {2}", Support.PrintTimeSpan(timeSpan), format, result);
if (result != expectedResult)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Return: '{2}', Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), format, expectedResult, result);
}
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), format, ex);
}
}
public static void VerifyToStringException<TException>(TimeSpan timeSpan, String format) where TException : Exception
{
iCountTestcases++;
if (verbose)
Logging.WriteLine("Expecting {2}: {0} ('{1}')", Support.PrintTimeSpan(timeSpan), format, typeof(TException));
try
{
String result = timeSpan.ToString(format);
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Exception: {2}, Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), format, typeof(TException), result);
}
catch (TException)
{
//Logging.WriteLine("INFO: {0}: {1}", ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), format, ex);
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;
using ViData;
namespace ViCommV2
{
public class ClientManager : IDisposable
{
private static ClientManager _instance;
private readonly IPEndPoint ip;
private readonly Socket socket;
private byte[] buffer;
public FormHelper forms = FormHelper.Instance;
private string guid;
public User user;
public ClientManager(string host, int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = 10;
socket.SendTimeout = 10;
ip = new IPEndPoint(IPAddress.Parse(host), port);
}
public static ClientManager Instance {
get {
if (_instance == null) {
_instance = new ClientManager(Tools.GetIP(), 5555);
}
return _instance;
}
}
public bool Connected {
get { return socket.Connected; }
}
public void Connect()
{
if (socket.Connected) {
return;
}
try {
socket.Connect(ip);
StartReceiving();
}
catch {
MessageBox.Show("Could not connect to server!", "Connecting error!");
}
}
public void Login(string login, byte[] pwd)
{
var p = new Packet(PacketType.Login);
p.User = new User(login, pwd);
Send(p);
}
public void LoginResult(Packet p)
{
var msg = p.Message;
if (p.User != null) {
guid = p.Message;
user = p.User;
var contacts = p.Information.Contacts.ToArray();
forms.Dispatcher.Invoke(new Action(() => {
forms.Main = new MainWindow();
if (forms.Login != null) {
forms.Login.state = LoginWindow.FormState.Logged;
forms.Login.Close();
}
foreach (var c in contacts) {
forms.Main.ListContacts.Items.Add(c);
}
forms.Main.Show();
}));
}
else {
MessageBox.Show(msg, "Login error!");
}
}
public void Register(string name, string email, byte[] pwd)
{
var p = new Packet(PacketType.Register);
p.User = new User(name, email, pwd, Tools.GenerateSalt());
Send(p);
}
public void RegisterResult(Packet p)
{
var result = p.Message[0].ToString();
var msg = p.Message.Substring(1);
// Result of registration
MessageBox.Show(msg, "Register");
if (result == "1") {
Login(p.User.Username, p.User.Password);
forms.Dispatcher.Invoke(new Action(() => {
forms.Register.Registered = true;
forms.Register.Close();
}));
}
}
public void Send(string msg)
{
var p = new Packet(PacketType.MultiChat);
p.User = new User(user.AvatarURI, user.NickColor);
p.Date = DateTime.Now;
p.Sender = user.Nickname;
p.Message = msg;
Send(p);
}
public void Send(Packet p)
{
try {
socket.Send(p.ToBytes());
}
catch (SocketException e) {
App.HandleException(e);
}
catch (Exception e) {
App.HandleException(e);
}
}
public void StartReceiving()
{
FormHelper.isClosing = false;
buffer = new byte[8192];
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
}
private void OnReceive(IAsyncResult ar)
{
try {
if (FormHelper.isClosing) {
return;
}
var readBytes = socket.EndReceive(ar);
if (readBytes > 0) {
Received(new Packet(buffer));
}
buffer = new byte[8192];
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
}
catch (ObjectDisposedException) {}
catch (SocketException e) {
App.HandleException(e);
}
catch (Exception e) {
App.HandleException(e);
}
}
private void Received(Packet p)
{
switch (p.Type) {
case PacketType.Login:
LoginResult(p);
break;
case PacketType.Disconnect:
Disconnect(p);
break;
case PacketType.Register:
RegisterResult(p);
break;
case PacketType.Information:
Information(p);
break;
case PacketType.SingleChat:
// Reserved
break;
case PacketType.MultiChat:
AppendText(p);
break;
default:
break;
}
}
private void Information(Packet p)
{
var main = forms.Main;
if (p.Information.Type == InformationType.Joining) {
AddItemToListBox(main.ListContacts, p.Information.User);
AppendText(p);
}
else if (p.Information.Type == InformationType.Leaving) {
RemoveItemFromListBox(main.ListContacts, p.Information.User);
AppendText(p);
}
else if (p.Information.Type == InformationType.Writing) {
if (p.Information.Message == "started") {
ChangeItemInListBox(main.ListContacts, p.Information.User, "*| " + p.Information.User);
}
else {
ChangeItemInListBox(main.ListContacts, "*| " + p.Information.User, p.Information.User);
}
}
}
public void AddItemToListBox(ListBox list, object o)
{
forms.Dispatcher.Invoke(new Action(() => { list.Items.Add(o); }));
}
public void RemoveItemFromListBox(ListBox list, object o)
{
forms.Dispatcher.Invoke(new Action(() => {
if (list.Items.Contains(o)) {
list.Items.Remove(o);
}
}));
}
public void ChangeItemInListBox(ListBox list, object o, object changed)
{
forms.Dispatcher.Invoke(new Action(() => {
if (list.Items.Contains(o)) {
var i = list.Items.IndexOf(o);
list.Items[i] = changed;
}
}));
}
private void AppendText(Packet packet)
{
forms.Dispatcher.Invoke(new Action(() => {
var main = forms.Main;
var sound = new Sound();
if (packet.Type == PacketType.Information) {
sound.Play(Sound.SoundType.Available);
var msg = packet.Information.User + " " + packet.Information.Message;
main.AppendInfoText(string.Format("* {0}", msg));
}
else {
MainWindow.RowType rowType;
if (packet.Sender != user.Nickname) {
rowType = MainWindow.RowType.Sender;
sound.Play(Sound.SoundType.Message);
}
else {
rowType = MainWindow.RowType.User;
}
main.AppendText(packet, rowType);
}
}));
}
public void Disconnect(Packet p)
{
MessageBox.Show(p.Message, p.Sender);
forms.Dispatcher.Invoke(new Action(() => {
forms.Login = new LoginWindow();
forms.Login.Show();
if (forms.Main != null) {
forms.Main.State = MainWindow.FormState.Close;
forms.Main.CloseWindow();
}
}));
Disconnect(true);
}
public void Disconnect(bool server)
{
if (server == false) {
if (socket.Connected) {
var p = new Packet(PacketType.Disconnect);
p.Message = guid;
socket.Send(p.ToBytes());
}
}
CloseConnection();
}
private void CloseConnection()
{
if (socket != null) {
socket.Close();
}
_instance = null;
}
#region Dispose Implementation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~ClientManager()
{
Dispose(false);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (_disposed) {
return;
}
if (disposing) {
// Free any other managed objects here.
socket.Dispose();
}
// Free any unmanaged objects here.
_disposed = true;
}
#endregion Dispose Implementation
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
// ReSharper disable once CheckNamespace
namespace System
{
[DebuggerStepThrough]
internal static class SharedTypeExtensions
{
public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type;
public static bool IsNullableType(this Type type)
{
var typeInfo = type.GetTypeInfo();
return !typeInfo.IsValueType
|| (typeInfo.IsGenericType
&& (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)));
}
public static Type MakeNullable(this Type type)
=> type.IsNullableType()
? type
: typeof(Nullable<>).MakeGenericType(type);
public static bool IsInteger(this Type type)
{
type = type.UnwrapNullableType();
return (type == typeof(int))
|| (type == typeof(long))
|| (type == typeof(short))
|| (type == typeof(byte))
|| (type == typeof(uint))
|| (type == typeof(ulong))
|| (type == typeof(ushort))
|| (type == typeof(sbyte))
|| (type == typeof(char));
}
public static PropertyInfo GetAnyProperty(this Type type, string name)
{
var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList();
if (props.Count > 1)
{
throw new AmbiguousMatchException();
}
return props.SingleOrDefault();
}
private static bool IsNonIntegerPrimitive(this Type type)
{
type = type.UnwrapNullableType();
return (type == typeof(bool))
|| (type == typeof(byte[]))
|| (type == typeof(DateTime))
|| (type == typeof(DateTimeOffset))
|| (type == typeof(decimal))
|| (type == typeof(double))
|| (type == typeof(float))
|| (type == typeof(Guid))
|| (type == typeof(string))
|| (type == typeof(TimeSpan))
|| type.GetTypeInfo().IsEnum;
}
public static bool IsPrimitive(this Type type)
=> type.IsInteger() || type.IsNonIntegerPrimitive();
public static bool IsInstantiable(this Type type) => IsInstantiable(type.GetTypeInfo());
private static bool IsInstantiable(TypeInfo type)
=> !type.IsAbstract
&& !type.IsInterface
&& (!type.IsGenericType || !type.IsGenericTypeDefinition);
public static bool IsGrouping(this Type type) => IsGrouping(type.GetTypeInfo());
private static bool IsGrouping(TypeInfo type)
=> type.IsGenericType
&& (type.GetGenericTypeDefinition() == typeof(IGrouping<,>)
|| type.GetGenericTypeDefinition() == typeof(IAsyncGrouping<,>));
public static Type UnwrapEnumType(this Type type)
{
var isNullable = type.IsNullableType();
var underlyingNonNullableType = isNullable ? type.UnwrapNullableType() : type;
if (!underlyingNonNullableType.GetTypeInfo().IsEnum)
{
return type;
}
var underlyingEnumType = Enum.GetUnderlyingType(underlyingNonNullableType);
return isNullable ? MakeNullable(underlyingEnumType) : underlyingEnumType;
}
public static Type GetSequenceType(this Type type)
{
var sequenceType = TryGetSequenceType(type);
if (sequenceType == null)
{
// TODO: Add exception message
throw new ArgumentException();
}
return sequenceType;
}
public static Type TryGetSequenceType(this Type type)
=> type.IsArray
? type.GetElementType()
: type.TryGetElementType(typeof(IDictionary<,>), 1)
?? type.TryGetElementType(typeof(IEnumerable<>))
?? type.TryGetElementType(typeof(IAsyncEnumerable<>));
public static Type TryGetElementType(this Type type, Type interfaceOrBaseType, int elementIndex = 0)
{
if (!type.GetTypeInfo().IsGenericTypeDefinition)
{
var types = GetGenericTypeImplementations(type, interfaceOrBaseType).ToList();
return types.Count == 1 ? types[0].GetTypeInfo().GenericTypeArguments[elementIndex] : null;
}
return null;
}
public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType)
{
var typeInfo = type.GetTypeInfo();
if (!typeInfo.IsGenericTypeDefinition)
{
return (interfaceOrBaseType.GetTypeInfo().IsInterface ? typeInfo.ImplementedInterfaces : type.GetBaseTypes())
.Union(new[] { type })
.Where(
t => t.GetTypeInfo().IsGenericType
&& (t.GetGenericTypeDefinition() == interfaceOrBaseType));
}
return Enumerable.Empty<Type>();
}
public static IEnumerable<Type> GetImplementationTypes(this Type type, Type interfaceOrBaseType)
{
TypeInfo typeInfo = type.GetTypeInfo();
return (interfaceOrBaseType.GetTypeInfo().IsInterface ? typeInfo.ImplementedInterfaces : type.GetBaseTypes())
.Union(new[] { type })
.Where(
t => t.GetTypeInfo().IsGenericType
&& (t.GetGenericTypeDefinition() == interfaceOrBaseType));
}
public static Type GetImplementationType(this Type type, Type interfaceOrBaseType)
=> type.GetGenericTypeImplementations(interfaceOrBaseType)
.FirstOrDefault();
public static bool TryGetImplementationType(this Type type, Type interfaceOrBaseType, out Type implementedInterfaceType)
=> (implementedInterfaceType = type.GetImplementationType(interfaceOrBaseType)) != null;
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
type = type.GetTypeInfo().BaseType;
while (type != null)
{
yield return type;
type = type.GetTypeInfo().BaseType;
}
}
public static IEnumerable<Type> GetTypesInHierarchy(this Type type)
{
while (type != null)
{
yield return type;
type = type.GetTypeInfo().BaseType;
}
}
public static ConstructorInfo GetDeclaredConstructor(this Type type, Type[] types)
{
types = types ?? new Type[0];
return type.GetTypeInfo().DeclaredConstructors
.SingleOrDefault(
c => !c.IsStatic
&& c.GetParameters().Select(p => p.ParameterType).SequenceEqual(types));
}
public static IEnumerable<PropertyInfo> GetPropertiesInHierarchy(this Type type, string name)
{
do
{
var typeInfo = type.GetTypeInfo();
var propertyInfo = typeInfo.GetDeclaredProperty(name);
if (propertyInfo != null
&& !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic)
{
yield return propertyInfo;
}
type = typeInfo.BaseType;
}
while (type != null);
}
public static IEnumerable<MemberInfo> GetMembersInHierarchy(this Type type, string name)
{
// Do the whole hierarchy for properties first since looking for fields is slower.
var currentType = type;
do
{
var typeInfo = currentType.GetTypeInfo();
var propertyInfo = typeInfo.GetDeclaredProperty(name);
if (propertyInfo != null
&& !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic)
{
yield return propertyInfo;
}
currentType = typeInfo.BaseType;
}
while (currentType != null);
currentType = type;
do
{
var fieldInfo = currentType.GetRuntimeFields().FirstOrDefault(f => f.Name == name && !f.IsStatic);
if (fieldInfo != null)
{
yield return fieldInfo;
}
currentType = currentType.GetTypeInfo().BaseType;
}
while (currentType != null);
}
private static readonly Dictionary<Type, object> CommonTypeDictionary = new Dictionary<Type, object>
{
{ typeof(int), default(int) },
{ typeof(Guid), default(Guid) },
{ typeof(DateTime), default(DateTime) },
{ typeof(DateTimeOffset), default(DateTimeOffset) },
{ typeof(long), default(long) },
{ typeof(bool), default(bool) },
{ typeof(double), default(double) },
{ typeof(short), default(short) },
{ typeof(float), default(float) },
{ typeof(byte), default(byte) },
{ typeof(char), default(char) },
{ typeof(uint), default(uint) },
{ typeof(ushort), default(ushort) },
{ typeof(ulong), default(ulong) },
{ typeof(sbyte), default(sbyte) }
};
public static object GetDefaultValue(this Type type)
{
if (!type.GetTypeInfo().IsValueType)
{
return null;
}
// A bit of perf code to avoid calling Activator.CreateInstance for common types and
// to avoid boxing on every call. This is about 50% faster than just calling CreateInstance
// for all value types.
object value;
return CommonTypeDictionary.TryGetValue(type, out value)
? value
: Activator.CreateInstance(type);
}
public static IEnumerable<TypeInfo> GetConstructableTypes(this Assembly assembly)
=> assembly.GetLoadableDefinedTypes().Where(
t => !t.IsAbstract
&& !t.IsGenericTypeDefinition);
public static IEnumerable<TypeInfo> GetLoadableDefinedTypes(this Assembly assembly)
{
try
{
return assembly.DefinedTypes;
}
catch (ReflectionTypeLoadException ex)
{
return ex.Types.Where(t => t != null).Select(IntrospectionExtensions.GetTypeInfo);
}
}
}
}
| |
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 ServantHR.Api.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
using System;
using Eto.Drawing;
using Eto.Forms;
using Eto.iOS.Drawing;
using SD = System.Drawing;
using Foundation;
using UIKit;
using Eto.Mac.Forms;
using System.Collections.Generic;
using System.Linq;
namespace Eto.iOS.Forms
{
public interface IIosViewControllerSource
{
UIViewController Controller { get; set; }
}
public interface IIosView : IMacControlHandler, IIosViewControllerSource
{
}
public abstract class IosView<TControl, TWidget, TCallback> : MacView<TControl, TWidget, TCallback>
where TControl: UIView
where TWidget: Control
where TCallback: Control.ICallback
{
public override UIView ContainerControl { get { return Control; } }
}
public abstract class MacView<TControl, TWidget, TCallback> : MacObject<TControl, TWidget, TCallback>, Control.IHandler, IIosView
where TControl: NSObject
where TWidget: Control
where TCallback: Control.ICallback
{
SizeF? naturalSize;
UIViewController controller;
public bool IsResizing { get; set; }
public UIViewController Controller
{
get { return controller ?? (controller = CreateController()); }
set { controller = value; }
}
protected virtual UIViewController CreateController()
{
return null;
}
public virtual UIView ContentControl { get { return ContainerControl; } }
public virtual UIView EventControl { get { return ContainerControl; } }
public abstract UIView ContainerControl { get; }
public bool AutoSize { get; protected set; }
public SizeF? PreferredSize { get; set; }
public virtual Size MinimumSize { get; set; }
public virtual Size? MaximumSize { get; set; }
public virtual Size Size
{
get { return ContainerControl.Frame.Size.ToEtoSize(); }
set
{
var oldSize = GetPreferredSize(SizeF.MaxValue);
PreferredSize = value;
var newSize = ContainerControl.Frame.Size;
if (value.Width >= 0)
newSize.Width = value.Width;
if (value.Height >= 0)
newSize.Height = value.Height;
ContainerControl.SetFrameSize(newSize);
AutoSize = value.Width == -1 && value.Height == -1;
CreateTracking();
LayoutIfNeeded(oldSize);
}
}
protected virtual bool LayoutIfNeeded(SizeF? oldPreferredSize = null, bool force = false)
{
naturalSize = null;
if (Widget.Loaded)
{
var oldSize = oldPreferredSize ?? ContainerControl.Frame.Size.ToEto();
var newSize = GetPreferredSize(SizeF.MaxValue);
if (newSize != oldSize || force)
{
var container = Widget.Parent.GetMacContainer();
if (container != null)
container.LayoutParent(true);
return true;
}
}
return false;
}
protected virtual void LayoutIfNeeded(Action action)
{
if (Widget.Loaded)
{
var size = GetPreferredSize(SizeF.MaxValue);
action();
LayoutIfNeeded(size);
}
else
action();
}
protected virtual SizeF GetNaturalSize(SizeF availableSize)
{
if (naturalSize != null)
return naturalSize.Value;
var control = Control as UIView;
if (control != null)
{
CoreGraphics.CGSize? size = (Widget.Loaded) ? (CoreGraphics.CGSize?)control.Frame.Size : null;
IsResizing = true;
control.SizeToFit();
naturalSize = control.Frame.Size.ToEto();
if (size != null)
control.SetFrameSize(size.Value);
IsResizing = false;
return naturalSize.Value;
}
return Size.Empty;
}
public virtual SizeF GetPreferredSize(SizeF availableSize)
{
var size = GetNaturalSize(availableSize);
if (!AutoSize && PreferredSize != null)
{
var preferredSize = PreferredSize.Value;
if (preferredSize.Width >= 0)
size.Width = preferredSize.Width;
if (preferredSize.Height >= 0)
size.Height = preferredSize.Height;
}
if (MinimumSize != Size.Empty)
size = SizeF.Max(size, MinimumSize);
if (MaximumSize != null)
size = SizeF.Min(size, MaximumSize.Value);
return size;
}
protected MacView()
{
this.AutoSize = true;
}
public virtual Size PositionOffset { get { return Size.Empty; } }
void CreateTracking()
{
/*
* use TOUCHES
if (!mouseMove)
return;
if (tracking != null)
Control.RemoveTrackingArea (tracking);
mouseDelegate = new MouseDelegate{ Widget = this.Widget, View = Control };
tracking = new NSTrackingArea (new SD.RectangleF (new SD.PointF (0, 0), Control.Frame.Size),
NSTrackingAreaOptions.ActiveAlways | NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.EnabledDuringMouseDrag,
mouseDelegate,
new NSDictionary ());
Control.AddTrackingArea (tracking);
*/
}
public virtual void SetParent(Container parent)
{
}
static readonly NSString frameKey = new NSString("frame");
public override void AttachEvent(string handler)
{
switch (handler)
{
case Eto.Forms.Control.MouseDownEvent:
case Eto.Forms.Control.MouseUpEvent:
case Eto.Forms.Control.MouseDoubleClickEvent:
case Eto.Forms.Control.MouseEnterEvent:
case Eto.Forms.Control.MouseLeaveEvent:
case Eto.Forms.Control.KeyDownEvent:
case Eto.Forms.Control.GotFocusEvent:
case Eto.Forms.Control.LostFocusEvent:
break;
case Eto.Forms.Control.MouseMoveEvent:
//mouseMove = true;
CreateTracking();
break;
case Eto.Forms.Control.SizeChangedEvent:
AddControlObserver(frameKey, e =>
{
var h = e.Handler as MacView<TControl,TWidget,TCallback>;
if (!h.IsResizing)
h.Callback.OnSizeChanged(h.Widget, EventArgs.Empty);
});
/*UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
this.AddObserver(null, UIDevice.OrientationDidChangeNotification, delegate {
Widget.OnSizeChanged (EventArgs.Empty);
});*/
/*Control.Window.PostsFrameChangedNotifications = true;
this.AddObserver (UIView.UIViewFrameDidChangeNotification, delegate {
Widget.OnSizeChanged (EventArgs.Empty);
});*/
break;
default:
base.AttachEvent(handler);
break;
}
}
public virtual void Invalidate()
{
EventControl.SetNeedsDisplay();
}
public virtual void Invalidate(Rectangle rect)
{
EventControl.SetNeedsDisplayInRect(rect.ToNS());
}
public Graphics CreateGraphics()
{
throw new NotSupportedException();
}
public virtual void SuspendLayout()
{
}
public virtual void ResumeLayout()
{
}
public void Focus()
{
EventControl.BecomeFirstResponder();
}
public virtual Color BackgroundColor
{
get { return ContainerControl.BackgroundColor.ToEto(); }
set { ContainerControl.BackgroundColor = value.ToNSUI(); }
}
public virtual bool Enabled
{
get { return EventControl.UserInteractionEnabled; }
set { EventControl.UserInteractionEnabled = value; }
}
public bool HasFocus
{
get { return EventControl.IsFirstResponder; }
}
public bool Visible
{
get { return !ContainerControl.Hidden; }
set
{
ContainerControl.Hidden = !value;
LayoutIfNeeded();
}
}
public virtual Font Font
{
get;
set;
}
public virtual void OnPreLoad(EventArgs e)
{
}
public virtual void OnLoad(EventArgs e)
{
}
public virtual void OnLoadComplete(EventArgs e)
{
}
public virtual void OnUnLoad(EventArgs e)
{
}
public IEnumerable<string> SupportedPlatformCommands
{
get { return Enumerable.Empty<string>(); }
}
public void MapPlatformCommand(string systemAction, Command command)
{
}
public PointF PointFromScreen(PointF point)
{
var sdpoint = point.ToNS();
sdpoint = ContainerControl.ConvertPointFromView(sdpoint, null);
sdpoint.Y = ContainerControl.Frame.Height - sdpoint.Y;
return sdpoint.ToEto();
}
public PointF PointToScreen(PointF point)
{
var sdpoint = point.ToNS();
sdpoint.Y = ContainerControl.Frame.Height - sdpoint.Y;
sdpoint = ContainerControl.ConvertPointToView(sdpoint, null);
return sdpoint.ToEto();
}
public Point Location
{
get { return ContainerControl.Frame.Location.ToEtoPoint(); }
}
public string ToolTip
{
get { return null; }
set { }
}
public Cursor Cursor
{
get { return null; }
set { }
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HtmlTextWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// HtmlTextWriter.cs
//
namespace System.Web.UI {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Globalization;
using System.Security.Permissions;
using System.Web.UI.WebControls;
using System.Web.Util;
public class HtmlTextWriter : TextWriter {
private Layout _currentLayout = new Layout(HorizontalAlign.NotSet, true /* wrap */);
private Layout _currentWrittenLayout = null;
internal virtual bool RenderDivAroundHiddenInputs {
get {
return true;
}
}
public virtual void EnterStyle(Style style, HtmlTextWriterTag tag) {
if (!style.IsEmpty || tag != HtmlTextWriterTag.Span) {
style.AddAttributesToRender(this);
RenderBeginTag(tag);
}
}
public virtual void ExitStyle(System.Web.UI.WebControls.Style style, HtmlTextWriterTag tag) {
// Review: This requires that the style doesn't change between beginstyle/endstyle.
if (!style.IsEmpty || tag != HtmlTextWriterTag.Span) {
RenderEndTag();
}
}
internal virtual void OpenDiv() {
OpenDiv(_currentLayout,
(_currentLayout != null) && (_currentLayout.Align != HorizontalAlign.NotSet),
(_currentLayout != null) && !_currentLayout.Wrap);
}
private void OpenDiv(Layout layout, bool writeHorizontalAlign, bool writeWrapping) {
WriteBeginTag("div");
if (writeHorizontalAlign) {
String alignment;
switch (layout.Align) {
case HorizontalAlign.Right:
alignment = "text-align:right";
break;
case HorizontalAlign.Center:
alignment = "text-align:center";
break;
default:
alignment = "text-align:left";
break;
}
WriteAttribute("style", alignment);
}
if (writeWrapping) {
WriteAttribute("mode",
layout.Wrap == true ? "wrap" : "nowrap");
}
Write('>');
_currentWrittenLayout = layout;
}
public virtual bool IsValidFormAttribute(String attribute) {
return true;
}
private TextWriter writer;
private int indentLevel;
private bool tabsPending;
private string tabString;
public const char TagLeftChar = '<';
public const char TagRightChar = '>';
public const string SelfClosingChars = " /";
public const string SelfClosingTagEnd = " />";
public const string EndTagLeftChars = "</";
public const char DoubleQuoteChar = '"';
public const char SingleQuoteChar = '\'';
public const char SpaceChar = ' ';
public const char EqualsChar = '=';
public const char SlashChar = '/';
public const string EqualsDoubleQuoteString = "=\"";
public const char SemicolonChar = ';';
public const char StyleEqualsChar = ':';
public const string DefaultTabString = "\t";
// The DesignerRegion attribute name must be kept in [....] with
// System.Web.UI.Design.DesignerRegion.DesignerRegionNameAttribute
internal const string DesignerRegionAttributeName = "_designerRegion";
private static Hashtable _tagKeyLookupTable;
private static Hashtable _attrKeyLookupTable;
private static TagInformation[] _tagNameLookupArray;
private static AttributeInformation[] _attrNameLookupArray;
private RenderAttribute[] _attrList;
private int _attrCount;
private int _endTagCount;
private TagStackEntry[] _endTags;
private HttpWriter _httpWriter;
private int _inlineCount;
private bool _isDescendant;
private RenderStyle[] _styleList;
private int _styleCount;
private int _tagIndex;
private HtmlTextWriterTag _tagKey;
private string _tagName;
static HtmlTextWriter() {
// register known tags
_tagKeyLookupTable = new Hashtable((int)HtmlTextWriterTag.Xml + 1);
_tagNameLookupArray = new TagInformation[(int)HtmlTextWriterTag.Xml + 1];
RegisterTag(String.Empty, HtmlTextWriterTag.Unknown, TagType.Other);
RegisterTag("a", HtmlTextWriterTag.A, TagType.Inline);
RegisterTag("acronym", HtmlTextWriterTag.Acronym, TagType.Inline);
RegisterTag("address", HtmlTextWriterTag.Address, TagType.Other);
RegisterTag("area", HtmlTextWriterTag.Area, TagType.NonClosing);
RegisterTag("b", HtmlTextWriterTag.B, TagType.Inline);
RegisterTag("base", HtmlTextWriterTag.Base, TagType.NonClosing);
RegisterTag("basefont", HtmlTextWriterTag.Basefont, TagType.NonClosing);
RegisterTag("bdo", HtmlTextWriterTag.Bdo, TagType.Inline);
RegisterTag("bgsound", HtmlTextWriterTag.Bgsound, TagType.NonClosing);
RegisterTag("big", HtmlTextWriterTag.Big, TagType.Inline);
RegisterTag("blockquote", HtmlTextWriterTag.Blockquote, TagType.Other);
RegisterTag("body", HtmlTextWriterTag.Body, TagType.Other);
// Devdiv 852940, BR is a self-closing tag
RegisterTag("br", HtmlTextWriterTag.Br,
BinaryCompatibility.Current.TargetsAtLeastFramework46 ? TagType.NonClosing : TagType.Other);
RegisterTag("button", HtmlTextWriterTag.Button, TagType.Inline);
RegisterTag("caption", HtmlTextWriterTag.Caption, TagType.Other);
RegisterTag("center", HtmlTextWriterTag.Center, TagType.Other);
RegisterTag("cite", HtmlTextWriterTag.Cite, TagType.Inline);
RegisterTag("code", HtmlTextWriterTag.Code, TagType.Inline);
RegisterTag("col", HtmlTextWriterTag.Col, TagType.NonClosing);
RegisterTag("colgroup", HtmlTextWriterTag.Colgroup, TagType.Other);
RegisterTag("del", HtmlTextWriterTag.Del, TagType.Inline);
RegisterTag("dd", HtmlTextWriterTag.Dd, TagType.Inline);
RegisterTag("dfn", HtmlTextWriterTag.Dfn, TagType.Inline);
RegisterTag("dir", HtmlTextWriterTag.Dir, TagType.Other);
RegisterTag("div", HtmlTextWriterTag.Div, TagType.Other);
RegisterTag("dl", HtmlTextWriterTag.Dl, TagType.Other);
RegisterTag("dt", HtmlTextWriterTag.Dt, TagType.Inline);
RegisterTag("em", HtmlTextWriterTag.Em, TagType.Inline);
RegisterTag("embed", HtmlTextWriterTag.Embed, TagType.NonClosing);
RegisterTag("fieldset", HtmlTextWriterTag.Fieldset, TagType.Other);
RegisterTag("font", HtmlTextWriterTag.Font, TagType.Inline);
RegisterTag("form", HtmlTextWriterTag.Form, TagType.Other);
RegisterTag("frame", HtmlTextWriterTag.Frame, TagType.NonClosing);
RegisterTag("frameset", HtmlTextWriterTag.Frameset, TagType.Other);
RegisterTag("h1", HtmlTextWriterTag.H1, TagType.Other);
RegisterTag("h2", HtmlTextWriterTag.H2, TagType.Other);
RegisterTag("h3", HtmlTextWriterTag.H3, TagType.Other);
RegisterTag("h4", HtmlTextWriterTag.H4, TagType.Other);
RegisterTag("h5", HtmlTextWriterTag.H5, TagType.Other);
RegisterTag("h6", HtmlTextWriterTag.H6, TagType.Other);
RegisterTag("head", HtmlTextWriterTag.Head, TagType.Other);
RegisterTag("hr", HtmlTextWriterTag.Hr, TagType.NonClosing);
RegisterTag("html", HtmlTextWriterTag.Html, TagType.Other);
RegisterTag("i", HtmlTextWriterTag.I, TagType.Inline);
RegisterTag("iframe", HtmlTextWriterTag.Iframe, TagType.Other);
RegisterTag("img", HtmlTextWriterTag.Img, TagType.NonClosing);
RegisterTag("input", HtmlTextWriterTag.Input, TagType.NonClosing);
RegisterTag("ins", HtmlTextWriterTag.Ins, TagType.Inline);
RegisterTag("isindex", HtmlTextWriterTag.Isindex, TagType.NonClosing);
RegisterTag("kbd", HtmlTextWriterTag.Kbd, TagType.Inline);
RegisterTag("label", HtmlTextWriterTag.Label, TagType.Inline);
RegisterTag("legend", HtmlTextWriterTag.Legend, TagType.Other);
RegisterTag("li", HtmlTextWriterTag.Li, TagType.Inline);
RegisterTag("link", HtmlTextWriterTag.Link, TagType.NonClosing);
RegisterTag("map", HtmlTextWriterTag.Map, TagType.Other);
RegisterTag("marquee", HtmlTextWriterTag.Marquee, TagType.Other);
RegisterTag("menu", HtmlTextWriterTag.Menu, TagType.Other);
RegisterTag("meta", HtmlTextWriterTag.Meta, TagType.NonClosing);
RegisterTag("nobr", HtmlTextWriterTag.Nobr, TagType.Inline);
RegisterTag("noframes", HtmlTextWriterTag.Noframes, TagType.Other);
RegisterTag("noscript", HtmlTextWriterTag.Noscript, TagType.Other);
RegisterTag("object", HtmlTextWriterTag.Object, TagType.Other);
RegisterTag("ol", HtmlTextWriterTag.Ol, TagType.Other);
RegisterTag("option", HtmlTextWriterTag.Option, TagType.Other);
RegisterTag("p", HtmlTextWriterTag.P, TagType.Inline);
RegisterTag("param", HtmlTextWriterTag.Param, TagType.Other);
RegisterTag("pre", HtmlTextWriterTag.Pre, TagType.Other);
RegisterTag("ruby", HtmlTextWriterTag.Ruby, TagType.Other);
RegisterTag("rt", HtmlTextWriterTag.Rt, TagType.Other);
RegisterTag("q", HtmlTextWriterTag.Q, TagType.Inline);
RegisterTag("s", HtmlTextWriterTag.S, TagType.Inline);
RegisterTag("samp", HtmlTextWriterTag.Samp, TagType.Inline);
RegisterTag("script", HtmlTextWriterTag.Script, TagType.Other);
RegisterTag("select", HtmlTextWriterTag.Select, TagType.Other);
RegisterTag("small", HtmlTextWriterTag.Small, TagType.Other);
RegisterTag("span", HtmlTextWriterTag.Span, TagType.Inline);
RegisterTag("strike", HtmlTextWriterTag.Strike, TagType.Inline);
RegisterTag("strong", HtmlTextWriterTag.Strong, TagType.Inline);
RegisterTag("style", HtmlTextWriterTag.Style, TagType.Other);
RegisterTag("sub", HtmlTextWriterTag.Sub, TagType.Inline);
RegisterTag("sup", HtmlTextWriterTag.Sup, TagType.Inline);
RegisterTag("table", HtmlTextWriterTag.Table, TagType.Other);
RegisterTag("tbody", HtmlTextWriterTag.Tbody, TagType.Other);
RegisterTag("td", HtmlTextWriterTag.Td, TagType.Inline);
RegisterTag("textarea", HtmlTextWriterTag.Textarea, TagType.Inline);
RegisterTag("tfoot", HtmlTextWriterTag.Tfoot, TagType.Other);
RegisterTag("th", HtmlTextWriterTag.Th, TagType.Inline);
RegisterTag("thead", HtmlTextWriterTag.Thead, TagType.Other);
RegisterTag("title", HtmlTextWriterTag.Title, TagType.Other);
RegisterTag("tr", HtmlTextWriterTag.Tr, TagType.Other);
RegisterTag("tt", HtmlTextWriterTag.Tt, TagType.Inline);
RegisterTag("u", HtmlTextWriterTag.U, TagType.Inline);
RegisterTag("ul", HtmlTextWriterTag.Ul, TagType.Other);
RegisterTag("var", HtmlTextWriterTag.Var, TagType.Inline);
RegisterTag("wbr", HtmlTextWriterTag.Wbr, TagType.NonClosing);
RegisterTag("xml", HtmlTextWriterTag.Xml, TagType.Other);
// register known attributes
_attrKeyLookupTable = new Hashtable((int)HtmlTextWriterAttribute.VCardName + 1);
_attrNameLookupArray = new AttributeInformation[(int)HtmlTextWriterAttribute.VCardName + 1];
RegisterAttribute("abbr", HtmlTextWriterAttribute.Abbr, true);
RegisterAttribute("accesskey", HtmlTextWriterAttribute.Accesskey, true);
RegisterAttribute("align", HtmlTextWriterAttribute.Align, false);
RegisterAttribute("alt", HtmlTextWriterAttribute.Alt, true);
RegisterAttribute("autocomplete", HtmlTextWriterAttribute.AutoComplete, false);
RegisterAttribute("axis", HtmlTextWriterAttribute.Axis, true);
RegisterAttribute("background", HtmlTextWriterAttribute.Background, true, true);
RegisterAttribute("bgcolor", HtmlTextWriterAttribute.Bgcolor, false);
RegisterAttribute("border", HtmlTextWriterAttribute.Border, false);
RegisterAttribute("bordercolor", HtmlTextWriterAttribute.Bordercolor, false);
RegisterAttribute("cellpadding", HtmlTextWriterAttribute.Cellpadding, false);
RegisterAttribute("cellspacing", HtmlTextWriterAttribute.Cellspacing, false);
RegisterAttribute("checked", HtmlTextWriterAttribute.Checked, false);
RegisterAttribute("class", HtmlTextWriterAttribute.Class, true);
RegisterAttribute("cols", HtmlTextWriterAttribute.Cols, false);
RegisterAttribute("colspan", HtmlTextWriterAttribute.Colspan, false);
RegisterAttribute("content", HtmlTextWriterAttribute.Content, true);
RegisterAttribute("coords", HtmlTextWriterAttribute.Coords, false);
RegisterAttribute("dir", HtmlTextWriterAttribute.Dir, false);
RegisterAttribute("disabled", HtmlTextWriterAttribute.Disabled, false);
RegisterAttribute("for", HtmlTextWriterAttribute.For, false);
RegisterAttribute("headers", HtmlTextWriterAttribute.Headers, true);
RegisterAttribute("height", HtmlTextWriterAttribute.Height, false);
RegisterAttribute("href", HtmlTextWriterAttribute.Href, true, true);
RegisterAttribute("id", HtmlTextWriterAttribute.Id, false);
RegisterAttribute("longdesc", HtmlTextWriterAttribute.Longdesc, true, true);
RegisterAttribute("maxlength", HtmlTextWriterAttribute.Maxlength, false);
RegisterAttribute("multiple", HtmlTextWriterAttribute.Multiple, false);
RegisterAttribute("name", HtmlTextWriterAttribute.Name, false);
RegisterAttribute("nowrap", HtmlTextWriterAttribute.Nowrap, false);
RegisterAttribute("onclick", HtmlTextWriterAttribute.Onclick, true);
RegisterAttribute("onchange", HtmlTextWriterAttribute.Onchange, true);
RegisterAttribute("readonly", HtmlTextWriterAttribute.ReadOnly, false);
RegisterAttribute("rel", HtmlTextWriterAttribute.Rel, false);
RegisterAttribute("rows", HtmlTextWriterAttribute.Rows, false);
RegisterAttribute("rowspan", HtmlTextWriterAttribute.Rowspan, false);
RegisterAttribute("rules", HtmlTextWriterAttribute.Rules, false);
RegisterAttribute("scope", HtmlTextWriterAttribute.Scope, false);
RegisterAttribute("selected", HtmlTextWriterAttribute.Selected, false);
RegisterAttribute("shape", HtmlTextWriterAttribute.Shape, false);
RegisterAttribute("size", HtmlTextWriterAttribute.Size, false);
RegisterAttribute("src", HtmlTextWriterAttribute.Src, true, true);
RegisterAttribute("style", HtmlTextWriterAttribute.Style, false);
RegisterAttribute("tabindex", HtmlTextWriterAttribute.Tabindex, false);
RegisterAttribute("target", HtmlTextWriterAttribute.Target, false);
RegisterAttribute("title", HtmlTextWriterAttribute.Title, true);
RegisterAttribute("type", HtmlTextWriterAttribute.Type, false);
RegisterAttribute("usemap", HtmlTextWriterAttribute.Usemap, false);
RegisterAttribute("valign", HtmlTextWriterAttribute.Valign, false);
RegisterAttribute("value", HtmlTextWriterAttribute.Value, true);
RegisterAttribute("vcard_name", HtmlTextWriterAttribute.VCardName, false);
RegisterAttribute("width", HtmlTextWriterAttribute.Width, false);
RegisterAttribute("wrap", HtmlTextWriterAttribute.Wrap, false);
RegisterAttribute(DesignerRegionAttributeName, HtmlTextWriterAttribute.DesignerRegion, false);
}
public override Encoding Encoding {
get {
return writer.Encoding;
}
}
// Gets or sets the new line character to use.
public override string NewLine {
get {
return writer.NewLine;
}
set {
writer.NewLine = value;
}
}
// Gets or sets the number of spaces to indent.
public int Indent {
get {
return indentLevel;
}
set {
Debug.Assert(value >= 0, "Bogus Indent... probably caused by mismatched Indent++ and Indent--");
if (value < 0) {
value = 0;
}
indentLevel = value;
}
}
//Gets or sets the TextWriter to use.
public TextWriter InnerWriter {
get {
return writer;
}
set {
writer = value;
_httpWriter = value as HttpWriter;
}
}
/*
//
*/
public virtual void BeginRender() {
}
//Closes the document being written to.
public override void Close() {
writer.Close();
}
public virtual void EndRender() {
}
public virtual void EnterStyle(System.Web.UI.WebControls.Style style) {
EnterStyle(style, HtmlTextWriterTag.Span);
}
public virtual void ExitStyle(System.Web.UI.WebControls.Style style) {
ExitStyle(style, HtmlTextWriterTag.Span);
}
public override void Flush() {
writer.Flush();
}
protected virtual void OutputTabs() {
if (tabsPending) {
for (int i=0; i < indentLevel; i++) {
writer.Write(tabString);
}
tabsPending = false;
}
}
//Writes a string to the text stream.
public override void Write(string s) {
if (tabsPending) {
OutputTabs();
}
writer.Write(s);
}
//Writes the text representation of a Boolean value to the text stream.
public override void Write(bool value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
//Writes a character to the text stream.
public override void Write(char value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes a character array to the text stream.
public override void Write(char[] buffer) {
if (tabsPending) {
OutputTabs();
}
writer.Write(buffer);
}
// Writes a subarray of characters to the text stream.
public override void Write(char[] buffer, int index, int count) {
if (tabsPending) {
OutputTabs();
}
writer.Write(buffer, index, count);
}
// Writes the text representation of a Double to the text stream.
public override void Write(double value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes the text representation of a Single to the text stream.
public override void Write(float value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes the text representation of an integer to the text stream.
public override void Write(int value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes the text representation of an 8-byte integer to the text stream.
public override void Write(long value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes the text representation of an object to the text stream.
public override void Write(object value) {
if (tabsPending) {
OutputTabs();
}
writer.Write(value);
}
// Writes out a formatted string, using the same semantics as specified.
public override void Write(string format, object arg0) {
if (tabsPending) {
OutputTabs();
}
writer.Write(format, arg0);
}
// Writes out a formatted string, using the same semantics as specified.
public override void Write(string format, object arg0, object arg1) {
if (tabsPending) {
OutputTabs();
}
writer.Write(format, arg0, arg1);
}
// Writes out a formatted string, using the same semantics as specified.
public override void Write(string format, params object[] arg) {
if (tabsPending) {
OutputTabs();
}
writer.Write(format, arg);
}
// Writes the specified string to a line without tabs.
public void WriteLineNoTabs(string s) {
writer.WriteLine(s);
tabsPending = true;
}
// Writes the specified string followed by a line terminator to the text stream.
public override void WriteLine(string s) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(s);
tabsPending = true;
}
// Writes a line terminator.
public override void WriteLine() {
writer.WriteLine();
tabsPending = true;
}
// Writes the text representation of a Boolean followed by a line terminator to the text stream.
public override void WriteLine(bool value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(char value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(char[] buffer) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(buffer);
tabsPending = true;
}
public override void WriteLine(char[] buffer, int index, int count) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(buffer, index, count);
tabsPending = true;
}
public override void WriteLine(double value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(float value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(int value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(long value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(object value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
public override void WriteLine(string format, object arg0) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(format, arg0);
tabsPending = true;
}
public override void WriteLine(string format, object arg0, object arg1) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(format, arg0, arg1);
tabsPending = true;
}
public override void WriteLine(string format, params object[] arg) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(format, arg);
tabsPending = true;
}
[CLSCompliant(false)]
public override void WriteLine(UInt32 value) {
if (tabsPending) {
OutputTabs();
}
writer.WriteLine(value);
tabsPending = true;
}
protected static void RegisterTag(string name, HtmlTextWriterTag key) {
RegisterTag(name, key, TagType.Other);
}
private static void RegisterTag(string name, HtmlTextWriterTag key, TagType type) {
string nameLCase = name.ToLower(CultureInfo.InvariantCulture);
_tagKeyLookupTable.Add(nameLCase, key);
// Pre-resolve the end tag
string endTag = null;
if (type != TagType.NonClosing && key != HtmlTextWriterTag.Unknown) {
endTag = EndTagLeftChars + nameLCase + TagRightChar.ToString(CultureInfo.InvariantCulture);
}
if ((int)key < _tagNameLookupArray.Length) {
_tagNameLookupArray[(int)key] = new TagInformation(name, type, endTag);
}
}
protected static void RegisterAttribute(string name, HtmlTextWriterAttribute key) {
RegisterAttribute(name, key, false);
}
private static void RegisterAttribute(string name, HtmlTextWriterAttribute key, bool encode) {
RegisterAttribute(name, key, encode, false);
}
private static void RegisterAttribute(string name, HtmlTextWriterAttribute key, bool encode, bool isUrl) {
string nameLCase = name.ToLower(CultureInfo.InvariantCulture);
_attrKeyLookupTable.Add(nameLCase, key);
if ((int)key < _attrNameLookupArray.Length) {
_attrNameLookupArray[(int)key] = new AttributeInformation(name, encode, isUrl);
}
}
protected static void RegisterStyle(string name, HtmlTextWriterStyle key) {
CssTextWriter.RegisterAttribute(name, key);
}
public HtmlTextWriter(TextWriter writer) : this(writer, DefaultTabString) {
}
public HtmlTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) {
this.writer = writer;
this.tabString = tabString;
indentLevel = 0;
tabsPending = false;
// If it's an http writer, save it
_httpWriter = writer as HttpWriter;
_isDescendant = (GetType() != typeof(HtmlTextWriter));
_attrCount = 0;
_styleCount = 0;
_endTagCount = 0;
_inlineCount = 0;
}
protected HtmlTextWriterTag TagKey {
get {
return _tagKey;
}
set {
_tagIndex = (int) value;
if (_tagIndex < 0 || _tagIndex >= _tagNameLookupArray.Length) {
throw new ArgumentOutOfRangeException("value");
}
_tagKey = value;
// If explicitly setting to uknown, keep the old tag name. This allows a string tag
// to be set without clobbering it if setting TagKey to itself.
if (value != HtmlTextWriterTag.Unknown) {
_tagName = _tagNameLookupArray[_tagIndex].name;
}
}
}
protected string TagName {
get {
return _tagName;
}
set {
_tagName = value;
_tagKey = GetTagKey(_tagName);
_tagIndex = (int) _tagKey;
Debug.Assert(_tagIndex >= 0 && _tagIndex < _tagNameLookupArray.Length);
}
}
public virtual void AddAttribute(string name,string value) {
HtmlTextWriterAttribute attributeKey = GetAttributeKey(name);
value = EncodeAttributeValue(attributeKey, value);
AddAttribute(name, value, attributeKey);
}
//do not fix this spelling error
//believe it or not, it is a backwards breaking change for languages that
//support late binding with named parameters VB.Net
public virtual void AddAttribute(string name,string value, bool fEndode) {
value = EncodeAttributeValue(value, fEndode);
AddAttribute(name, value, GetAttributeKey(name));
}
public virtual void AddAttribute(HtmlTextWriterAttribute key,string value) {
int attributeIndex = (int) key;
if (attributeIndex >= 0 && attributeIndex < _attrNameLookupArray.Length) {
AttributeInformation info = _attrNameLookupArray[attributeIndex];
AddAttribute(info.name,value,key, info.encode, info.isUrl);
}
}
public virtual void AddAttribute(HtmlTextWriterAttribute key,string value, bool fEncode) {
int attributeIndex = (int) key;
if (attributeIndex >= 0 && attributeIndex < _attrNameLookupArray.Length) {
AttributeInformation info = _attrNameLookupArray[attributeIndex];
AddAttribute(info.name,value,key, fEncode, info.isUrl);
}
}
protected virtual void AddAttribute(string name, string value, HtmlTextWriterAttribute key) {
AddAttribute(name, value, key, false, false);
}
private void AddAttribute(string name, string value, HtmlTextWriterAttribute key, bool encode, bool isUrl) {
if(_attrList == null) {
_attrList = new RenderAttribute[20];
}
else if (_attrCount >= _attrList.Length) {
RenderAttribute[] newArray = new RenderAttribute[_attrList.Length * 2];
Array.Copy(_attrList, newArray, _attrList.Length);
_attrList = newArray;
}
RenderAttribute attr;
attr.name = name;
attr.value = value;
attr.key = key;
attr.encode = encode;
attr.isUrl = isUrl;
_attrList[_attrCount] = attr;
_attrCount++;
}
public virtual void AddStyleAttribute(string name, string value) {
AddStyleAttribute(name, value, CssTextWriter.GetStyleKey(name));
}
public virtual void AddStyleAttribute(HtmlTextWriterStyle key, string value) {
AddStyleAttribute(CssTextWriter.GetStyleName(key), value, key);
}
protected virtual void AddStyleAttribute(string name, string value, HtmlTextWriterStyle key) {
if(_styleList == null) {
_styleList = new RenderStyle[20];
}
else if (_styleCount > _styleList.Length) {
RenderStyle[] newArray = new RenderStyle[_styleList.Length * 2];
Array.Copy(_styleList, newArray, _styleList.Length);
_styleList = newArray;
}
RenderStyle style;
style.name = name;
style.key = key;
string attributeValue = value;
if (CssTextWriter.IsStyleEncoded(key)) {
// note that only css attributes in an inline style value need to be attribute encoded
// since CssTextWriter is used to render both embedded stylesheets and style attributes
// the attribute encoding is done here.
attributeValue = HttpUtility.HtmlAttributeEncode(value);
}
style.value = attributeValue;
_styleList[_styleCount] = style;
_styleCount++;
}
protected string EncodeAttributeValue(string value, bool fEncode) {
if (value == null) {
return null;
}
if (!fEncode)
return value;
return HttpUtility.HtmlAttributeEncode(value);
}
protected virtual string EncodeAttributeValue(HtmlTextWriterAttribute attrKey, string value) {
bool encode = true;
if (0 <= (int)attrKey && (int)attrKey < _attrNameLookupArray.Length) {
encode = _attrNameLookupArray[(int)attrKey].encode;
}
return EncodeAttributeValue(value, encode);
}
// This does minimal URL encoding by converting spaces in the url to "%20".
protected string EncodeUrl(string url) {
// VSWhidbey 454348: escaped spaces in UNC share paths don't work in IE, so
// we're not going to encode if it's a share.
if (!UrlPath.IsUncSharePath(url)) {
return HttpUtility.UrlPathEncode(url);
}
return url;
}
protected HtmlTextWriterAttribute GetAttributeKey(string attrName) {
if (!String.IsNullOrEmpty(attrName)) {
object key = _attrKeyLookupTable[attrName.ToLower(CultureInfo.InvariantCulture)];
if (key != null)
return(HtmlTextWriterAttribute)key;
}
return(HtmlTextWriterAttribute)(-1);
}
protected string GetAttributeName(HtmlTextWriterAttribute attrKey) {
if ((int)attrKey >= 0 && (int)attrKey < _attrNameLookupArray.Length)
return _attrNameLookupArray[(int)attrKey].name;
return string.Empty;
}
protected HtmlTextWriterStyle GetStyleKey(string styleName) {
return CssTextWriter.GetStyleKey(styleName);
}
protected string GetStyleName(HtmlTextWriterStyle styleKey) {
return CssTextWriter.GetStyleName(styleKey);
}
protected virtual HtmlTextWriterTag GetTagKey(string tagName) {
if (!String.IsNullOrEmpty(tagName)) {
object key = _tagKeyLookupTable[tagName.ToLower(CultureInfo.InvariantCulture)];
if (key != null)
return(HtmlTextWriterTag)key;
}
return HtmlTextWriterTag.Unknown;
}
protected virtual string GetTagName(HtmlTextWriterTag tagKey) {
int tagIndex = (int) tagKey;
if (tagIndex >= 0 && tagIndex < _tagNameLookupArray.Length)
return _tagNameLookupArray[tagIndex].name;
return string.Empty;
}
protected bool IsAttributeDefined(HtmlTextWriterAttribute key) {
for (int i = 0; i < _attrCount; i++) {
if (_attrList[i].key == key) {
return true;
}
}
return false;
}
protected bool IsAttributeDefined(HtmlTextWriterAttribute key, out string value) {
value = null;
for (int i = 0; i < _attrCount; i++) {
if (_attrList[i].key == key) {
value = _attrList[i].value;
return true;
}
}
return false;
}
protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key) {
for (int i = 0; i < _styleCount; i++) {
if (_styleList[i].key == key) {
return true;
}
}
return false;
}
protected bool IsStyleAttributeDefined(HtmlTextWriterStyle key, out string value) {
value = null;
for (int i = 0; i < _styleCount; i++) {
if (_styleList[i].key == key) {
value = _styleList[i].value;
return true;
}
}
return false;
}
protected virtual bool OnAttributeRender(string name, string value, HtmlTextWriterAttribute key) {
return true;
}
protected virtual bool OnStyleAttributeRender(string name, string value, HtmlTextWriterStyle key) {
return true;
}
protected virtual bool OnTagRender(string name, HtmlTextWriterTag key) {
return true;
}
protected string PopEndTag() {
if (_endTagCount <= 0) {
throw new InvalidOperationException(SR.GetString(SR.HTMLTextWriterUnbalancedPop));
}
_endTagCount--;
TagKey = _endTags[_endTagCount].tagKey;
return _endTags[_endTagCount].endTagText;
}
protected void PushEndTag(string endTag) {
if(_endTags == null) {
_endTags = new TagStackEntry[16];
}
else if (_endTagCount >= _endTags.Length) {
TagStackEntry[] newArray = new TagStackEntry[_endTags.Length * 2];
Array.Copy(_endTags, newArray, _endTags.Length);
_endTags = newArray;
}
_endTags[_endTagCount].tagKey = _tagKey;
_endTags[_endTagCount].endTagText= endTag;
_endTagCount++;
}
// This calls filers out all attributes and style attributes by calling OnAttributeRender
// and OnStyleAttributeRender on all properites and updates the lists</para>
protected virtual void FilterAttributes() {
// Create the filtered list of styles
int newStyleCount = 0;
for (int i = 0; i < _styleCount; i++) {
RenderStyle style = _styleList[i];
if (OnStyleAttributeRender(style.name, style.value, style.key)) {
// Update the list. This can be done in place
_styleList[newStyleCount] = style;
newStyleCount++;
}
}
// Update the count
_styleCount = newStyleCount;
// Create the filtered list of attributes
int newAttrCount = 0;
for (int i = 0; i < _attrCount; i++) {
RenderAttribute attr = _attrList[i];
if (OnAttributeRender(attr.name, attr.value, attr.key)) {
// Update the list. This can be done in place
_attrList[newAttrCount] = attr;
newAttrCount++;
}
}
// Update the count
_attrCount = newAttrCount;
}
public virtual void RenderBeginTag(string tagName) {
this.TagName = tagName;
RenderBeginTag(_tagKey);
}
public virtual void RenderBeginTag(HtmlTextWriterTag tagKey) {
this.TagKey = tagKey;
bool renderTag = true;
if (_isDescendant) {
renderTag = OnTagRender(_tagName, _tagKey);
// Inherited renderers will be expecting to be able to filter any of the attributes at this point
FilterAttributes();
// write text before begin tag
string textBeforeTag = RenderBeforeTag();
if (textBeforeTag != null) {
if (tabsPending) {
OutputTabs();
}
writer.Write(textBeforeTag);
}
}
// gather information about this tag.
TagInformation tagInfo = _tagNameLookupArray[_tagIndex];
TagType tagType = tagInfo.tagType;
bool renderEndTag = renderTag && (tagType != TagType.NonClosing);
string endTag = renderEndTag? tagInfo.closingTag : null;
// write the begin tag
if (renderTag) {
if (tabsPending) {
OutputTabs();
}
writer.Write(TagLeftChar);
writer.Write(_tagName);
string styleValue = null;
for (int i = 0; i < _attrCount; i++) {
RenderAttribute attr = _attrList[i];
if (attr.key == HtmlTextWriterAttribute.Style) {
// append style attribute in with other styles
styleValue = attr.value;
}
else {
writer.Write(SpaceChar);
writer.Write(attr.name);
if (attr.value != null) {
writer.Write(EqualsDoubleQuoteString);
string attrValue = attr.value;
if (attr.isUrl) {
if (attr.key != HtmlTextWriterAttribute.Href || !attrValue.StartsWith("javascript:", StringComparison.Ordinal)) {
attrValue = EncodeUrl(attrValue);
}
}
if (attr.encode) {
WriteHtmlAttributeEncode(attrValue);
}
else {
writer.Write(attrValue);
}
writer.Write(DoubleQuoteChar);
}
}
}
if (_styleCount > 0 || styleValue != null) {
writer.Write(SpaceChar);
writer.Write("style");
writer.Write(EqualsDoubleQuoteString);
CssTextWriter.WriteAttributes(writer, _styleList, _styleCount);
if (styleValue != null) {
writer.Write(styleValue);
}
writer.Write(DoubleQuoteChar);
}
if (tagType == TagType.NonClosing) {
writer.Write(SelfClosingTagEnd);
}
else {
writer.Write(TagRightChar);
}
}
string textBeforeContent = RenderBeforeContent();
if (textBeforeContent != null) {
if (tabsPending) {
OutputTabs();
}
writer.Write(textBeforeContent);
}
// write text before the content
if (renderEndTag) {
if (tagType == TagType.Inline) {
_inlineCount += 1;
}
else {
// writeline and indent before rendering content
WriteLine();
Indent++;
}
// Manually build end tags for unknown tag types.
if (endTag == null) {
endTag = EndTagLeftChars + _tagName + TagRightChar.ToString(CultureInfo.InvariantCulture);
}
}
if (_isDescendant) {
// append text after the tag
string textAfterTag = RenderAfterTag();
if (textAfterTag != null) {
endTag = (endTag == null) ? textAfterTag : textAfterTag + endTag;
}
// build end content and push it on stack to write in RenderEndTag
// prepend text after the content
string textAfterContent = RenderAfterContent();
if (textAfterContent != null) {
endTag = (endTag == null) ? textAfterContent : textAfterContent + endTag;
}
}
// push end tag onto stack
PushEndTag(endTag);
// flush attribute and style lists for next tag
_attrCount = 0;
_styleCount = 0;
}
public virtual void RenderEndTag() {
string endTag = PopEndTag();
if (endTag != null) {
if (_tagNameLookupArray[_tagIndex].tagType == TagType.Inline) {
_inlineCount -= 1;
// Never inject crlfs at end of inline tags.
//
Write(endTag);
}
else {
// unindent if not an inline tag
WriteLine();
this.Indent--;
Write(endTag);
}
}
}
protected virtual string RenderBeforeTag() {
return null;
}
protected virtual string RenderBeforeContent() {
return null;
}
protected virtual string RenderAfterContent() {
return null;
}
protected virtual string RenderAfterTag() {
return null;
}
public virtual void WriteAttribute(string name, string value) {
WriteAttribute(name, value, false /*encode*/);
}
public virtual void WriteAttribute(string name, string value, bool fEncode) {
writer.Write(SpaceChar);
writer.Write(name);
if (value != null) {
writer.Write(EqualsDoubleQuoteString);
if (fEncode) {
WriteHtmlAttributeEncode(value);
}
else {
writer.Write(value);
}
writer.Write(DoubleQuoteChar);
}
}
public virtual void WriteBeginTag(string tagName) {
if (tabsPending) {
OutputTabs();
}
writer.Write(TagLeftChar);
writer.Write(tagName);
}
public virtual void WriteBreak() {
// Space between br and / is for improved html compatibility. See XHTML 1.0 specification, section C.2.
Write("<br />");
}
// DevDiv 33149: A backward compat. switch for Everett rendering
internal void WriteObsoleteBreak() {
Write("<br>");
}
public virtual void WriteFullBeginTag(string tagName) {
if (tabsPending) {
OutputTabs();
}
writer.Write(TagLeftChar);
writer.Write(tagName);
writer.Write(TagRightChar);
}
public virtual void WriteEndTag(string tagName) {
if (tabsPending) {
OutputTabs();
}
writer.Write(TagLeftChar);
writer.Write(SlashChar);
writer.Write(tagName);
writer.Write(TagRightChar);
}
public virtual void WriteStyleAttribute(string name, string value) {
WriteStyleAttribute(name, value, false /*encode*/);
}
public virtual void WriteStyleAttribute(string name, string value, bool fEncode) {
writer.Write(name);
writer.Write(StyleEqualsChar);
if (fEncode) {
WriteHtmlAttributeEncode(value);
}
else {
writer.Write(value);
}
writer.Write(SemicolonChar);
}
internal void WriteUTF8ResourceString(IntPtr pv, int offset, int size, bool fAsciiOnly) {
// If we have an http writer, we can use the faster code path. Otherwise,
// get a String out of the resource and write it.
if (_httpWriter != null) {
if (tabsPending) {
OutputTabs();
}
_httpWriter.WriteUTF8ResourceString(pv, offset, size, fAsciiOnly);
}
else {
Write(StringResourceManager.ResourceToString(pv, offset, size));
}
}
public virtual void WriteEncodedUrl(String url) {
int i = url.IndexOf('?');
if (i != -1) {
WriteUrlEncodedString(url.Substring(0, i), false);
Write(url.Substring(i));
}
else {
WriteUrlEncodedString(url, false);
}
}
public virtual void WriteEncodedUrlParameter(String urlText) {
WriteUrlEncodedString(urlText, true);
}
public virtual void WriteEncodedText(String text) {
if (text == null) {
throw new ArgumentNullException("text");
}
const char NBSP = '\u00A0';
// When inner text is retrieved for a text control, is
// decoded to 0x00A0 (code point for nbsp in Unicode).
// HtmlEncode doesn't encode 0x00A0 to , we need to do it
// manually here.
int length = text.Length;
int pos = 0;
while (pos < length) {
int nbsp = text.IndexOf(NBSP, pos);
if (nbsp < 0) {
HttpUtility.HtmlEncode(pos == 0 ? text : text.Substring(pos, length - pos), this);
pos = length;
}
else {
if (nbsp > pos) {
HttpUtility.HtmlEncode(text.Substring(pos, nbsp - pos), this);
}
Write(" ");
pos = nbsp + 1;
}
}
}
protected void WriteUrlEncodedString(String text, bool argument) {
int length = text.Length;
for (int i = 0; i < length; i++) {
char ch = text[i];
if (HttpEncoderUtility.IsUrlSafeChar(ch)) {
Write(ch);
}
else if ( !argument &&
(ch == '/' ||
ch == ':' ||
ch == '#' ||
ch == ','
)
) {
Write(ch);
}
else if (ch == ' ' && argument) {
Write('+');
}
// for chars that their code number is less than 128 and have
// not been handled above
else if ((ch & 0xff80) == 0) {
Write('%');
Write(HttpEncoderUtility.IntToHex((ch >> 4) & 0xf));
Write(HttpEncoderUtility.IntToHex((ch) & 0xf));
}
else {
// VSWhidbey 448625: For DBCS characters, use UTF8 encoding
// which can be handled by IIS5 and above.
Write(HttpUtility.UrlEncodeNonAscii(Char.ToString(ch), Encoding.UTF8));
}
}
}
internal void WriteHtmlAttributeEncode(string s) {
HttpUtility.HtmlAttributeEncode(s, _httpWriter ?? writer);
}
internal class Layout {
private bool _wrap;
private HorizontalAlign _align;
/*
public Layout(Layout currentLayout) {
Align = currentLayout.Align;
Wrap = currentLayout.Wrap;
}
*/
public Layout(HorizontalAlign alignment, bool wrapping) {
Align = alignment;
Wrap = wrapping;
}
public bool Wrap
{
get
{
return _wrap;
}
set
{
_wrap = value;
}
}
public HorizontalAlign Align
{
get
{
return _align;
}
set
{
_align = value;
}
}
/*
public bool Compare(Layout layout) {
return Wrap == layout.Wrap && Align == layout.Align;
}
public void MergeWith(Layout layout) {
if (Align == HorizontalAlign.NotSet) {
Align = layout.Align;
}
if (Wrap) {
Wrap = layout.Wrap;
}
}
*/
}
private struct TagStackEntry {
public HtmlTextWriterTag tagKey;
public string endTagText;
}
private struct RenderAttribute {
public string name;
public string value;
public HtmlTextWriterAttribute key;
public bool encode;
public bool isUrl;
}
private struct AttributeInformation {
public string name;
public bool isUrl;
public bool encode;
public AttributeInformation(string name, bool encode, bool isUrl) {
this.name = name;
this.encode = encode;
this.isUrl = isUrl;
}
}
private enum TagType {
Inline,
NonClosing,
Other,
}
private struct TagInformation {
public string name;
public TagType tagType;
public string closingTag;
public TagInformation(string name, TagType tagType, string closingTag) {
this.name = name;
this.tagType = tagType;
this.closingTag = closingTag;
}
}
}
}
| |
// 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.Runtime.InteropServices;
using Xunit;
using System.Numerics;
namespace System.Numerics.Tests
{
public class Matrix3x2Tests
{
static Matrix3x2 GenerateMatrixNumberFrom1To6()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 3.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
return a;
}
static Matrix3x2 GenerateTestMatrix()
{
Matrix3x2 m = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
m.Translation = new Vector2(111.0f, 222.0f);
return m;
}
// A test for Identity
[Fact]
public void Matrix3x2IdentityTest()
{
Matrix3x2 val = new Matrix3x2();
val.M11 = val.M22 = 1.0f;
Assert.True(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly.");
}
// A test for Determinant
[Fact]
public void Matrix3x2DeterminantTest()
{
Matrix3x2 target = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
float val = 1.0f;
float det = target.GetDeterminant();
Assert.True(MathHelper.Equal(val, det), "Matrix3x2.Determinant was not set correctly.");
}
// A test for Determinant
// Determinant test |A| = 1 / |A'|
[Fact]
public void Matrix3x2DeterminantTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 5.0f;
a.M12 = 2.0f;
a.M21 = 12.0f;
a.M22 = 6.8f;
a.M31 = 6.5f;
a.M32 = 1.0f;
Matrix3x2 i;
Assert.True(Matrix3x2.Invert(a, out i));
float detA = a.GetDeterminant();
float detI = i.GetDeterminant();
float t = 1.0f / detI;
// only accurate to 3 precision
Assert.True(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.Determinant was not set correctly.");
// sanity check against 4x4 version
Assert.Equal(new Matrix4x4(a).GetDeterminant(), detA);
Assert.Equal(new Matrix4x4(i).GetDeterminant(), detI);
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.8660254f;
expected.M12 = -0.5f;
expected.M21 = 0.5f;
expected.M22 = 0.8660254f;
expected.M31 = 0;
expected.M32 = 0;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value.");
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertIdentityTest()
{
Matrix3x2 mtx = Matrix3x2.Identity;
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Assert.True(MathHelper.Equal(actual, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertTranslationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateTranslation(23, 42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertRotationTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertScaleTest()
{
Matrix3x2 mtx = Matrix3x2.CreateScale(23, -42);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for Invert (Matrix3x2)
[Fact]
public void Matrix3x2InvertAffineTest()
{
Matrix3x2 mtx = Matrix3x2.CreateRotation(2) *
Matrix3x2.CreateScale(23, -42) *
Matrix3x2.CreateTranslation(17, 53);
Matrix3x2 actual;
Assert.True(Matrix3x2.Invert(mtx, out actual));
Matrix3x2 i = mtx * actual;
Assert.True(MathHelper.Equal(i, Matrix3x2.Identity));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationTest()
{
float radians = MathHelper.ToRadians(50.0f);
Matrix3x2 expected = new Matrix3x2();
expected.M11 = 0.642787635f;
expected.M12 = 0.766044438f;
expected.M21 = -0.766044438f;
expected.M22 = 0.642787635f;
Matrix3x2 actual;
actual = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.CreateRotation did not return the expected value.");
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationCenterTest()
{
float radians = MathHelper.ToRadians(30.0f);
Vector2 center = new Vector2(23, 42);
Matrix3x2 rotateAroundZero = Matrix3x2.CreateRotation(radians, Vector2.Zero);
Matrix3x2 rotateAroundZeroExpected = Matrix3x2.CreateRotation(radians);
Assert.True(MathHelper.Equal(rotateAroundZero, rotateAroundZeroExpected));
Matrix3x2 rotateAroundCenter = Matrix3x2.CreateRotation(radians, center);
Matrix3x2 rotateAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateRotation(radians) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(rotateAroundCenter, rotateAroundCenterExpected));
}
// A test for CreateRotation (float)
[Fact]
public void Matrix3x2CreateRotationRightAngleTest()
{
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 0, 0), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, 0, 0), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 0, 0), actual));
}
// A test for CreateRotation (float, Vector2f)
[Fact]
public void Matrix3x2CreateRotationRightAngleCenterTest()
{
Vector2 center = new Vector2(3, 7);
// 90 degree rotations must be exact!
Matrix3x2 actual = Matrix3x2.CreateRotation(0, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi, center);
Assert.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 3 / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 2, center);
Assert.Equal(new Matrix3x2(1, 0, 0, 1, 0, 0), actual);
actual = Matrix3x2.CreateRotation(MathHelper.Pi * 5 / 2, center);
Assert.Equal(new Matrix3x2(0, 1, -1, 0, 10, 4), actual);
actual = Matrix3x2.CreateRotation(-MathHelper.Pi / 2, center);
Assert.Equal(new Matrix3x2(0, -1, 1, 0, -4, 10), actual);
// But merely close-to-90 rotations should not be excessively clamped.
float delta = MathHelper.ToRadians(0.01f);
actual = Matrix3x2.CreateRotation(MathHelper.Pi + delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
actual = Matrix3x2.CreateRotation(MathHelper.Pi - delta, center);
Assert.False(MathHelper.Equal(new Matrix3x2(-1, 0, 0, -1, 6, 14), actual));
}
// A test for Invert (Matrix3x2)
// Non invertible matrix - determinant is zero - singular matrix
[Fact]
public void Matrix3x2InvertTest1()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 0.0f;
a.M12 = 2.0f;
a.M21 = 0.0f;
a.M22 = 4.0f;
a.M31 = 5.0f;
a.M32 = 6.0f;
float detA = a.GetDeterminant();
Assert.True(MathHelper.Equal(detA, 0.0f), "Matrix3x2.Invert did not return the expected value.");
Matrix3x2 actual;
Assert.False(Matrix3x2.Invert(a, out actual));
// all the elements in Actual is NaN
Assert.True(
float.IsNaN(actual.M11) && float.IsNaN(actual.M12) &&
float.IsNaN(actual.M21) && float.IsNaN(actual.M22) &&
float.IsNaN(actual.M31) && float.IsNaN(actual.M32)
, "Matrix3x2.Invert did not return the expected value.");
}
// A test for Lerp (Matrix3x2, Matrix3x2, float)
[Fact]
public void Matrix3x2LerpTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = 12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
float t = 0.5f;
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + (b.M11 - a.M11) * t;
expected.M12 = a.M12 + (b.M12 - a.M12) * t;
expected.M21 = a.M21 + (b.M21 - a.M21) * t;
expected.M22 = a.M22 + (b.M22 - a.M22) * t;
expected.M31 = a.M31 + (b.M31 - a.M31) * t;
expected.M32 = a.M32 + (b.M32 - a.M32) * t;
Matrix3x2 actual;
actual = Matrix3x2.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Lerp did not return the expected value.");
}
// A test for operator - (Matrix3x2)
[Fact]
public void Matrix3x2UnaryNegationTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator - (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator - did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = a * b;
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = a44 * b44;
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator * (Matrix3x2, Matrix3x2)
// Multiply with identity matrix
[Fact]
public void Matrix3x2MultiplyTest4()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 1.0f;
a.M12 = 2.0f;
a.M21 = 5.0f;
a.M22 = -6.0f;
a.M31 = 9.0f;
a.M32 = 10.0f;
Matrix3x2 b = new Matrix3x2();
b = Matrix3x2.Identity;
Matrix3x2 expected = a;
Matrix3x2 actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator * did not return the expected value.");
}
// A test for operator + (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AdditionTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.operator + did not return the expected value.");
}
// A test for ToString ()
[Fact]
public void Matrix3x2ToStringTest()
{
Matrix3x2 a = new Matrix3x2();
a.M11 = 11.0f;
a.M12 = -12.0f;
a.M21 = 21.0f;
a.M22 = 22.0f;
a.M31 = 31.0f;
a.M32 = 32.0f;
string expected = "{ {M11:11 M12:-12} " +
"{M21:21 M22:22} " +
"{M31:31 M32:32} }";
string actual;
actual = a.ToString();
Assert.Equal(expected, actual);
}
// A test for Add (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2AddTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 + b.M11;
expected.M12 = a.M12 + b.M12;
expected.M21 = a.M21 + b.M21;
expected.M22 = a.M22 + b.M22;
expected.M31 = a.M31 + b.M31;
expected.M32 = a.M32 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Matrix3x2EqualsTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Vector4();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for GetHashCode ()
[Fact]
public void Matrix3x2GetHashCodeTest()
{
Matrix3x2 target = GenerateMatrixNumberFrom1To6();
int expected = target.M11.GetHashCode() + target.M12.GetHashCode() +
target.M21.GetHashCode() + target.M22.GetHashCode() +
target.M31.GetHashCode() + target.M32.GetHashCode();
int actual;
actual = target.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2MultiplyTest3()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = a.M11 * b.M11 + a.M12 * b.M21;
expected.M12 = a.M11 * b.M12 + a.M12 * b.M22;
expected.M21 = a.M21 * b.M11 + a.M22 * b.M21;
expected.M22 = a.M21 * b.M12 + a.M22 * b.M22;
expected.M31 = a.M31 * b.M11 + a.M32 * b.M21 + b.M31;
expected.M32 = a.M31 * b.M12 + a.M32 * b.M22 + b.M32;
Matrix3x2 actual;
actual = Matrix3x2.Multiply(a, b);
Assert.Equal(expected, actual);
// Sanity check by comparison with 4x4 multiply.
a = Matrix3x2.CreateRotation(MathHelper.ToRadians(30)) * Matrix3x2.CreateTranslation(23, 42);
b = Matrix3x2.CreateScale(3, 7) * Matrix3x2.CreateTranslation(666, -1);
actual = Matrix3x2.Multiply(a, b);
Matrix4x4 a44 = new Matrix4x4(a);
Matrix4x4 b44 = new Matrix4x4(b);
Matrix4x4 expected44 = Matrix4x4.Multiply(a44, b44);
Matrix4x4 actual44 = new Matrix4x4(actual);
Assert.True(MathHelper.Equal(expected44, actual44), "Matrix3x2.Multiply did not return the expected value.");
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest5()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = Matrix3x2.Multiply(a, 3);
Assert.Equal(expected, actual);
}
// A test for Multiply (Matrix3x2, float)
[Fact]
public void Matrix3x2MultiplyTest6()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2(3, 6, 9, 12, 15, 18);
Matrix3x2 actual = a * 3;
Assert.Equal(expected, actual);
}
// A test for Negate (Matrix3x2)
[Fact]
public void Matrix3x2NegateTest()
{
Matrix3x2 m = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
expected.M11 = -1.0f;
expected.M12 = -2.0f;
expected.M21 = -3.0f;
expected.M22 = -4.0f;
expected.M31 = -5.0f;
expected.M32 = -6.0f;
Matrix3x2 actual;
actual = Matrix3x2.Negate(m);
Assert.Equal(expected, actual);
}
// A test for operator != (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2InequalityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2EqualityTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Matrix3x2, Matrix3x2)
[Fact]
public void Matrix3x2SubtractTest()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
Matrix3x2 expected = new Matrix3x2();
Matrix3x2 actual;
actual = Matrix3x2.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f)
[Fact]
public void Matrix3x2CreateScaleTest1()
{
Vector2 scales = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scales);
Assert.Equal(expected, actual);
}
// A test for CreateScale (Vector2f, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest1()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float)
[Fact]
public void Matrix3x2CreateScaleTest2()
{
float scale = 2.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 2.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(scale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest2()
{
float scale = 5;
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateScale (float, float)
[Fact]
public void Matrix3x2CreateScaleTest3()
{
float xScale = 2.0f;
float yScale = 3.0f;
Matrix3x2 expected = new Matrix3x2(
2.0f, 0.0f,
0.0f, 3.0f,
0.0f, 0.0f);
Matrix3x2 actual = Matrix3x2.CreateScale(xScale, yScale);
Assert.Equal(expected, actual);
}
// A test for CreateScale (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateScaleCenterTest3()
{
Vector2 scale = new Vector2(3, 4);
Vector2 center = new Vector2(23, 42);
Matrix3x2 scaleAroundZero = Matrix3x2.CreateScale(scale.X, scale.Y, Vector2.Zero);
Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale.X, scale.Y);
Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));
Matrix3x2 scaleAroundCenter = Matrix3x2.CreateScale(scale.X, scale.Y, center);
Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale.X, scale.Y) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
}
// A test for CreateTranslation (Vector2f)
[Fact]
public void Matrix3x2CreateTranslationTest1()
{
Vector2 position = new Vector2(2.0f, 3.0f);
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(position);
Assert.Equal(expected, actual);
}
// A test for CreateTranslation (float, float)
[Fact]
public void Matrix3x2CreateTranslationTest2()
{
float xPosition = 2.0f;
float yPosition = 3.0f;
Matrix3x2 expected = new Matrix3x2(
1.0f, 0.0f,
0.0f, 1.0f,
2.0f, 3.0f);
Matrix3x2 actual = Matrix3x2.CreateTranslation(xPosition, yPosition);
Assert.Equal(expected, actual);
}
// A test for Translation
[Fact]
public void Matrix3x2TranslationTest()
{
Matrix3x2 a = GenerateTestMatrix();
Matrix3x2 b = a;
// Transfomed vector that has same semantics of property must be same.
Vector2 val = new Vector2(a.M31, a.M32);
Assert.Equal(val, a.Translation);
// Set value and get value must be same.
val = new Vector2(1.0f, 2.0f);
a.Translation = val;
Assert.Equal(val, a.Translation);
// Make sure it only modifies expected value of matrix.
Assert.True(
a.M11 == b.M11 && a.M12 == b.M12 &&
a.M21 == b.M21 && a.M22 == b.M22 &&
a.M31 != b.M31 && a.M32 != b.M32,
"Matrix3x2.Translation modified unexpected value of matrix.");
}
// A test for Equals (Matrix3x2)
[Fact]
public void Matrix3x2EqualsTest1()
{
Matrix3x2 a = GenerateMatrixNumberFrom1To6();
Matrix3x2 b = GenerateMatrixNumberFrom1To6();
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.M11 = 11.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewIdentityTest()
{
Matrix3x2 expected = Matrix3x2.Identity;
Matrix3x2 actual = Matrix3x2.CreateSkew(0, 0);
Assert.Equal(expected, actual);
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXTest()
{
Matrix3x2 expected = new Matrix3x2(1, 0, -0.414213562373095f, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(-MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0, 0.414213562373095f, 1, 0, 0);
actual = Matrix3x2.CreateSkew(MathHelper.Pi / 8, 0);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(0.414213568f, 1), result));
result = Vector2.Transform(new Vector2(0, -1), actual);
Assert.True(MathHelper.Equal(new Vector2(-0.414213568f, -1), result));
result = Vector2.Transform(new Vector2(3, 10), actual);
Assert.True(MathHelper.Equal(new Vector2(7.14213568f, 10), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 0, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(0, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
expected = new Matrix3x2(1, 0.414213562373095f, 0, 1, 0, 0);
actual = Matrix3x2.CreateSkew(0, MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 0.414213568f), result));
result = Vector2.Transform(new Vector2(-1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(-1, -0.414213568f), result));
result = Vector2.Transform(new Vector2(10, 3), actual);
Assert.True(MathHelper.Equal(new Vector2(10, 7.14213568f), result));
}
// A test for CreateSkew (float, float)
[Fact]
public void Matrix3x2CreateSkewXYTest()
{
Matrix3x2 expected = new Matrix3x2(1, -0.414213562373095f, 1, 1, 0, 0);
Matrix3x2 actual = Matrix3x2.CreateSkew(MathHelper.Pi / 4, -MathHelper.Pi / 8);
Assert.True(MathHelper.Equal(expected, actual));
Vector2 result = Vector2.Transform(new Vector2(0, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(0, 0), result));
result = Vector2.Transform(new Vector2(1, 0), actual);
Assert.True(MathHelper.Equal(new Vector2(1, -0.414213562373095f), result));
result = Vector2.Transform(new Vector2(0, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(1, 1), result));
result = Vector2.Transform(new Vector2(1, 1), actual);
Assert.True(MathHelper.Equal(new Vector2(2, 0.585786437626905f), result));
}
// A test for CreateSkew (float, float, Vector2f)
[Fact]
public void Matrix3x2CreateSkewCenterTest()
{
float skewX = 1, skewY = 2;
Vector2 center = new Vector2(23, 42);
Matrix3x2 skewAroundZero = Matrix3x2.CreateSkew(skewX, skewY, Vector2.Zero);
Matrix3x2 skewAroundZeroExpected = Matrix3x2.CreateSkew(skewX, skewY);
Assert.True(MathHelper.Equal(skewAroundZero, skewAroundZeroExpected));
Matrix3x2 skewAroundCenter = Matrix3x2.CreateSkew(skewX, skewY, center);
Matrix3x2 skewAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateSkew(skewX, skewY) * Matrix3x2.CreateTranslation(center);
Assert.True(MathHelper.Equal(skewAroundCenter, skewAroundCenterExpected));
}
// A test for IsIdentity
[Fact]
public void Matrix3x2IsIdentityTest()
{
Assert.True(Matrix3x2.Identity.IsIdentity);
Assert.True(new Matrix3x2(1, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(0, 0, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 1, 0, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 1, 1, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 0, 0, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 1, 0).IsIdentity);
Assert.False(new Matrix3x2(1, 0, 0, 1, 0, 1).IsIdentity);
}
// A test for Matrix3x2 comparison involving NaN values
[Fact]
public void Matrix3x2EqualsNanTest()
{
Matrix3x2 a = new Matrix3x2(float.NaN, 0, 0, 0, 0, 0);
Matrix3x2 b = new Matrix3x2(0, float.NaN, 0, 0, 0, 0);
Matrix3x2 c = new Matrix3x2(0, 0, float.NaN, 0, 0, 0);
Matrix3x2 d = new Matrix3x2(0, 0, 0, float.NaN, 0, 0);
Matrix3x2 e = new Matrix3x2(0, 0, 0, 0, float.NaN, 0);
Matrix3x2 f = new Matrix3x2(0, 0, 0, 0, 0, float.NaN);
Assert.False(a == new Matrix3x2());
Assert.False(b == new Matrix3x2());
Assert.False(c == new Matrix3x2());
Assert.False(d == new Matrix3x2());
Assert.False(e == new Matrix3x2());
Assert.False(f == new Matrix3x2());
Assert.True(a != new Matrix3x2());
Assert.True(b != new Matrix3x2());
Assert.True(c != new Matrix3x2());
Assert.True(d != new Matrix3x2());
Assert.True(e != new Matrix3x2());
Assert.True(f != new Matrix3x2());
Assert.False(a.Equals(new Matrix3x2()));
Assert.False(b.Equals(new Matrix3x2()));
Assert.False(c.Equals(new Matrix3x2()));
Assert.False(d.Equals(new Matrix3x2()));
Assert.False(e.Equals(new Matrix3x2()));
Assert.False(f.Equals(new Matrix3x2()));
Assert.False(a.IsIdentity);
Assert.False(b.IsIdentity);
Assert.False(c.IsIdentity);
Assert.False(d.IsIdentity);
Assert.False(e.IsIdentity);
Assert.False(f.IsIdentity);
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
Assert.False(d.Equals(d));
Assert.False(e.Equals(e));
Assert.False(f.Equals(f));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Matrix3x2SizeofTest()
{
Assert.Equal(24, sizeof(Matrix3x2));
Assert.Equal(48, sizeof(Matrix3x2_2x));
Assert.Equal(28, sizeof(Matrix3x2PlusFloat));
Assert.Equal(56, sizeof(Matrix3x2PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2_2x
{
Matrix3x2 a;
Matrix3x2 b;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat
{
Matrix3x2 v;
float f;
}
[StructLayout(LayoutKind.Sequential)]
struct Matrix3x2PlusFloat_2x
{
Matrix3x2PlusFloat a;
Matrix3x2PlusFloat b;
}
//// A test to make sure the fields are laid out how we expect
//[Fact]
//public unsafe void Matrix3x2FieldOffsetTest()
//{
// Matrix3x2* ptr = (Matrix3x2*)0;
// Assert.Equal(new IntPtr(0), new IntPtr(&ptr->M11));
// Assert.Equal(new IntPtr(4), new IntPtr(&ptr->M12));
// Assert.Equal(new IntPtr(8), new IntPtr(&ptr->M21));
// Assert.Equal(new IntPtr(12), new IntPtr(&ptr->M22));
// Assert.Equal(new IntPtr(16), new IntPtr(&ptr->M31));
// Assert.Equal(new IntPtr(20), new IntPtr(&ptr->M32));
//}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright 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.Generic;
using System.Linq;
using Microsoft.Hadoop.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Test.HDInsight.CmdLetTests;
using Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.Utilities;
using Microsoft.WindowsAzure.Management.HDInsight;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.Commands.CommandImplementations;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.DataObjects;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.GetAzureHDInsightClusters;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.ServiceLocation;
using Microsoft.Azure.Common.Authentication;
using System.IO;
namespace Microsoft.WindowsAzure.Commands.Test.HDInsight.CommandTests
{
[TestClass]
public class HDInsightGetCommandTests : HDInsightTestCaseBase
{
[TestCleanup]
public override void TestCleanup()
{
base.TestCleanup();
}
[TestMethod]
[TestCategory("CheckIn")]
public void ICanPerform_GetClusters_HDInsightGetCommand()
{
var client = ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateGet();
client.CurrentSubscription = GetCurrentSubscription();
client.EndProcessing();
IEnumerable<AzureHDInsightCluster> containers = from container in client.Output
where container.Name.Equals(TestCredentials.WellKnownCluster.DnsName)
select container;
Assert.AreEqual(1, containers.Count());
}
[TestMethod]
[TestCategory("CheckIn")]
public void ICanPerform_GetClusters_HDInsightGetCommand_DnsName()
{
IHDInsightCertificateCredential creds = GetValidCredentials();
var client = ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateGet();
client.CurrentSubscription = GetCurrentSubscription();
client.Name = TestCredentials.WellKnownCluster.DnsName;
client.EndProcessing();
IEnumerable<AzureHDInsightCluster> containers = from container in client.Output
where container.Name.Equals(TestCredentials.WellKnownCluster.DnsName)
select container;
Assert.AreEqual(1, containers.Count());
}
[TestMethod]
[TestCategory("CheckIn")]
public void ICanPerform_GetClusters_HDInsightGetCommand_InvalidDnsName()
{
IHDInsightCertificateCredential creds = GetValidCredentials();
var client = ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateGet();
client.CurrentSubscription = GetCurrentSubscription();
client.Name = Guid.NewGuid().ToString("N");
client.EndProcessing();
Assert.IsFalse(client.Output.Any());
}
[TestMethod]
[TestCategory("CheckIn")]
public void CommandsNeedCurrentSubscriptionSet()
{
IHDInsightCertificateCredential creds = GetValidCredentials();
var getClustersCommand = new GetAzureHDInsightClusterCommand();
try
{
getClustersCommand.GetClient(false);
Assert.Fail("Should have failed.");
}
catch (ArgumentNullException noSubscriptionException)
{
Assert.AreEqual(noSubscriptionException.ParamName, "CurrentSubscription");
}
}
[TestMethod]
[TestCategory("CheckIn")]
public void CanGetSubscriptionsCertificateCredentialFromCurrentSubscription()
{
var getClustersCommand = new GetAzureHDInsightClusterCommand();
var waSubscription = GetCurrentSubscription();
ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
var subscriptionCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription, profileClient.Profile.Context.Environment, profileClient.Profile);
Assert.IsInstanceOfType(subscriptionCreds, typeof(HDInsightCertificateCredential));
var asCertificateCreds = subscriptionCreds as HDInsightCertificateCredential;
Assert.AreEqual(waSubscription.Id, asCertificateCreds.SubscriptionId);
Assert.IsNotNull(asCertificateCreds.Certificate);
}
[TestMethod]
[TestCategory("CheckIn")]
public void CanGetAccessTokenCertificateCredentialFromCurrentSubscription()
{
var getClustersCommand = new GetAzureHDInsightClusterCommand();
var waSubscription = new AzureSubscription()
{
Id = IntegrationTestBase.TestCredentials.SubscriptionId,
};
ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
profileClient.Profile.Accounts["test"] = new AzureAccount
{
Id = "test",
Type = AzureAccount.AccountType.User,
Properties =
new Dictionary<AzureAccount.Property, string>
{
{AzureAccount.Property.Subscriptions, IntegrationTestBase.TestCredentials.SubscriptionId.ToString() }
}
};
profileClient.Profile.Save();
waSubscription.Account = "test";
var accessTokenCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription, profileClient.Profile.Context.Environment, profileClient.Profile);
Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
var asAccessTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
Assert.AreEqual("abc", asAccessTokenCreds.AccessToken);
Assert.AreEqual(waSubscription.Id, asAccessTokenCreds.SubscriptionId);
}
[TestMethod]
[TestCategory("CheckIn")]
public void CanGetJobSubmissionCertificateCredentialFromCurrentSubscription()
{
var getClustersCommand = new GetAzureHDInsightJobCommand();
var waSubscription = GetCurrentSubscription();
ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
var subscriptionCreds = getClustersCommand.GetJobSubmissionClientCredentials(
waSubscription,
profileClient.Profile.Context.Environment,
IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName,
profileClient.Profile);
Assert.IsInstanceOfType(subscriptionCreds, typeof(JobSubmissionCertificateCredential));
var asCertificateCreds = subscriptionCreds as JobSubmissionCertificateCredential;
Assert.AreEqual(waSubscription.Id, asCertificateCreds.SubscriptionId);
Assert.AreEqual(IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName, asCertificateCreds.Cluster);
}
[TestMethod]
[TestCategory("CheckIn")]
public void CanGetJobSubmissionAccessTokenCredentialFromCurrentSubscription()
{
var getClustersCommand = new GetAzureHDInsightJobCommand();
var waSubscription = new AzureSubscription()
{
Id = IntegrationTestBase.TestCredentials.SubscriptionId,
Account = "test"
};
ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
profileClient.Profile.Accounts["test"] = new AzureAccount
{
Id = "test",
Type = AzureAccount.AccountType.User,
Properties =
new Dictionary<AzureAccount.Property, string>
{
{AzureAccount.Property.Subscriptions, IntegrationTestBase.TestCredentials.SubscriptionId.ToString() }
}
};
profileClient.Profile.Save();
var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
waSubscription,
profileClient.Profile.Context.Environment,
IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName,
profileClient.Profile);
Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
var asTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
Assert.IsNotNull(asTokenCreds);
Assert.AreEqual("abc", asTokenCreds.AccessToken);
}
[TestMethod]
[TestCategory("CheckIn")]
public void CanGetBasicAuthCredentialFromCredentials()
{
var getClustersCommand = new GetAzureHDInsightJobCommand();
getClustersCommand.Credential = GetPSCredential(TestCredentials.AzureUserName, TestCredentials.AzurePassword);
var waSubscription = new AzureSubscription()
{
Id = IntegrationTestBase.TestCredentials.SubscriptionId,
};
waSubscription.Account = "test";
var profile = new AzureSMProfile();
ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
waSubscription,
profileClient.Profile.Context.Environment,
IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName, profile);
Assert.IsInstanceOfType(accessTokenCreds, typeof(BasicAuthCredential));
var asBasicAuthCredentials = accessTokenCreds as BasicAuthCredential;
Assert.IsNotNull(asBasicAuthCredentials);
Assert.AreEqual(IntegrationTestBase.TestCredentials.AzureUserName, asBasicAuthCredentials.UserName);
Assert.AreEqual(IntegrationTestBase.TestCredentials.AzurePassword, asBasicAuthCredentials.Password);
}
[TestMethod]
[TestCategory("CheckIn")]
public void GetJobSubmissionCredentialsThrowsInvalidOperationException()
{
string invalidClusterName = Guid.NewGuid().ToString("N");
var getClustersCommand = new GetAzureHDInsightJobCommand();
try
{
getClustersCommand.GetClient(invalidClusterName);
Assert.Fail("Should have failed.");
}
catch (InvalidOperationException invalidOperationException)
{
Assert.AreEqual("Expected either a Subscription or Credential parameter.", invalidOperationException.Message);
}
}
[TestInitialize]
public override void Initialize()
{
base.Initialize();
}
}
}
| |
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 MyWebapi.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;
}
}
}
| |
using ClosedXML.Excel.Drawings;
using System;
using System.Drawing;
using System.IO;
namespace ClosedXML.Excel
{
public enum XLWorksheetVisibility { Visible, Hidden, VeryHidden }
public interface IXLWorksheet : IXLRangeBase, IDisposable
{
/// <summary>
/// Gets the workbook that contains this worksheet
/// </summary>
XLWorkbook Workbook { get; }
/// <summary>
/// Gets or sets the default column width for this worksheet.
/// </summary>
Double ColumnWidth { get; set; }
/// <summary>
/// Gets or sets the default row height for this worksheet.
/// </summary>
Double RowHeight { get; set; }
/// <summary>
/// Gets or sets the name (caption) of this worksheet.
/// </summary>
String Name { get; set; }
/// <summary>
/// Gets or sets the position of the sheet.
/// <para>When setting the Position all other sheets' positions are shifted accordingly.</para>
/// </summary>
Int32 Position { get; set; }
/// <summary>
/// Gets an object to manipulate the sheet's print options.
/// </summary>
IXLPageSetup PageSetup { get; }
/// <summary>
/// Gets an object to manipulate the Outline levels.
/// </summary>
IXLOutline Outline { get; }
/// <summary>
/// Gets the first row of the worksheet.
/// </summary>
IXLRow FirstRow();
/// <summary>
/// Gets the first row of the worksheet that contains a cell with a value.
/// <para>Formatted empty cells do not count.</para>
/// </summary>
IXLRow FirstRowUsed();
/// <summary>
/// Gets the first row of the worksheet that contains a cell with a value.
/// </summary>
/// <param name="includeFormats">If set to <c>true</c> formatted empty cells will count as used.</param>
IXLRow FirstRowUsed(Boolean includeFormats);
/// <summary>
/// Gets the last row of the worksheet.
/// </summary>
IXLRow LastRow();
/// <summary>
/// Gets the last row of the worksheet that contains a cell with a value.
/// </summary>
IXLRow LastRowUsed();
/// <summary>
/// Gets the last row of the worksheet that contains a cell with a value.
/// </summary>
/// <param name="includeFormats">If set to <c>true</c> formatted empty cells will count as used.</param>
IXLRow LastRowUsed(Boolean includeFormats);
/// <summary>
/// Gets the first column of the worksheet.
/// </summary>
IXLColumn FirstColumn();
/// <summary>
/// Gets the first column of the worksheet that contains a cell with a value.
/// </summary>
IXLColumn FirstColumnUsed();
/// <summary>
/// Gets the first column of the worksheet that contains a cell with a value.
/// </summary>
/// <param name="includeFormats">If set to <c>true</c> formatted empty cells will count as used.</param>
IXLColumn FirstColumnUsed(Boolean includeFormats);
/// <summary>
/// Gets the last column of the worksheet.
/// </summary>
IXLColumn LastColumn();
/// <summary>
/// Gets the last column of the worksheet that contains a cell with a value.
/// </summary>
IXLColumn LastColumnUsed();
/// <summary>
/// Gets the last column of the worksheet that contains a cell with a value.
/// </summary>
/// <param name="includeFormats">If set to <c>true</c> formatted empty cells will count as used.</param>
IXLColumn LastColumnUsed(Boolean includeFormats);
/// <summary>
/// Gets a collection of all columns in this worksheet.
/// </summary>
IXLColumns Columns();
/// <summary>
/// Gets a collection of the specified columns in this worksheet, separated by commas.
/// <para>e.g. Columns("G:H"), Columns("10:11,13:14"), Columns("P:Q,S:T"), Columns("V")</para>
/// </summary>
/// <param name="columns">The columns to return.</param>
IXLColumns Columns(String columns);
/// <summary>
/// Gets a collection of the specified columns in this worksheet.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLColumns Columns(String firstColumn, String lastColumn);
/// <summary>
/// Gets a collection of the specified columns in this worksheet.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLColumns Columns(Int32 firstColumn, Int32 lastColumn);
/// <summary>
/// Gets a collection of all rows in this worksheet.
/// </summary>
IXLRows Rows();
/// <summary>
/// Gets a collection of the specified rows in this worksheet, separated by commas.
/// <para>e.g. Rows("4:5"), Rows("7:8,10:11"), Rows("13")</para>
/// </summary>
/// <param name="rows">The rows to return.</param>
IXLRows Rows(String rows);
/// <summary>
/// Gets a collection of the specified rows in this worksheet.
/// </summary>
/// <param name="firstRow">The first row to return.</param>
/// <param name="lastRow">The last row to return.</param>
/// <returns></returns>
IXLRows Rows(Int32 firstRow, Int32 lastRow);
/// <summary>
/// Gets the specified row of the worksheet.
/// </summary>
/// <param name="row">The worksheet's row.</param>
IXLRow Row(Int32 row);
/// <summary>
/// Gets the specified column of the worksheet.
/// </summary>
/// <param name="column">The worksheet's column.</param>
IXLColumn Column(Int32 column);
/// <summary>
/// Gets the specified column of the worksheet.
/// </summary>
/// <param name="column">The worksheet's column.</param>
IXLColumn Column(String column);
/// <summary>
/// Gets the cell at the specified row and column.
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, int column);
/// <summary>Gets the cell at the specified address.</summary>
/// <param name="cellAddressInRange">The cell address in the worksheet.</param>
IXLCell Cell(string cellAddressInRange);
/// <summary>
/// Gets the cell at the specified row and column.
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, string column);
/// <summary>Gets the cell at the specified address.</summary>
/// <param name="cellAddressInRange">The cell address in the worksheet.</param>
IXLCell Cell(IXLAddress cellAddressInRange);
/// <summary>
/// Returns the specified range.
/// </summary>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(IXLRangeAddress rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <para>e.g. Range("A1"), Range("A1:C2")</para>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(string rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCell">The first cell in the range.</param>
/// <param name="lastCell"> The last cell in the range.</param>
IXLRange Range(IXLCell firstCell, IXLCell lastCell);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the worksheet.</param>
/// <param name="lastCellAddress"> The last cell address in the worksheet.</param>
IXLRange Range(string firstCellAddress, string lastCellAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the worksheet.</param>
/// <param name="lastCellAddress"> The last cell address in the worksheet.</param>
IXLRange Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress);
/// <summary>Returns a collection of ranges, separated by commas.</summary>
/// <para>e.g. Ranges("A1"), Ranges("A1:C2"), Ranges("A1:B2,D1:D4")</para>
/// <param name="ranges">The ranges to return.</param>
IXLRanges Ranges(string ranges);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellRow"> The first cell's row of the range to return.</param>
/// <param name="firstCellColumn">The first cell's column of the range to return.</param>
/// <param name="lastCellRow"> The last cell's row of the range to return.</param>
/// <param name="lastCellColumn"> The last cell's column of the range to return.</param>
/// <returns>.</returns>
IXLRange Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn);
/// <summary>Gets the number of rows in this worksheet.</summary>
int RowCount();
/// <summary>Gets the number of columns in this worksheet.</summary>
int ColumnCount();
/// <summary>
/// Collapses all outlined rows.
/// </summary>
IXLWorksheet CollapseRows();
/// <summary>
/// Collapses all outlined columns.
/// </summary>
IXLWorksheet CollapseColumns();
/// <summary>
/// Expands all outlined rows.
/// </summary>
IXLWorksheet ExpandRows();
/// <summary>
/// Expands all outlined columns.
/// </summary>
IXLWorksheet ExpandColumns();
/// <summary>
/// Collapses the outlined rows of the specified level.
/// </summary>
/// <param name="outlineLevel">The outline level.</param>
IXLWorksheet CollapseRows(Int32 outlineLevel);
/// <summary>
/// Collapses the outlined columns of the specified level.
/// </summary>
/// <param name="outlineLevel">The outline level.</param>
IXLWorksheet CollapseColumns(Int32 outlineLevel);
/// <summary>
/// Expands the outlined rows of the specified level.
/// </summary>
/// <param name="outlineLevel">The outline level.</param>
IXLWorksheet ExpandRows(Int32 outlineLevel);
/// <summary>
/// Expands the outlined columns of the specified level.
/// </summary>
/// <param name="outlineLevel">The outline level.</param>
IXLWorksheet ExpandColumns(Int32 outlineLevel);
/// <summary>
/// Deletes this worksheet.
/// </summary>
void Delete();
/// <summary>
/// Gets an object to manage this worksheet's named ranges.
/// </summary>
IXLNamedRanges NamedRanges { get; }
/// <summary>
/// Gets the specified named range.
/// </summary>
/// <param name="rangeName">Name of the range.</param>
IXLNamedRange NamedRange(String rangeName);
/// <summary>
/// Gets an object to manage how the worksheet is going to displayed by Excel.
/// </summary>
IXLSheetView SheetView { get; }
/// <summary>
/// Gets the Excel table of the given index
/// </summary>
/// <param name="index">Index of the table to return</param>
IXLTable Table(Int32 index);
/// <summary>
/// Gets the Excel table of the given name
/// </summary>
/// <param name="name">Name of the table to return</param>
IXLTable Table(String name);
/// <summary>
/// Gets an object to manage this worksheet's Excel tables
/// </summary>
IXLTables Tables { get; }
/// <summary>
/// Copies the
/// </summary>
/// <param name="newSheetName"></param>
/// <returns></returns>
IXLWorksheet CopyTo(String newSheetName);
IXLWorksheet CopyTo(String newSheetName, Int32 position);
IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName);
IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position);
IXLRange RangeUsed();
IXLRange RangeUsed(bool includeFormats);
IXLDataValidations DataValidations { get; }
XLWorksheetVisibility Visibility { get; set; }
IXLWorksheet Hide();
IXLWorksheet Unhide();
IXLSheetProtection Protection { get; }
IXLSheetProtection Protect();
IXLSheetProtection Protect(String password);
IXLSheetProtection Unprotect();
IXLSheetProtection Unprotect(String password);
IXLSortElements SortRows { get; }
IXLSortElements SortColumns { get; }
IXLRange Sort();
IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
//IXLCharts Charts { get; }
Boolean ShowFormulas { get; set; }
Boolean ShowGridLines { get; set; }
Boolean ShowOutlineSymbols { get; set; }
Boolean ShowRowColHeaders { get; set; }
Boolean ShowRuler { get; set; }
Boolean ShowWhiteSpace { get; set; }
Boolean ShowZeros { get; set; }
IXLWorksheet SetShowFormulas(); IXLWorksheet SetShowFormulas(Boolean value);
IXLWorksheet SetShowGridLines(); IXLWorksheet SetShowGridLines(Boolean value);
IXLWorksheet SetShowOutlineSymbols(); IXLWorksheet SetShowOutlineSymbols(Boolean value);
IXLWorksheet SetShowRowColHeaders(); IXLWorksheet SetShowRowColHeaders(Boolean value);
IXLWorksheet SetShowRuler(); IXLWorksheet SetShowRuler(Boolean value);
IXLWorksheet SetShowWhiteSpace(); IXLWorksheet SetShowWhiteSpace(Boolean value);
IXLWorksheet SetShowZeros(); IXLWorksheet SetShowZeros(Boolean value);
XLColor TabColor { get; set; }
IXLWorksheet SetTabColor(XLColor color);
Boolean TabSelected { get; set; }
Boolean TabActive { get; set; }
IXLWorksheet SetTabSelected(); IXLWorksheet SetTabSelected(Boolean value);
IXLWorksheet SetTabActive(); IXLWorksheet SetTabActive(Boolean value);
IXLPivotTable PivotTable(String name);
IXLPivotTables PivotTables { get; }
Boolean RightToLeft { get; set; }
IXLWorksheet SetRightToLeft(); IXLWorksheet SetRightToLeft(Boolean value);
IXLBaseAutoFilter AutoFilter { get; }
IXLRows RowsUsed(Boolean includeFormats = false, Func<IXLRow, Boolean> predicate = null);
IXLRows RowsUsed(Func<IXLRow, Boolean> predicate);
IXLColumns ColumnsUsed(Boolean includeFormats = false, Func<IXLColumn, Boolean> predicate = null);
IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate);
IXLRanges MergedRanges { get; }
IXLConditionalFormats ConditionalFormats { get; }
IXLRanges SelectedRanges { get; }
IXLCell ActiveCell { get; set; }
Object Evaluate(String expression);
/// <summary>
/// Force recalculation of all cell formulas.
/// </summary>
void RecalculateAllFormulas();
String Author { get; set; }
IXLPictures Pictures { get; }
IXLPicture Picture(String pictureName);
IXLPicture AddPicture(Stream stream);
IXLPicture AddPicture(Stream stream, String name);
IXLPicture AddPicture(Stream stream, XLPictureFormat format);
IXLPicture AddPicture(Stream stream, XLPictureFormat format, String name);
IXLPicture AddPicture(Bitmap bitmap);
IXLPicture AddPicture(Bitmap bitmap, String name);
IXLPicture AddPicture(String imageFile);
IXLPicture AddPicture(String imageFile, String name);
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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 HOLDER 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.Linq;
using System.Text;
using OpenSim.Region.Physics.Manager;
using log4net;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using OpenSim.Framework;
using System.Runtime.InteropServices;
using System.IO;
using OpenSim.Region.Interfaces;
namespace InWorldz.PhysxPhysics
{
internal class PhysxScene : PhysicsScene
{
[DllImport("kernel32.dll")]
static extern bool SetThreadPriority(IntPtr hThread, ThreadPriorityLevel nPriority);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
public const int TIMESTEP = 15;
public const float TIMESTEP_IN_SECONDS = TIMESTEP / 1000.0f;
public const float DILATED_TIMESTEP_IN_SECONDS = TIMESTEP_IN_SECONDS * 2.0f;
public const int SIMULATE_DELAY_TO_BEGIN_DILATION = (int)(TIMESTEP * 1.9f);
private const int UPDATE_WATCHDOG_FRAMES = 200;
private const int CHECK_EXPIRED_KINEMATIC_FRAMES = (int) ((1.0f / TIMESTEP_IN_SECONDS) * 60.0f);
private const int UPDATE_FPS_FRAMES = 30;
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Debugging.PhysxErrorCallback s_ErrorCallback = new Debugging.PhysxErrorCallback();
public PhysX.Material DEFAULT_MATERIAL;
private static PhysX.Foundation _foundation;
private static PhysX.Physics _physics;
private PhysX.SceneDesc _sceneDesc;
private PhysX.Scene _scene;
private Meshing.TerrainMesher _terrainMesher;
private TerrainManager _terrainMgr;
private Meshing.MeshingStage _meshingStage;
private Thread HeartbeatThread;
private Thread TimingThread;
private ManualResetEventSlim _timingSignal = new ManualResetEventSlim(true);
private uint _lastSimulate;
private int _frameNum;
private OpenSim.Framework.LocklessQueue<Commands.ICommand> _currentCommandQueue = new OpenSim.Framework.LocklessQueue<Commands.ICommand>();
private OpenSim.Framework.LocklessQueue<Commands.ICommand> _waitingCommandQueue = new OpenSim.Framework.LocklessQueue<Commands.ICommand>();
private C5.HashSet<PhysxPrim> _allPrims = new C5.HashSet<PhysxPrim>();
private C5.HashSet<PhysxPrim> _dynPrims = new C5.HashSet<PhysxPrim>();
private C5.HashSet<PhysxPrim> _collisionRepeatPrims = new C5.HashSet<PhysxPrim>();
private delegate void TaintHandler(PhysxPrim prim, TaintType taint);
private readonly Dictionary<TaintType, TaintHandler> _taintHandlers;
private volatile bool _stop = false;
private bool _simulating = false;
private KinematicManager _kinematicManager = new KinematicManager();
private uint _lastFpsCalc = (uint)Environment.TickCount;
private short _framesSinceLastFpsCalc = 0;
private volatile float _currFps = 60.0f;
private bool _gridmode = true;
private class DelayedCommandInfo
{
public Commands.ICommand Initiator;
public Dictionary<Type, LinkedListNode<Commands.ICommand>> TopCullables;
public LinkedList<Commands.ICommand> Commands;
}
/// <summary>
/// Stores commands that are being delayed pending execution of an async operation on a prim (such as meshing)
/// This ensures a proper order of execution for physics commands
/// </summary>
private Dictionary<PhysxPrim, DelayedCommandInfo> _delayedCommands = new Dictionary<PhysxPrim, DelayedCommandInfo>();
/// <summary>
/// Manages the agent actors in this scene
/// </summary>
private PhysX.ControllerManager _controllerManager;
/// <summary>
/// Holds the avatar/character actors in the scene
/// </summary>
private C5.HashSet<PhysxCharacter> _charActors = new C5.HashSet<PhysxCharacter>();
private SimulationEventCallbackDelegator _simEventDelegator;
private MovingIntegerAverage _frameTimeAvg = new MovingIntegerAverage(10);
private OpenMetaverse.UUID _regionId;
internal OpenMetaverse.UUID RegionID
{
get
{
return _regionId;
}
}
private Queue<Commands.ICommand> _freedCommands = new Queue<Commands.ICommand>();
public override float SimulationFPS
{
get
{
return _currFps;
}
}
public override bool Simulating
{
get
{
return _simulating;
}
set
{
_simulating = value;
}
}
internal PhysX.Scene SceneImpl
{
get
{
return _scene;
}
}
internal Meshing.MeshingStage MeshingStageImpl
{
get
{
return _meshingStage;
}
}
internal PhysX.ControllerManager ControllerManager
{
get
{
return _controllerManager;
}
}
public override int SimulationFrameTimeAvg
{
get
{
return _frameTimeAvg.CalculateAverage();
}
}
public uint CurrentFrameNum
{
get
{
return (uint)_frameNum;
}
}
public override OpenSim.Region.Interfaces.ITerrainChannel TerrainChannel { get; set; }
public override RegionSettings RegionSettings { get; set; }
public Debugging.ContactDebugManager ContactDebug { get; set; }
public IEnumerable<PhysxPrim> DynamicPrims
{
get
{
return _dynPrims;
}
}
IMesher _mesher;
public override IMesher Mesher
{
get
{
return _mesher;
}
}
internal OpenMetaverse.Vector2[] RegionWaterCurrents = null;
internal OpenMetaverse.Vector2[] RegionWindGround = null;
internal OpenMetaverse.Vector2[] RegionWindAloft = null;
internal float[] RegionTerrainRanges = null;
internal float[] RegionTerrainMaxHeights = null;
public PhysxScene()
{
_taintHandlers = new Dictionary<TaintType, TaintHandler>()
{
{TaintType.MadeDynamic, HandlePrimMadeDynamic},
{TaintType.MadeStatic, HandlePrimMadeStatic},
{TaintType.ChangedScale, HandlePrimChangedShape},
{TaintType.ChangedShape, HandlePrimChangedShape}
};
ContactDebug = new Debugging.ContactDebugManager(this);
}
private void CreateDefaults()
{
DEFAULT_MATERIAL = _physics.CreateMaterial(0.5f, 0.5f, 0.15f);
}
public override void Initialize(IMesher meshmerizer, Nini.Config.IConfigSource config, OpenMetaverse.UUID regionId)
{
_regionId = regionId;
_mesher = meshmerizer;
m_log.Info("[InWorldz.PhysxPhysics] Creating PhysX scene");
if (config.Configs["InWorldz.PhysxPhysics"] != null)
{
Settings.Instance.UseVisualDebugger = config.Configs["InWorldz.PhysxPhysics"].GetBoolean("use_visual_debugger", false);
Settings.Instance.UseCCD = config.Configs["InWorldz.PhysxPhysics"].GetBoolean("use_ccd", true);
Settings.Instance.Gravity = config.Configs["InWorldz.PhysxPhysics"].GetFloat("gravity", -9.8f);
Settings.Instance.ThrowOnSdkError = config.Configs["InWorldz.PhysxPhysics"].GetBoolean("throw_on_sdk_error", false);
Settings.Instance.InstrumentMeshing = config.Configs["InWorldz.PhysxPhysics"].GetBoolean("instrument_meshing", false);
}
else
{
Settings.Instance.UseVisualDebugger = false;
Settings.Instance.UseCCD = true;
Settings.Instance.Gravity = -9.8f;
Settings.Instance.ThrowOnSdkError = false;
Settings.Instance.InstrumentMeshing = false;
}
Nini.Config.IConfig startupcfg = config.Configs["Startup"];
if (startupcfg != null)
_gridmode = startupcfg.GetBoolean("gridmode", false);
if (_foundation == null)
{
_foundation = new PhysX.Foundation(s_ErrorCallback);
_physics = new PhysX.Physics(_foundation);
Material.BuiltinMaterialInit(_physics);
}
_sceneDesc = new PhysX.SceneDesc(null, Settings.Instance.UseCCD);
_sceneDesc.Gravity = new PhysX.Math.Vector3(0f, 0f, Settings.Instance.Gravity);
_simEventDelegator = new SimulationEventCallbackDelegator();
_simEventDelegator.OnContactCallback += this.OnContact;
_simEventDelegator.OnTriggerCallback += this.OnTrigger;
_sceneDesc.SimulationEventCallback = _simEventDelegator;
_scene = _physics.CreateScene(_sceneDesc);
Preload();
if (Settings.Instance.UseCCD)
{
_scene.SetFlag(PhysX.SceneFlag.SweptIntegration, true);
}
if (Settings.Instance.UseVisualDebugger && _physics.RemoteDebugger != null)
{
_physics.RemoteDebugger.Connect("localhost", null, null, PhysX.VisualDebugger.VisualDebuggerConnectionFlag.Debug, null);
}
_controllerManager = _scene.CreateControllerManager();
CreateDefaults();
_terrainMesher = new Meshing.TerrainMesher(_scene);
_terrainMgr = new TerrainManager(_scene, _terrainMesher, regionId);
_meshingStage = new Meshing.MeshingStage(_scene, meshmerizer, _terrainMesher);
_meshingStage.OnShapeNeedsFreeing += new Meshing.MeshingStage.ShapeNeedsFreeingDelegate(_meshingStage_OnShapeNeedsFreeing);
_kinematicManager = new KinematicManager();
//fire up our work loop
HeartbeatThread = Watchdog.StartThread(new ThreadStart(Heartbeat), "Physics Heartbeat",
ThreadPriority.Normal, false);
TimingThread = Watchdog.StartThread(new ThreadStart(DoTiming), string.Format("Physics Timing"),
ThreadPriority.Highest, false);
}
private void Preload()
{
using (PhysX.Collection coll = _scene.Physics.CreateCollection())
{
using (MemoryStream ms = new MemoryStream())
{
coll.Deserialize(ms);
}
}
}
void _meshingStage_OnShapeNeedsFreeing(PhysicsShape shape)
{
this.QueueCommand(new Commands.DestroyShapeCmd { Shape = shape });
}
void DoTiming()
{
IntPtr thrdHandle = GetCurrentThread();
SetThreadPriority(thrdHandle, ThreadPriorityLevel.TimeCritical);
while (!_stop)
{
_timingSignal.Set();
if (_frameNum % 100 == 0)
{
Watchdog.UpdateThread();
}
Thread.Sleep(TIMESTEP);
Interlocked.Increment(ref _frameNum);
}
}
private void Heartbeat()
{
uint lastSimulateFrame = 0;
while (!_stop)
{
uint startingFrame = (uint)Environment.TickCount;
bool processedCommandsThisIteration = ProcessQueueCommands();
uint uframe = (uint)_frameNum;
if (_simulating && (uframe > lastSimulateFrame))
{
uint tickCount = (uint)Environment.TickCount;
uint ticksSinceLastSimulate = Math.Max(tickCount - _lastSimulate, TIMESTEP);
_lastSimulate = (uint)Environment.TickCount;
lastSimulateFrame = uframe;
if (ticksSinceLastSimulate >= SIMULATE_DELAY_TO_BEGIN_DILATION)
{
Simulate(DILATED_TIMESTEP_IN_SECONDS, ticksSinceLastSimulate, uframe, true);
//m_log.DebugFormat("[PHYSICS]: Dilated simulate {0}", ticksSinceLastSimulate);
}
else
{
Simulate(ticksSinceLastSimulate * 0.001f, ticksSinceLastSimulate, uframe, false);
}
++_framesSinceLastFpsCalc;
if (uframe % UPDATE_WATCHDOG_FRAMES == 0)
{
Watchdog.UpdateThread();
}
if (uframe % CHECK_EXPIRED_KINEMATIC_FRAMES == 0)
{
this.CheckForExpiredKinematics();
}
if (uframe % UPDATE_FPS_FRAMES == 0)
{
this.UpdateFpsCalc();
//CheckForPhysicsLongFramesAndDebug();
}
}
_frameTimeAvg.AddValue((uint)Environment.TickCount - startingFrame);
ContactDebug.OnFramePassed();
if (_currentCommandQueue.Count == 0)
{
_timingSignal.Wait();
}
_timingSignal.Reset();
}
}
private void CheckForPhysicsLongFramesAndDebug()
{
throw new NotImplementedException();
}
//Stopwatch sw = new Stopwatch();
public override float Simulate(float timeStep, uint ticksSinceLastSimulate, uint frameNum, bool dilated)
{
//sw.Start();
_scene.Simulate(timeStep);
_scene.FetchResults(true);
//sw.Stop();
//m_log.DebugFormat("Simulate took: {0}", sw.Elapsed);
//sw.Reset();
ProcessDynamicPrimChanges(timeStep, ticksSinceLastSimulate, frameNum);
ProcessCollisionRepeats(timeStep, ticksSinceLastSimulate, frameNum);
//run avatar dynamics at 1/2 simulation speed (30fps nominal)
if (frameNum % 2 == 0)
{
ProcessAvatarDynamics(timeStep, ticksSinceLastSimulate, frameNum);
}
return 0.0f;
}
private void UpdateFpsCalc()
{
uint msSinceLastCalc = (uint)Environment.TickCount - _lastFpsCalc;
_currFps = _framesSinceLastFpsCalc / (msSinceLastCalc * 0.001f);
_framesSinceLastFpsCalc = 0;
_lastFpsCalc = (uint)Environment.TickCount;
//Console.WriteLine("FPS: {0}", _currFps);
//const float LOW_FPS_THRESHOLD = 54.0f;
const float LOW_FPS_THRESHOLD = 25.0f;
if (_currFps < LOW_FPS_THRESHOLD)
{
m_log.WarnFormat("[InWorldz.PhysxPhysics] Low physics FPS {0}", _currFps);
}
}
private void CheckForExpiredKinematics()
{
_kinematicManager.CheckForExipiredKinematics();
}
public override PhysicsActor AddAvatar(string avName, OpenMetaverse.Vector3 position, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector3 size, bool isFlying, OpenMetaverse.Vector3 initialVelocity)
{
Commands.CreateCharacterCmd cmd = new Commands.CreateCharacterCmd(size.Z, size.X, position, rotation, isFlying, initialVelocity);
this.QueueCommand(cmd);
cmd.FinshedEvent.Wait();
cmd.Dispose();
return cmd.FinalActor;
}
public override void RemoveAvatar(PhysicsActor actor)
{
this.QueueCommand(new Commands.RemoveCharacterCmd((PhysxCharacter)actor));
}
public override void RemovePrim(PhysicsActor prim)
{
this.QueueCommand(new Commands.RemoveObjectCmd((PhysxPrim)prim));
}
/// <summary>
/// The AddPrimShape calls are pseudo synchronous by default.
/// </summary>
/// <param name="primName"></param>
/// <param name="pbs"></param>
/// <param name="position"></param>
/// <param name="size"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public override PhysicsActor AddPrimShape(string primName, AddPrimShapeFlags flags, BulkShapeData shapeData)
{
Commands.CreateObjectCmd createObj = new Commands.CreateObjectCmd(
null, primName, shapeData.Pbs, shapeData.Position, shapeData.Size, shapeData.Rotation, shapeData.Velocity,
shapeData.AngularVelocity, Meshing.MeshingStage.SCULPT_MESH_LOD, flags, (Material)shapeData.Material,
shapeData.PhysicsProperties, shapeData.SerializedShapes, shapeData.ObjectReceivedOn);
this.QueueCommand(createObj);
createObj.FinshedEvent.Wait(); //wait for meshing and all prerequisites to complete
createObj.Dispose();
return createObj.FinalPrim;
}
public override void BulkAddPrimShapes(ICollection<BulkShapeData> shapeData, AddPrimShapeFlags flags)
{
Commands.BulkCreateObjectCmd createObjs = new Commands.BulkCreateObjectCmd(flags, shapeData);
this.QueueCommand(createObjs);
createObjs.FinishedEvent.Wait(); //wait for meshing and all prerequisites to complete
createObjs.Dispose();
}
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
//throw new NotSupportedException("AddPhysicsActorTaint must be called with a taint type");
}
public override void AddPhysicsActorTaint(PhysicsActor prim, TaintType taint)
{
TaintHandler handler;
if (_taintHandlers.TryGetValue(taint, out handler))
{
handler((PhysxPrim)prim, taint);
}
}
private void HandlePrimMadeStatic(PhysxPrim prim, TaintType taint)
{
this.QueueCommand(new Commands.SetPhysicalityCmd(prim, false));
}
private void HandlePrimMadeDynamic(PhysxPrim prim, TaintType taint)
{
this.QueueCommand(new Commands.SetPhysicalityCmd(prim, true));
}
private void HandlePrimChangedShape(PhysxPrim prim, TaintType taint)
{
this.QueueCommand(new Commands.ChangedShapeCmd(prim));
}
private void ProcessAvatarDynamics(float timeStep, uint ticksSinceLastSimulate, uint frameNum)
{
_controllerManager.ComputeInteractions(TimeSpan.FromMilliseconds(ticksSinceLastSimulate));
foreach (PhysxCharacter character in _charActors)
{
character.SyncWithPhysics(timeStep, ticksSinceLastSimulate, frameNum);
}
}
private void ProcessDynamicPrimChanges(float timeStep, uint ticksSinceLastSimulate, uint frameNum)
{
foreach (PhysicsActor actor in _dynPrims)
{
actor.SyncWithPhysics(timeStep, ticksSinceLastSimulate, frameNum);
}
}
private void ProcessCollisionRepeats(float timeStep, uint ticksSinceLastSimulate, uint frameNum)
{
//repeat collision notifications every 4 frames (7.5 fps nominal)
if (ticksSinceLastSimulate > 0 && frameNum % 4 == 0)
{
foreach (PhysicsActor actor in _collisionRepeatPrims)
{
actor.DoCollisionRepeats(timeStep, ticksSinceLastSimulate, frameNum);
}
}
}
private bool ProcessQueueCommands()
{
OpenSim.Framework.LocklessQueue<Commands.ICommand> oldCurrentQueue = Interlocked.Exchange<OpenSim.Framework.LocklessQueue<Commands.ICommand>>(ref _currentCommandQueue, _waitingCommandQueue);
try
{
if (oldCurrentQueue.Count == 0)
{
_waitingCommandQueue = oldCurrentQueue;
return false;
}
while (oldCurrentQueue.Count > 0)
{
Commands.ICommand cmd;
if (oldCurrentQueue.Dequeue(out cmd))
{
//remember, each command that is executed from the queue may free other
//commands that are waiting on that command to complete. therefore, after executing
//each command from the current queue, we must check to see if new commands
//have been put into the freed queue, and execute those. this ensures proper
//ordering of commands relative to each object
DelayOrExecuteCommand(cmd);
ExecuteFreedCommands();
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PhysxScene]: ProcessQueueCommands exception:\n {0}", e);
}
_waitingCommandQueue = oldCurrentQueue;
return true;
}
private void ExecuteFreedCommands()
{
while (_freedCommands.Count > 0)
{
DelayOrExecuteCommand(_freedCommands.Dequeue());
}
}
private void DelayOrExecuteCommand(Commands.ICommand cmd)
{
if (!this.CheckDelayedCommand(cmd))
{
//Util.DebugOut(cmd.ToString());
cmd.Execute(this);
}
}
private bool CheckDelayedCommand(Commands.ICommand cmd)
{
if (cmd.AffectsMultiplePrims())
{
bool delay = false;
Commands.IMultiPrimCommand mpCommand = (Commands.IMultiPrimCommand)cmd;
IEnumerable<PhysxPrim> targets = mpCommand.GetTargetPrims();
foreach (PhysxPrim target in targets)
{
delay |= CheckAddDelay(cmd, target);
}
//if (delay) m_log.DebugFormat("[InWorldz.PhysX] Delaying physics command pending command completion");
return delay;
}
else
{
PhysxPrim target = cmd.GetTargetPrim();
if (target == null)
{
return false;
}
return CheckAddDelay(cmd, target);
}
}
private bool CheckAddDelay(Commands.ICommand cmd, PhysxPrim target)
{
DelayedCommandInfo delayInfo;
if (_delayedCommands.TryGetValue(target, out delayInfo) && delayInfo.Initiator != cmd)
{
//if we're already the last delayed command delayed behind the other command
//for the given prim, we only need to be added once per command so we can safely
//just return
if (delayInfo.Commands.Count > 0 && delayInfo.Commands.Last.Value == cmd)
{
return true;
}
//before adding this new command to wait, check to see if it is cullable.
//if the command is cullable, and has the same targets, we replace it with this command
//maintaining its position in the queue
LinkedListNode<Commands.ICommand> cmdNode;
if (cmd.IsCullable
&& delayInfo.TopCullables != null && delayInfo.TopCullables.TryGetValue(cmd.GetType(), out cmdNode)
&& HasSameTargets(cmdNode.Value, cmd))
{
cmdNode.Value = cmd;
if (cmd.AffectsMultiplePrims()) ((Commands.IMultiPrimCommand)cmd).AddDelay();
return true;
}
else
{
cmdNode = delayInfo.Commands.AddLast(cmd);
if (cmd.AffectsMultiplePrims()) ((Commands.IMultiPrimCommand)cmd).AddDelay();
if (cmd.IsCullable)
{
if (delayInfo.TopCullables == null)
{
delayInfo.TopCullables = new Dictionary<Type, LinkedListNode<Commands.ICommand>>();
}
delayInfo.TopCullables.Add(cmd.GetType(), cmdNode);
}
return true;
}
}
return false;
}
private bool HasSameTargets(Commands.ICommand cmd1, Commands.ICommand cmd2)
{
if (cmd1.AffectsMultiplePrims() != cmd2.AffectsMultiplePrims())
{
m_log.ErrorFormat("[InWorldz.PhysxPhysics] Asked to check command targets for different command types!");
return false;
}
if (cmd1.AffectsMultiplePrims())
{
IEnumerator<PhysxPrim> cmd1prims = ((Commands.IMultiPrimCommand)cmd1).GetTargetPrims().GetEnumerator();
IEnumerator<PhysxPrim> cmd2prims = ((Commands.IMultiPrimCommand)cmd2).GetTargetPrims().GetEnumerator();
bool cmd1end = false;
bool cmd2end = false;
while (true)
{
cmd1end = cmd1prims.MoveNext();
cmd2end = cmd2prims.MoveNext();
if (cmd1end || cmd2end) break;
if (cmd1prims.Current != cmd2prims.Current) return false;
}
return cmd1end == cmd2end;
}
else
{
return cmd1.GetTargetPrim() == cmd2.GetTargetPrim();
}
}
public override void GetResults()
{
}
public override void SetTerrain(float[] heightMap, int revision)
{
this._meshingStage.MeshHeightfield(heightMap,
delegate(Tuple<PhysX.TriangleMesh, MemoryStream> meshedHeightfield)
{
this.QueueCommand(new Commands.SetTerrainCmd(meshedHeightfield, revision));
});
}
/// <summary>
/// Called by the loader before the scene loop is running
/// </summary>
/// <param name="heightMap"></param>
public override void SetStartupTerrain(float[] heightMap, int revision)
{
m_log.Info("[InWorldz.PhysxPhysics] Setting starup terrain");
this.QueueCommand(new Commands.SetTerrainCmd(heightMap, true, revision));
}
public void SetTerrainSync(float[] heightMap, bool canLoadFromCache, int revision)
{
_terrainMgr.SetTerrainSync(heightMap, canLoadFromCache, revision);
}
internal void SetPremeshedTerrainSync(Tuple<PhysX.TriangleMesh, MemoryStream> premeshedTerrainData, int revision)
{
_terrainMgr.SetTerrainPremeshedSync(premeshedTerrainData, revision);
}
public override void SetWaterLevel(float baseheight)
{
//NOP
}
public override void Dispose()
{
_stop = true;
TimingThread.Join();
_timingSignal.Set();
HeartbeatThread.Join();
_meshingStage.InformCachesToPerformDirectDeletes();
foreach (PhysxPrim actor in _allPrims)
{
actor.Dispose();
}
_meshingStage.Stop();
_meshingStage.Dispose();
_terrainMgr.Dispose();
}
public override Dictionary<uint, float> GetTopColliders()
{
return new Dictionary<uint, float>();
}
public override bool IsThreaded
{
get { return false; }
}
public void QueueCommand(Commands.ICommand command)
{
_currentCommandQueue.Enqueue(command);
_timingSignal.Set();
}
internal void AddPrimSync(PhysxPrim prim, bool physical, bool kinematicStatic)
{
_allPrims.Add(prim);
if (physical) _dynPrims.Add(prim);
if (kinematicStatic) _kinematicManager.KinematicChanged(prim);
}
internal void PrimMadeDynamic(PhysxPrim prim)
{
_dynPrims.Add(prim);
_kinematicManager.KinematicRemoved(prim);
}
internal void PrimMadeStaticKinematic(PhysxPrim actor)
{
_dynPrims.Remove(actor);
_kinematicManager.KinematicChanged(actor);
}
internal void UpdateKinematic(PhysxPrim actor)
{
_kinematicManager.KinematicChanged(actor);
}
internal void RemovePrim(PhysxPrim prim)
{
_dynPrims.Remove(prim);
_allPrims.Remove(prim);
_collisionRepeatPrims.Remove(prim);
_kinematicManager.KinematicRemoved(prim);
_delayedCommands.Remove(prim);
prim.Dispose();
}
internal void PrimBecameChild(PhysxPrim prim)
{
_dynPrims.Remove(prim);
_allPrims.Remove(prim);
_kinematicManager.KinematicRemoved(prim);
_delayedCommands.Remove(prim);
}
internal void BeginDelayCommands(PhysxPrim prim, Commands.ICommand initiator)
{
DelayedCommandInfo info = new DelayedCommandInfo { Commands = new LinkedList<Commands.ICommand>(), Initiator = initiator };
_delayedCommands.Add(prim, info);
}
internal void EndDelayCommands(PhysxPrim prim)
{
DelayedCommandInfo delayedCmds;
if (_delayedCommands.TryGetValue(prim, out delayedCmds))
{
_delayedCommands.Remove(prim);
foreach (Commands.ICommand cmd in delayedCmds.Commands)
{
if (cmd.RemoveWaitAndCheckReady())
{
this.EnqueueFreedCommand(cmd);
}
}
}
}
/// <summary>
/// Enqueues commands to be processed FIRST on the next physics spin
/// This ensures that commands that were blocked and delayed for a specific
/// object run first before other commands that may have gotten in just after
/// the delay was released
/// </summary>
/// <param name="cmd"></param>
private void EnqueueFreedCommand(Commands.ICommand cmd)
{
_freedCommands.Enqueue(cmd);
}
internal void AddCharacterSync(PhysxCharacter newChar)
{
_charActors.Add(newChar);
}
internal void RemoveCharacterSync(PhysxCharacter physxCharacter)
{
_charActors.Remove(physxCharacter);
}
private void OnContact(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs)
{
if ((contactPairHeader.Flags & PhysX.ContactPairHeaderFlag.DeletedActor0) == 0)
{
bool wasPrim = TryInformPrimOfContactChange(contactPairHeader, pairs, 0);
if (! wasPrim)
{
TryInformCharacterOfContactChange(contactPairHeader, pairs, 0);
}
}
if ((contactPairHeader.Flags & PhysX.ContactPairHeaderFlag.DeletedActor1) == 0)
{
bool wasPrim = TryInformPrimOfContactChange(contactPairHeader, pairs, 1);
if (!wasPrim)
{
TryInformCharacterOfContactChange(contactPairHeader, pairs, 1);
}
}
}
private bool TryInformCharacterOfContactChange(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs, int actorIndex)
{
PhysxCharacter character = contactPairHeader.Actors[actorIndex].UserData as PhysxCharacter;
if (character != null)
{
character.OnContactChangeSync(contactPairHeader, pairs, actorIndex);
return true;
}
else
{
return false;
}
}
private bool TryInformPrimOfContactChange(PhysX.ContactPairHeader contactPairHeader, PhysX.ContactPair[] pairs, int actorIndex)
{
PhysxPrim prim = contactPairHeader.Actors[actorIndex].UserData as PhysxPrim;
if (prim != null)
{
prim.OnContactChangeSync(contactPairHeader, pairs, actorIndex);
return true;
}
else
{
return false;
}
}
void OnTrigger(PhysX.TriggerPair[] pairs)
{
foreach (var pair in pairs)
{
if (pair.TriggerShape != null)
{
PhysxPrim triggerPrim = pair.TriggerShape.Actor.UserData as PhysxPrim;
if (triggerPrim != null)
{
triggerPrim.OnTrigger(pair);
}
}
}
}
internal void WakeAllDynamics()
{
foreach (PhysxPrim prim in _dynPrims)
{
prim.WakeUp();
}
}
public override IMaterial FindMaterialImpl(OpenMetaverse.Material materialEnum)
{
return Material.FindImpl(materialEnum);
}
public void PrimWantsCollisionRepeat(PhysxPrim prim)
{
_collisionRepeatPrims.Add(prim);
}
public void PrimDisabledCollisionRepeat(PhysxPrim prim)
{
_collisionRepeatPrims.Remove(prim);
}
public void ForEachCharacter(Action<PhysxCharacter> eachCallback)
{
foreach (PhysxCharacter character in _charActors)
{
eachCallback(character);
}
}
public override void DumpCollisionInfo()
{
ContactDebug.OnDataReady += new Debugging.ContactDebugManager.DataCallback(ContactDebug_OnDataReady);
ContactDebug.BeginCollectingContactData();
}
void ContactDebug_OnDataReady(IEnumerable<KeyValuePair<PhysX.Actor, int>> data)
{
m_log.InfoFormat("[InWorldz.PhysX.Debugging] Contact Dump --");
foreach (var kvp in data)
{
if (kvp.Key.UserData == null) continue;
PhysxPrim prim = kvp.Key.UserData as PhysxPrim;
if (prim == null)
{
m_log.DebugFormat("[InWorldz.PhysX.Debugging]: (object) {0}", kvp.Value);
}
else
{
OpenMetaverse.Vector3 pos = prim.Position;
m_log.DebugFormat("[InWorldz.PhysX.Debugging]: {0} {1} at {2}/{3}/{4}", prim.SOPName, kvp.Value,
(int)(pos.X + 0.5), (int)(pos.Y + 0.5), (int)(pos.Z + 0.5));
}
}
ContactDebug.OnDataReady -= new Debugging.ContactDebugManager.DataCallback(ContactDebug_OnDataReady);
}
internal void DisableKinematicTransitionTracking(PhysxPrim physxPrim)
{
_kinematicManager.KinematicRemoved(physxPrim);
}
internal void ChildPrimDeleted(PhysxPrim childPrim)
{
_collisionRepeatPrims.Remove(childPrim);
}
public override void SendPhysicsWindData(OpenMetaverse.Vector2[] sea, OpenMetaverse.Vector2[] gnd, OpenMetaverse.Vector2[] air,
float[] ranges, float[] maxheights)
{
QueueCommand(
new Commands.GenericSyncCmd(
(PhysxScene scene) =>
{
scene.RegionWaterCurrents = sea;
scene.RegionWindGround = gnd;
scene.RegionWindAloft = air;
scene.RegionTerrainRanges = ranges;
scene.RegionTerrainMaxHeights = maxheights;
}
));
}
public override List<ContactResult> RayCastWorld(OpenMetaverse.Vector3 start, OpenMetaverse.Vector3 direction, float distance,
int hitAmounts)
{
List<ContactResult> contactResults = new List<ContactResult>();
AutoResetEvent ev = new AutoResetEvent(false);
RayCastWorld(start, direction, distance, hitAmounts, (r) =>
{
contactResults = r;
ev.Set();
});
ev.WaitOne(1000);
return contactResults;
}
public override void RayCastWorld(OpenMetaverse.Vector3 start, OpenMetaverse.Vector3 direction, float distance,
int hitAmounts, Action<List<ContactResult>> result)
{
QueueCommand(
new Commands.GenericSyncCmd(
(PhysxScene scene) =>
{
GetRayCastResults(start, direction, distance, hitAmounts, result, scene);
}
));
}
private void GetRayCastResults(OpenMetaverse.Vector3 start, OpenMetaverse.Vector3 direction,
float distance, int hitAmounts, Action<List<ContactResult>> result, PhysxScene scene)
{
int buffercount = 16;
int maxbuffercount = 1024;
PhysX.RaycastHit[] hits = null;
direction = OpenMetaverse.Vector3.Normalize(direction);
//Increase the buffer count if the call indicates overflow. Prevent infinite loops.
while (hits == null && buffercount <= maxbuffercount)
{
hits = SceneImpl.RaycastMultiple(PhysUtil.OmvVectorToPhysx(start),
PhysUtil.OmvVectorToPhysx(direction),
distance, PhysX.SceneQueryFlags.All,
buffercount,
null);
buffercount *= 2;
}
List<ContactResult> contactResults = new List<ContactResult>();
if (hits != null)
{
List<PhysX.RaycastHit> hitsSorted = new List<PhysX.RaycastHit>(hits);
hitsSorted.Sort((a, b) => a.Distance.CompareTo(b.Distance));
int count = 0;
foreach (PhysX.RaycastHit hit in hitsSorted)
{
contactResults.Add(new ContactResult()
{
Distance = hit.Distance,
FaceIndex = hit.FaceIndex,
CollisionActor = hit.Shape.Actor.UserData as PhysicsActor,
Position = PhysUtil.PhysxVectorToOmv(hit.Impact),
Normal = PhysUtil.PhysxVectorToOmv(hit.Normal),
});
if (++count >= hitAmounts)
break;
}
}
result(contactResults);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SpoolingTask.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// A factory class to execute spooling logic.
/// </summary>
internal static class SpoolingTask
{
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Executes synchronously,
// and by the time this API has returned all of the results have been produced.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Debug.Assert(partitions.PartitionCount == channels.Length);
Debug.Assert(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// A stop-and-go merge uses the current thread for one task and then blocks before
// returning to the caller, until all results have been accumulated. We do this by
// running the last partition on the calling thread.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(
maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Runs asynchronously.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolPipeline<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Debug.Assert(partitions.PartitionCount == channels.Length);
Debug.Assert(groupState != null);
// Ensure all tasks in this query are parented under a common root. Because this
// is a pipelined query, we detach it from the parent (to avoid blocking the calling
// thread), and run the query on a separate thread.
Task rootTask = new Task(
() =>
{
// Create tasks that will enumerate the partitions in parallel. Because we're pipelining,
// we will begin running these tasks in parallel and then return.
for (int i = 0; i < partitions.PartitionCount; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// And schedule it for execution. This is done after beginning to ensure no thread tries to
// end the query before its root task has been recorded properly.
rootTask.Start(taskScheduler);
// We don't call QueryEnd here; when we return, the query is still executing, and the
// last enumerator to be disposed of will call QueryEnd for us.
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. This is a for-all style
// execution, meaning that the query will be run fully (for effect) before returning
// and that there are no channels into which data will be queued.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// taskScheduler - the task manager on which to execute
//
internal static void SpoolForAll<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler)
{
Debug.Assert(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// Create tasks that will enumerate the partitions in parallel "for effect"; in other words,
// no data will be placed into any kind of producer-consumer channel.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private SynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal StopAndGoSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Debug.Assert(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
SynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
destination.Init();
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private AsynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal PipelineSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Debug.Assert(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
AsynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
// Flush remaining data to the query consumer in preparation for channel shutdown.
destination.FlushBuffers();
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal ForAllSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source)
: base(taskIndex, groupState)
{
Debug.Assert(source != null);
_source = source;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream for effect.
TInputOutput currentUnused = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
//Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks
while (_source.MoveNext(ref currentUnused, ref keyUnused))
;
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Dispose of the source enumerator
_source.Dispose();
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using EnvDTE;
using EnvDTE80;
using Gallio.Common.Collections;
using Gallio.Runtime.Extensibility;
using Gallio.VisualStudio.Shell.Core;
using Microsoft.VisualStudio.CommandBars;
using stdole;
namespace Gallio.VisualStudio.Shell.UI.Commands
{
/// <summary>
/// Installs, removes and executes Visual Studio commands.
/// </summary>
public class DefaultCommandManager : ICommandManager
{
private readonly ComponentHandle<ICommand, CommandTraits>[] commandHandles;
private readonly DefaultShell shell;
private Dictionary<string, CommandPresentation> commandPresentations;
/// <summary>
/// Initializes the command manager.
/// </summary>
/// <param name="commandHandles">The command handles.</param>
/// <param name="shell">The shell.</param>
public DefaultCommandManager(ComponentHandle<ICommand, CommandTraits>[] commandHandles, IShell shell)
{
this.commandHandles = commandHandles;
this.shell = (DefaultShell) shell;
commandPresentations = new Dictionary<string, CommandPresentation>();
}
internal void Initialize()
{
shell.ShellHooks.Exec += Exec;
shell.ShellHooks.QueryStatus += QueryStatus;
InstallActions();
}
internal void Shutdown()
{
shell.ShellHooks.Exec -= Exec;
shell.ShellHooks.QueryStatus -= QueryStatus;
}
private void InstallActions()
{
if (commandPresentations != null)
return;
commandPresentations = new Dictionary<string, CommandPresentation>();
foreach (var commandHandle in commandHandles)
{
CommandTraits traits = commandHandle.GetTraits();
Commands2 commands = (Commands2) shell.DTE.Commands;
Command command;
try
{
command = commands.Item(traits.CommandName, 0);
}
catch
{
object[] contextGuids = null;
command = commands.AddNamedCommand2(shell.ShellAddIn,
traits.CommandName,
traits.Caption,
traits.Tooltip,
true, 59, ref contextGuids,
(int) ToVsCommandStatus(traits.Status),
(int) ToVsCommandStyle(traits.Style),
ToVsCommandControlType(traits.ControlType));
}
CommandBarButton[] controls = GenericCollectionUtils.ConvertAllToArray(traits.CommandBarPaths,
commandBarPath =>
{
CommandBar commandBar = GetCommandBar(commandBarPath);
CommandBarButton commandBarButton = GetOrCreateCommandBarButton(commandBar, command, commands);
return commandBarButton;
});
CommandPresentation presentation = new CommandPresentation(commandHandle, command, controls);
presentation.Icon = traits.Icon;
presentation.Caption = traits.Caption;
presentation.Tooltip = traits.Tooltip;
presentation.Status = traits.Status;
commandPresentations.Add(traits.CommandName, presentation);
}
}
private CommandBarButton GetOrCreateCommandBarButton(CommandBar commandBar, Command command, Commands2 commands)
{
foreach (CommandBarControl control in commandBar.Controls)
{
CommandBarButton button = control as CommandBarButton;
if (button != null)
{
string guid;
int id;
commands.CommandInfo(control, out guid, out id);
if (command.Guid == guid)
return button;
}
}
return (CommandBarButton)command.AddControl(commandBar, 1);
}
private CommandBar GetCommandBar(string commandPath)
{
string[] segments = commandPath.Split('\\');
string commandBarName = segments[0];
CommandBar commandBar = ((CommandBars)shell.DTE.CommandBars)[commandBarName];
for (int i = 1; i < segments.Length; i++)
commandBar = ((CommandBarPopup)commandBar.Controls[segments[i]]).CommandBar;
return commandBar;
}
private void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus statusOption, ref object commandText)
{
if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
{
CommandPresentation commandPresentation;
if (commandPresentations.TryGetValue(commandName, out commandPresentation))
{
commandPresentation.UpdateCommandStatus();
statusOption = ToVsCommandStatus(commandPresentation.Status);
}
else
{
statusOption = vsCommandStatus.vsCommandStatusUnsupported;
}
}
}
private void Exec(string commandName, vsCommandExecOption executeOption, ref object variantIn, ref object variantOut, ref bool handled)
{
handled = false;
if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
CommandPresentation commandPresentation;
if (commandPresentations.TryGetValue(commandName, out commandPresentation))
{
commandPresentation.ExecuteCommand();
handled = true;
}
}
}
private static vsCommandStatus ToVsCommandStatus(CommandStatus status)
{
switch (status)
{
case CommandStatus.Enabled:
return vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;
case CommandStatus.Invisible:
return vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusInvisible;
case CommandStatus.Latched:
return vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusLatched;
case CommandStatus.Ninched:
return vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusNinched;
default:
throw new ArgumentOutOfRangeException("status");
}
}
private static vsCommandStyle ToVsCommandStyle(CommandStyle style)
{
switch (style)
{
case CommandStyle.PictureAndText:
return vsCommandStyle.vsCommandStylePictAndText;
case CommandStyle.Picture:
return vsCommandStyle.vsCommandStylePict;
case CommandStyle.Text:
return vsCommandStyle.vsCommandStyleText;
default:
throw new ArgumentOutOfRangeException("style");
}
}
private static vsCommandControlType ToVsCommandControlType(CommandControlType controlType)
{
switch (controlType)
{
case CommandControlType.Button:
return vsCommandControlType.vsCommandControlTypeButton;
case CommandControlType.DropDown:
return vsCommandControlType.vsCommandControlTypeDropDownCombo;
default:
throw new ArgumentOutOfRangeException("controlType");
}
}
private class CommandPresentation : ICommandPresentation
{
private readonly ComponentHandle<ICommand, CommandTraits> commandHandle;
private readonly Command vsCommand;
private readonly CommandBarButton[] vsCommandBarButtons;
private Icon icon;
private string caption;
private string tooltip;
private CommandStatus status;
public CommandPresentation(ComponentHandle<ICommand, CommandTraits> commandHandle,
Command vsCommand, CommandBarButton[] vsCommandBarButtons)
{
this.commandHandle = commandHandle;
this.vsCommand = vsCommand;
this.vsCommandBarButtons = vsCommandBarButtons;
}
public ComponentHandle<ICommand, CommandTraits> CommandHandle
{
get { return commandHandle; }
}
public Command VsCommand
{
get { return vsCommand; }
}
public CommandBarButton[] VsCommandBarButtons
{
get { return vsCommandBarButtons; }
}
public string Caption
{
get { return caption; }
set
{
caption = value;
foreach (var vsCommandBarButton in vsCommandBarButtons)
vsCommandBarButton.Caption = value;
}
}
public string Tooltip
{
get { return tooltip; }
set
{
tooltip = value;
foreach (var vsCommandBarButton in vsCommandBarButtons)
vsCommandBarButton.TooltipText = value;
}
}
public Icon Icon
{
get { return icon; }
set
{
icon = value;
StdPicture picture = (StdPicture)ImageConversionUtils.GetIPictureDispFromImage(value.ToBitmap());
foreach (var vsCommandBarButton in vsCommandBarButtons)
vsCommandBarButton.Picture = picture;
}
}
public CommandStatus Status
{
get { return status; }
set { status = value; }
}
public void ExecuteCommand()
{
commandHandle.GetComponent().Execute(this);
}
public void UpdateCommandStatus()
{
commandHandle.GetComponent().Update(this);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract partial class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
List<State[]> allStates = StateArrayTempate.ToList();
State[] errorStates = StateArrayTempate[0];
State[] valueStates = StateArrayTempate[7];
EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken));
foreach (ulong valueToken in enumValuesAndNames.Values)
{
if (allStates.Count <= (int)valueToken)
{
JsonToken token = (JsonToken)valueToken;
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private List<JsonPosition>? _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the destination should be closed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the destination when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the JSON should be auto-completed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to auto-complete the JSON when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool AutoCompleteOnClose { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = _stack?.Count ?? 0;
if (Peek() != JsonContainerType.None)
{
depth++;
}
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None || _stack == null)
{
return string.Empty;
}
return JsonPosition.BuildPath(_stack, null);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack!, current);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string? _dateFormatString;
private CultureInfo? _culture;
/// <summary>
/// Gets or sets a value indicating how JSON text output should be formatted.
/// </summary>
public Formatting Formatting
{
get => _formatting;
set
{
if (value < Formatting.None || value > Formatting.Indented)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_formatting = value;
}
}
/// <summary>
/// Gets or sets how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get => _dateFormatHandling;
set
{
if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get => _dateTimeZoneHandling;
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get => _stringEscapeHandling;
set
{
if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>,
/// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get => _floatFormatHandling;
set
{
if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text.
/// </summary>
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.InvariantCulture;
set => _culture = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriter"/> class.
/// </summary>
protected JsonWriter()
{
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
AutoCompleteOnClose = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
}
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack != null && _stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the destination and also flushes the destination.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this writer.
/// If <see cref="CloseOutput"/> is set to <c>true</c>, the destination is also closed.
/// If <see cref="AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public virtual void Close()
{
if (AutoCompleteOnClose)
{
AutoCompleteAll();
}
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
WriteToken(reader, writeChildren, true, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.
/// </param>
public void WriteToken(JsonToken token, object? value)
{
switch (token)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment(value?.ToString());
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_BIG_INTEGER
if (value is BigInteger integer)
{
WriteValue(integer);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is decimal decimalValue)
{
WriteValue(decimalValue);
}
else if (value is double doubleValue)
{
WriteValue(doubleValue);
}
else if (value is float floatValue)
{
WriteValue(floatValue);
}
else
{
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_DATE_TIME_OFFSET
if (value is DateTimeOffset dt)
{
WriteValue(dt);
}
else
#endif
{
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Raw:
WriteRawValue(value?.ToString());
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is Guid guid)
{
WriteValue(guid);
}
else
{
WriteValue((byte[])value!);
}
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type.");
}
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteToken(token, null);
}
internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
int initialDepth = CalculateWriteTokenInitialDepth(reader);
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
else
{
if (writeComments || reader.TokenType != JsonToken.Comment)
{
WriteToken(reader.TokenType, reader.Value);
}
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth))
{
throw JsonWriterException.Create(this, "Unexpected end when reading token.", null);
}
}
private bool IsWriteTokenIncomplete(JsonReader reader, bool writeChildren, int initialDepth)
{
int finalDepth = CalculateWriteTokenFinalDepth(reader);
return initialDepth < finalDepth ||
(writeChildren && initialDepth == finalDepth && JsonTokenUtils.IsStartToken(reader.TokenType));
}
private int CalculateWriteTokenInitialDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsStartToken(type) ? reader.Depth : reader.Depth + 1;
}
private int CalculateWriteTokenFinalDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsEndToken(type) ? reader.Depth - 1 : reader.Depth;
}
private void WriteConstructorDate(JsonReader reader)
{
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string? errorMessage))
{
throw JsonWriterException.Create(this, errorMessage, null);
}
WriteValue(dateTime);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
int levelsToComplete = CalculateLevelsToComplete(type);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
{
WriteNull();
}
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
{
WriteIndent();
}
}
WriteEnd(token);
UpdateCurrentState();
}
}
private int CalculateLevelsToComplete(JsonContainerType type)
{
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack![currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
{
throw JsonWriterException.Create(this, "No token to close.", null);
}
return levelsToComplete;
}
private void UpdateCurrentState()
{
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
{
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
}
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
{
WriteIndentSpace();
}
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
WriteIndent();
}
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string? json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string? json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string? value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[]? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
}
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
}
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object? value)
{
if (value == null)
{
WriteNull();
}
else
{
#if HAVE_BIG_INTEGER
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
{
throw CreateUnsupportedTypeException(this, value);
}
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string? text)
{
InternalWriteComment();
}
/// <summary>
/// Writes the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
while (true)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
return;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
return;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
return;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
return;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
return;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
return;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
return;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
return;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
return;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
return;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
return;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
return;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
return;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
return;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
return;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
return;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
return;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
return;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
return;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
return;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
return;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
return;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
return;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
return;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
return;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
return;
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
return;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
return;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
return;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
return;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
return;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
return;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
return;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
return;
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
return;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
return;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
return;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
return;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
return;
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
return;
#endif
default:
#if HAVE_ICONVERTIBLE
if (value is IConvertible convertible)
{
ResolveConvertibleValue(convertible, out typeCode, out value);
continue;
}
#endif
// write an unknown null value, fix https://github.com/JamesNK/Newtonsoft.Json/issues/1460
if (value == null)
{
writer.WriteNull();
return;
}
throw CreateUnsupportedTypeException(writer, value);
}
}
}
#if HAVE_ICONVERTIBLE
private static void ResolveConvertibleValue(IConvertible convertible, out PrimitiveTypeCode typeCode, out object value)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertible);
// if convertible has an underlying typecode of Object then attempt to convert it to a string
typeCode = typeInformation.TypeCode == PrimitiveTypeCode.Object ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = typeInformation.TypeCode == PrimitiveTypeCode.Object ? typeof(string) : typeInformation.Type;
value = convertible.ToType(resolvedType, CultureInfo.InvariantCulture);
}
#endif
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the <see cref="JsonWriter"/>.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string s))
{
throw new ArgumentException("A name is required when setting property name state.", nameof(value));
}
InternalWritePropertyName(s);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException(nameof(token));
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
{
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Exception information provided through
/// a call to one of the Logger.*Exception() methods.
/// </summary>
[LayoutRenderer("exception")]
[ThreadAgnostic]
[ThreadSafe]
public class ExceptionLayoutRenderer : LayoutRenderer
{
private string _format;
private string _innerFormat = string.Empty;
private readonly Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>> _renderingfunctions;
private static readonly Dictionary<string, ExceptionRenderingFormat> _formatsMapping = new Dictionary<string, ExceptionRenderingFormat>(StringComparer.OrdinalIgnoreCase)
{
{"MESSAGE",ExceptionRenderingFormat.Message},
{"TYPE", ExceptionRenderingFormat.Type},
{"SHORTTYPE",ExceptionRenderingFormat.ShortType},
{"TOSTRING",ExceptionRenderingFormat.ToString},
{"METHOD",ExceptionRenderingFormat.Method},
{"STACKTRACE", ExceptionRenderingFormat.StackTrace},
{"DATA",ExceptionRenderingFormat.Data},
{"@",ExceptionRenderingFormat.Serialize},
};
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class.
/// </summary>
public ExceptionLayoutRenderer()
{
Format = "message";
Separator = " ";
ExceptionDataSeparator = ";";
InnerExceptionSeparator = EnvironmentHelper.NewLine;
MaxInnerExceptionLevel = 0;
_renderingfunctions = new Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>>()
{
{ExceptionRenderingFormat.Message, AppendMessage},
{ExceptionRenderingFormat.Type, AppendType},
{ExceptionRenderingFormat.ShortType, AppendShortType},
{ExceptionRenderingFormat.ToString, AppendToString},
{ExceptionRenderingFormat.Method, AppendMethod},
{ExceptionRenderingFormat.StackTrace, AppendStackTrace},
{ExceptionRenderingFormat.Data, AppendData},
{ExceptionRenderingFormat.Serialize, AppendSerializeObject},
};
}
/// <summary>
/// Gets or sets the format of the output. Must be a comma-separated list of exception
/// properties: Message, Type, ShortType, ToString, Method, StackTrace.
/// This parameter value is case-insensitive.
/// </summary>
/// <see cref="Formats"/>
/// <see cref="ExceptionRenderingFormat"/>
/// <docgen category='Rendering Options' order='10' />
[DefaultParameter]
public string Format
{
get => _format;
set
{
_format = value;
Formats = CompileFormat(value);
}
}
/// <summary>
/// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception
/// properties: Message, Type, ShortType, ToString, Method, StackTrace.
/// This parameter value is case-insensitive.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string InnerFormat
{
get => _innerFormat;
set
{
_innerFormat = value;
InnerFormats = CompileFormat(value);
}
}
/// <summary>
/// Gets or sets the separator used to concatenate parts specified in the Format.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(" ")]
public string Separator { get; set; }
/// <summary>
/// Gets or sets the separator used to concatenate exception data specified in the Format.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(";")]
public string ExceptionDataSeparator { get; set; }
/// <summary>
/// Gets or sets the maximum number of inner exceptions to include in the output.
/// By default inner exceptions are not enabled for compatibility with NLog 1.0.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(0)]
public int MaxInnerExceptionLevel { get; set; }
/// <summary>
/// Gets or sets the separator between inner exceptions.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string InnerExceptionSeparator { get; set; }
/// <summary>
/// Gets the formats of the output of inner exceptions to be rendered in target.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
/// <see cref="ExceptionRenderingFormat"/>
public List<ExceptionRenderingFormat> Formats
{
get;
private set;
}
/// <summary>
/// Gets the formats of the output to be rendered in target.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
/// <see cref="ExceptionRenderingFormat"/>
public List<ExceptionRenderingFormat> InnerFormats
{
get;
private set;
}
/// <summary>
/// Renders the specified exception information and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
Exception primaryException = logEvent.Exception;
if (primaryException != null)
{
AppendException(primaryException, Formats, builder);
int currentLevel = 0;
if (currentLevel < MaxInnerExceptionLevel)
{
currentLevel = AppendInnerExceptionTree(primaryException, currentLevel, builder);
#if !NET3_5 && !SILVERLIGHT4
AggregateException asyncException = primaryException as AggregateException;
if (asyncException != null)
{
AppendAggregateException(asyncException, currentLevel, builder);
}
#endif
}
}
}
#if !NET3_5 && !SILVERLIGHT4
private void AppendAggregateException(AggregateException primaryException, int currentLevel, StringBuilder builder)
{
var asyncException = primaryException.Flatten();
if (asyncException.InnerExceptions != null)
{
for (int i = 0; i < asyncException.InnerExceptions.Count && currentLevel < MaxInnerExceptionLevel; i++, currentLevel++)
{
var currentException = asyncException.InnerExceptions[i];
if (ReferenceEquals(currentException, primaryException.InnerException))
continue; // Skip firstException when it is innerException
if (currentException == null)
{
InternalLogger.Debug("Skipping rendering exception as exception is null");
continue;
}
AppendInnerException(currentException, builder);
currentLevel++;
currentLevel = AppendInnerExceptionTree(currentException, currentLevel, builder);
}
}
}
#endif
private int AppendInnerExceptionTree(Exception currentException, int currentLevel, StringBuilder sb)
{
currentException = currentException.InnerException;
while (currentException != null && currentLevel < MaxInnerExceptionLevel)
{
AppendInnerException(currentException, sb);
currentLevel++;
currentException = currentException.InnerException;
}
return currentLevel;
}
private void AppendInnerException(Exception currentException, StringBuilder builder)
{
// separate inner exceptions
builder.Append(InnerExceptionSeparator);
AppendException(currentException, InnerFormats ?? Formats, builder);
}
private void AppendException(Exception currentException, IEnumerable<ExceptionRenderingFormat> renderFormats, StringBuilder builder)
{
int orgLength = builder.Length;
foreach (ExceptionRenderingFormat renderingFormat in renderFormats)
{
if (orgLength != builder.Length)
{
orgLength = builder.Length;
builder.Append(Separator);
}
int beforeRenderLength = builder.Length;
var currentRenderFunction = _renderingfunctions[renderingFormat];
currentRenderFunction(builder, currentException);
if (builder.Length == beforeRenderLength && builder.Length != orgLength)
{
builder.Length = orgLength;
}
}
}
/// <summary>
/// Appends the Message of an Exception to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The exception containing the Message to append.</param>
protected virtual void AppendMessage(StringBuilder sb, Exception ex)
{
try
{
sb.Append(ex.Message);
}
catch (Exception exception)
{
var message =
$"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}.";
sb.Append("NLog message: ");
sb.Append(message);
InternalLogger.Warn(exception, message);
}
}
/// <summary>
/// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose method name should be appended.</param>
protected virtual void AppendMethod(StringBuilder sb, Exception ex)
{
#if SILVERLIGHT || NETSTANDARD1_0
sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace));
#else
if (ex.TargetSite != null)
{
sb.Append(ex.TargetSite.ToString());
}
#endif
}
/// <summary>
/// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose stack trace should be appended.</param>
protected virtual void AppendStackTrace(StringBuilder sb, Exception ex)
{
if (!string.IsNullOrEmpty(ex.StackTrace))
sb.Append(ex.StackTrace);
}
/// <summary>
/// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose call to ToString() should be appended.</param>
protected virtual void AppendToString(StringBuilder sb, Exception ex)
{
sb.Append(ex.ToString());
}
/// <summary>
/// Appends the type of an Exception to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose type should be appended.</param>
protected virtual void AppendType(StringBuilder sb, Exception ex)
{
sb.Append(ex.GetType().FullName);
}
/// <summary>
/// Appends the short type of an Exception to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose short type should be appended.</param>
protected virtual void AppendShortType(StringBuilder sb, Exception ex)
{
sb.Append(ex.GetType().Name);
}
/// <summary>
/// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose Data property elements should be appended.</param>
protected virtual void AppendData(StringBuilder sb, Exception ex)
{
if (ex.Data != null && ex.Data.Count > 0)
{
string separator = string.Empty;
foreach (var key in ex.Data.Keys)
{
sb.Append(separator);
sb.AppendFormat("{0}: {1}", key, ex.Data[key]);
separator = ExceptionDataSeparator;
}
}
}
/// <summary>
/// Appends all the serialized properties of an Exception into the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="ex">The Exception whose properties should be appended.</param>
protected virtual void AppendSerializeObject(StringBuilder sb, Exception ex)
{
ConfigurationItemFactory.Default.ValueFormatter.FormatValue(ex, null, MessageTemplates.CaptureType.Serialize, null, sb);
}
/// <summary>
/// Split the string and then compile into list of Rendering formats.
/// </summary>
/// <param name="formatSpecifier"></param>
/// <returns></returns>
private static List<ExceptionRenderingFormat> CompileFormat(string formatSpecifier)
{
List<ExceptionRenderingFormat> formats = new List<ExceptionRenderingFormat>();
string[] parts = formatSpecifier.Replace(" ", string.Empty).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
{
ExceptionRenderingFormat renderingFormat;
if (_formatsMapping.TryGetValue(s, out renderingFormat))
{
formats.Add(renderingFormat);
}
else
{
InternalLogger.Warn("Unknown exception data target: {0}", s);
}
}
return formats;
}
#if SILVERLIGHT || NETSTANDARD1_0
/// <summary>
/// Find name of method on stracktrace.
/// </summary>
/// <param name="stackTrace">Full stracktrace</param>
/// <returns></returns>
protected static string ParseMethodNameFromStackTrace(string stackTrace)
{
if (string.IsNullOrEmpty(stackTrace))
return string.Empty;
// get the first line of the stack trace
string stackFrameLine;
int p = stackTrace.IndexOfAny(new[] { '\r', '\n' });
if (p >= 0)
{
stackFrameLine = stackTrace.Substring(0, p);
}
else
{
stackFrameLine = stackTrace;
}
// stack trace is composed of lines which look like this
//
// at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something)
//
// "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis
int lastSpace = -1;
int startPos = 0;
int endPos = stackFrameLine.Length;
for (int i = 0; i < stackFrameLine.Length; ++i)
{
switch (stackFrameLine[i])
{
case ' ':
lastSpace = i;
break;
case '(':
startPos = lastSpace + 1;
break;
case ')':
endPos = i + 1;
// end the loop
i = stackFrameLine.Length;
break;
}
}
return stackTrace.Substring(startPos, endPos - startPos);
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
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>
/// AlertRulesOperations operations.
/// </summary>
internal partial class AlertRulesOperations : IServiceOperations<MonitorManagementClient>, IAlertRulesOperations
{
/// <summary>
/// Initializes a new instance of the AlertRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AlertRulesOperations(MonitorManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorManagementClient
/// </summary>
public MonitorManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates an alert rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='parameters'>
/// The parameters of the rule to create or update.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AlertRuleResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string ruleName, AlertRuleResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-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("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.insights/alertrules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AlertRuleResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_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 an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-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("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.insights/alertrules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_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>
/// Gets an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </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<AlertRuleResource>> GetWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-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("ruleName", ruleName);
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.insights/alertrules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AlertRuleResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AlertRuleResource>(_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>
/// List the alert rules within a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<AlertRuleResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-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("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", 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.insights/alertrules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<AlertRuleResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<AlertRuleResource>>(_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;
}
}
}
| |
using Xunit;
using Shouldly;
using System.Linq;
using System;
using System.Text.RegularExpressions;
namespace AutoMapper.UnitTests
{
public class MapFromReverseResolveUsing : AutoMapperSpecBase
{
public class Source
{
public int Total { get; set; }
}
public class Destination
{
public int Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c =>
{
c.CreateMap<Destination, Source>()
.ForMember(dest => dest.Total, opt => opt.MapFrom(x => x.Total))
.ReverseMap()
.ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>());
});
public class CustomResolver : IValueResolver<Source, Destination, int>
{
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return Int32.MaxValue;
}
}
[Fact]
public void Should_use_the_resolver()
{
Mapper.Map<Destination>(new Source()).Total.ShouldBe(int.MaxValue);
}
}
public class MethodsWithReverse : AutoMapperSpecBase
{
class Order
{
public OrderItem[] OrderItems { get; set; }
}
class OrderItem
{
public string Product { get; set; }
}
class OrderDto
{
public int OrderItemsCount { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c=>
{
c.CreateMap<Order, OrderDto>().ReverseMap();
});
[Fact]
public void ShouldMapOk()
{
Mapper.Map<Order>(new OrderDto());
}
}
public class ReverseForPath : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder CustomerHolder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerName { get; set; }
public decimal Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<OrderDto, Order>()
.ForPath(o => o.CustomerHolder.Customer.Name, o => o.MapFrom(s => s.CustomerName))
.ForPath(o => o.CustomerHolder.Customer.Total, o => o.MapFrom(s => s.Total))
.ReverseMap();
});
[Fact]
public void Should_flatten()
{
var model = new Order {
CustomerHolder = new CustomerHolder {
Customer = new Customer { Name = "George Costanza", Total = 74.85m }
}
};
var dto = Mapper.Map<OrderDto>(model);
dto.CustomerName.ShouldBe("George Costanza");
dto.Total.ShouldBe(74.85m);
}
}
public class ReverseMapFrom : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder CustomerHolder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerName { get; set; }
public decimal Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ForMember(d => d.CustomerName, o => o.MapFrom(s => s.CustomerHolder.Customer.Name))
.ForMember(d => d.Total, o => o.MapFrom(s => s.CustomerHolder.Customer.Total))
.ReverseMap();
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerName = "George Costanza", Total = 74.85m };
var model = Mapper.Map<Order>(dto);
model.CustomerHolder.Customer.Name.ShouldBe("George Costanza");
model.CustomerHolder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseDefaultFlatteningWithIgnoreMember : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder Customerholder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerholderCustomerName { get; set; }
public decimal CustomerholderCustomerTotal { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ReverseMap()
.ForMember(d=>d.Customerholder, o=>o.Ignore())
.ForPath(d=>d.Customerholder.Customer.Total, o=>o.MapFrom(s=>s.CustomerholderCustomerTotal));
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m };
var model = Mapper.Map<Order>(dto);
model.Customerholder.Customer.Name.ShouldBeNull();
model.Customerholder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseDefaultFlattening : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder Customerholder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerholderCustomerName { get; set; }
public decimal CustomerholderCustomerTotal { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ReverseMap();
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m };
var model = Mapper.Map<Order>(dto);
model.Customerholder.Customer.Name.ShouldBe("George Costanza");
model.Customerholder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseMapConventions : AutoMapperSpecBase
{
Rotator_Ad_Run _destination;
DateTime _startDate = DateTime.Now, _endDate = DateTime.Now.AddHours(2);
public class Rotator_Ad_Run
{
public DateTime Start_Date { get; set; }
public DateTime End_Date { get; set; }
public bool Enabled { get; set; }
}
public class RotatorAdRunViewModel
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool Enabled { get; set; }
}
public class UnderscoreNamingConvention : INamingConvention
{
public Regex SplittingExpression { get; } = new Regex(@"\p{Lu}[a-z0-9]*(?=_?)");
public string SeparatorCharacter => "_";
public string ReplaceValue(Match match)
{
return match.Value;
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateProfile("MyMapperProfile", prf =>
{
prf.SourceMemberNamingConvention = new UnderscoreNamingConvention();
prf.CreateMap<Rotator_Ad_Run, RotatorAdRunViewModel>();
});
cfg.CreateProfile("MyMapperProfile2", prf =>
{
prf.DestinationMemberNamingConvention = new UnderscoreNamingConvention();
prf.CreateMap<RotatorAdRunViewModel, Rotator_Ad_Run>();
});
});
protected override void Because_of()
{
_destination = Mapper.Map<RotatorAdRunViewModel, Rotator_Ad_Run>(new RotatorAdRunViewModel { Enabled = true, EndDate = _endDate, StartDate = _startDate });
}
[Fact]
public void Should_apply_the_convention_in_reverse()
{
_destination.Enabled.ShouldBeTrue();
_destination.End_Date.ShouldBe(_endDate);
_destination.Start_Date.ShouldBe(_startDate);
}
}
public class When_reverse_mapping_classes_with_simple_properties : AutoMapperSpecBase
{
private Source _source;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ReverseMap();
});
protected override void Because_of()
{
var dest = new Destination
{
Value = 10
};
_source = Mapper.Map<Destination, Source>(dest);
}
[Fact]
public void Should_create_a_map_with_the_reverse_items()
{
_source.Value.ShouldBe(10);
}
}
public class When_validating_only_against_source_members_and_source_matches : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source);
});
[Fact]
public void Should_only_map_source_members()
{
var typeMap = ConfigProvider.FindTypeMapFor<Source, Destination>();
typeMap.GetPropertyMaps().Count().ShouldBe(1);
}
[Fact]
public void Should_not_throw_any_configuration_validation_errors()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_source_does_not_match : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source);
});
[Fact]
public void Should_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value3 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source)
.ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value2));
});
[Fact]
public void Should_not_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped_with_resolvers : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value3 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source)
.ForMember(dest => dest.Value3, opt => opt.ResolveUsing(src => src.Value2))
.ForSourceMember(src => src.Value2, opt => opt.Ignore());
});
[Fact]
public void Should_not_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_reverse_mapping_and_ignoring_via_method : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public int Value { get; set; }
public int Ignored { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>()
.ForMember(d => d.Ignored, opt => opt.Ignore())
.ReverseMap();
});
[Fact]
public void Should_show_valid()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_reverse_mapping_and_ignoring : SpecBase
{
public class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
}
public class Foo2
{
public string Bar { get; set; }
public string Boo { get; set; }
}
[Fact]
public void GetUnmappedPropertyNames_ShouldReturnBoo()
{
//Arrange
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, Foo2>();
});
var typeMap = config.GetAllTypeMaps()
.First(x => x.SourceType == typeof(Foo) && x.DestinationType == typeof(Foo2));
//Act
var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames();
//Assert
unmappedPropertyNames[0].ShouldBe("Boo");
}
[Fact]
public void WhenSecondCallTo_GetUnmappedPropertyNames_ShouldReturnBoo()
{
//Arrange
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, Foo2>().ReverseMap();
});
var typeMap = config.GetAllTypeMaps()
.First(x => x.SourceType == typeof(Foo2) && x.DestinationType == typeof(Foo));
//Act
var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames();
//Assert
unmappedPropertyNames[0].ShouldBe("Boo");
}
}
public class When_reverse_mapping_open_generics : AutoMapperSpecBase
{
private Source<int> _source;
public class Source<T>
{
public T Value { get; set; }
}
public class Destination<T>
{
public T Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(Source<>), typeof(Destination<>))
.ReverseMap();
});
protected override void Because_of()
{
var dest = new Destination<int>
{
Value = 10
};
_source = Mapper.Map<Destination<int>, Source<int>>(dest);
}
[Fact]
public void Should_create_a_map_with_the_reverse_items()
{
_source.Value.ShouldBe(10);
}
}
}
| |
using System;
using SubSonic.Schema;
using SubSonic.DataProviders;
using System.Data;
namespace Solution.DataAccess.DataModel {
/// <summary>
/// Table: Report_Month
/// Primary Key: Id
/// </summary>
public class Report_MonthStructs: DatabaseTable {
public Report_MonthStructs(IDataProvider provider):base("Report_Month",provider){
ClassName = "Report_Month";
SchemaName = "dbo";
Columns.Add(new DatabaseColumn("Id", this)
{
IsPrimaryKey = true,
DataType = DbType.Int32,
IsNullable = false,
AutoIncrement = true,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "Id"
});
Columns.Add(new DatabaseColumn("YM", this)
{
IsPrimaryKey = false,
DataType = DbType.String,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 7,
PropertyName = "YM"
});
Columns.Add(new DatabaseColumn("emp_id", this)
{
IsPrimaryKey = false,
DataType = DbType.String,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 12,
PropertyName = "emp_id"
});
Columns.Add(new DatabaseColumn("join_id", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "join_id"
});
Columns.Add(new DatabaseColumn("depart_id", this)
{
IsPrimaryKey = false,
DataType = DbType.String,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 30,
PropertyName = "depart_id"
});
Columns.Add(new DatabaseColumn("audit", this)
{
IsPrimaryKey = false,
DataType = DbType.Int16,
IsNullable = false,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "audit"
});
Columns.Add(new DatabaseColumn("auditor", this)
{
IsPrimaryKey = false,
DataType = DbType.String,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 20,
PropertyName = "auditor"
});
Columns.Add(new DatabaseColumn("audit_date", this)
{
IsPrimaryKey = false,
DataType = DbType.DateTime,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "audit_date"
});
Columns.Add(new DatabaseColumn("update_date", this)
{
IsPrimaryKey = false,
DataType = DbType.DateTime,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "update_date"
});
Columns.Add(new DatabaseColumn("month_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Int16,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "month_days"
});
Columns.Add(new DatabaseColumn("plan_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "plan_days"
});
Columns.Add(new DatabaseColumn("sun_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "sun_days"
});
Columns.Add(new DatabaseColumn("hd_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "hd_days"
});
Columns.Add(new DatabaseColumn("cal_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "cal_days"
});
Columns.Add(new DatabaseColumn("duty_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "duty_days"
});
Columns.Add(new DatabaseColumn("work_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "work_days"
});
Columns.Add(new DatabaseColumn("absent_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "absent_days"
});
Columns.Add(new DatabaseColumn("leave_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave_days"
});
Columns.Add(new DatabaseColumn("fact_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "fact_hrs"
});
Columns.Add(new DatabaseColumn("basic_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "basic_hrs"
});
Columns.Add(new DatabaseColumn("mid_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "mid_hrs"
});
Columns.Add(new DatabaseColumn("ns_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ns_hrs"
});
Columns.Add(new DatabaseColumn("ot_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_hrs"
});
Columns.Add(new DatabaseColumn("sun_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "sun_hrs"
});
Columns.Add(new DatabaseColumn("hd_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "hd_hrs"
});
Columns.Add(new DatabaseColumn("absent_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "absent_hrs"
});
Columns.Add(new DatabaseColumn("late_mins", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late_mins"
});
Columns.Add(new DatabaseColumn("late_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late_count"
});
Columns.Add(new DatabaseColumn("leave_mins", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave_mins"
});
Columns.Add(new DatabaseColumn("leave_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave_count"
});
Columns.Add(new DatabaseColumn("ot_late_mins", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_late_mins"
});
Columns.Add(new DatabaseColumn("ot_leave_mins", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_leave_mins"
});
Columns.Add(new DatabaseColumn("ot_late_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_late_count"
});
Columns.Add(new DatabaseColumn("ot_leave_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_leave_count"
});
Columns.Add(new DatabaseColumn("ns_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ns_count"
});
Columns.Add(new DatabaseColumn("mid_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "mid_count"
});
Columns.Add(new DatabaseColumn("ot_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_count"
});
Columns.Add(new DatabaseColumn("absent_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "absent_count"
});
Columns.Add(new DatabaseColumn("l0hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l0hrs"
});
Columns.Add(new DatabaseColumn("l1hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l1hrs"
});
Columns.Add(new DatabaseColumn("l2hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l2hrs"
});
Columns.Add(new DatabaseColumn("l3hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l3hrs"
});
Columns.Add(new DatabaseColumn("l4hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l4hrs"
});
Columns.Add(new DatabaseColumn("l5hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l5hrs"
});
Columns.Add(new DatabaseColumn("l6hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l6hrs"
});
Columns.Add(new DatabaseColumn("l7hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l7hrs"
});
Columns.Add(new DatabaseColumn("l8hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l8hrs"
});
Columns.Add(new DatabaseColumn("l9hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l9hrs"
});
Columns.Add(new DatabaseColumn("l10hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l10hrs"
});
Columns.Add(new DatabaseColumn("l11hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l11hrs"
});
Columns.Add(new DatabaseColumn("l12hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l12hrs"
});
Columns.Add(new DatabaseColumn("l13hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l13hrs"
});
Columns.Add(new DatabaseColumn("l14hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l14hrs"
});
Columns.Add(new DatabaseColumn("l15hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l15hrs"
});
Columns.Add(new DatabaseColumn("outwork_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "outwork_hrs"
});
Columns.Add(new DatabaseColumn("shutdown_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "shutdown_hrs"
});
Columns.Add(new DatabaseColumn("outwork_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "outwork_days"
});
Columns.Add(new DatabaseColumn("shutdown_days", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "shutdown_days"
});
Columns.Add(new DatabaseColumn("shift_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "shift_hrs"
});
Columns.Add(new DatabaseColumn("onwatch_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "onwatch_hrs"
});
Columns.Add(new DatabaseColumn("sign_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "sign_count"
});
Columns.Add(new DatabaseColumn("need_sign_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "need_sign_count"
});
Columns.Add(new DatabaseColumn("l0day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l0day"
});
Columns.Add(new DatabaseColumn("l1day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l1day"
});
Columns.Add(new DatabaseColumn("l2day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l2day"
});
Columns.Add(new DatabaseColumn("l3day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l3day"
});
Columns.Add(new DatabaseColumn("l4day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l4day"
});
Columns.Add(new DatabaseColumn("l5day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l5day"
});
Columns.Add(new DatabaseColumn("l6day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l6day"
});
Columns.Add(new DatabaseColumn("l7day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l7day"
});
Columns.Add(new DatabaseColumn("l8day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l8day"
});
Columns.Add(new DatabaseColumn("L9day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "L9day"
});
Columns.Add(new DatabaseColumn("l10day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l10day"
});
Columns.Add(new DatabaseColumn("l11day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l11day"
});
Columns.Add(new DatabaseColumn("l12day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l12day"
});
Columns.Add(new DatabaseColumn("l13day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l13day"
});
Columns.Add(new DatabaseColumn("l14day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l14day"
});
Columns.Add(new DatabaseColumn("l15day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l15day"
});
Columns.Add(new DatabaseColumn("outwork_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "outwork_count"
});
Columns.Add(new DatabaseColumn("shutdown_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "shutdown_count"
});
Columns.Add(new DatabaseColumn("l0count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l0count"
});
Columns.Add(new DatabaseColumn("l1count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l1count"
});
Columns.Add(new DatabaseColumn("l2count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l2count"
});
Columns.Add(new DatabaseColumn("l3count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l3count"
});
Columns.Add(new DatabaseColumn("l4count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l4count"
});
Columns.Add(new DatabaseColumn("l5count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l5count"
});
Columns.Add(new DatabaseColumn("l6count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l6count"
});
Columns.Add(new DatabaseColumn("l7count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l7count"
});
Columns.Add(new DatabaseColumn("l8count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l8count"
});
Columns.Add(new DatabaseColumn("L9count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "L9count"
});
Columns.Add(new DatabaseColumn("l10count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l10count"
});
Columns.Add(new DatabaseColumn("l11count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l11count"
});
Columns.Add(new DatabaseColumn("l12count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l12count"
});
Columns.Add(new DatabaseColumn("l13count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l13count"
});
Columns.Add(new DatabaseColumn("l14count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l14count"
});
Columns.Add(new DatabaseColumn("l15count", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "l15count"
});
Columns.Add(new DatabaseColumn("ot_sun_day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_sun_day"
});
Columns.Add(new DatabaseColumn("ot_nd_day", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "ot_nd_day"
});
Columns.Add(new DatabaseColumn("bait_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "bait_hrs"
});
Columns.Add(new DatabaseColumn("lesshrs_count", this)
{
IsPrimaryKey = false,
DataType = DbType.Int32,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "lesshrs_count"
});
Columns.Add(new DatabaseColumn("over_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "over_hrs"
});
Columns.Add(new DatabaseColumn("late1_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late1_min"
});
Columns.Add(new DatabaseColumn("late2_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late2_min"
});
Columns.Add(new DatabaseColumn("late3_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late3_min"
});
Columns.Add(new DatabaseColumn("late4_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late4_min"
});
Columns.Add(new DatabaseColumn("late5_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "late5_min"
});
Columns.Add(new DatabaseColumn("leave1_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave1_min"
});
Columns.Add(new DatabaseColumn("leave2_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave2_min"
});
Columns.Add(new DatabaseColumn("leave3_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave3_min"
});
Columns.Add(new DatabaseColumn("leave4_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave4_min"
});
Columns.Add(new DatabaseColumn("leave5_min", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "leave5_min"
});
Columns.Add(new DatabaseColumn("input_ot_hrs", this)
{
IsPrimaryKey = false,
DataType = DbType.Decimal,
IsNullable = true,
AutoIncrement = false,
IsForeignKey = false,
MaxLength = 0,
PropertyName = "input_ot_hrs"
});
}
public IColumn Id{
get{
return this.GetColumn("Id");
}
}
public IColumn YM{
get{
return this.GetColumn("YM");
}
}
public IColumn emp_id{
get{
return this.GetColumn("emp_id");
}
}
public IColumn join_id{
get{
return this.GetColumn("join_id");
}
}
public IColumn depart_id{
get{
return this.GetColumn("depart_id");
}
}
public IColumn audit{
get{
return this.GetColumn("audit");
}
}
public IColumn auditor{
get{
return this.GetColumn("auditor");
}
}
public IColumn audit_date{
get{
return this.GetColumn("audit_date");
}
}
public IColumn update_date{
get{
return this.GetColumn("update_date");
}
}
public IColumn month_days{
get{
return this.GetColumn("month_days");
}
}
public IColumn plan_days{
get{
return this.GetColumn("plan_days");
}
}
public IColumn sun_days{
get{
return this.GetColumn("sun_days");
}
}
public IColumn hd_days{
get{
return this.GetColumn("hd_days");
}
}
public IColumn cal_days{
get{
return this.GetColumn("cal_days");
}
}
public IColumn duty_days{
get{
return this.GetColumn("duty_days");
}
}
public IColumn work_days{
get{
return this.GetColumn("work_days");
}
}
public IColumn absent_days{
get{
return this.GetColumn("absent_days");
}
}
public IColumn leave_days{
get{
return this.GetColumn("leave_days");
}
}
public IColumn fact_hrs{
get{
return this.GetColumn("fact_hrs");
}
}
public IColumn basic_hrs{
get{
return this.GetColumn("basic_hrs");
}
}
public IColumn mid_hrs{
get{
return this.GetColumn("mid_hrs");
}
}
public IColumn ns_hrs{
get{
return this.GetColumn("ns_hrs");
}
}
public IColumn ot_hrs{
get{
return this.GetColumn("ot_hrs");
}
}
public IColumn sun_hrs{
get{
return this.GetColumn("sun_hrs");
}
}
public IColumn hd_hrs{
get{
return this.GetColumn("hd_hrs");
}
}
public IColumn absent_hrs{
get{
return this.GetColumn("absent_hrs");
}
}
public IColumn late_mins{
get{
return this.GetColumn("late_mins");
}
}
public IColumn late_count{
get{
return this.GetColumn("late_count");
}
}
public IColumn leave_mins{
get{
return this.GetColumn("leave_mins");
}
}
public IColumn leave_count{
get{
return this.GetColumn("leave_count");
}
}
public IColumn ot_late_mins{
get{
return this.GetColumn("ot_late_mins");
}
}
public IColumn ot_leave_mins{
get{
return this.GetColumn("ot_leave_mins");
}
}
public IColumn ot_late_count{
get{
return this.GetColumn("ot_late_count");
}
}
public IColumn ot_leave_count{
get{
return this.GetColumn("ot_leave_count");
}
}
public IColumn ns_count{
get{
return this.GetColumn("ns_count");
}
}
public IColumn mid_count{
get{
return this.GetColumn("mid_count");
}
}
public IColumn ot_count{
get{
return this.GetColumn("ot_count");
}
}
public IColumn absent_count{
get{
return this.GetColumn("absent_count");
}
}
public IColumn l0hrs{
get{
return this.GetColumn("l0hrs");
}
}
public IColumn l1hrs{
get{
return this.GetColumn("l1hrs");
}
}
public IColumn l2hrs{
get{
return this.GetColumn("l2hrs");
}
}
public IColumn l3hrs{
get{
return this.GetColumn("l3hrs");
}
}
public IColumn l4hrs{
get{
return this.GetColumn("l4hrs");
}
}
public IColumn l5hrs{
get{
return this.GetColumn("l5hrs");
}
}
public IColumn l6hrs{
get{
return this.GetColumn("l6hrs");
}
}
public IColumn l7hrs{
get{
return this.GetColumn("l7hrs");
}
}
public IColumn l8hrs{
get{
return this.GetColumn("l8hrs");
}
}
public IColumn l9hrs{
get{
return this.GetColumn("l9hrs");
}
}
public IColumn l10hrs{
get{
return this.GetColumn("l10hrs");
}
}
public IColumn l11hrs{
get{
return this.GetColumn("l11hrs");
}
}
public IColumn l12hrs{
get{
return this.GetColumn("l12hrs");
}
}
public IColumn l13hrs{
get{
return this.GetColumn("l13hrs");
}
}
public IColumn l14hrs{
get{
return this.GetColumn("l14hrs");
}
}
public IColumn l15hrs{
get{
return this.GetColumn("l15hrs");
}
}
public IColumn outwork_hrs{
get{
return this.GetColumn("outwork_hrs");
}
}
public IColumn shutdown_hrs{
get{
return this.GetColumn("shutdown_hrs");
}
}
public IColumn outwork_days{
get{
return this.GetColumn("outwork_days");
}
}
public IColumn shutdown_days{
get{
return this.GetColumn("shutdown_days");
}
}
public IColumn shift_hrs{
get{
return this.GetColumn("shift_hrs");
}
}
public IColumn onwatch_hrs{
get{
return this.GetColumn("onwatch_hrs");
}
}
public IColumn sign_count{
get{
return this.GetColumn("sign_count");
}
}
public IColumn need_sign_count{
get{
return this.GetColumn("need_sign_count");
}
}
public IColumn l0day{
get{
return this.GetColumn("l0day");
}
}
public IColumn l1day{
get{
return this.GetColumn("l1day");
}
}
public IColumn l2day{
get{
return this.GetColumn("l2day");
}
}
public IColumn l3day{
get{
return this.GetColumn("l3day");
}
}
public IColumn l4day{
get{
return this.GetColumn("l4day");
}
}
public IColumn l5day{
get{
return this.GetColumn("l5day");
}
}
public IColumn l6day{
get{
return this.GetColumn("l6day");
}
}
public IColumn l7day{
get{
return this.GetColumn("l7day");
}
}
public IColumn l8day{
get{
return this.GetColumn("l8day");
}
}
public IColumn L9day{
get{
return this.GetColumn("L9day");
}
}
public IColumn l10day{
get{
return this.GetColumn("l10day");
}
}
public IColumn l11day{
get{
return this.GetColumn("l11day");
}
}
public IColumn l12day{
get{
return this.GetColumn("l12day");
}
}
public IColumn l13day{
get{
return this.GetColumn("l13day");
}
}
public IColumn l14day{
get{
return this.GetColumn("l14day");
}
}
public IColumn l15day{
get{
return this.GetColumn("l15day");
}
}
public IColumn outwork_count{
get{
return this.GetColumn("outwork_count");
}
}
public IColumn shutdown_count{
get{
return this.GetColumn("shutdown_count");
}
}
public IColumn l0count{
get{
return this.GetColumn("l0count");
}
}
public IColumn l1count{
get{
return this.GetColumn("l1count");
}
}
public IColumn l2count{
get{
return this.GetColumn("l2count");
}
}
public IColumn l3count{
get{
return this.GetColumn("l3count");
}
}
public IColumn l4count{
get{
return this.GetColumn("l4count");
}
}
public IColumn l5count{
get{
return this.GetColumn("l5count");
}
}
public IColumn l6count{
get{
return this.GetColumn("l6count");
}
}
public IColumn l7count{
get{
return this.GetColumn("l7count");
}
}
public IColumn l8count{
get{
return this.GetColumn("l8count");
}
}
public IColumn L9count{
get{
return this.GetColumn("L9count");
}
}
public IColumn l10count{
get{
return this.GetColumn("l10count");
}
}
public IColumn l11count{
get{
return this.GetColumn("l11count");
}
}
public IColumn l12count{
get{
return this.GetColumn("l12count");
}
}
public IColumn l13count{
get{
return this.GetColumn("l13count");
}
}
public IColumn l14count{
get{
return this.GetColumn("l14count");
}
}
public IColumn l15count{
get{
return this.GetColumn("l15count");
}
}
public IColumn ot_sun_day{
get{
return this.GetColumn("ot_sun_day");
}
}
public IColumn ot_nd_day{
get{
return this.GetColumn("ot_nd_day");
}
}
public IColumn bait_hrs{
get{
return this.GetColumn("bait_hrs");
}
}
public IColumn lesshrs_count{
get{
return this.GetColumn("lesshrs_count");
}
}
public IColumn over_hrs{
get{
return this.GetColumn("over_hrs");
}
}
public IColumn late1_min{
get{
return this.GetColumn("late1_min");
}
}
public IColumn late2_min{
get{
return this.GetColumn("late2_min");
}
}
public IColumn late3_min{
get{
return this.GetColumn("late3_min");
}
}
public IColumn late4_min{
get{
return this.GetColumn("late4_min");
}
}
public IColumn late5_min{
get{
return this.GetColumn("late5_min");
}
}
public IColumn leave1_min{
get{
return this.GetColumn("leave1_min");
}
}
public IColumn leave2_min{
get{
return this.GetColumn("leave2_min");
}
}
public IColumn leave3_min{
get{
return this.GetColumn("leave3_min");
}
}
public IColumn leave4_min{
get{
return this.GetColumn("leave4_min");
}
}
public IColumn leave5_min{
get{
return this.GetColumn("leave5_min");
}
}
public IColumn input_ot_hrs{
get{
return this.GetColumn("input_ot_hrs");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.