context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//------------------------------------------------------------------------------
// <copyright file="TreeNodeCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using System.Runtime.InteropServices;
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing.Design;
using System.Globalization;
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
Editor("System.Windows.Forms.Design.TreeNodeCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))
]
public class TreeNodeCollection : IList {
private TreeNode owner;
/// A caching mechanism for key accessor
/// We use an index here rather than control so that we don't have lifetime
/// issues by holding on to extra references.
private int lastAccessedIndex = -1;
//this index is used to optimize performance of AddRange
//items are added from last to first after this index
//(to work around TV_INSertItem comctl32 perf issue with consecutive adds in the end of the list)
private int fixedIndex = -1;
internal TreeNodeCollection(TreeNode owner) {
this.owner = owner;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.FixedIndex"]/*' />
/// <internalonly/>
internal int FixedIndex
{
get {
return fixedIndex;
}
set {
fixedIndex = value;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual TreeNode this[int index] {
get {
if (index < 0 || index >= owner.childCount) {
throw new ArgumentOutOfRangeException("index");
}
return owner.children[index];
}
set {
if (index < 0 || index >= owner.childCount)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.InvalidArgument, "index", (index).ToString(CultureInfo.CurrentCulture)));
value.parent = owner;
value.index = index;
owner.children[index] = value;
value.Realize(false);
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.this"]/*' />
/// <internalonly/>
object IList.this[int index] {
get {
return this[index];
}
set {
if (value is TreeNode) {
this[index] = (TreeNode)value;
}
else {
throw new ArgumentException(SR.GetString(SR.TreeNodeCollectionBadTreeNode), "value");
}
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.this"]/*' />
/// <devdoc>
/// <para>Retrieves the child control with the specified key.</para>
/// </devdoc>
public virtual TreeNode this[string key] {
get {
// We do not support null and empty string as valid keys.
if (string.IsNullOrEmpty(key)){
return null;
}
// Search for the key in our collection
int index = IndexOfKey(key);
if (IsValidIndex(index)) {
return this[index];
}
else {
return null;
}
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Count"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
// VSWhidbey 152051: Make this property available to Intellisense. (Removed the EditorBrowsable attribute.)
[Browsable(false)]
public int Count {
get {
return owner.childCount;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.ICollection.SyncRoot"]/*' />
/// <internalonly/>
object ICollection.SyncRoot {
get {
return this;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.ICollection.IsSynchronized"]/*' />
/// <internalonly/>
bool ICollection.IsSynchronized {
get {
return false;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.IsFixedSize"]/*' />
/// <internalonly/>
bool IList.IsFixedSize {
get {
return false;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IsReadOnly"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsReadOnly {
get {
return false;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string text) {
TreeNode tn = new TreeNode(text);
Add(tn);
return tn;
}
// <-- NEW ADD OVERLOADS IN WHIDBEY
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add1"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string key, string text) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
Add(tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add2"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string key, string text, int imageIndex) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageIndex = imageIndex;
Add(tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add3"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string key, string text, string imageKey) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageKey = imageKey;
Add(tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add4"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string key, string text, int imageIndex, int selectedImageIndex) {
TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex);
tn.Name = key;
Add(tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add5"]/*' />
/// <devdoc>
/// Creates a new child node under this node. Child node is positioned after siblings.
/// </devdoc>
public virtual TreeNode Add(string key, string text, string imageKey, string selectedImageKey) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageKey = imageKey;
tn.SelectedImageKey = selectedImageKey;
Add(tn);
return tn;
}
// END - NEW ADD OVERLOADS IN WHIDBEY -->
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.AddRange"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual void AddRange(TreeNode[] nodes) {
if (nodes == null) {
throw new ArgumentNullException("nodes");
}
if (nodes.Length == 0)
return;
TreeView tv = owner.TreeView;
if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) {
tv.BeginUpdate();
}
owner.Nodes.FixedIndex = owner.childCount;
owner.EnsureCapacity(nodes.Length);
for (int i = nodes.Length-1 ; i >= 0; i--) {
AddInternal(nodes[i],i);
}
owner.Nodes.FixedIndex = -1;
if (tv != null && nodes.Length > TreeNode.MAX_TREENODES_OPS) {
tv.EndUpdate();
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Find"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public TreeNode[] Find (string key, bool searchAllChildren) {
ArrayList foundNodes = FindInternal(key, searchAllChildren, this, new ArrayList());
//
TreeNode[] stronglyTypedFoundNodes = new TreeNode[foundNodes.Count];
foundNodes.CopyTo(stronglyTypedFoundNodes, 0);
return stronglyTypedFoundNodes;
}
private ArrayList FindInternal(string key, bool searchAllChildren, TreeNodeCollection treeNodeCollectionToLookIn, ArrayList foundTreeNodes) {
if ((treeNodeCollectionToLookIn == null) || (foundTreeNodes == null)) {
return null;
}
// Perform breadth first search - as it's likely people will want tree nodes belonging
// to the same parent close to each other.
for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) {
if (treeNodeCollectionToLookIn[i] == null){
continue;
}
if (WindowsFormsUtils.SafeCompareStrings(treeNodeCollectionToLookIn[i].Name, key, /* ignoreCase = */ true)) {
foundTreeNodes.Add(treeNodeCollectionToLookIn[i]);
}
}
// Optional recurive search for controls in child collections.
if (searchAllChildren){
for (int i = 0; i < treeNodeCollectionToLookIn.Count; i++) {
if (treeNodeCollectionToLookIn[i] == null){
continue;
}
if ((treeNodeCollectionToLookIn[i].Nodes != null) && treeNodeCollectionToLookIn[i].Nodes.Count > 0){
// if it has a valid child collecion, append those results to our collection
foundTreeNodes = FindInternal(key, searchAllChildren, treeNodeCollectionToLookIn[i].Nodes, foundTreeNodes);
}
}
}
return foundTreeNodes;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Add1"]/*' />
/// <devdoc>
/// Adds a new child node to this node. Child node is positioned after siblings.
/// </devdoc>
public virtual int Add(TreeNode node) {
return AddInternal(node, 0);
}
private int AddInternal(TreeNode node, int delta) {
if (node == null) {
throw new ArgumentNullException("node");
}
if (node.handle != IntPtr.Zero)
throw new ArgumentException(SR.GetString(SR.OnlyOneControl, node.Text), "node");
// If the TreeView is sorted, index is ignored
TreeView tv = owner.TreeView;
if (tv != null && tv.Sorted) {
return owner.AddSorted(node);
}
node.parent = owner;
int fixedIndex = owner.Nodes.FixedIndex;
if (fixedIndex != -1) {
node.index = fixedIndex + delta;
}
else {
//if fixedIndex != -1 capacity was ensured by AddRange
Debug.Assert(delta == 0,"delta should be 0");
owner.EnsureCapacity(1);
node.index = owner.childCount;
}
owner.children[node.index] = node;
owner.childCount++;
node.Realize(false);
if (tv != null && node == tv.selectedNode)
tv.SelectedNode = node; // communicate this to the handle
if (tv != null && tv.TreeViewNodeSorter != null) {
tv.Sort();
}
return node.index;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.Add"]/*' />
/// <internalonly/>
int IList.Add(object node) {
if (node == null) {
throw new ArgumentNullException("node");
}
else if (node is TreeNode) {
return Add((TreeNode)node);
}
else
{
return Add(node.ToString()).index;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(TreeNode node) {
return IndexOf(node) != -1;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.ContainsKey"]/*' />
/// <devdoc>
/// <para>Returns true if the collection contains an item with the specified key, false otherwise.</para>
/// </devdoc>
public virtual bool ContainsKey(string key) {
return IsValidIndex(IndexOfKey(key));
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.Contains"]/*' />
/// <internalonly/>
bool IList.Contains(object node) {
if (node is TreeNode) {
return Contains((TreeNode)node);
}
else {
return false;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(TreeNode node) {
for(int index=0; index < Count; ++index) {
if (this[index] == node) {
return index;
}
}
return -1;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.IndexOf"]/*' />
/// <internalonly/>
int IList.IndexOf(object node) {
if (node is TreeNode) {
return IndexOf((TreeNode)node);
}
else {
return -1;
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.this"]/*' />
/// <devdoc>
/// <para>The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1.</para>
/// </devdoc>
public virtual int IndexOfKey(String key) {
// Step 0 - Arg validation
if (string.IsNullOrEmpty(key)){
return -1; // we dont support empty or null keys.
}
// step 1 - check the last cached item
if (IsValidIndex(lastAccessedIndex))
{
if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) {
return lastAccessedIndex;
}
}
// step 2 - search for the item
for (int i = 0; i < this.Count; i ++) {
if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) {
lastAccessedIndex = i;
return i;
}
}
// step 3 - we didn't find it. Invalidate the last accessed index and return -1.
lastAccessedIndex = -1;
return -1;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual void Insert(int index, TreeNode node) {
if (node.handle != IntPtr.Zero)
throw new ArgumentException(SR.GetString(SR.OnlyOneControl, node.Text), "node");
// If the TreeView is sorted, index is ignored
TreeView tv = owner.TreeView;
if (tv != null && tv.Sorted) {
owner.AddSorted(node);
return;
}
if (index < 0) index = 0;
if (index > owner.childCount) index = owner.childCount;
owner.InsertNodeAt(index, node);
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.Insert"]/*' />
/// <internalonly/>
void IList.Insert(int index, object node) {
if (node is TreeNode) {
Insert(index, (TreeNode)node);
}
else {
throw new ArgumentException(SR.GetString(SR.TreeNodeCollectionBadTreeNode), "node");
}
}
// <-- NEW INSERT OVERLOADS IN WHIDBEY
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert1"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string text) {
TreeNode tn = new TreeNode(text);
Insert(index, tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert2"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string key, string text) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
Insert(index, tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert3"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string key, string text, int imageIndex) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageIndex = imageIndex;
Insert(index, tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert4"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string key, string text, string imageKey) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageKey = imageKey;
Insert(index, tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert5"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string key, string text, int imageIndex, int selectedImageIndex) {
TreeNode tn = new TreeNode(text, imageIndex, selectedImageIndex);
tn.Name = key;
Insert(index, tn);
return tn;
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Insert6"]/*' />
/// <devdoc>
/// Inserts a new child node on this node. Child node is positioned as specified by index.
/// </devdoc>
public virtual TreeNode Insert(int index, string key, string text, string imageKey, string selectedImageKey) {
TreeNode tn = new TreeNode(text);
tn.Name = key;
tn.ImageKey = imageKey;
tn.SelectedImageKey = selectedImageKey;
Insert(index, tn);
return tn;
}
// END - NEW INSERT OVERLOADS IN WHIDBEY -->
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IsValidIndex"]/*' />
/// <devdoc>
/// <para>Determines if the index is valid for the collection.</para>
/// </devdoc>
/// <internalonly/>
private bool IsValidIndex(int index) {
return ((index >= 0) && (index < this.Count));
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Clear"]/*' />
/// <devdoc>
/// Remove all nodes from the tree view.
/// </devdoc>
public virtual void Clear() {
owner.Clear();
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(Array dest, int index) {
if (owner.childCount > 0) {
System.Array.Copy(owner.children, 0, dest, index, owner.childCount);
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.Remove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(TreeNode node) {
node.Remove();
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.IList.Remove"]/*' />
/// <internalonly/>
void IList.Remove(object node) {
if (node is TreeNode ) {
Remove((TreeNode)node);
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.RemoveAt"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual void RemoveAt(int index) {
this[index].Remove();
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.RemoveByKey"]/*' />
/// <devdoc>
/// <para>Removes the child control with the specified key.</para>
/// </devdoc>
public virtual void RemoveByKey(string key) {
int index = IndexOfKey(key);
if (IsValidIndex(index)) {
RemoveAt(index);
}
}
/// <include file='doc\TreeNodeCollection.uex' path='docs/doc[@for="TreeNodeCollection.GetEnumerator"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public IEnumerator GetEnumerator() {
return new WindowsFormsUtils.ArraySubsetEnumerator(owner.children, owner.childCount);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows
{
public enum BaseValueSource
{
Unknown = 0,
Default = 1,
Inherited = 2,
DefaultStyle = 3,
DefaultStyleTrigger = 4,
Style = 5,
TemplateTrigger = 6,
StyleTrigger = 7,
ImplicitStyleReference = 8,
ParentTemplate = 9,
ParentTemplateTrigger = 10,
Local = 11,
}
public enum ColumnSpaceDistribution
{
Left = 0,
Right = 1,
Between = 2,
}
public delegate void ExitEventHandler(Object sender, ExitEventArgs e);
public enum FigureHorizontalAnchor
{
PageLeft = 0,
PageCenter = 1,
PageRight = 2,
ContentLeft = 3,
ContentCenter = 4,
ContentRight = 5,
ColumnLeft = 6,
ColumnCenter = 7,
ColumnRight = 8,
}
public enum FigureUnitType
{
Auto = 0,
Pixel = 1,
Column = 2,
Content = 3,
Page = 4,
}
public enum FigureVerticalAnchor
{
PageTop = 0,
PageCenter = 1,
PageBottom = 2,
ContentTop = 3,
ContentCenter = 4,
ContentBottom = 5,
ParagraphTop = 6,
}
public enum FrameworkPropertyMetadataOptions
{
None = 0,
AffectsMeasure = 1,
AffectsArrange = 2,
AffectsParentMeasure = 4,
AffectsParentArrange = 8,
AffectsRender = 16,
Inherits = 32,
OverridesInheritanceBehavior = 64,
NotDataBindable = 128,
BindsTwoWayByDefault = 256,
Journal = 1024,
SubPropertiesDoNotAffectRender = 2048,
}
public enum GridUnitType
{
Auto = 0,
Pixel = 1,
Star = 2,
}
public enum HorizontalAlignment
{
Left = 0,
Center = 1,
Right = 2,
Stretch = 3,
}
public enum InheritanceBehavior
{
Default = 0,
SkipToAppNow = 1,
SkipToAppNext = 2,
SkipToThemeNow = 3,
SkipToThemeNext = 4,
SkipAllNow = 5,
SkipAllNext = 6,
}
public enum LineStackingStrategy
{
BlockLineHeight = 0,
MaxHeight = 1,
}
public enum MessageBoxButton
{
OK = 0,
OKCancel = 1,
YesNoCancel = 3,
YesNo = 4,
}
public enum MessageBoxImage
{
None = 0,
Hand = 16,
Question = 32,
Exclamation = 48,
Asterisk = 64,
Stop = 16,
Error = 16,
Warning = 48,
Information = 64,
}
public enum MessageBoxOptions
{
None = 0,
ServiceNotification = 2097152,
DefaultDesktopOnly = 131072,
RightAlign = 524288,
RtlReading = 1048576,
}
public enum MessageBoxResult
{
None = 0,
OK = 1,
Cancel = 2,
Yes = 6,
No = 7,
}
public enum PowerLineStatus
{
Offline = 0,
Online = 1,
Unknown = 255,
}
public enum ReasonSessionEnding : byte
{
Logoff = 0,
Shutdown = 1,
}
public delegate void RequestBringIntoViewEventHandler(Object sender, RequestBringIntoViewEventArgs e);
public enum ResizeMode
{
NoResize = 0,
CanMinimize = 1,
CanResize = 2,
CanResizeWithGrip = 3,
}
public enum ResourceDictionaryLocation
{
None = 0,
SourceAssembly = 1,
ExternalAssembly = 2,
}
public delegate void RoutedPropertyChangedEventHandler<T>(Object sender, RoutedPropertyChangedEventArgs<T> e);
public delegate void SessionEndingCancelEventHandler(Object sender, SessionEndingCancelEventArgs e);
public enum ShutdownMode : byte
{
OnLastWindowClose = 0,
OnMainWindowClose = 1,
OnExplicitShutdown = 2,
}
public delegate void SizeChangedEventHandler(Object sender, SizeChangedEventArgs e);
public delegate void StartupEventHandler(Object sender, StartupEventArgs e);
public enum VerticalAlignment
{
Top = 0,
Center = 1,
Bottom = 2,
Stretch = 3,
}
public enum WindowStartupLocation
{
Manual = 0,
CenterScreen = 1,
CenterOwner = 2,
}
public enum WindowState
{
Normal = 0,
Minimized = 1,
Maximized = 2,
}
public enum WindowStyle
{
None = 0,
SingleBorderWindow = 1,
ThreeDBorderWindow = 2,
ToolWindow = 3,
}
public enum WrapDirection
{
None = 0,
Left = 1,
Right = 2,
Both = 3,
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Mercurial.Attributes;
namespace Mercurial
{
/// <summary>
/// This class implements the "hg push" command (<see href="http://www.selenic.com/mercurial/hg.1.html#push"/>):
/// push changes to the specified destination.
/// </summary>
public sealed class PushCommand : MercurialCommandBase<PushCommand>
{
/// <summary>
/// This is the backing field for the <see cref="Revisions"/> property.
/// </summary>
private readonly List<RevSpec> _Revisions = new List<RevSpec>();
/// <summary>
/// This is the backing field for the <see cref="Bookmarks"/> property.
/// </summary>
private readonly List<string> _Bookmarks = new List<string>();
/// <summary>
/// This is the backing field for the <see cref="Destination"/> property.
/// </summary>
private string _Destination = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="SshCommand"/> property.
/// </summary>
private string _SshCommand = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="RemoteCommand"/> property.
/// </summary>
private string _RemoteCommand = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="VerifyServerCertificate"/> property.
/// </summary>
private bool _VerifyServerCertificate = true;
/// <summary>
/// Initializes a new instance of the <see cref="PushCommand"/> class.
/// </summary>
public PushCommand()
: base("push")
{
// Do nothing here
}
/// <summary>
/// Gets the collection of bookmarks to push.
/// Default is empty.
/// </summary>
[RepeatableArgument(Option = "--bookmark")]
public Collection<string> Bookmarks
{
get
{
return new Collection<string>(_Bookmarks);
}
}
/// <summary>
/// Gets or sets the ssh command to use when pushing.
/// Default is <see cref="string.Empty"/>.
/// </summary>
[NullableArgument(NonNullOption = "--ssh")]
[DefaultValue("")]
public string SshCommand
{
get
{
return _SshCommand;
}
set
{
_SshCommand = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Gets or sets the hg command to run on the remote side.
/// Default is <see cref="string.Empty"/>.
/// </summary>
[NullableArgument(NonNullOption = "--remotecmd")]
[DefaultValue("")]
public string RemoteCommand
{
get
{
return _RemoteCommand;
}
set
{
_RemoteCommand = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Gets or sets a value indicating whether to verify the server certificate. If set to <c>false</c>, will ignore web.cacerts configuration.
/// Default value is <c>true</c>.
/// </summary>
[BooleanArgument(FalseOption = "--insecure")]
[DefaultValue(true)]
public bool VerifyServerCertificate
{
get
{
return _VerifyServerCertificate;
}
set
{
RequiresVersion(new Version(1, 7, 5), "VerifyServerCertificate property of the PushCommand class");
_VerifyServerCertificate = value;
}
}
/// <summary>
/// Sets the <see cref="VerifyServerCertificate"/> property to the specified value and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="VerifyServerCertificate"/> property.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithVerifyServerCertificate(bool value)
{
VerifyServerCertificate = value;
return this;
}
/// <summary>
/// Gets or sets the destination to pull from. If <see cref="string.Empty"/>, push to the
/// default destination. Default is <see cref="string.Empty"/>.
/// </summary>
[NullableArgument]
[DefaultValue("")]
public string Destination
{
get
{
return _Destination;
}
set
{
_Destination = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Gets or sets a value indicating whether to force push to the destination, even if
/// the repositories are unrelated, or pushing would create new heads in the
/// destination repository. Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--force")]
[DefaultValue(false)]
public bool Force
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether to allow creating a new branch in the destination
/// repository. Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--new-branch")]
[DefaultValue(false)]
public bool AllowCreatingNewBranch
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether to push large repositories in chunks.
/// Default is <c>false</c>.
/// </summary>
[BooleanArgument(TrueOption = "--chunked")]
[DefaultValue(false)]
public bool ChunkedTransfer
{
get;
set;
}
/// <summary>
/// Gets the collection of revisions to include when pushing.
/// If empty, push all changes. Default is empty.
/// </summary>
[RepeatableArgument(Option = "--rev")]
public Collection<RevSpec> Revisions
{
get
{
return new Collection<RevSpec>(_Revisions);
}
}
/// <summary>
/// Sets the <see cref="Destination"/> property to the specified value and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Destination"/> property.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithDestination(string value)
{
Destination = value;
return this;
}
/// <summary>
/// Sets the <see cref="Force"/> property to the specified value and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Force"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithForce(bool value = true)
{
Force = value;
return this;
}
/// <summary>
/// Sets the <see cref="AllowCreatingNewBranch"/> property to the specified value and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="AllowCreatingNewBranch"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithAllowCreatingNewBranch(bool value = true)
{
AllowCreatingNewBranch = value;
return this;
}
/// <summary>
/// Sets the <see cref="ChunkedTransfer"/> property to the specified value and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="ChunkedTransfer"/> property.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithChunkedTransfer(bool value)
{
ChunkedTransfer = value;
return this;
}
/// <summary>
/// Adds the value to the <see cref="Bookmarks"/> collection property and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The value to add to the <see cref="Bookmarks"/> collection property.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithBookmark(string value)
{
Bookmarks.Add(value);
return this;
}
/// <summary>
/// Adds the value to the <see cref="Revisions"/> collection property and
/// returns this <see cref="PushCommand"/> instance.
/// </summary>
/// <param name="value">
/// The value to add to the <see cref="Revisions"/> collection property.
/// </param>
/// <returns>
/// This <see cref="PushCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public PushCommand WithRevision(RevSpec value)
{
Revisions.Add(value);
return this;
}
/// <summary>
/// Validates the command configuration. This method should throw the necessary
/// exceptions to signal missing or incorrect configuration (like attempting to
/// add files to the repository without specifying which files to add.)
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>The <see cref="VerifyServerCertificate"/> command was used with Mercurial 1.7.4 or older.</para>
/// </exception>
public override void Validate()
{
base.Validate();
if (Bookmarks.Count > 0)
RequiresVersion(new Version(1, 8), "Bookmarks property of the PushCommand class");
if (!VerifyServerCertificate && ClientExecutable.CurrentVersion < new Version(1, 7, 5))
throw new InvalidOperationException("The 'VerifyServerCertificate' property is only available in Mercurial 1.7.5 and newer");
}
}
}
| |
using System.Threading.Tasks;
using Attest.Fake.Setup.Contracts;
namespace Attest.Fake.Setup
{
/// <summary>
/// Represents visitor for different async callbacks without return value and no parameters.
/// </summary>
class MethodCallbackVisitorAsync : IMethodCallbackVisitorAsync
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
public Task Visit(OnErrorCallback onErrorCallback)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
public Task Visit(OnCompleteCallback onCompleteCallback)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback());
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback</param>
public Task Visit(ProgressCallback progressCallback)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
public Task Visit(OnCancelCallback onCancelCallback)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback.
/// </summary>
/// <param name="withoutCallback">Callback</param>
public Task Visit(OnWithoutCallback withoutCallback)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
/// <summary>
/// Represents visitor for different async callbacks without return value and one parameter.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
public class MethodCallbackVisitorAsync<T> : IMethodCallbackVisitorAsync<T>
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
/// <param name="arg">Parameter</param>
public Task Visit(OnErrorCallback<T> onErrorCallback, T arg)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
/// <param name="arg">Parameter</param>
public Task Visit(OnCompleteCallback<T> onCompleteCallback, T arg)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback(arg));
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback.</param>
/// <param name="arg">Parameter.</param>
public Task Visit(ProgressCallback<T> progressCallback, T arg)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this, arg));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
/// <param name="arg">Parameter.</param>
public Task Visit(OnCancelCallback<T> onCancelCallback, T arg)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback
/// </summary>
/// <param name="withoutCallback">Callback</param>
/// <param name="arg">Parameter.</param>
public Task Visit(OnWithoutCallback<T> withoutCallback, T arg)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
/// <summary>
/// Represents visitor for different async callbacks without return value and two parameters.
/// </summary>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <seealso cref="MethodCallbackVisitorHelper" />
public class MethodCallbackVisitorAsync<T1, T2> : IMethodCallbackVisitorAsync<T1, T2>
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
public Task Visit(OnErrorCallback<T1, T2> onErrorCallback, T1 arg1, T2 arg2)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
public Task Visit(OnCompleteCallback<T1, T2> onCompleteCallback, T1 arg1, T2 arg2)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback(arg1, arg2));
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback.</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
public Task Visit(ProgressCallback<T1, T2> progressCallback, T1 arg1, T2 arg2)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
public Task Visit(OnCancelCallback<T1, T2> onCancelCallback, T1 arg1, T2 arg2)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback
/// </summary>
/// <param name="withoutCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
public Task Visit(OnWithoutCallback<T1, T2> withoutCallback, T1 arg1, T2 arg2)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
/// <summary>
/// Represents visitor for different callbacks without return value and three parameters.
/// </summary>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <seealso cref="MethodCallbackVisitorHelper" />
public class MethodCallbackVisitorAsync<T1, T2, T3> : IMethodCallbackVisitorAsync<T1, T2, T3>
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
public Task Visit(OnErrorCallback<T1, T2, T3> onErrorCallback, T1 arg1, T2 arg2, T3 arg3)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
public Task Visit(OnCompleteCallback<T1, T2, T3> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback(arg1, arg2, arg3));
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback.</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
public Task Visit(ProgressCallback<T1, T2, T3> progressCallback, T1 arg1, T2 arg2, T3 arg3)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
public Task Visit(OnCancelCallback<T1, T2, T3> onCancelCallback, T1 arg1, T2 arg2, T3 arg3)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback
/// </summary>
/// <param name="withoutCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
public Task Visit(OnWithoutCallback<T1, T2, T3> withoutCallback, T1 arg1, T2 arg2, T3 arg3)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
/// <summary>
/// Represents visitor for different async callbacks without return value and four parameters.
/// </summary>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <typeparam name="T4">The type of the fourth parameter.</typeparam>
/// <seealso cref="MethodCallbackVisitorHelper" />
public class MethodCallbackVisitorAsync<T1, T2, T3, T4> : IMethodCallbackVisitorAsync<T1, T2, T3, T4>
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
public Task Visit(OnErrorCallback<T1, T2, T3, T4> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
public Task Visit(OnCompleteCallback<T1, T2, T3, T4> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback(arg1, arg2, arg3, arg4));
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback.</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
public Task Visit(ProgressCallback<T1, T2, T3, T4> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3, arg4));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
public Task Visit(OnCancelCallback<T1, T2, T3, T4> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback
/// </summary>
/// <param name="withoutCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
public Task Visit(OnWithoutCallback<T1, T2, T3, T4> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
/// <summary>
/// Represents visitor for different async callbacks without return value and five parameters.
/// </summary>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <typeparam name="T4">The type of the fourth parameter.</typeparam>
/// <typeparam name="T5">The type of the fifth parameter.</typeparam>
/// <seealso cref="MethodCallbackVisitorHelper" />
public class MethodCallbackVisitorAsync<T1, T2, T3, T4, T5> : IMethodCallbackVisitorAsync<T1, T2, T3, T4, T5>
{
/// <summary>
/// Visits exception throwing callback
/// </summary>
/// <param name="onErrorCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
/// <param name="arg5">Fifth parameter</param>
public Task Visit(OnErrorCallback<T1, T2, T3, T4, T5> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return MethodCallbackVisitorHelperAsync.VisitError(onErrorCallback);
}
/// <summary>
/// Visits successful completion callback
/// </summary>
/// <param name="onCompleteCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
/// <param name="arg5">Fifth parameter</param>
public Task Visit(OnCompleteCallback<T1, T2, T3, T4, T5> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return MethodCallbackVisitorHelperAsync.VisitComplete(() => onCompleteCallback.Callback(arg1, arg2, arg3, arg4, arg5));
}
/// <summary>
/// Visits progress callback
/// </summary>
/// <param name="progressCallback">Callback.</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
/// <param name="arg5">Fifth parameter</param>
public Task Visit(ProgressCallback<T1, T2, T3, T4, T5> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return MethodCallbackVisitorHelperAsync.VisitProgress(progressCallback, c => c.Accept(this, arg1, arg2, arg3, arg4, arg5));
}
/// <summary>
/// Visits cancellation callback
/// </summary>
/// <param name="onCancelCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
/// <param name="arg5">Fifth parameter</param>
public Task Visit(OnCancelCallback<T1, T2, T3, T4, T5> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return MethodCallbackVisitorHelperAsync.VisitCancel();
}
/// <summary>
/// Visits never-ending callback
/// </summary>
/// <param name="withoutCallback">Callback</param>
/// <param name="arg1">First parameter</param>
/// <param name="arg2">Second parameter</param>
/// <param name="arg3">Third parameter</param>
/// <param name="arg4">Fourth parameter</param>
/// <param name="arg5">Fifth parameter</param>
public Task Visit(OnWithoutCallback<T1, T2, T3, T4, T5> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
return MethodCallbackVisitorHelperAsync.VisitWithout();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
sealed public class NumberFormatInfo : IFormatProvider, ICloneable
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo s_invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] { 3 };
internal int[] currencyGroupSizes = new int[] { 3 };
internal int[] percentGroupSizes = new int[] { 3 };
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
internal String numberGroupSeparator = ",";
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
internal String percentDecimalSeparator = ".";
internal String percentGroupSeparator = ",";
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
[OptionalField(VersionAdded = 2)]
internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
[OptionalField(VersionAdded = 2)]
internal int digitSubstitution = (int)DigitShapes.None;
internal bool isReadOnly = false;
// Is this NumberFormatInfo for invariant culture?
[OptionalField(VersionAdded = 2)]
internal bool m_isInvariant = false;
public NumberFormatInfo() : this(null)
{
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx) { }
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx) { }
private static void VerifyDecimalSeparator(String decSep, String propertyName)
{
if (decSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
if (decSep.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyDecString);
}
Contract.EndContractBlock();
}
private static void VerifyGroupSeparator(String groupSep, String propertyName)
{
if (groupSep == null)
{
throw new ArgumentNullException(propertyName,
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
}
private static void VerifyNativeDigits(string[] nativeDig, string propertyName)
{
if (nativeDig == null)
{
throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array);
}
if (nativeDig.Length != 10)
{
throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName);
}
Contract.EndContractBlock();
for (int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue);
}
if (nativeDig[i].Length != 1)
{
if (nativeDig[i].Length != 2)
{
// Not 1 or 2 UTF-16 code points
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
else if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1]))
{
// 2 UTF-6 code points, but not a surrogate pair
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse)
{
// Not the appropriate digit according to the Unicode data properties
// (Digit 0 must be a 0, etc.).
throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
}
private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName)
{
switch (digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
case DigitShapes.NativeNational:
// Success.
break;
default:
throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName);
}
}
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
[Pure]
private void VerifyWritable()
{
if (isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo
{
get
{
if (s_invariantInfo == null)
{
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
s_invariantInfo = ReadOnly(nfi);
}
return s_invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
{
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
if (cultureProvider != null && !cultureProvider._isInherited)
{
info = cultureProvider.numInfo;
if (info != null)
{
return info;
}
else
{
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
if (info != null)
{
return info;
}
if (formatProvider != null)
{
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null)
{
return info;
}
}
return CurrentInfo;
}
public Object Clone()
{
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits
{
get { return currencyDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
}
public String CurrencyDecimalSeparator
{
get { return currencyDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator));
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly
{
get
{
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
internal static void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
}
}
public int[] CurrencyGroupSizes
{
get
{
return ((int[])currencyGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(CurrencyGroupSizes),
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes
{
get
{
return ((int[])numberGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NumberGroupSizes),
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes
{
get
{
return ((int[])percentGroupSizes.Clone());
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PercentGroupSizes),
SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
percentGroupSizes = inputSizes;
}
}
public String CurrencyGroupSeparator
{
get { return currencyGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
currencyGroupSeparator = value;
}
}
public String CurrencySymbol
{
get { return currencySymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(CurrencySymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo
{
get
{
System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture._isInherited)
{
NumberFormatInfo info = culture.numInfo;
if (info != null)
{
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public String NaNSymbol
{
get
{
return nanSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NaNSymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern
{
get { return currencyNegativePattern; }
set
{
if (value < 0 || value > 15)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
15));
}
Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern
{
get { return numberNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4)
{
throw new ArgumentOutOfRangeException(
nameof(NumberNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
4));
}
Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern
{
get { return percentPositivePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
nameof(PercentPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern
{
get { return percentNegativePattern; }
set
{
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11)
{
throw new ArgumentOutOfRangeException(
nameof(PercentNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
11));
}
Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
}
public String NegativeInfinitySymbol
{
get
{
return negativeInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public String NegativeSign
{
get { return negativeSign; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(NegativeSign),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits
{
get { return numberDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(NumberDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
}
public String NumberDecimalSeparator
{
get { return numberDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
numberDecimalSeparator = value;
}
}
public String NumberGroupSeparator
{
get { return numberGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern
{
get { return currencyPositivePattern; }
set
{
if (value < 0 || value > 3)
{
throw new ArgumentOutOfRangeException(
nameof(CurrencyPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
}
public String PositiveInfinitySymbol
{
get
{
return positiveInfinitySymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public String PositiveSign
{
get { return positiveSign; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PositiveSign),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits
{
get { return percentDecimalDigits; }
set
{
if (value < 0 || value > 99)
{
throw new ArgumentOutOfRangeException(
nameof(PercentDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
}
public String PercentDecimalSeparator
{
get { return percentDecimalSeparator; }
set
{
VerifyWritable();
VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
percentDecimalSeparator = value;
}
}
public String PercentGroupSeparator
{
get { return percentGroupSeparator; }
set
{
VerifyWritable();
VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
percentGroupSeparator = value;
}
}
public String PercentSymbol
{
get
{
return percentSymbol;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PercentSymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
}
public String PerMilleSymbol
{
get { return perMilleSymbol; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(PerMilleSymbol),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
}
public string[] NativeDigits
{
get { return (String[])nativeDigits.Clone(); }
set
{
VerifyWritable();
VerifyNativeDigits(value, nameof(NativeDigits));
nativeDigits = value;
}
}
public DigitShapes DigitSubstitution
{
get { return (DigitShapes)digitSubstitution; }
set
{
VerifyWritable();
VerifyDigitSubstitution(value, nameof(DigitSubstitution));
digitSubstitution = (int)value;
}
}
public Object GetFormat(Type formatType)
{
return formatType == typeof(NumberFormatInfo) ? this : null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
{
if (nfi == null)
{
throw new ArgumentNullException(nameof(nfi));
}
Contract.EndContractBlock();
if (nfi.IsReadOnly)
{
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0)
{
throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
{
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0)
{
throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // Check for hex number
throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
} // NumberFormatInfo
}
| |
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the sqlite3_get_table() and //sqlite3_free_table()
** interface routines. These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdlib.h>
//#include <string.h>
#if !SQLITE_OMIT_GET_TABLE
/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.
*/
class TabResult {
public string[] azResult;
public string zErrMsg;
public int nResult;
public int nAlloc;
public int nRow;
public int nColumn;
public int nData;
public int rc;
};
/*
** This routine is called once for each row in the result table. Its job
** is to fill in the TabResult structure appropriately, allocating new
** memory as necessary.
*/
static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv )
{
string[] argv = (string[])Oargv;
string[]colv = (string[])Ocolv;
TabResult p = (TabResult)pArg;
int need;
int i;
string z;
/* Make sure there is enough space in p.azResult to hold everything
** we need to remember from this invocation of the callback.
*/
if( p.nRow==0 && argv!=null ){
need = (int)nCol*2;
}else{
need = (int)nCol;
}
if( p.nData + need >= p.nAlloc ){
string[] azNew;
p.nAlloc = p.nAlloc*2 + need + 1;
azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc );
if( azNew==null ) goto malloc_failed;
p.azResult = azNew;
}
/* If this is the first row, then generate an extra row containing
** the names of all columns.
*/
if( p.nRow==0 ){
p.nColumn = (int)nCol;
for(i=0; i<nCol; i++){
z = sqlite3_mprintf("%s", colv[i]);
if( z==null ) goto malloc_failed;
p.azResult[p.nData++ -1] = z;
}
}else if( p.nColumn!=nCol ){
//sqlite3_free(ref p.zErrMsg);
p.zErrMsg = sqlite3_mprintf(
"sqlite3_get_table() called with two or more incompatible queries"
);
p.rc = SQLITE_ERROR;
return 1;
}
/* Copy over the row data
*/
if( argv!=null ){
for(i=0; i<nCol; i++){
if( argv[i]==null ){
z = null;
}else{
int n = sqlite3Strlen30(argv[i])+1;
//z = sqlite3_malloc( n );
//if( z==0 ) goto malloc_failed;
z= argv[i];//memcpy(z, argv[i], n);
}
p.azResult[p.nData++ -1] = z;
}
p.nRow++;
}
return 0;
malloc_failed:
p.rc = SQLITE_NOMEM;
return 1;
}
/*
** Query the database. But instead of invoking a callback for each row,
** malloc() for space to hold the result and return the entire results
** at the conclusion of the call.
**
** The result that is written to ***pazResult is held in memory obtained
** from malloc(). But the caller cannot free this memory directly.
** Instead, the entire table should be passed to //sqlite3_free_table() when
** the calling procedure is finished using it.
*/
static public int sqlite3_get_table(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
ref string[] pazResult, /* Write the result table here */
ref int pnRow, /* Write the number of rows in the result here */
ref int pnColumn, /* Write the number of columns of result here */
ref string pzErrMsg /* Write error messages here */
){
int rc;
TabResult res = new TabResult();
pazResult = null;
pnColumn = 0;
pnRow = 0;
pzErrMsg = "";
res.zErrMsg = "";
res.nResult = 0;
res.nRow = 0;
res.nColumn = 0;
res.nData = 1;
res.nAlloc = 20;
res.rc = SQLITE_OK;
res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc );
if( res.azResult==null ){
db.errCode = SQLITE_NOMEM;
return SQLITE_NOMEM;
}
res.azResult[0] = null;
rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg);
//Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
//res.azResult = SQLITE_INT_TO_PTR( res.nData );
if( (rc&0xff)==SQLITE_ABORT ){
//sqlite3_free_table(ref res.azResult[1] );
if( res.zErrMsg !=""){
if( pzErrMsg !=null ){
//sqlite3_free(ref pzErrMsg);
pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
}
//sqlite3_free(ref res.zErrMsg);
}
db.errCode = res.rc; /* Assume 32-bit assignment is atomic */
return res.rc;
}
//sqlite3_free(ref res.zErrMsg);
if( rc!=SQLITE_OK ){
//sqlite3_free_table(ref res.azResult[1]);
return rc;
}
if( res.nAlloc>res.nData ){
string[] azNew;
Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
//if( azNew==null ){
// //sqlite3_free_table(ref res.azResult[1]);
// db.errCode = SQLITE_NOMEM;
// return SQLITE_NOMEM;
//}
res.nAlloc = res.nData+1;
//res.azResult = azNew;
}
pazResult = res.azResult;
pnColumn = res.nColumn;
pnRow = res.nRow;
return rc;
}
/*
** This routine frees the space the sqlite3_get_table() malloced.
*/
static void //sqlite3_free_table(
ref string azResult /* Result returned from from sqlite3_get_table() */
){
if( azResult !=null){
int i, n;
//azResult--;
//Debug.Assert( azResult!=0 );
//n = SQLITE_PTR_TO_INT(azResult[0]);
//for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); }
//sqlite3_free(ref azResult);
}
}
#endif //* SQLITE_OMIT_GET_TABLE */
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Joueur.cs
{
public class ArgParser
{
public class Argument
{
public enum Store { Value, True, False }
public Store HowToStore;
public string Destination;
public object Default;
public string Help;
public string[] Aliases;
public bool Required;
public Argument(string[] aliases, string destination, string help, bool required = false, object defaultValue = null, Store? howToStore = null)
{
this.Aliases = aliases;
this.Destination = destination;
this.Help = help;
this.Required = required;
if (howToStore == null)
{
this.HowToStore = Store.Value;
}
else
{
this.HowToStore = (Store)howToStore;
}
this.Default = defaultValue;
switch (this.HowToStore)
{
case Store.True:
this.Default = false;
break;
case Store.False:
this.Default = true;
break;
}
}
}
private string Help;
private Argument[] Arguments;
private Dictionary<string, object> ParsedValues;
private Dictionary<string, Argument> AliasToArgument;
private Queue<Argument> ExpectedOrderedArgs;
private int ErrorCode;
public ArgParser(string[] args, string help, Argument[] arguments, int errorCode = 1)
{
this.Help = help;
this.ErrorCode = errorCode;
this.ParsedValues = new Dictionary<string, object>();
this.AliasToArgument = new Dictionary<string, Argument>();
this.ExpectedOrderedArgs = new Queue<Argument>();
this.BuildValidArguments(arguments);
this.ParseConsoleArgs(args);
this.CheckRequired();
}
private void BuildValidArguments(Argument[] arguments)
{
this.Arguments = new Argument[arguments.Length + 1];
this.Arguments[0] = new Argument(new string[] { "-h", "--help" }, "help", "Shows this help message and exits");
int i = 1;
foreach (var argument in arguments)
{
this.Arguments[i++] = argument;
if (!this.ParsedValues.ContainsKey(argument.Destination))
{
this.ParsedValues.Add(argument.Destination, argument.Default);
}
foreach (var alias in argument.Aliases)
{
if (alias.StartsWith("-"))
{
this.AliasToArgument.Add(alias, argument);
}
else // it is not an option, but an expected arg
{
this.ExpectedOrderedArgs.Enqueue(argument);
break;
}
}
}
}
private void ParseConsoleArgs(string[] args)
{
Argument currentArgument = null;
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (arg == "-h" || arg == "--help")
{
this.GetHelp();
}
if (this.AliasToArgument.ContainsKey(arg))
{
currentArgument = this.AliasToArgument[arg];
}
else if (this.ExpectedOrderedArgs.Count() > 0)
{
currentArgument = this.ExpectedOrderedArgs.Dequeue();
this.ParsedValues[currentArgument.Destination] = arg;
continue;
}
else
{
Console.Error.WriteLine("Unexpected arg alias '" + arg + "'");
this.GetHelp();
}
// check for flags (value that don't have leading values)
object value = null;
if (currentArgument.HowToStore == Argument.Store.False)
{
value = false;
}
else if (currentArgument.HowToStore == Argument.Store.True)
{
value = true;
}
if (value != null)
{
this.ParsedValues[currentArgument.Destination] = value;
}
else if (i < args.Length - 1)
{
this.ParsedValues[currentArgument.Destination] = args[++i];
}
else
{
Console.Error.WriteLine("Error: Missing value for '" + arg + "'");
this.GetHelp();
}
}
}
public bool HasValue(string key)
{
return this.ParsedValues.GetValueOrDefault(key, null) != null;
}
public T GetValue<T>(string key)
{
if (this.HasValue(key))
{
var value = this.ParsedValues[key];
if (typeof(T) == typeof(int) && value.GetType() == typeof(string))
{
value = Int32.Parse((string)value);
}
return (T)value;
}
else
{
return default(T);
}
}
public string GetHelpString()
{
var s = new StringBuilder();
int maxStringLength = 0;
var requiredArgs = new List<Tuple<string, string>>();
var optionalArgs = new List<Tuple<string, string>>();
s.Append("\nUsage: ");
foreach (var argument in this.Arguments)
{
string all = String.Join(", ", argument.Aliases);
maxStringLength = Math.Max(maxStringLength, all.Length);
if (!argument.Required)
{
optionalArgs.Add(new Tuple<string, string>(all, argument.Help));
s.Append("[");
for (int i = 0; i < argument.Aliases.Length; i++)
{
s.Append(argument.Aliases[i]);
if (i < argument.Aliases.Length - 1)
{
s.Append(", ");
}
}
s.Append("] ");
}
}
s.Append(" ");
foreach (var argument in this.Arguments)
{
if (argument.Required)
{
string all = String.Join(", ", argument.Aliases);
requiredArgs.Add(new Tuple<string, string>(all, argument.Help));
s.Append("<" + argument.Aliases[0] + "> ");
}
}
s.Append("\n\n");
s.Append(this.Help);
s.Append("\n\nPositional Arguments:\n");
foreach (var tuple in requiredArgs)
{
s.Append(" ");
s.Append(tuple.Item1.PadRight(maxStringLength, ' '));
s.Append(" ");
s.Append(tuple.Item2);
s.Append("\n");
}
s.Append("\n\nOptional Arguments:\n");
foreach (var tuple in optionalArgs)
{
s.Append(" ");
s.Append(tuple.Item1.PadRight(maxStringLength, ' '));
s.Append(" ");
s.Append(tuple.Item2);
s.Append("\n");
}
return s.ToString();
}
public void GetHelp()
{
Console.Write(this.GetHelpString());
System.Environment.Exit(this.ErrorCode);
}
public void CheckRequired()
{
foreach (var argument in this.Arguments)
{
if (argument.Required && !this.HasValue(argument.Destination))
{
Console.Error.WriteLine("Error: missing value for '" + argument.Destination + "'.");
this.GetHelp();
}
}
}
}
}
| |
using FluentAssertions;
using IdentityServer.UnitTests.Common;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Stores.Serialization;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer.UnitTests.Services.Default
{
public class DefaultRefreshTokenServiceTests
{
private DefaultRefreshTokenService _subject;
private DefaultRefreshTokenStore _store;
private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal();
private StubClock _clock = new StubClock();
public DefaultRefreshTokenServiceTests()
{
_store = new DefaultRefreshTokenStore(
new InMemoryPersistedGrantStore(),
new PersistentGrantSerializer(),
new DefaultHandleGenerationService(),
TestLogger.Create<DefaultRefreshTokenStore>());
_subject = new DefaultRefreshTokenService(
_clock,
_store,
TestLogger.Create<DefaultRefreshTokenService>());
}
[Fact]
public async Task CreateRefreshToken_token_exists_in_store()
{
var client = new Client();
var accessToken = new Token();
var handle = await _subject.CreateRefreshTokenAsync(_user, accessToken, client);
(await _store.GetRefreshTokenAsync(handle)).Should().NotBeNull();
}
[Fact]
public async Task CreateRefreshToken_should_match_absolute_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 10
};
var handle = await _subject.CreateRefreshTokenAsync(_user, new Token(), client);
var refreshToken = (await _store.GetRefreshTokenAsync(handle));
refreshToken.Should().NotBeNull();
refreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime);
}
[Fact]
public async Task CreateRefreshToken_should_cap_sliding_lifetime_that_exceeds_absolute_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 100,
AbsoluteRefreshTokenLifetime = 10
};
var handle = await _subject.CreateRefreshTokenAsync(_user, new Token(), client);
var refreshToken = (await _store.GetRefreshTokenAsync(handle));
refreshToken.Should().NotBeNull();
refreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime);
}
[Fact]
public async Task CreateRefreshToken_should_match_sliding_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 10
};
var handle = await _subject.CreateRefreshTokenAsync(_user, new Token(), client);
var refreshToken = (await _store.GetRefreshTokenAsync(handle));
refreshToken.Should().NotBeNull();
refreshToken.Lifetime.Should().Be(client.SlidingRefreshTokenLifetime);
}
[Fact]
public async Task UpdateRefreshToken_one_time_use_should_create_new_token()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.OneTimeOnly
};
var refreshToken = new RefreshToken
{
CreationTime = DateTime.UtcNow,
Lifetime = 10,
AccessToken = new Token
{
ClientId = client.ClientId,
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Claims = new List<Claim>()
{
new Claim("sub", "123")
}
}
};
var handle = await _store.StoreRefreshTokenAsync(refreshToken);
(await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client))
.Should().NotBeNull()
.And
.NotBe(handle);
}
[Fact]
public async Task UpdateRefreshToken_sliding_with_non_zero_absolute_should_update_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 10,
AbsoluteRefreshTokenLifetime = 100
};
var now = DateTime.UtcNow;
_clock.UtcNowFunc = () => now;
var handle = await _store.StoreRefreshTokenAsync(new RefreshToken
{
CreationTime = now.AddSeconds(-10),
AccessToken = new Token
{
ClientId = client.ClientId,
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Claims = new List<Claim>()
{
new Claim("sub", "123")
}
}
});
var refreshToken = await _store.GetRefreshTokenAsync(handle);
var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client);
newHandle.Should().NotBeNull().And.Be(handle);
var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle);
newRefreshToken.Should().NotBeNull();
newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime);
}
[Fact]
public async Task UpdateRefreshToken_lifetime_exceeds_absolute_should_be_absolute_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 10,
AbsoluteRefreshTokenLifetime = 1000
};
var now = DateTime.UtcNow;
_clock.UtcNowFunc = () => now;
var handle = await _store.StoreRefreshTokenAsync(new RefreshToken
{
CreationTime = now.AddSeconds(-1000),
AccessToken = new Token
{
ClientId = client.ClientId,
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Claims = new List<Claim>()
{
new Claim("sub", "123")
}
}
});
var refreshToken = await _store.GetRefreshTokenAsync(handle);
var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client);
newHandle.Should().NotBeNull().And.Be(handle);
var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle);
newRefreshToken.Should().NotBeNull();
newRefreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime);
}
[Fact]
public async Task UpdateRefreshToken_sliding_with_zero_absolute_should_update_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 10,
AbsoluteRefreshTokenLifetime = 0
};
var now = DateTime.UtcNow;
_clock.UtcNowFunc = () => now;
var handle = await _store.StoreRefreshTokenAsync(new RefreshToken
{
CreationTime = now.AddSeconds(-1000),
AccessToken = new Token
{
ClientId = client.ClientId,
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Claims = new List<Claim>()
{
new Claim("sub", "123")
}
}
});
var refreshToken = await _store.GetRefreshTokenAsync(handle);
var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client);
newHandle.Should().NotBeNull().And.Be(handle);
var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle);
newRefreshToken.Should().NotBeNull();
newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime);
}
[Fact]
public async Task UpdateRefreshToken_for_onetime_and_sliding_with_zero_absolute_should_update_lifetime()
{
var client = new Client
{
ClientId = "client1",
RefreshTokenUsage = TokenUsage.OneTimeOnly,
RefreshTokenExpiration = TokenExpiration.Sliding,
SlidingRefreshTokenLifetime = 10,
AbsoluteRefreshTokenLifetime = 0
};
var now = DateTime.UtcNow;
_clock.UtcNowFunc = () => now;
var handle = await _store.StoreRefreshTokenAsync(new RefreshToken
{
CreationTime = now.AddSeconds(-1000),
AccessToken = new Token
{
ClientId = client.ClientId,
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Claims = new List<Claim>()
{
new Claim("sub", "123")
}
}
});
var refreshToken = await _store.GetRefreshTokenAsync(handle);
var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client);
newHandle.Should().NotBeNull().And.NotBe(handle);
var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle);
newRefreshToken.Should().NotBeNull();
newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime);
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using gov.va.medora.mdo;
using System.IO;
using System.Xml.Serialization;
using gov.va.medora.mdo.domain.ccd;
namespace gov.va.medora.mdws.dto
{
public class TaggedTextArray : AbstractArrayTO
{
public TaggedText[] results;
private bool textOnly;
public TaggedTextArray() { }
public TaggedTextArray(IndexedHashtable t)
{
this.textOnly = false;
setProps(t);
}
public TaggedTextArray(IndexedHashtable t, bool textOnly)
{
this.textOnly = textOnly;
setProps(t);
}
public TaggedTextArray(OrderedDictionary d)
{
this.textOnly = false;
if (d == null || d.Count == 0)
{
return;
}
this.results = new TaggedText[d.Count];
int i = 0;
foreach (DictionaryEntry de in d)
{
this.results[i++] = new TaggedText(de);
}
}
private void setProps(IndexedHashtable t)
{
this.results = new TaggedText[t.Count];
for (int i = 0; i < t.Count; i++)
{
this.results[i] = new TaggedText();
this.results[i].tag = (string)t.GetKey(i);
if (t.GetValue(i) == null)
{
continue;
}
Type vType = t.GetValue(i).GetType();
if (vType == typeof(string))
{
this.results[i].text = (string)t.GetValue(i);
}
else if (vType == typeof(string[]))
{
string[] a = (string[])t.GetValue(i);
this.results[i].taggedResults = new TaggedText[a.Length];
for (int j = 0; j < a.Length; j++)
{
if (textOnly)
{
this.results[i].taggedResults[j] = new TaggedText("", a[j]);
}
else
{
this.results[i].taggedResults[j] = new TaggedText(a[j]);
}
}
}
else if (vType == typeof(Dictionary<string, ArrayList>))
{
Dictionary<string, ArrayList> d = (Dictionary<string, ArrayList>)t.GetValue(i);
this.results[i].taggedResults = new TaggedText[d.Count];
int j = 0;
foreach (KeyValuePair<string, ArrayList> kvp in d)
{
this.results[i].taggedResults[j++] = new TaggedText(kvp);
}
}
else if (vType == typeof(IndexedHashtable))
{
IndexedHashtable tbl = (IndexedHashtable)t.GetValue(i);
this.results[i].taggedResults = new TaggedText[tbl.Count];
for (int j = 0; j < tbl.Count; j++)
{
this.results[i].taggedResults[j] = new TaggedText((string)tbl.GetKey(j),(string)tbl.GetValue(j));
}
}
else if (vType == typeof(DictionaryHashList))
{
DictionaryHashList d = (DictionaryHashList)t.GetValue(i);
this.results[i].taggedResults = new TaggedText[d.Count];
for (int j = 0; j < d.Count; j++)
{
this.results[i].taggedResults[j] = new TaggedText(d[j]);
}
}
else if (vType == typeof(KeyValuePair<int, string>))
{
if (t.Count == 1)
{
this.results = new TaggedText[] { new TaggedText((KeyValuePair<int, string>)t.GetValue(i)) };
}
else
{
this.results[i].taggedResults = new TaggedText[] { new TaggedText((KeyValuePair<int, string>)t.GetValue(i)) };
}
}
else if (vType == typeof(DateTime))
{
string s = ((DateTime)t.GetValue(i)).ToString("yyyyMMdd.HHmmss");
if (t.Count == 1)
{
this.results = new TaggedText[] { new TaggedText(t.GetKey(i).ToString(), s) };
}
else
{
this.results[i].taggedResults = new TaggedText[] { new TaggedText(t.GetKey(i).ToString(), s) };
}
}
else if (vType == typeof(StringDictionary))
{
StringDictionary sd = (StringDictionary)t.GetValue(i);
this.results[i] = new TaggedText(this.results[i].tag, sd);
}
else if (vType == typeof(OrderedDictionary))
{
OrderedDictionary d = (OrderedDictionary)t.GetValue(i);
this.results[i] = new TaggedText(this.results[i].tag, d);
}
else if (vType == typeof(User))
{
string s = ((User)t.GetValue(i)).Uid;
this.results[i].text = s;
}
else if (MdwsUtils.isException(t.GetValue(i)))
{
this.results[i].fault = new FaultTO((Exception)t.GetValue(i));
}
else if (vType == typeof(gov.va.medora.mdo.domain.ccd.ContinuityOfCareRecord))
{
// serialize CCR as XML
MemoryStream memStream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(ContinuityOfCareRecord));
serializer.Serialize(memStream, new ContinuityOfCareRecord());
this.results[i] = new TaggedText(this.results[i].tag, "<![CDATA[" + System.Text.Encoding.UTF8.GetString(memStream.ToArray()) + "]]>");
}
}
this.count = t.Count;
}
public TaggedTextArray(StringDictionary d)
{
if (d == null)
{
this.count = 0;
return;
}
this.results = new TaggedText[d.Count];
int i = 0;
foreach (DictionaryEntry de in d)
{
this.results[i++] = new TaggedText(de);
}
this.count = d.Count;
}
public TaggedTextArray(Dictionary<string, string> d)
{
if (d == null)
{
this.count = 0;
return;
}
this.count = d.Count;
this.results = new TaggedText[this.count];
int index = 0;
foreach(KeyValuePair<string, string> kvp in d)
{
this.results[index++] = new TaggedText(kvp);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Amazon.ElasticLoadBalancing;
using Amazon.ElasticLoadBalancing.Model;
using NUnit.Framework;
using CommonTests.Framework;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class ElasticLoadBalancing : TestBase<AmazonElasticLoadBalancingClient>
{
const string SDK_TEST_PREFIX = "aws-net-sdk";
public string AVAILABILITY_ZONE_1;
public string AVAILABILITY_ZONE_2;
public const String PROTOCOL = "HTTP";
string loadBalancerName;
[OneTimeTearDown]
public void Cleanup()
{
BaseClean();
}
[OneTimeSetUp]
public void TestCleanup()
{
if (loadBalancerName != null)
{
Client.DeleteLoadBalancerAsync(new DeleteLoadBalancerRequest()
{
LoadBalancerName = loadBalancerName
}).Wait();
}
}
[Test]
[Category("ElasticLoadBalancing")]
public void TestLoadBalancerOperations()
{
using(var ec2 = CreateClient<Amazon.EC2.AmazonEC2Client>())
{
var regionName = TestRunner.RegionEndpoint.SystemName;
var availabilityZones = ec2.DescribeAvailabilityZonesAsync(new Amazon.EC2.Model.DescribeAvailabilityZonesRequest
{
Filters = new List<Amazon.EC2.Model.Filter>
{
new Amazon.EC2.Model.Filter
{
Name = "region-name",
Values = new List<string>
{
regionName
}
}
}
}).Result.AvailabilityZones;
AVAILABILITY_ZONE_1 = availabilityZones[0].ZoneName;
AVAILABILITY_ZONE_2 = availabilityZones[1].ZoneName;
}
loadBalancerName = SDK_TEST_PREFIX+"-lb" + DateTime.Now.Ticks;
Listener expectedListener = new Listener()
{
InstancePort = 8080,
LoadBalancerPort = 80,
Protocol = PROTOCOL
};
// Create a load balancer
string dnsName = Client.CreateLoadBalancerAsync(
new CreateLoadBalancerRequest()
{
LoadBalancerName = loadBalancerName,
AvailabilityZones = new List<string>() { AVAILABILITY_ZONE_1 },
Listeners = new List<Listener>() { expectedListener }
}).Result.DNSName;
try
{
Assert.IsFalse(string.IsNullOrEmpty(dnsName));
// Configure health checks
HealthCheck expectedHealthCheck = new HealthCheck()
{
Interval = 120,
Target = "HTTP:80/ping",
Timeout = 60,
UnhealthyThreshold = 9,
HealthyThreshold = 10
};
HealthCheck createdHealthCheck = Client.ConfigureHealthCheckAsync(
new ConfigureHealthCheckRequest()
{
LoadBalancerName = loadBalancerName,
HealthCheck = expectedHealthCheck
}).Result.HealthCheck;
Assert.AreEqual(expectedHealthCheck.HealthyThreshold, createdHealthCheck.HealthyThreshold);
Assert.AreEqual(expectedHealthCheck.Interval, createdHealthCheck.Interval);
Assert.AreEqual(expectedHealthCheck.Target, createdHealthCheck.Target);
Assert.AreEqual(expectedHealthCheck.Timeout, createdHealthCheck.Timeout);
Assert.AreEqual(expectedHealthCheck.UnhealthyThreshold, createdHealthCheck.UnhealthyThreshold);
// Describe
List<LoadBalancerDescription> loadBalancerDescriptions =
Client.DescribeLoadBalancersAsync(
new DescribeLoadBalancersRequest()
{
LoadBalancerNames = new List<string>() { loadBalancerName }
}
).Result.LoadBalancerDescriptions;
Assert.AreEqual(1, loadBalancerDescriptions.Count);
LoadBalancerDescription loadBalancer = loadBalancerDescriptions[0];
Assert.AreEqual(loadBalancerName, loadBalancer.LoadBalancerName);
Assert.AreEqual(1, loadBalancer.AvailabilityZones.Count);
Assert.IsTrue(loadBalancer.AvailabilityZones.Contains(AVAILABILITY_ZONE_1));
Assert.IsNotNull(loadBalancer.CreatedTime);
Assert.AreEqual(dnsName, loadBalancer.DNSName);
Assert.AreEqual(expectedHealthCheck.Target, loadBalancer.HealthCheck.Target);
Assert.IsTrue(loadBalancer.Instances.Count == 0);
Assert.AreEqual(1, loadBalancer.ListenerDescriptions.Count);
Assert.AreEqual((double)8080, (double)loadBalancer.ListenerDescriptions[0].Listener.InstancePort, 0.0);
Assert.AreEqual((double)80, (double)loadBalancer.ListenerDescriptions[0].Listener.LoadBalancerPort, 0.0);
Assert.AreEqual(PROTOCOL, loadBalancer.ListenerDescriptions[0].Listener.Protocol);
Assert.AreEqual(loadBalancerName, loadBalancer.LoadBalancerName);
Assert.IsNotNull(loadBalancer.SourceSecurityGroup);
Assert.IsNotNull(loadBalancer.SourceSecurityGroup.GroupName);
Assert.IsNotNull(loadBalancer.SourceSecurityGroup.OwnerAlias);
// Enabled AZs
List<String> availabilityZones =
Client.EnableAvailabilityZonesForLoadBalancerAsync(
new EnableAvailabilityZonesForLoadBalancerRequest()
{
LoadBalancerName = loadBalancerName,
AvailabilityZones = new List<string>() { AVAILABILITY_ZONE_2 }
}
).Result.AvailabilityZones;
Assert.AreEqual(2, availabilityZones.Count);
Assert.IsTrue(availabilityZones.Contains(AVAILABILITY_ZONE_1));
Assert.IsTrue(availabilityZones.Contains(AVAILABILITY_ZONE_2));
UtilityMethods.Sleep(TimeSpan.FromSeconds(10));
// Disable AZs
availabilityZones =
Client.DisableAvailabilityZonesForLoadBalancerAsync(
new DisableAvailabilityZonesForLoadBalancerRequest()
{
LoadBalancerName = loadBalancerName,
AvailabilityZones = new List<string>() { AVAILABILITY_ZONE_2 }
}
).Result.AvailabilityZones;
Assert.AreEqual(1, availabilityZones.Count);
Assert.IsTrue(availabilityZones.Contains(AVAILABILITY_ZONE_1));
Assert.IsFalse(availabilityZones.Contains(AVAILABILITY_ZONE_2));
// Create LB stickiness policy
String policyName = SDK_TEST_PREFIX + "-policy-" + DateTime.Now.Ticks;
Client.CreateLBCookieStickinessPolicyAsync(new CreateLBCookieStickinessPolicyRequest()
{
LoadBalancerName = loadBalancerName,
PolicyName = policyName
}).Wait();
// Attach the policy to a listener
Client.SetLoadBalancerPoliciesOfListenerAsync(new SetLoadBalancerPoliciesOfListenerRequest()
{
LoadBalancerName = loadBalancerName,
LoadBalancerPort = 80,
PolicyNames = new List<string>() { policyName }
}).Wait();
Assert.IsTrue(DoesLoadBalancerHaveListenerWithPolicy(loadBalancerName, policyName));
// Remove the policy from the listener
Client.SetLoadBalancerPoliciesOfListenerAsync(new SetLoadBalancerPoliciesOfListenerRequest()
{
LoadBalancerName = loadBalancerName,
LoadBalancerPort = 80
}).Wait();
Assert.IsFalse(DoesLoadBalancerHaveListenerWithPolicy(loadBalancerName, policyName));
// Delete the policy
Client.DeleteLoadBalancerPolicyAsync(new DeleteLoadBalancerPolicyRequest(loadBalancerName, policyName)).Wait();
}
finally
{
// Delete the test load balancer
Client.DeleteLoadBalancerAsync(new DeleteLoadBalancerRequest() { LoadBalancerName = loadBalancerName }).Wait();
}
}
private bool DoesLoadBalancerHaveListenerWithPolicy(String loadBalancerName, String policyName)
{
List<LoadBalancerDescription> loadBalancers = Client.DescribeLoadBalancersAsync(
new DescribeLoadBalancersRequest() { LoadBalancerNames = new List<string>() { loadBalancerName } })
.Result.LoadBalancerDescriptions;
if (loadBalancers.Count == 0) Assert.Fail("Unknown load balancer: " + loadBalancerName);
List<ListenerDescription> listeners = loadBalancers[0].ListenerDescriptions;
foreach (ListenerDescription listener in listeners)
{
if (listener.PolicyNames.Contains(policyName))
return true;
}
return false;
}
}
}
| |
using ClosedXML.Excel.CalcEngine;
using ClosedXML.Excel.Drawings;
using ClosedXML.Excel.Misc;
using ClosedXML.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
namespace ClosedXML.Excel
{
internal class XLWorksheet : XLRangeBase, IXLWorksheet
{
#region Events
public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedRows;
public XLReentrantEnumerableSet<XLCallbackAction> RangeShiftedColumns;
#endregion Events
#region Fields
private readonly Dictionary<Int32, Int32> _columnOutlineCount = new Dictionary<Int32, Int32>();
private readonly Dictionary<Int32, Int32> _rowOutlineCount = new Dictionary<Int32, Int32>();
internal Int32 ZOrder = 1;
private String _name;
internal Int32 _position;
private Double _rowHeight;
private Boolean _tabActive;
internal Boolean EventTrackingEnabled;
#endregion Fields
#region Constructor
public XLWorksheet(String sheetName, XLWorkbook workbook)
: base(
new XLRangeAddress(
new XLAddress(null, XLHelper.MinRowNumber, XLHelper.MinColumnNumber, false, false),
new XLAddress(null, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber, false, false)))
{
EventTrackingEnabled = workbook.EventTracking == XLEventTracking.Enabled;
Workbook = workbook;
RangeShiftedRows = new XLReentrantEnumerableSet<XLCallbackAction>();
RangeShiftedColumns = new XLReentrantEnumerableSet<XLCallbackAction>();
RangeAddress.Worksheet = this;
RangeAddress.FirstAddress.Worksheet = this;
RangeAddress.LastAddress.Worksheet = this;
Pictures = new XLPictures(this);
NamedRanges = new XLNamedRanges(this);
SheetView = new XLSheetView();
Tables = new XLTables();
Hyperlinks = new XLHyperlinks();
DataValidations = new XLDataValidations();
PivotTables = new XLPivotTables();
Protection = new XLSheetProtection();
AutoFilter = new XLAutoFilter();
ConditionalFormats = new XLConditionalFormats();
SetStyle(workbook.Style);
Internals = new XLWorksheetInternals(new XLCellsCollection(), new XLColumnsCollection(),
new XLRowsCollection(), new XLRanges());
PageSetup = new XLPageSetup((XLPageSetup)workbook.PageOptions, this);
Outline = new XLOutline(workbook.Outline);
_columnWidth = workbook.ColumnWidth;
_rowHeight = workbook.RowHeight;
RowHeightChanged = Math.Abs(workbook.RowHeight - XLWorkbook.DefaultRowHeight) > XLHelper.Epsilon;
Name = sheetName;
SubscribeToShiftedRows((range, rowsShifted) => this.WorksheetRangeShiftedRows(range, rowsShifted));
SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted));
Charts = new XLCharts();
ShowFormulas = workbook.ShowFormulas;
ShowGridLines = workbook.ShowGridLines;
ShowOutlineSymbols = workbook.ShowOutlineSymbols;
ShowRowColHeaders = workbook.ShowRowColHeaders;
ShowRuler = workbook.ShowRuler;
ShowWhiteSpace = workbook.ShowWhiteSpace;
ShowZeros = workbook.ShowZeros;
RightToLeft = workbook.RightToLeft;
TabColor = XLColor.NoColor;
SelectedRanges = new XLRanges();
Author = workbook.Author;
}
#endregion Constructor
//private IXLStyle _style;
private const String InvalidNameChars = @":\/?*[]";
public string LegacyDrawingId;
public Boolean LegacyDrawingIsNew;
private Double _columnWidth;
public XLWorksheetInternals Internals { get; private set; }
public override IEnumerable<IXLStyle> Styles
{
get
{
UpdatingStyle = true;
yield return GetStyle();
foreach (XLCell c in Internals.CellsCollection.GetCells())
yield return c.Style;
UpdatingStyle = false;
}
}
public override Boolean UpdatingStyle { get; set; }
public override IXLStyle InnerStyle
{
get { return GetStyle(); }
set { SetStyle(value); }
}
internal Boolean RowHeightChanged { get; set; }
internal Boolean ColumnWidthChanged { get; set; }
public Int32 SheetId { get; set; }
internal String RelId { get; set; }
public XLDataValidations DataValidations { get; private set; }
public IXLCharts Charts { get; private set; }
public XLSheetProtection Protection { get; private set; }
public XLAutoFilter AutoFilter { get; private set; }
#region IXLWorksheet Members
public XLWorkbook Workbook { get; private set; }
public override IXLStyle Style
{
get
{
return GetStyle();
}
set
{
SetStyle(value);
foreach (XLCell cell in Internals.CellsCollection.GetCells())
cell.Style = value;
}
}
public Double ColumnWidth
{
get { return _columnWidth; }
set
{
ColumnWidthChanged = true;
_columnWidth = value;
}
}
public Double RowHeight
{
get { return _rowHeight; }
set
{
RowHeightChanged = true;
_rowHeight = value;
}
}
public String Name
{
get { return _name; }
set
{
if (value.IndexOfAny(InvalidNameChars.ToCharArray()) != -1)
throw new ArgumentException("Worksheet names cannot contain any of the following characters: " +
InvalidNameChars);
if (String.IsNullOrWhiteSpace(value))
throw new ArgumentException("Worksheet names cannot be empty");
if (value.Length > 31)
throw new ArgumentException("Worksheet names cannot be more than 31 characters");
Workbook.WorksheetsInternal.Rename(_name, value);
_name = value;
}
}
public Int32 Position
{
get { return _position; }
set
{
if (value > Workbook.WorksheetsInternal.Count + Workbook.UnsupportedSheets.Count + 1)
throw new IndexOutOfRangeException("Index must be equal or less than the number of worksheets + 1.");
if (value < _position)
{
Workbook.WorksheetsInternal
.Where<XLWorksheet>(w => w.Position >= value && w.Position < _position)
.ForEach(w => w._position += 1);
}
if (value > _position)
{
Workbook.WorksheetsInternal
.Where<XLWorksheet>(w => w.Position <= value && w.Position > _position)
.ForEach(w => (w)._position -= 1);
}
_position = value;
}
}
public IXLPageSetup PageSetup { get; private set; }
public IXLOutline Outline { get; private set; }
IXLRow IXLWorksheet.FirstRowUsed()
{
return FirstRowUsed();
}
IXLRow IXLWorksheet.FirstRowUsed(Boolean includeFormats)
{
return FirstRowUsed(includeFormats);
}
IXLRow IXLWorksheet.LastRowUsed()
{
return LastRowUsed();
}
IXLRow IXLWorksheet.LastRowUsed(Boolean includeFormats)
{
return LastRowUsed(includeFormats);
}
IXLColumn IXLWorksheet.LastColumn()
{
return LastColumn();
}
IXLColumn IXLWorksheet.FirstColumn()
{
return FirstColumn();
}
IXLRow IXLWorksheet.FirstRow()
{
return FirstRow();
}
IXLRow IXLWorksheet.LastRow()
{
return LastRow();
}
IXLColumn IXLWorksheet.FirstColumnUsed()
{
return FirstColumnUsed();
}
IXLColumn IXLWorksheet.FirstColumnUsed(Boolean includeFormats)
{
return FirstColumnUsed(includeFormats);
}
IXLColumn IXLWorksheet.LastColumnUsed()
{
return LastColumnUsed();
}
IXLColumn IXLWorksheet.LastColumnUsed(Boolean includeFormats)
{
return LastColumnUsed(includeFormats);
}
public IXLColumns Columns()
{
var retVal = new XLColumns(this);
var columnList = new List<Int32>();
if (Internals.CellsCollection.Count > 0)
columnList.AddRange(Internals.CellsCollection.ColumnsUsed.Keys);
if (Internals.ColumnsCollection.Count > 0)
columnList.AddRange(Internals.ColumnsCollection.Keys.Where(c => !columnList.Contains(c)));
foreach (int c in columnList)
retVal.Add(Column(c));
return retVal;
}
public IXLColumns Columns(String columns)
{
var retVal = new XLColumns(null);
var columnPairs = columns.Split(',');
foreach (string tPair in columnPairs.Select(pair => pair.Trim()))
{
String firstColumn;
String lastColumn;
if (tPair.Contains(':') || tPair.Contains('-'))
{
var columnRange = XLHelper.SplitRange(tPair);
firstColumn = columnRange[0];
lastColumn = columnRange[1];
}
else
{
firstColumn = tPair;
lastColumn = tPair;
}
Int32 tmp;
if (Int32.TryParse(firstColumn, out tmp))
{
foreach (IXLColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn)))
retVal.Add((XLColumn)col);
}
else
{
foreach (IXLColumn col in Columns(firstColumn, lastColumn))
retVal.Add((XLColumn)col);
}
}
return retVal;
}
public IXLColumns Columns(String firstColumn, String lastColumn)
{
return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn),
XLHelper.GetColumnNumberFromLetter(lastColumn));
}
public IXLColumns Columns(Int32 firstColumn, Int32 lastColumn)
{
var retVal = new XLColumns(null);
for (int co = firstColumn; co <= lastColumn; co++)
retVal.Add(Column(co));
return retVal;
}
public IXLRows Rows()
{
var retVal = new XLRows(this);
var rowList = new List<Int32>();
if (Internals.CellsCollection.Count > 0)
rowList.AddRange(Internals.CellsCollection.RowsUsed.Keys);
if (Internals.RowsCollection.Count > 0)
rowList.AddRange(Internals.RowsCollection.Keys.Where(r => !rowList.Contains(r)));
foreach (int r in rowList)
retVal.Add(Row(r));
return retVal;
}
public IXLRows Rows(String rows)
{
var retVal = new XLRows(null);
var rowPairs = rows.Split(',');
foreach (string tPair in rowPairs.Select(pair => pair.Trim()))
{
String firstRow;
String lastRow;
if (tPair.Contains(':') || tPair.Contains('-'))
{
var rowRange = XLHelper.SplitRange(tPair);
firstRow = rowRange[0];
lastRow = rowRange[1];
}
else
{
firstRow = tPair;
lastRow = tPair;
}
foreach (IXLRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow)))
retVal.Add((XLRow)row);
}
return retVal;
}
public IXLRows Rows(Int32 firstRow, Int32 lastRow)
{
var retVal = new XLRows(null);
for (int ro = firstRow; ro <= lastRow; ro++)
retVal.Add(Row(ro));
return retVal;
}
IXLRow IXLWorksheet.Row(Int32 row)
{
return Row(row);
}
IXLColumn IXLWorksheet.Column(Int32 column)
{
return Column(column);
}
IXLColumn IXLWorksheet.Column(String column)
{
return Column(column);
}
IXLCell IXLWorksheet.Cell(int row, int column)
{
return Cell(row, column);
}
IXLCell IXLWorksheet.Cell(string cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLCell IXLWorksheet.Cell(int row, string column)
{
return Cell(row, column);
}
IXLCell IXLWorksheet.Cell(IXLAddress cellAddressInRange)
{
return Cell(cellAddressInRange);
}
IXLRange IXLWorksheet.Range(IXLRangeAddress rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLWorksheet.Range(string rangeAddress)
{
return Range(rangeAddress);
}
IXLRange IXLWorksheet.Range(IXLCell firstCell, IXLCell lastCell)
{
return Range(firstCell, lastCell);
}
IXLRange IXLWorksheet.Range(string firstCellAddress, string lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLWorksheet.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress)
{
return Range(firstCellAddress, lastCellAddress);
}
IXLRange IXLWorksheet.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn)
{
return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn);
}
public IXLWorksheet CollapseRows()
{
Enumerable.Range(1, 8).ForEach(i => CollapseRows(i));
return this;
}
public IXLWorksheet CollapseColumns()
{
Enumerable.Range(1, 8).ForEach(i => CollapseColumns(i));
return this;
}
public IXLWorksheet ExpandRows()
{
Enumerable.Range(1, 8).ForEach(i => ExpandRows(i));
return this;
}
public IXLWorksheet ExpandColumns()
{
Enumerable.Range(1, 8).ForEach(i => ExpandRows(i));
return this;
}
public IXLWorksheet CollapseRows(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Collapse());
return this;
}
public IXLWorksheet CollapseColumns(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Collapse());
return this;
}
public IXLWorksheet ExpandRows(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.RowsCollection.Values.Where(r => r.OutlineLevel == outlineLevel).ForEach(r => r.Expand());
return this;
}
public IXLWorksheet ExpandColumns(Int32 outlineLevel)
{
if (outlineLevel < 1 || outlineLevel > 8)
throw new ArgumentOutOfRangeException("outlineLevel", "Outline level must be between 1 and 8.");
Internals.ColumnsCollection.Values.Where(c => c.OutlineLevel == outlineLevel).ForEach(c => c.Expand());
return this;
}
public void Delete()
{
Workbook.WorksheetsInternal.Delete(Name);
}
public IXLNamedRanges NamedRanges { get; private set; }
public IXLNamedRange NamedRange(String rangeName)
{
return NamedRanges.NamedRange(rangeName);
}
public IXLSheetView SheetView { get; private set; }
public IXLTables Tables { get; private set; }
public IXLTable Table(Int32 index)
{
return Tables.Table(index);
}
public IXLTable Table(String name)
{
return Tables.Table(name);
}
public IXLWorksheet CopyTo(String newSheetName)
{
return CopyTo(Workbook, newSheetName, Workbook.WorksheetsInternal.Count + 1);
}
public IXLWorksheet CopyTo(String newSheetName, Int32 position)
{
return CopyTo(Workbook, newSheetName, position);
}
public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName)
{
return CopyTo(workbook, newSheetName, workbook.WorksheetsInternal.Count + 1);
}
public IXLWorksheet CopyTo(XLWorkbook workbook, String newSheetName, Int32 position)
{
var targetSheet = (XLWorksheet)workbook.WorksheetsInternal.Add(newSheetName, position);
Internals.ColumnsCollection.ForEach(kp => targetSheet.Internals.ColumnsCollection.Add(kp.Key, new XLColumn(kp.Value)));
Internals.RowsCollection.ForEach(kp => targetSheet.Internals.RowsCollection.Add(kp.Key, new XLRow(kp.Value)));
Internals.CellsCollection.GetCells().ForEach(c => targetSheet.Cell(c.Address).CopyFrom(c, false));
DataValidations.ForEach(dv => targetSheet.DataValidations.Add(new XLDataValidation(dv)));
targetSheet.Visibility = Visibility;
targetSheet.ColumnWidth = ColumnWidth;
targetSheet.ColumnWidthChanged = ColumnWidthChanged;
targetSheet.RowHeight = RowHeight;
targetSheet.RowHeightChanged = RowHeightChanged;
targetSheet.SetStyle(Style);
targetSheet.PageSetup = new XLPageSetup((XLPageSetup)PageSetup, targetSheet);
(targetSheet.PageSetup.Header as XLHeaderFooter).Changed = true;
(targetSheet.PageSetup.Footer as XLHeaderFooter).Changed = true;
targetSheet.Outline = new XLOutline(Outline);
targetSheet.SheetView = new XLSheetView(SheetView);
Internals.MergedRanges.ForEach(
kp => targetSheet.Internals.MergedRanges.Add(targetSheet.Range(kp.RangeAddress.ToString())));
foreach (var picture in Pictures)
{
var newPic = targetSheet.AddPicture(picture.ImageStream, picture.Format, picture.Name)
.WithPlacement(picture.Placement)
.WithSize(picture.Width, picture.Height);
switch (picture.Placement)
{
case XLPicturePlacement.FreeFloating:
newPic.MoveTo(picture.Left, picture.Top);
break;
case XLPicturePlacement.Move:
var newAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false);
newPic.MoveTo(newAddress, picture.GetOffset(XLMarkerPosition.TopLeft));
break;
case XLPicturePlacement.MoveAndSize:
var newFromAddress = new XLAddress(targetSheet, picture.TopLeftCellAddress.RowNumber, picture.TopLeftCellAddress.ColumnNumber, false, false);
var newToAddress = new XLAddress(targetSheet, picture.BottomRightCellAddress.RowNumber, picture.BottomRightCellAddress.ColumnNumber, false, false);
newPic.MoveTo(newFromAddress, picture.GetOffset(XLMarkerPosition.TopLeft), newToAddress, picture.GetOffset(XLMarkerPosition.BottomRight));
break;
}
}
foreach (var nr in NamedRanges)
{
var ranges = new XLRanges();
foreach (var r in nr.Ranges)
{
if (this == r.Worksheet)
// Named ranges on the source worksheet have to point to the new destination sheet
ranges.Add(targetSheet.Range(r.RangeAddress.FirstAddress.RowNumber, r.RangeAddress.FirstAddress.ColumnNumber, r.RangeAddress.LastAddress.RowNumber, r.RangeAddress.LastAddress.ColumnNumber));
else
ranges.Add(r);
}
targetSheet.NamedRanges.Add(nr.Name, ranges);
}
foreach (XLTable t in Tables.Cast<XLTable>())
{
String tableName = t.Name;
var table = targetSheet.Tables.Any(tt => tt.Name == tableName)
? new XLTable(targetSheet.Range(t.RangeAddress.ToString()), true)
: new XLTable(targetSheet.Range(t.RangeAddress.ToString()), tableName, true);
table.RelId = t.RelId;
table.EmphasizeFirstColumn = t.EmphasizeFirstColumn;
table.EmphasizeLastColumn = t.EmphasizeLastColumn;
table.ShowRowStripes = t.ShowRowStripes;
table.ShowColumnStripes = t.ShowColumnStripes;
table.ShowAutoFilter = t.ShowAutoFilter;
table.Theme = t.Theme;
table._showTotalsRow = t.ShowTotalsRow;
table._uniqueNames.Clear();
t._uniqueNames.ForEach(n => table._uniqueNames.Add(n));
Int32 fieldCount = t.ColumnCount();
for (Int32 f = 0; f < fieldCount; f++)
{
var tableField = table.Field(f) as XLTableField;
var tField = t.Field(f) as XLTableField;
tableField.Index = tField.Index;
tableField.Name = tField.Name;
tableField.totalsRowLabel = tField.totalsRowLabel;
tableField.totalsRowFunction = tField.totalsRowFunction;
}
}
if (AutoFilter.Enabled)
targetSheet.Range(AutoFilter.Range.RangeAddress).SetAutoFilter();
return targetSheet;
}
private String ReplaceRelativeSheet(string newSheetName, String value)
{
if (String.IsNullOrWhiteSpace(value)) return value;
var newValue = new StringBuilder();
var addresses = value.Split(',');
foreach (var address in addresses)
{
var pair = address.Split('!');
if (pair.Length == 2)
{
String sheetName = pair[0];
if (sheetName.StartsWith("'"))
sheetName = sheetName.Substring(1, sheetName.Length - 2);
String name = sheetName.ToLower().Equals(Name.ToLower())
? newSheetName
: sheetName;
newValue.Append(String.Format("{0}!{1}", name.WrapSheetNameInQuotesIfRequired(), pair[1]));
}
else
{
newValue.Append(address);
}
}
return newValue.ToString();
}
public new IXLHyperlinks Hyperlinks { get; private set; }
IXLDataValidations IXLWorksheet.DataValidations
{
get { return DataValidations; }
}
private XLWorksheetVisibility _visibility;
public XLWorksheetVisibility Visibility
{
get { return _visibility; }
set
{
if (value != XLWorksheetVisibility.Visible)
TabSelected = false;
_visibility = value;
}
}
public IXLWorksheet Hide()
{
Visibility = XLWorksheetVisibility.Hidden;
return this;
}
public IXLWorksheet Unhide()
{
Visibility = XLWorksheetVisibility.Visible;
return this;
}
IXLSheetProtection IXLWorksheet.Protection
{
get { return Protection; }
}
public IXLSheetProtection Protect()
{
return Protection.Protect();
}
public IXLSheetProtection Protect(String password)
{
return Protection.Protect(password);
}
public IXLSheetProtection Unprotect()
{
return Protection.Unprotect();
}
public IXLSheetProtection Unprotect(String password)
{
return Protection.Unprotect(password);
}
public new IXLRange Sort()
{
return GetRangeForSort().Sort();
}
public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending,
Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return GetRangeForSort().Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks);
}
public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending,
Boolean matchCase = false, Boolean ignoreBlanks = true)
{
return GetRangeForSort().Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks);
}
public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false,
Boolean ignoreBlanks = true)
{
return GetRangeForSort().SortLeftToRight(sortOrder, matchCase, ignoreBlanks);
}
public Boolean ShowFormulas { get; set; }
public Boolean ShowGridLines { get; set; }
public Boolean ShowOutlineSymbols { get; set; }
public Boolean ShowRowColHeaders { get; set; }
public Boolean ShowRuler { get; set; }
public Boolean ShowWhiteSpace { get; set; }
public Boolean ShowZeros { get; set; }
public IXLWorksheet SetShowFormulas()
{
ShowFormulas = true;
return this;
}
public IXLWorksheet SetShowFormulas(Boolean value)
{
ShowFormulas = value;
return this;
}
public IXLWorksheet SetShowGridLines()
{
ShowGridLines = true;
return this;
}
public IXLWorksheet SetShowGridLines(Boolean value)
{
ShowGridLines = value;
return this;
}
public IXLWorksheet SetShowOutlineSymbols()
{
ShowOutlineSymbols = true;
return this;
}
public IXLWorksheet SetShowOutlineSymbols(Boolean value)
{
ShowOutlineSymbols = value;
return this;
}
public IXLWorksheet SetShowRowColHeaders()
{
ShowRowColHeaders = true;
return this;
}
public IXLWorksheet SetShowRowColHeaders(Boolean value)
{
ShowRowColHeaders = value;
return this;
}
public IXLWorksheet SetShowRuler()
{
ShowRuler = true;
return this;
}
public IXLWorksheet SetShowRuler(Boolean value)
{
ShowRuler = value;
return this;
}
public IXLWorksheet SetShowWhiteSpace()
{
ShowWhiteSpace = true;
return this;
}
public IXLWorksheet SetShowWhiteSpace(Boolean value)
{
ShowWhiteSpace = value;
return this;
}
public IXLWorksheet SetShowZeros()
{
ShowZeros = true;
return this;
}
public IXLWorksheet SetShowZeros(Boolean value)
{
ShowZeros = value;
return this;
}
public XLColor TabColor { get; set; }
public IXLWorksheet SetTabColor(XLColor color)
{
TabColor = color;
return this;
}
public Boolean TabSelected { get; set; }
public Boolean TabActive
{
get { return _tabActive; }
set
{
if (value && !_tabActive)
{
foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal)
ws._tabActive = false;
}
_tabActive = value;
}
}
public IXLWorksheet SetTabSelected()
{
TabSelected = true;
return this;
}
public IXLWorksheet SetTabSelected(Boolean value)
{
TabSelected = value;
return this;
}
public IXLWorksheet SetTabActive()
{
TabActive = true;
return this;
}
public IXLWorksheet SetTabActive(Boolean value)
{
TabActive = value;
return this;
}
IXLPivotTable IXLWorksheet.PivotTable(String name)
{
return PivotTable(name);
}
public IXLPivotTables PivotTables { get; private set; }
public Boolean RightToLeft { get; set; }
public IXLWorksheet SetRightToLeft()
{
RightToLeft = true;
return this;
}
public IXLWorksheet SetRightToLeft(Boolean value)
{
RightToLeft = value;
return this;
}
public new IXLRanges Ranges(String ranges)
{
var retVal = new XLRanges();
foreach (string rangeAddressStr in ranges.Split(',').Select(s => s.Trim()))
{
if (XLHelper.IsValidRangeAddress(rangeAddressStr))
retVal.Add(Range(new XLRangeAddress(Worksheet, rangeAddressStr)));
else if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0))
NamedRange(rangeAddressStr).Ranges.ForEach(retVal.Add);
else
{
Workbook.NamedRanges.First(n =>
String.Compare(n.Name, rangeAddressStr, true) == 0
&& n.Ranges.First().Worksheet == this)
.Ranges.ForEach(retVal.Add);
}
}
return retVal;
}
IXLBaseAutoFilter IXLWorksheet.AutoFilter
{
get { return AutoFilter; }
}
public IXLRows RowsUsed(Boolean includeFormats = false, Func<IXLRow, Boolean> predicate = null)
{
var rows = new XLRows(Worksheet);
var rowsUsed = new HashSet<Int32>();
Internals.RowsCollection.Keys.ForEach(r => rowsUsed.Add(r));
Internals.CellsCollection.RowsUsed.Keys.ForEach(r => rowsUsed.Add(r));
foreach (var rowNum in rowsUsed)
{
var row = Row(rowNum);
if (!row.IsEmpty(includeFormats) && (predicate == null || predicate(row)))
rows.Add(row);
else
row.Dispose();
}
return rows;
}
public IXLRows RowsUsed(Func<IXLRow, Boolean> predicate = null)
{
return RowsUsed(false, predicate);
}
public IXLColumns ColumnsUsed(Boolean includeFormats = false, Func<IXLColumn, Boolean> predicate = null)
{
var columns = new XLColumns(Worksheet);
var columnsUsed = new HashSet<Int32>();
Internals.ColumnsCollection.Keys.ForEach(r => columnsUsed.Add(r));
Internals.CellsCollection.ColumnsUsed.Keys.ForEach(r => columnsUsed.Add(r));
foreach (var columnNum in columnsUsed)
{
var column = Column(columnNum);
if (!column.IsEmpty(includeFormats) && (predicate == null || predicate(column)))
columns.Add(column);
else
column.Dispose();
}
return columns;
}
public IXLColumns ColumnsUsed(Func<IXLColumn, Boolean> predicate = null)
{
return ColumnsUsed(false, predicate);
}
public new void Dispose()
{
if (AutoFilter != null)
AutoFilter.Dispose();
Internals.Dispose();
this.Pictures.ForEach(p => p.Dispose());
base.Dispose();
}
#endregion IXLWorksheet Members
#region Outlines
public void IncrementColumnOutline(Int32 level)
{
if (level <= 0) return;
if (!_columnOutlineCount.ContainsKey(level))
_columnOutlineCount.Add(level, 0);
_columnOutlineCount[level]++;
}
public void DecrementColumnOutline(Int32 level)
{
if (level <= 0) return;
if (!_columnOutlineCount.ContainsKey(level))
_columnOutlineCount.Add(level, 0);
if (_columnOutlineCount[level] > 0)
_columnOutlineCount[level]--;
}
public Int32 GetMaxColumnOutline()
{
var list = _columnOutlineCount.Where(kp => kp.Value > 0).ToList();
return list.Count == 0 ? 0 : list.Max(kp => kp.Key);
}
public void IncrementRowOutline(Int32 level)
{
if (level <= 0) return;
if (!_rowOutlineCount.ContainsKey(level))
_rowOutlineCount.Add(level, 0);
_rowOutlineCount[level]++;
}
public void DecrementRowOutline(Int32 level)
{
if (level <= 0) return;
if (!_rowOutlineCount.ContainsKey(level))
_rowOutlineCount.Add(level, 0);
if (_rowOutlineCount[level] > 0)
_rowOutlineCount[level]--;
}
public Int32 GetMaxRowOutline()
{
return _rowOutlineCount.Count == 0 ? 0 : _rowOutlineCount.Where(kp => kp.Value > 0).Max(kp => kp.Key);
}
#endregion Outlines
public HashSet<Int32> GetStyleIds()
{
return Internals.CellsCollection.GetStyleIds(GetStyleId());
}
public XLRow FirstRowUsed()
{
return FirstRowUsed(false);
}
public XLRow FirstRowUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngRow = asRange.FirstRowUsed(includeFormats))
return rngRow != null ? Row(rngRow.RangeAddress.FirstAddress.RowNumber) : null;
}
public XLRow LastRowUsed()
{
return LastRowUsed(false);
}
public XLRow LastRowUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngRow = asRange.LastRowUsed(includeFormats))
return rngRow != null ? Row(rngRow.RangeAddress.LastAddress.RowNumber) : null;
}
public XLColumn LastColumn()
{
return Column(XLHelper.MaxColumnNumber);
}
public XLColumn FirstColumn()
{
return Column(1);
}
public XLRow FirstRow()
{
return Row(1);
}
public XLRow LastRow()
{
return Row(XLHelper.MaxRowNumber);
}
public XLColumn FirstColumnUsed()
{
return FirstColumnUsed(false);
}
public XLColumn FirstColumnUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngColumn = asRange.FirstColumnUsed(includeFormats))
return rngColumn != null ? Column(rngColumn.RangeAddress.FirstAddress.ColumnNumber) : null;
}
public XLColumn LastColumnUsed()
{
return LastColumnUsed(false);
}
public XLColumn LastColumnUsed(Boolean includeFormats)
{
using (var asRange = AsRange())
using (var rngColumn = asRange.LastColumnUsed(includeFormats))
return rngColumn != null ? Column(rngColumn.RangeAddress.LastAddress.ColumnNumber) : null;
}
public XLRow Row(Int32 row)
{
return Row(row, true);
}
public XLColumn Column(Int32 column)
{
if (column <= 0 || column > XLHelper.MaxColumnNumber)
throw new IndexOutOfRangeException(String.Format("Column number must be between 1 and {0}",
XLHelper.MaxColumnNumber));
Int32 thisStyleId = GetStyleId();
if (!Internals.ColumnsCollection.ContainsKey(column))
{
// This is a new row so we're going to reference all
// cells in this row to preserve their formatting
Internals.RowsCollection.Keys.ForEach(r => Cell(r, column));
Internals.ColumnsCollection.Add(column,
new XLColumn(column, new XLColumnParameters(this, thisStyleId, false)));
}
return new XLColumn(column, new XLColumnParameters(this, thisStyleId, true));
}
public IXLColumn Column(String column)
{
return Column(XLHelper.GetColumnNumberFromLetter(column));
}
public override XLRange AsRange()
{
return Range(1, 1, XLHelper.MaxRowNumber, XLHelper.MaxColumnNumber);
}
public void Clear()
{
Internals.CellsCollection.Clear();
Internals.ColumnsCollection.Clear();
Internals.MergedRanges.Clear();
Internals.RowsCollection.Clear();
}
private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted)
{
var newMerge = new XLRanges();
foreach (IXLRange rngMerged in Internals.MergedRanges)
{
if (range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber
&& rngMerged.RangeAddress.FirstAddress.RowNumber >= range.RangeAddress.FirstAddress.RowNumber
&& rngMerged.RangeAddress.LastAddress.RowNumber <= range.RangeAddress.LastAddress.RowNumber)
{
var newRng = Range(
rngMerged.RangeAddress.FirstAddress.RowNumber,
rngMerged.RangeAddress.FirstAddress.ColumnNumber + columnsShifted,
rngMerged.RangeAddress.LastAddress.RowNumber,
rngMerged.RangeAddress.LastAddress.ColumnNumber + columnsShifted);
newMerge.Add(newRng);
}
else if (
!(range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.FirstAddress.ColumnNumber
&& range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.LastAddress.RowNumber))
newMerge.Add(rngMerged);
}
Internals.MergedRanges = newMerge;
Workbook.Worksheets.ForEach(ws => MoveNamedRangesColumns(range, columnsShifted, ws.NamedRanges));
MoveNamedRangesColumns(range, columnsShifted, Workbook.NamedRanges);
ShiftConditionalFormattingColumns(range, columnsShifted);
ShiftPageBreaksColumns(range, columnsShifted);
}
private void ShiftPageBreaksColumns(XLRange range, int columnsShifted)
{
for (var i = 0; i < PageSetup.ColumnBreaks.Count; i++)
{
int br = PageSetup.ColumnBreaks[i];
if (range.RangeAddress.FirstAddress.ColumnNumber <= br)
{
PageSetup.ColumnBreaks[i] = br + columnsShifted;
}
}
}
private void ShiftConditionalFormattingColumns(XLRange range, int columnsShifted)
{
Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber;
if (firstColumn == 1) return;
Int32 lastColumn = range.RangeAddress.FirstAddress.ColumnNumber + columnsShifted - 1;
Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber;
Int32 lastRow = range.RangeAddress.LastAddress.RowNumber;
var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn);
var fc = insertedRange.FirstColumn();
var model = fc.ColumnLeft();
Int32 modelFirstRow = model.RangeAddress.FirstAddress.RowNumber;
if (ConditionalFormats.Any(cf => cf.Range.Intersects(model)))
{
for (Int32 ro = firstRow; ro <= lastRow; ro++)
{
var cellModel = model.Cell(ro - modelFirstRow + 1);
foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel.AsRange())).ToList())
{
Range(ro, firstColumn, ro, lastColumn).AddConditionalFormat(cf);
}
}
}
insertedRange.Dispose();
model.Dispose();
fc.Dispose();
}
private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted)
{
var newMerge = new XLRanges();
foreach (IXLRange rngMerged in Internals.MergedRanges)
{
if (range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber
&& rngMerged.RangeAddress.FirstAddress.ColumnNumber >= range.RangeAddress.FirstAddress.ColumnNumber
&& rngMerged.RangeAddress.LastAddress.ColumnNumber <= range.RangeAddress.LastAddress.ColumnNumber)
{
var newRng = Range(
rngMerged.RangeAddress.FirstAddress.RowNumber + rowsShifted,
rngMerged.RangeAddress.FirstAddress.ColumnNumber,
rngMerged.RangeAddress.LastAddress.RowNumber + rowsShifted,
rngMerged.RangeAddress.LastAddress.ColumnNumber);
newMerge.Add(newRng);
}
else if (!(range.RangeAddress.FirstAddress.RowNumber <= rngMerged.RangeAddress.FirstAddress.RowNumber
&& range.RangeAddress.FirstAddress.ColumnNumber <= rngMerged.RangeAddress.LastAddress.ColumnNumber))
newMerge.Add(rngMerged);
}
Internals.MergedRanges = newMerge;
Workbook.Worksheets.ForEach(ws => MoveNamedRangesRows(range, rowsShifted, ws.NamedRanges));
MoveNamedRangesRows(range, rowsShifted, Workbook.NamedRanges);
ShiftConditionalFormattingRows(range, rowsShifted);
ShiftPageBreaksRows(range, rowsShifted);
}
private void ShiftPageBreaksRows(XLRange range, int rowsShifted)
{
for (var i = 0; i < PageSetup.RowBreaks.Count; i++)
{
int br = PageSetup.RowBreaks[i];
if (range.RangeAddress.FirstAddress.RowNumber <= br)
{
PageSetup.RowBreaks[i] = br + rowsShifted;
}
}
}
private void ShiftConditionalFormattingRows(XLRange range, int rowsShifted)
{
Int32 firstRow = range.RangeAddress.FirstAddress.RowNumber;
if (firstRow == 1) return;
SuspendEvents();
var rangeUsed = range.Worksheet.RangeUsed(true);
IXLRangeAddress usedAddress;
if (rangeUsed == null)
usedAddress = range.RangeAddress;
else
usedAddress = rangeUsed.RangeAddress;
ResumeEvents();
if (firstRow < usedAddress.FirstAddress.RowNumber) firstRow = usedAddress.FirstAddress.RowNumber;
Int32 lastRow = range.RangeAddress.FirstAddress.RowNumber + rowsShifted - 1;
if (lastRow > usedAddress.LastAddress.RowNumber) lastRow = usedAddress.LastAddress.RowNumber;
Int32 firstColumn = range.RangeAddress.FirstAddress.ColumnNumber;
if (firstColumn < usedAddress.FirstAddress.ColumnNumber) firstColumn = usedAddress.FirstAddress.ColumnNumber;
Int32 lastColumn = range.RangeAddress.LastAddress.ColumnNumber;
if (lastColumn > usedAddress.LastAddress.ColumnNumber) lastColumn = usedAddress.LastAddress.ColumnNumber;
var insertedRange = Range(firstRow, firstColumn, lastRow, lastColumn);
var fr = insertedRange.FirstRow();
var model = fr.RowAbove();
Int32 modelFirstColumn = model.RangeAddress.FirstAddress.ColumnNumber;
if (ConditionalFormats.Any(cf => cf.Range.Intersects(model)))
{
for (Int32 co = firstColumn; co <= lastColumn; co++)
{
var cellModel = model.Cell(co - modelFirstColumn + 1);
foreach (var cf in ConditionalFormats.Where(cf => cf.Range.Intersects(cellModel.AsRange())).ToList())
{
Range(firstRow, co, lastRow, co).AddConditionalFormat(cf);
}
}
}
insertedRange.Dispose();
model.Dispose();
fr.Dispose();
}
internal void BreakConditionalFormatsIntoCells(List<IXLAddress> addresses)
{
var newConditionalFormats = new XLConditionalFormats();
SuspendEvents();
foreach (var conditionalFormat in ConditionalFormats)
{
foreach (XLCell cell in conditionalFormat.Range.Cells(c => !addresses.Contains(c.Address)))
{
var row = cell.Address.RowNumber;
var column = cell.Address.ColumnLetter;
var newConditionalFormat = new XLConditionalFormat(cell.AsRange(), true);
newConditionalFormat.CopyFrom(conditionalFormat);
newConditionalFormat.Values.Values.Where(f => f.IsFormula)
.ForEach(f => f._value = XLHelper.ReplaceRelative(f.Value, row, column));
newConditionalFormats.Add(newConditionalFormat);
}
conditionalFormat.Range.Dispose();
}
ResumeEvents();
ConditionalFormats = newConditionalFormats;
}
private void MoveNamedRangesRows(XLRange range, int rowsShifted, IXLNamedRanges namedRanges)
{
foreach (XLNamedRange nr in namedRanges)
{
var newRangeList =
nr.RangeList.Select(r => XLCell.ShiftFormulaRows(r, this, range, rowsShifted)).Where(
newReference => newReference.Length > 0).ToList();
nr.RangeList = newRangeList;
}
}
private void MoveNamedRangesColumns(XLRange range, int columnsShifted, IXLNamedRanges namedRanges)
{
foreach (XLNamedRange nr in namedRanges)
{
var newRangeList =
nr.RangeList.Select(r => XLCell.ShiftFormulaColumns(r, this, range, columnsShifted)).Where(
newReference => newReference.Length > 0).ToList();
nr.RangeList = newRangeList;
}
}
public void NotifyRangeShiftedRows(XLRange range, Int32 rowsShifted)
{
if (RangeShiftedRows != null)
{
foreach (var item in RangeShiftedRows)
{
item.Action(range, rowsShifted);
}
}
}
public void NotifyRangeShiftedColumns(XLRange range, Int32 columnsShifted)
{
if (RangeShiftedColumns != null)
{
foreach (var item in RangeShiftedColumns)
{
item.Action(range, columnsShifted);
}
}
}
public XLRow Row(Int32 row, Boolean pingCells)
{
if (row <= 0 || row > XLHelper.MaxRowNumber)
throw new IndexOutOfRangeException(String.Format("Row number must be between 1 and {0}",
XLHelper.MaxRowNumber));
Int32 styleId;
XLRow rowToUse;
if (Internals.RowsCollection.TryGetValue(row, out rowToUse))
styleId = rowToUse.GetStyleId();
else
{
if (pingCells)
{
// This is a new row so we're going to reference all
// cells in columns of this row to preserve their formatting
var usedColumns = from c in Internals.ColumnsCollection
join dc in Internals.CellsCollection.ColumnsUsed.Keys
on c.Key equals dc
where !Internals.CellsCollection.Contains(row, dc)
select dc;
usedColumns.ForEach(c => Cell(row, c));
}
styleId = GetStyleId();
Internals.RowsCollection.Add(row, new XLRow(row, new XLRowParameters(this, styleId, false)));
}
return new XLRow(row, new XLRowParameters(this, styleId));
}
private IXLRange GetRangeForSort()
{
var range = RangeUsed();
SortColumns.ForEach(e => range.SortColumns.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase));
SortRows.ForEach(e => range.SortRows.Add(e.ElementNumber, e.SortOrder, e.IgnoreBlanks, e.MatchCase));
return range;
}
public XLPivotTable PivotTable(String name)
{
return (XLPivotTable)PivotTables.PivotTable(name);
}
public new IXLCells Cells()
{
return Cells(true, true);
}
public new IXLCells Cells(Boolean usedCellsOnly)
{
if (usedCellsOnly)
return Cells(true, true);
else
return Range(FirstCellUsed(), LastCellUsed()).Cells(false, true);
}
public new XLCell Cell(String cellAddressInRange)
{
if (XLHelper.IsValidA1Address(cellAddressInRange))
return Cell(XLAddress.Create(this, cellAddressInRange));
if (NamedRanges.Any(n => String.Compare(n.Name, cellAddressInRange, true) == 0))
return (XLCell)NamedRange(cellAddressInRange).Ranges.First().FirstCell();
var namedRanges = Workbook.NamedRanges.FirstOrDefault(n =>
String.Compare(n.Name, cellAddressInRange, true) == 0
&& n.Ranges.Count == 1);
if (namedRanges == null || !namedRanges.Ranges.Any()) return null;
return (XLCell)namedRanges.Ranges.First().FirstCell();
}
internal XLCell CellFast(String cellAddressInRange)
{
return Cell(XLAddress.Create(this, cellAddressInRange));
}
public override XLRange Range(String rangeAddressStr)
{
if (XLHelper.IsValidRangeAddress(rangeAddressStr))
return Range(new XLRangeAddress(Worksheet, rangeAddressStr));
if (rangeAddressStr.Contains("["))
return Table(rangeAddressStr.Substring(0, rangeAddressStr.IndexOf("["))) as XLRange;
if (NamedRanges.Any(n => String.Compare(n.Name, rangeAddressStr, true) == 0))
return (XLRange)NamedRange(rangeAddressStr).Ranges.First();
var namedRanges = Workbook.NamedRanges.FirstOrDefault(n =>
String.Compare(n.Name, rangeAddressStr, true) == 0
&& n.Ranges.Count == 1
);
if (namedRanges == null || !namedRanges.Ranges.Any()) return null;
return (XLRange)namedRanges.Ranges.First();
}
public IXLRanges MergedRanges { get { return Internals.MergedRanges; } }
public IXLConditionalFormats ConditionalFormats { get; private set; }
private Boolean _eventTracking;
public void SuspendEvents()
{
_eventTracking = EventTrackingEnabled;
EventTrackingEnabled = false;
}
public void ResumeEvents()
{
EventTrackingEnabled = _eventTracking;
}
public IXLRanges SelectedRanges { get; internal set; }
public IXLCell ActiveCell { get; set; }
private XLCalcEngine _calcEngine;
private XLCalcEngine CalcEngine
{
get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); }
}
public Object Evaluate(String expression)
{
return CalcEngine.Evaluate(expression);
}
public String Author { get; set; }
public override string ToString()
{
return this.Name;
}
public IXLPictures Pictures { get; private set; }
public IXLPicture Picture(string pictureName)
{
return Pictures.Picture(pictureName);
}
public IXLPicture AddPicture(Stream stream)
{
return Pictures.Add(stream);
}
public IXLPicture AddPicture(Stream stream, string name)
{
return Pictures.Add(stream, name);
}
internal IXLPicture AddPicture(Stream stream, string name, int Id)
{
return (Pictures as XLPictures).Add(stream, name, Id);
}
public IXLPicture AddPicture(Stream stream, XLPictureFormat format)
{
return Pictures.Add(stream, format);
}
public IXLPicture AddPicture(Stream stream, XLPictureFormat format, string name)
{
return Pictures.Add(stream, format, name);
}
public IXLPicture AddPicture(Bitmap bitmap)
{
return Pictures.Add(bitmap);
}
public IXLPicture AddPicture(Bitmap bitmap, string name)
{
return Pictures.Add(bitmap, name);
}
public IXLPicture AddPicture(string imageFile)
{
return Pictures.Add(imageFile);
}
public IXLPicture AddPicture(string imageFile, string name)
{
return Pictures.Add(imageFile, name);
}
public override Boolean IsEntireRow()
{
return true;
}
public override Boolean IsEntireColumn()
{
return true;
}
internal void SetValue<T>(T value, int ro, int co) where T : class
{
if (value == null)
this.Cell(ro, co).SetValue(String.Empty);
else if (value is IConvertible)
this.Cell(ro, co).SetValue((T)Convert.ChangeType(value, typeof(T)));
else
this.Cell(ro, co).SetValue(value);
}
}
}
| |
using System;
public static class GlobalMembersWbmp_im2im
{
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
static int Main()
{
gdImageStruct src;
gdImageStruct dst;
int b;
object p;
int size = 0;
int status = 0;
struct struct CuTestImageResult result = {0, 0};
src = gd.gdImageCreate(100, 100);
if (src == null)
{
Console.Write("could not create src\n");
return 1;
}
gd.gdImageColorAllocate(src, 0xFF, 0xFF, 0xFF); // allocate white for background color
b = gd.gdImageColorAllocate(src, 0, 0, 0);
gd.gdImageRectangle(src, 20, 20, 79, 79, b);
gd.gdImageEllipse(src, 70, 25, 30, 20, b);
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define OUTPUT_WBMP(name) do { FILE *fp; fp = fopen("wbmp_im2im_" #name ".wbmp", "wb"); if (fp) { gd.gdImageWBMP(name, 1, fp); fclose(fp); } } while (0)
#define OUTPUT_WBMP
do
{
FILE fp;
fp = fopen("wbmp_im2im_" "src" ".wbmp", "wb");
if (fp != null)
{
gd.gdImageWBMP(src, 1, fp);
fclose(fp);
}
} while (0);
p = gd.gdImageWBMPPtr(src, size, 1);
if (p == null)
{
status = 1;
Console.Write("p is null\n");
goto door0;
}
if (size <= 0)
{
status = 1;
Console.Write("size is non-positive\n");
goto door1;
}
dst = gd.gdImageCreateFromWBMPPtr(size, p);
if (dst == null)
{
status = 1;
Console.Write("could not create dst\n");
goto door1;
}
do
{
FILE fp;
fp = fopen("wbmp_im2im_" "dst" ".wbmp", "wb");
if (fp != null)
{
gd.gdImageWBMP(dst, 1, fp);
fclose(fp);
}
} while (0);
GlobalMembersGdtest.gd.gdTestImageDiff(src, dst, null, result);
if (result.pixels_changed > 0)
{
status = 1;
Console.Write("pixels changed: {0:D}\n", result.pixels_changed);
}
gd.gdImageDestroy(dst);
door1:
gd.gdFree(p);
door0:
gd.gdImageDestroy(src);
return status;
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.CloudTrail;
using Amazon.CloudTrail.Model;
using Amazon.CloudTrail.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class CloudTrailMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("cloudtrail-2013-11-01.normal.json", "cloudtrail.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void CreateTrailMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateTrailRequest>();
var marshaller = new CreateTrailRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateTrailRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateTrail").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateTrailResponseUnmarshaller.Instance.Unmarshall(context)
as CreateTrailResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void DeleteTrailMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteTrailRequest>();
var marshaller = new DeleteTrailRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteTrailRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteTrail").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteTrailResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteTrailResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void DescribeTrailsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeTrailsRequest>();
var marshaller = new DescribeTrailsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeTrailsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeTrails").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeTrailsResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeTrailsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void GetTrailStatusMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetTrailStatusRequest>();
var marshaller = new GetTrailStatusRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetTrailStatusRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetTrailStatus").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetTrailStatusResponseUnmarshaller.Instance.Unmarshall(context)
as GetTrailStatusResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void LookupEventsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<LookupEventsRequest>();
var marshaller = new LookupEventsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<LookupEventsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("LookupEvents").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = LookupEventsResponseUnmarshaller.Instance.Unmarshall(context)
as LookupEventsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void StartLoggingMarshallTest()
{
var request = InstantiateClassGenerator.Execute<StartLoggingRequest>();
var marshaller = new StartLoggingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<StartLoggingRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StartLogging").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = StartLoggingResponseUnmarshaller.Instance.Unmarshall(context)
as StartLoggingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void StopLoggingMarshallTest()
{
var request = InstantiateClassGenerator.Execute<StopLoggingRequest>();
var marshaller = new StopLoggingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<StopLoggingRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StopLogging").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = StopLoggingResponseUnmarshaller.Instance.Unmarshall(context)
as StopLoggingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CloudTrail")]
public void UpdateTrailMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UpdateTrailRequest>();
var marshaller = new UpdateTrailRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UpdateTrailRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateTrail").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = UpdateTrailResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateTrailResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Collections;
using System.Xml.Serialization;
// borrowed from:
// http://www.xmlforasp.net/codebank/util/srcview.aspx?path=../../CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.src&file=SchemaBuilder.cs&font=3
namespace Lewis.Xml.Converters
{
public enum NestingType
{
RussianDoll,
SeparateComplexTypes
}
public class Xml2Xsd
{
private Hashtable XmlNS = new Hashtable();
private XmlNamespaceManager nsmgr;
public void ValidateSchema(object sender, ValidationEventArgs args) { }
public Xml2Xsd(System.Xml.XmlNameTable tableName)
{
// initialize code here
nsmgr = new XmlNamespaceManager(tableName);
nsmgr.AddNamespace("xsd", schemaNS);
nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
nsmgr.AddNamespace("msdata", "urn:schemas-microsoft-com:xml-msdata");
foreach (String prefix in nsmgr)
{
XmlNS.Add(prefix, nsmgr.LookupNamespace(prefix));
}
}
static string schemaNS = "http://www.w3.org/2001/XMLSchema";
ArrayList complexTypes = new ArrayList();
NestingType generationType;
public string BuildXSD(string xml, NestingType type)
{
generationType = type;
//Create schema element
XmlSchema schema = new XmlSchema();
schema.ElementFormDefault = XmlSchemaForm.Qualified;
schema.AttributeFormDefault = XmlSchemaForm.Unqualified;
schema.Version = "1.0";
//Add additional namespaces using the Add() method shown below
//if desired
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsd", schemaNS);
ns.Add("xs", "http://www.w3.org/2001/XMLSchema");
ns.Add("msdata", "urn:schemas-microsoft-com:xml-msdata");
schema.Namespaces = ns;
//Begin parsing source XML document
XmlDocument doc = new XmlDocument();
try
{ //Assume string XML
doc.LoadXml(xml);
}
catch
{
try
{ //String XML load failed. Try loading as a file path
doc.Load(xml);
}
catch
{
return "XML document is not well-formed.";
}
}
XmlElement root = doc.DocumentElement;
//Create root element definition for schema
//Call CreateComplexType to either add a complexType tag
//or simply add the necesary schema attributes
XmlSchemaElement elem = CreateComplexType(root);
//Add root element definition into the XmlSchema object
schema.Items.Add(elem);
//Reverse elements in ArrayList so root complexType appears first
//where applicable
complexTypes.Reverse();
//In cases where the user wants to separate out the complexType tags
//loop through the complexType ArrayList and add the types to the schema
foreach(object obj in complexTypes)
{
XmlSchemaComplexType ct = (XmlSchemaComplexType)obj;
schema.Items.Add(ct);
}
//Compile the schema and then write its contents to a StringWriter
try
{
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add(schema);
xss.ValidationEventHandler += new ValidationEventHandler(ValidateSchema);
xss.Compile();
StringWriter sw = new StringWriter();
string retval = sw.ToString();
schema.Write(sw);
sw.Flush();
sw.Close();
sw.Dispose();
return retval;
}
catch (Exception exp)
{
return exp.Message;
}
}
public XmlSchemaElement CreateComplexType(XmlElement element)
{
ArrayList namesArray = new ArrayList();
//Create complexType
XmlSchemaComplexType ct = new XmlSchemaComplexType();
if (element.HasChildNodes)
{
//loop through children and place in schema sequence tag
XmlSchemaSequence seq = new XmlSchemaSequence();
foreach (XmlNode node in element.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element)
{
if (namesArray.BinarySearch(node.Name) < 0)
{
namesArray.Add(node.Name);
namesArray.Sort(); //Needed for BinarySearch()
XmlElement tempNode = (XmlElement)node;
XmlSchemaElement sElem = null;
//If node has children or attributes then create a new
//complexType container
if (tempNode.HasChildNodes || tempNode.HasAttributes)
{
sElem = CreateComplexType(tempNode);
}
else
{ //No comlexType needed...add SchemaTypeName
sElem = new XmlSchemaElement();
sElem.Name = tempNode.Name;
string el_namesp = schemaNS;
string el_name = sElem.Name;
if (sElem.Name.IndexOf(":") > 0)
{
el_name = sElem.Name.Split(':')[1];
string prefix = sElem.Name.Split(':')[0];
el_namesp = XmlNS[prefix].ToString();
}
if (tempNode.InnerText == null || tempNode.InnerText == String.Empty)
{
sElem.SchemaTypeName = new XmlQualifiedName("string", el_namesp);
}
else
{
//Try to detect the appropriate data type for the element
sElem.SchemaTypeName = new XmlQualifiedName(CheckDataType(tempNode.InnerText), el_namesp);
}
}
//Detect if node repeats in XML so we can handle maxOccurs
try
{
//We don't support namespaces now so prevent an error if one occurs
if (element.SelectNodes(node.Name, nsmgr).Count > 1)
{
sElem.MaxOccursString = "unbounded";
}
}
catch (Exception ex)
{
throw ex;
}
//Add element to sequence tag
seq.Items.Add(sElem);
}
}
}
//Add sequence tag to complexType tag
if (seq.Items.Count > 0) ct.Particle = seq;
}
if (element.HasAttributes)
{
foreach (XmlAttribute att in element.Attributes)
{
if (att.Name.IndexOf("xmlns") == -1)
{
string namesp = schemaNS;
string name = att.Name;
string prefix = string.Empty;
if (att.Name.IndexOf(":") > 0)
{
name = att.Name.Split(':')[1];
prefix = att.Name.Split(':')[0];
namesp = XmlNS[prefix].ToString();
}
XmlSchemaAttribute sAtt = new XmlSchemaAttribute();
sAtt.Name = name;
sAtt.SchemaTypeName = new XmlQualifiedName(CheckDataType(att.Value), namesp);
ct.Attributes.Add(sAtt);
}
}
}
//Now that complexType is created, create element and add
//complexType into the element using its SchemaType property
string elnamesp = schemaNS;
string elname = element.Name;
if (element.Name.IndexOf(":") > 0)
{
elname = element.Name.Split(':')[1];
string prefix = element.Name.Split(':')[0];
elnamesp = XmlNS[prefix].ToString();
}
XmlSchemaElement elem = new XmlSchemaElement();
elem.Name = elname;
if (ct.Attributes.Count > 0 || ct.Particle != null)
{
//Handle nesting style of schema
if (generationType == NestingType.SeparateComplexTypes)
{
string typeName = element.Name + "Type";
ct.Name = typeName;
complexTypes.Add(ct);
elem.SchemaTypeName = new XmlQualifiedName(typeName, null);
}
else
{
elem.SchemaType = ct;
}
}
else
{
if (element.InnerText == null || element.InnerText == String.Empty)
{
elem.SchemaTypeName = new XmlQualifiedName("string", elnamesp);
}
else
{
elem.SchemaTypeName = new XmlQualifiedName(CheckDataType(element.InnerText), elnamesp);
}
}
return elem;
}
private string CheckDataType(string data)
{
//Int test
try
{
Int32.Parse(data);
return "int";
}
catch {}
//Decimal test
try
{
Decimal.Parse(data);
return "decimal";
}
catch {}
//DateTime test
try
{
DateTime.Parse(data);
return "dateTime";
}
catch {}
//Boolean test
if (data.ToLower() == "true" || data.ToLower() == "false")
{
return "boolean";
}
return "string";
}
}
}
| |
namespace Boxed.Templates.FunctionalTest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Boxed.DotnetNewTest;
using Boxed.Templates.FunctionalTest.Constants;
using Boxed.Templates.FunctionalTest.Models;
using Xunit;
public class GraphQLTemplateTest
{
public GraphQLTemplateTest() =>
DotnetNew.Install<GraphQLTemplateTest>("GraphQLTemplate.sln").Wait();
[Theory]
[Trait("IsUsingDotnetRun", "false")]
[InlineData("Default")]
[InlineData("NoForwardedHeaders", "forwarded-headers=false")]
[InlineData("NoHostFiltering", "host-filtering=false")]
[InlineData("NoForwardedHeadersOrHostFiltering", "forwarded-headers=false", "host-filtering=false")]
public async Task RestoreAndBuild_Default_Successful(string name, params string[] arguments)
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var dictionary = arguments
.Select(x => x.Split('=', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x => x.First(), x => x.Last());
var project = await tempDirectory.DotnetNew("graphql", name, dictionary);
await project.DotnetRestore();
await project.DotnetBuild();
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_Default_Successful()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew("graphql", "Default");
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\Default",
async (httpClient, httpsClient) =>
{
var httpResponse = await httpClient.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
var httpsResponse = await httpsClient.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
var statusResponse = await httpsClient.GetAsync("status");
Assert.Equal(HttpStatusCode.OK, statusResponse.StatusCode);
var statusSelfResponse = await httpsClient.GetAsync("status/self");
Assert.Equal(HttpStatusCode.OK, statusSelfResponse.StatusCode);
var robotsTxtResponse = await httpsClient.GetAsync("robots.txt");
Assert.Equal(HttpStatusCode.OK, robotsTxtResponse.StatusCode);
var securityTxtResponse = await httpsClient.GetAsync(".well-known/security.txt");
Assert.Equal(HttpStatusCode.OK, securityTxtResponse.StatusCode);
var humansTxtResponse = await httpsClient.GetAsync("humans.txt");
Assert.Equal(HttpStatusCode.OK, humansTxtResponse.StatusCode);
});
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_HealthCheckFalse_Successful()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew(
"graphql",
"HealthCheckFalse",
new Dictionary<string, string>()
{
{ "health-check", "false" },
});
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\HealthCheckFalse",
async httpClient =>
{
var statusResponse = await httpClient.GetAsync("status");
Assert.Equal(HttpStatusCode.NotFound, statusResponse.StatusCode);
var statusSelfResponse = await httpClient.GetAsync("status/self");
Assert.Equal(HttpStatusCode.NotFound, statusSelfResponse.StatusCode);
});
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_QueryGraphQlIntrospection_ReturnsResults()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew("graphql", "Default");
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\Default",
async (httpClient, httpsClient) =>
{
var introspectionQuery = await httpClient.PostGraphQL(GraphQlQuery.Introspection);
Assert.Equal(HttpStatusCode.OK, introspectionQuery.StatusCode);
var introspectionContent = await introspectionQuery.Content.ReadAsAsync<GraphQLResponse>();
Assert.Null(introspectionContent.Errors);
});
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_HttpsEverywhereFalse_Successful()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew(
"graphql",
"HttpsEverywhereFalse",
new Dictionary<string, string>()
{
{ "https-everywhere", "false" },
});
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\HttpsEverywhereFalse",
async (httpClient) =>
{
var httpResponse = await httpClient.GetAsync("/");
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
});
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_AuthorizationTrue_Returns400BadRequest()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew(
"graphql",
"AuthorizationTrue",
new Dictionary<string, string>()
{
{ "authorization", "true" },
});
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\AuthorizationTrue",
async (httpClient) =>
{
var httpResponse = await httpClient.PostGraphQL(
"query getHuman { human(id: \"94fbd693-2027-4804-bf40-ed427fe76fda\") { dateOfBirth } }");
var response = await httpResponse.Content.ReadAsAsync<GraphQLResponse>();
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
var error = Assert.Single(response.Errors);
Assert.Equal(
"GraphQL.Validation.ValidationError: You are not authorized to run this query.\nRequired claim 'role' with any value of 'admin' is not present.",
error.Message);
});
}
}
[Fact]
[Trait("IsUsingDotnetRun", "true")]
public async Task Run_AuthorizationFalse_DateOfBirthReturnedSuccessfully()
{
using (var tempDirectory = TempDirectory.NewTempDirectory())
{
var project = await tempDirectory.DotnetNew(
"graphql",
"AuthorizationFalse",
new Dictionary<string, string>()
{
{ "authorization", "false" },
});
await project.DotnetRestore();
await project.DotnetBuild();
await project.DotnetRun(
@"Source\AuthorizationFalse",
async (httpClient) =>
{
var httpResponse = await httpClient.PostGraphQL(
"query getHuman { human(id: \"94fbd693-2027-4804-bf40-ed427fe76fda\") { dateOfBirth } }");
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
});
}
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Scaffolding;
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal
{
public class MySqlDatabaseModelFactory : IDatabaseModelFactory
{
private MySqlConnection _connection;
private DatabaseModel _databaseModel;
private Dictionary<string, DatabaseTable> _tables;
public MySqlDatabaseModelFactory(ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateCommandsLogger();
}
protected virtual ILogger Logger { get; }
private void ResetState()
{
_connection = null;
_databaseModel = new DatabaseModel();
_tables = new Dictionary<string, DatabaseTable>();
}
public DatabaseModel Create(string connectionString, IEnumerable<string> tables, IEnumerable<string> schemas)
{
using (var connection = new MySqlConnection(connectionString))
{
return Create(connection, tables, schemas);
}
}
public DatabaseModel Create(DbConnection connection, IEnumerable<string> tables, IEnumerable<string> schemas)
{
ResetState();
_connection = (MySqlConnection)connection;
var connectionStartedOpen = _connection.State == ConnectionState.Open;
if (!connectionStartedOpen)
{
_connection.Open();
}
try
{
_databaseModel.DatabaseName = _connection.Database;
_databaseModel.DefaultSchema = null;
GetTables(tables.ToList());
GetColumns();
GetPrimaryKeys();
GetIndexes();
GetConstraints();
return _databaseModel;
}
finally
{
if (!connectionStartedOpen)
{
_connection.Close();
}
}
}
private const string GetTablesQuery = @"SHOW FULL TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
private void GetTables(List<string> allowedTables)
{
using (var command = new MySqlCommand(GetTablesQuery, _connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var table = new DatabaseTable
{
Schema = null,
Name = reader.GetString(0).Replace("`", "")
};
if (allowedTables.Count == 0
|| allowedTables.Contains(table.Name))
{
_databaseModel.Tables.Add(table);
_tables[table.Name] = table;
}
}
}
}
private const string GetColumnsQuery = @"SHOW COLUMNS FROM `{0}`";
private void GetColumns()
{
foreach (var x in _tables)
{
using (var command = new MySqlCommand(string.Format(GetColumnsQuery, x.Key), _connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var extra = reader.GetString(5);
ValueGenerated valueGenerated;
if (extra.IndexOf("auto_increment", StringComparison.Ordinal) >= 0)
{
valueGenerated = ValueGenerated.OnAdd;
}
else if (extra.IndexOf("on update", StringComparison.Ordinal) >= 0)
{
if (reader[4] != DBNull.Value && extra.IndexOf(reader[4].ToString(), StringComparison.Ordinal) > 0)
{
valueGenerated = ValueGenerated.OnAddOrUpdate;
}
else
{
valueGenerated = ValueGenerated.OnUpdate;
}
}
else
{
valueGenerated = ValueGenerated.Never;
}
var column = new DatabaseColumn
{
Table = x.Value,
Name = reader.GetString(0),
StoreType = Regex.Replace(reader.GetString(1), @"(?<=int)\(\d+\)(?=\sunsigned)",
string.Empty),
IsNullable = reader.GetString(2) == "YES",
DefaultValueSql = reader[4] == DBNull.Value
? null
: '\'' + ParseToMySqlString(reader[4].ToString()) + '\'',
ValueGenerated = valueGenerated
};
x.Value.Columns.Add(column);
}
}
}
}
private string ParseToMySqlString(string str)
{
// Pending the MySqlConnector implement MySqlCommandBuilder class
return str
.Replace("\\", "\\\\")
.Replace("'", "\\'")
.Replace("\"", "\\\"");
}
private const string GetPrimaryQuery = @"SELECT `INDEX_NAME`,
`NON_UNIQUE`,
GROUP_CONCAT(`COLUMN_NAME` ORDER BY `SEQ_IN_INDEX` SEPARATOR ',') AS COLUMNS
FROM `INFORMATION_SCHEMA`.`STATISTICS`
WHERE `TABLE_SCHEMA` = '{0}'
AND `TABLE_NAME` = '{1}'
AND `INDEX_NAME` = 'PRIMARY'
GROUP BY `INDEX_NAME`, `NON_UNIQUE`;";
/// <remarks>
/// Primary keys are handled as in <see cref="GetConstraints"/>, not here
/// </remarks>
private void GetPrimaryKeys()
{
foreach (var x in _tables)
{
using (var command =
new MySqlCommand(string.Format(GetPrimaryQuery, _connection.Database, x.Key),
_connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
try
{
var index = new DatabasePrimaryKey
{
Table = x.Value,
Name = reader.GetString(0)
};
foreach (var column in reader.GetString(2).Split(','))
{
index.Columns.Add(x.Value.Columns.Single(y => y.Name == column));
}
x.Value.PrimaryKey = index;
}
catch (Exception ex)
{
Logger.LogError(ex, "Error assigning primary key for {table}.", x.Key);
}
}
}
}
}
private const string GetIndexesQuery = @"SELECT `INDEX_NAME`,
`NON_UNIQUE`,
GROUP_CONCAT(`COLUMN_NAME` ORDER BY `SEQ_IN_INDEX` SEPARATOR ',') AS COLUMNS
FROM `INFORMATION_SCHEMA`.`STATISTICS`
WHERE `TABLE_SCHEMA` = '{0}'
AND `TABLE_NAME` = '{1}'
AND `INDEX_NAME` <> 'PRIMARY'
GROUP BY `INDEX_NAME`, `NON_UNIQUE`;";
/// <remarks>
/// Primary keys are handled as in <see cref="GetConstraints"/>, not here
/// </remarks>
private void GetIndexes()
{
foreach (var x in _tables)
{
using (var command =
new MySqlCommand(string.Format(GetIndexesQuery, _connection.Database, x.Key),
_connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
try
{
var index = new DatabaseIndex
{
Table = x.Value,
Name = reader.GetString(0),
IsUnique = reader.GetFieldType(1) == typeof(string)
? reader.GetString(1) == "1"
: !reader.GetBoolean(1)
};
foreach (var column in reader.GetString(2).Split(','))
{
index.Columns.Add(x.Value.Columns.Single(y => y.Name == column));
}
x.Value.Indexes.Add(index);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error assigning index for {table}.", x.Key);
}
}
}
}
}
private const string GetConstraintsQuery = @"SELECT
`CONSTRAINT_NAME`,
`TABLE_NAME`,
`REFERENCED_TABLE_NAME`,
GROUP_CONCAT(CONCAT_WS('|', `COLUMN_NAME`, `REFERENCED_COLUMN_NAME`) ORDER BY `ORDINAL_POSITION` SEPARATOR ',') AS PAIRED_COLUMNS,
(SELECT `DELETE_RULE` FROM `INFORMATION_SCHEMA`.`REFERENTIAL_CONSTRAINTS` WHERE `REFERENTIAL_CONSTRAINTS`.`CONSTRAINT_NAME` = `KEY_COLUMN_USAGE`.`CONSTRAINT_NAME` AND `REFERENTIAL_CONSTRAINTS`.`CONSTRAINT_SCHEMA` = `KEY_COLUMN_USAGE`.`CONSTRAINT_SCHEMA`) AS `DELETE_RULE`
FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`
WHERE `TABLE_SCHEMA` = '{0}'
AND `TABLE_NAME` = '{1}'
AND `CONSTRAINT_NAME` <> 'PRIMARY'
AND `REFERENCED_TABLE_NAME` IS NOT NULL
GROUP BY `CONSTRAINT_SCHEMA`,
`CONSTRAINT_NAME`,
`TABLE_NAME`,
`REFERENCED_TABLE_NAME`;";
private void GetConstraints()
{
foreach (var x in _tables)
{
using (var command =
new MySqlCommand(string.Format(GetConstraintsQuery, _connection.Database, x.Key),
_connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var referencedTableName = reader.GetString(2);
if (_tables.TryGetValue(referencedTableName, out var referencedTable))
{
var fkInfo = new DatabaseForeignKey
{
Name = reader.GetString(0),
OnDelete = ConvertToReferentialAction(reader.GetString(4)),
Table = x.Value,
PrincipalTable = referencedTable
};
foreach (var pair in reader.GetString(3).Split(','))
{
fkInfo.Columns.Add(x.Value.Columns.Single(y =>
string.Equals(y.Name, pair.Split('|')[0], StringComparison.OrdinalIgnoreCase)));
fkInfo.PrincipalColumns.Add(fkInfo.PrincipalTable.Columns.Single(y =>
string.Equals(y.Name, pair.Split('|')[1], StringComparison.OrdinalIgnoreCase)));
}
x.Value.ForeignKeys.Add(fkInfo);
}
else
{
Logger.LogWarning($"Referenced table `{referencedTableName}` is not in dictionary.");
}
}
}
}
}
private static ReferentialAction? ConvertToReferentialAction(string onDeleteAction)
{
switch (onDeleteAction.ToUpperInvariant())
{
case "RESTRICT":
return ReferentialAction.Restrict;
case "CASCADE":
return ReferentialAction.Cascade;
case "SET NULL":
return ReferentialAction.SetNull;
case "NO ACTION":
return ReferentialAction.NoAction;
default:
return null;
}
}
}
}
| |
/*
* DictionaryAdapter.cs - Adapt a generic dictionary into a non-generic one.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Generics
{
using System;
public sealed class DictionaryAdapter<KeyT, ValueT>
: System.Collections.IDictionary, System.Collections.ICollection,
System.Collections.IEnumerable
{
// Internal state.
private IDictionary<KeyT, ValueT> dict;
// Constructor.
public DictionaryAdapter(IDictionary<KeyT, ValueT> dict)
{
if(dict == null)
{
throw new ArgumentNullException("dict");
}
this.dict = dict;
}
// Implement the non-generic IDictionary interface.
public void Add(Object key, Object value)
{
if(key == null)
{
// Cannot use null keys with non-generic dictionaries.
throw new ArgumentNullException("key");
}
else if(!(key is KeyT))
{
// Wrong type of key to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_KeyType"));
}
if(typeof(ValueT).IsValueType)
{
if(value == null || !(value is ValueT))
{
// Wrong type of value to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_ValueType"));
}
}
else
{
if(value != null && !(value is ValueT))
{
// Wrong type of value to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_ValueType"));
}
}
dict.Add((KeyT)key, (ValueT)value);
}
public void Clear()
{
dict.Clear();
}
public bool Contains(Object key)
{
if(key == null)
{
throw new ArgumentNullException("key");
}
else if(key is KeyT)
{
return dict.Contains((KeyT)key);
}
else
{
return false;
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new DictionaryEnumeratorAdapter(dict.GetIterator());
}
public void Remove(Object key)
{
if(key == null)
{
throw new ArgumentNullException("key");
}
else if(key is KeyT)
{
dict.Remove((KeyT)key);
}
}
public bool IsFixedSize
{
get
{
return dict.IsFixedSize;
}
}
public bool IsReadOnly
{
get
{
return dict.IsReadOnly;
}
}
public Object this[Object key]
{
get
{
return dict[(KeyT)key];
}
set
{
if(key == null)
{
// Cannot use null keys with non-generic dictionaries.
throw new ArgumentNullException("key");
}
else if(!(key is KeyT))
{
// Wrong type of key to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_KeyType"));
}
if(typeof(ValueT).IsValueType)
{
if(value == null || !(value is ValueT))
{
// Wrong type of value to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_ValueType"));
}
}
else
{
if(value != null && !(value is ValueT))
{
// Wrong type of value to add to this dictionary.
throw new InvalidOperationException
(S._("Invalid_ValueType"));
}
}
dict[(KeyT)key] = (ValueT)value;
}
}
public ICollection Keys
{
get
{
return new CollectionAdapter<KeyT>(dict.Keys);
}
}
public ICollection Values
{
get
{
return new CollectionAdapter<ValueT>(dict.Values);
}
}
// Implement the non-generic ICollection interface.
public void CopyTo(Array array, int index)
{
IDictionaryIterator<KeyT, ValueT> iterator = dict.GetIterator();
while(iterator.MoveNext())
{
array.SetValue(iterator.Current, index++);
}
}
public int Count
{
get
{
return dict.Count;
}
}
public bool IsSynchronized
{
get
{
return dict.IsSynchronized;
}
}
public Object SyncRoot
{
get
{
return dict.SyncRoot;
}
}
// Implement the non-generic IEnumerable interface.
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return new EnumeratorAdapter< DictionaryEntry<KeyT, ValueT> >
(dict.GetIterator());
}
}; // class DictionaryAdapter<KeyT, ValueT>
}; // namespace Generics
| |
// 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.
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
#if USE_REFEMIT || uapaot
public class XmlObjectSerializerContext
#else
internal class XmlObjectSerializerContext
#endif
{
protected XmlObjectSerializer serializer;
protected DataContract rootTypeDataContract;
internal ScopedKnownTypes scopedKnownTypes = new ScopedKnownTypes();
protected DataContractDictionary serializerKnownDataContracts;
private bool _isSerializerKnownDataContractsSetExplicit;
protected IList<Type> serializerKnownTypeList;
private int _itemCount;
private int _maxItemsInObjectGraph;
private StreamingContext _streamingContext;
private bool _ignoreExtensionDataObject;
private DataContractResolver _dataContractResolver;
private KnownTypeDataContractResolver _knownTypeResolver;
internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject,
DataContractResolver dataContractResolver)
{
this.serializer = serializer;
_itemCount = 1;
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_streamingContext = streamingContext;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
_dataContractResolver = dataContractResolver;
}
internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null)
{
}
internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract
, DataContractResolver dataContractResolver
)
: this(serializer,
serializer.MaxItemsInObjectGraph,
new StreamingContext(),
serializer.IgnoreExtensionDataObject,
dataContractResolver
)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
}
internal virtual SerializationMode Mode
{
get { return SerializationMode.SharedContract; }
}
internal virtual bool IsGetOnlyCollection
{
get { return false; }
set { }
}
#if USE_REFEMIT
public StreamingContext GetStreamingContext()
#else
internal StreamingContext GetStreamingContext()
#endif
{
return _streamingContext;
}
#if USE_REFEMIT
public void IncrementItemCount(int count)
#else
internal void IncrementItemCount(int count)
#endif
{
if (count > _maxItemsInObjectGraph - _itemCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, _maxItemsInObjectGraph)));
_itemCount += count;
}
internal int RemainingItemCount
{
get { return _maxItemsInObjectGraph - _itemCount; }
}
internal bool IgnoreExtensionDataObject
{
get { return _ignoreExtensionDataObject; }
}
protected DataContractResolver DataContractResolver
{
get { return _dataContractResolver; }
}
protected KnownTypeDataContractResolver KnownTypeResolver
{
get
{
if (_knownTypeResolver == null)
{
_knownTypeResolver = new KnownTypeDataContractResolver(this);
}
return _knownTypeResolver;
}
}
internal DataContract GetDataContract(Type type)
{
return GetDataContract(type.TypeHandle, type);
}
internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(typeHandle), typeHandle, type, Mode);
}
else
{
return DataContract.GetDataContract(typeHandle, type, Mode);
}
}
internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContractSkipValidation(typeId, typeHandle, type);
}
else
{
return DataContract.GetDataContractSkipValidation(typeId, typeHandle, type);
}
}
internal virtual DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
if (IsGetOnlyCollection)
{
return DataContract.GetGetOnlyCollectionDataContract(id, typeHandle, null /*type*/, Mode);
}
else
{
return DataContract.GetDataContract(id, typeHandle, Mode);
}
}
internal virtual void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
{
if (!isMemberTypeSerializable)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
}
internal virtual Type GetSurrogatedType(Type type)
{
return type;
}
internal virtual DataContractDictionary SerializerKnownDataContracts
{
get
{
// This field must be initialized during construction by serializers using data contracts.
if (!_isSerializerKnownDataContractsSetExplicit)
{
this.serializerKnownDataContracts = serializer.KnownDataContracts;
_isSerializerKnownDataContractsSetExplicit = true;
}
return this.serializerKnownDataContracts;
}
}
private DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname)
{
DataContractDictionary serializerKnownDataContracts = this.SerializerKnownDataContracts;
if (serializerKnownDataContracts == null)
return null;
DataContract outDataContract;
return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null;
}
internal static DataContractDictionary GetDataContractsForKnownTypes(IList<Type> knownTypeList)
{
if (knownTypeList == null) return null;
DataContractDictionary dataContracts = new DataContractDictionary();
Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>();
for (int i = 0; i < knownTypeList.Count; i++)
{
Type knownType = knownTypeList[i];
if (knownType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.NullKnownType, "knownTypes")));
DataContract.CheckAndAdd(knownType, typesChecked, ref dataContracts);
}
return dataContracts;
}
internal bool IsKnownType(DataContract dataContract, DataContractDictionary knownDataContracts, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (knownDataContracts != null)
{
scopedKnownTypes.Push(knownDataContracts);
knownTypesAddedInCurrentScope = true;
}
bool isKnownType = IsKnownType(dataContract, declaredType);
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
return isKnownType;
}
internal bool IsKnownType(DataContract dataContract, Type declaredType)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/ /*, declaredType */);
return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType;
}
internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName)
{
DataContract dataContract = ResolveDataContractFromKnownTypes(typeName);
return dataContract == null ? null : dataContract.UnderlyingType;
}
private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName)
{
DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace);
if (dataContract == null)
{
#if uapaot
if (typeName.Name == Globals.SafeSerializationManagerName && typeName.Namespace == Globals.SafeSerializationManagerNamespace && Globals.TypeOfSafeSerializationManager != null)
{
return GetDataContract(Globals.TypeOfSafeSerializationManager);
}
#endif
dataContract = scopedKnownTypes.GetDataContract(typeName);
if (dataContract == null)
{
dataContract = GetDataContractFromSerializerKnownTypes(typeName);
}
}
return dataContract;
}
protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract)
{
XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs);
DataContract dataContract;
if (_dataContractResolver == null)
{
dataContract = ResolveDataContractFromKnownTypes(qname);
}
else
{
Type dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, null, KnownTypeResolver);
dataContract = dataContractType == null ? null : GetDataContract(dataContractType);
}
if (dataContract == null)
{
if (memberTypeContract != null
&& !memberTypeContract.UnderlyingType.IsInterface
&& memberTypeContract.StableName == qname)
{
dataContract = memberTypeContract;
}
if (dataContract == null && rootTypeDataContract != null)
{
if (rootTypeDataContract.StableName == qname)
dataContract = rootTypeDataContract;
else
{
CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract;
while (collectionContract != null)
{
DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType));
if (itemContract.StableName == qname)
{
dataContract = itemContract;
break;
}
collectionContract = itemContract as CollectionDataContract;
}
}
}
}
return dataContract;
}
internal void PushKnownTypes(DataContract dc)
{
if (dc != null && dc.KnownDataContracts != null)
{
scopedKnownTypes.Push(dc.KnownDataContracts);
}
}
internal void PopKnownTypes(DataContract dc)
{
if (dc != null && dc.KnownDataContracts != null)
{
scopedKnownTypes.Pop();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Sonic Ether/SESSAO")]
public class SESSAO : MonoBehaviour
{
private Material material;
public bool visualizeSSAO;
private Texture2D ditherTexture;
private Texture2D ditherTextureSmall;
private bool skipThisFrame = false;
[Range(0.02f, 5.0f)]
public float radius = 1.0f;
[Range(-0.2f, 0.5f)]
public float bias = 0.1f;
[Range(0.1f, 3.0f)]
public float bilateralDepthTolerance = 0.2f;
[Range(1.0f, 5.0f)]
public float zThickness = 2.35f;
[Range(0.5f, 5.0f)]
public float occlusionIntensity = 1.3f;
[Range(1.0f, 6.0f)]
public float sampleDistributionCurve = 1.15f;
[Range(0.0f, 1.0f)]
public float colorBleedAmount = 1.0f;
[Range(0.1f, 3.0f)]
public float brightnessThreshold;
public float drawDistance = 500.0f;
public float drawDistanceFadeSize = 1.0f;
public bool reduceSelfBleeding = true;
public bool useDownsampling = false;
public bool halfSampling = false;
public bool preserveDetails = false;
[HideInInspector]
public Camera attachedCamera;
private object initChecker = null;
void CheckInit()
{
if (initChecker == null)
{
Init();
}
}
void Init()
{
skipThisFrame = false;
Shader shader = Shader.Find("Hidden/SESSAO");
if (!shader)
{
skipThisFrame = true;
return;
}
material = new Material(shader);
attachedCamera = this.GetComponent<Camera>();
attachedCamera.depthTextureMode |= DepthTextureMode.Depth;
attachedCamera.depthTextureMode |= DepthTextureMode.DepthNormals;
SetupDitherTexture();
SetupDitherTextureSmall();
initChecker = new object();
}
void Cleanup()
{
DestroyImmediate(material);
initChecker = null;
}
void SetupDitherTextureSmall()
{
ditherTextureSmall = new Texture2D(3, 3, TextureFormat.Alpha8, false);
ditherTextureSmall.filterMode = FilterMode.Point;
float[] ditherPattern = new float[9]
// {9, 2, 7,
// 4, 5, 6,
// 3, 8, 1};
{8, 1, 6,
3, 0, 4,
7, 2, 5};
for (int i = 0; i < 9; i++)
{
Color pixelColor = new Color(0f, 0f, 0f, ditherPattern [i] / 9.0f);
int xCoord = i % 3;
int yCoord = Mathf.FloorToInt((float)i / 3.0f);
ditherTextureSmall.SetPixel(xCoord, yCoord, pixelColor);
}
ditherTextureSmall.Apply();
ditherTextureSmall.hideFlags = HideFlags.HideAndDontSave;
}
void SetupDitherTexture()
{
ditherTexture = new Texture2D(5, 5, TextureFormat.Alpha8, false);
ditherTexture.filterMode = FilterMode.Point;
float[] ditherPattern = new float[25]
{12.0f, 1.0f, 10.0f, 3.0f, 20.0f,
5.0f, 18.0f, 7.0f, 16.0f, 9.0f,
24.0f, 2.0f, 11.0f, 6.0f, 22.0f,
15.0f, 8.0f, 0.0f, 13.0f, 19.0f,
4.0f, 21.0f, 14.0f, 23.0f, 17.0f};
for (int i = 0; i < 25; i++)
{
Color pixelColor = new Color(0f, 0f, 0f, ditherPattern [i] / 25.0f);
int xCoord = i % 5;
int yCoord = Mathf.FloorToInt((float)i / 5.0f);
ditherTexture.SetPixel(xCoord, yCoord, pixelColor);
}
ditherTexture.Apply();
ditherTexture.hideFlags = HideFlags.HideAndDontSave;
}
void Start()
{
CheckInit();
}
void OnEnable()
{
CheckInit();
}
void OnDisable()
{
Cleanup();
}
void Update()
{
drawDistance = Mathf.Max(0.0f, drawDistance);
drawDistanceFadeSize = Mathf.Max(0.001f, drawDistanceFadeSize);
bilateralDepthTolerance = Mathf.Max(0.000001f, bilateralDepthTolerance);
}
[ImageEffectOpaque]
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
CheckInit();
if (skipThisFrame)
{
Graphics.Blit(source, destination);
return;
}
material.hideFlags = HideFlags.HideAndDontSave;
material.SetTexture("_DitherTexture", preserveDetails ? ditherTextureSmall : ditherTexture);
material.SetInt("PreserveDetails", preserveDetails ? 1 : 0);
material.SetMatrix("ProjectionMatrixInverse", GetComponent<Camera>().projectionMatrix.inverse);
RenderTexture ssao1 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf);
RenderTexture ssao2 = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGBHalf);
RenderTexture colorDownsampled1 = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, source.format);
colorDownsampled1.wrapMode = TextureWrapMode.Clamp;
colorDownsampled1.filterMode = FilterMode.Bilinear;
Graphics.Blit(source, colorDownsampled1);
material.SetTexture("_ColorDownsampled", colorDownsampled1);
RenderTexture ssaoDownsampled = null;
material.SetFloat("Radius", radius);
material.SetFloat("Bias", bias);
material.SetFloat("DepthTolerance", bilateralDepthTolerance);
material.SetFloat("ZThickness", zThickness);
material.SetFloat("Intensity", occlusionIntensity);
material.SetFloat("SampleDistributionCurve", sampleDistributionCurve);
material.SetFloat("ColorBleedAmount", colorBleedAmount);
material.SetFloat("DrawDistance", drawDistance);
material.SetFloat("DrawDistanceFadeSize", drawDistanceFadeSize);
material.SetFloat("SelfBleedReduction", reduceSelfBleeding ? 1.0f : 0.0f);
material.SetFloat("BrightnessThreshold", brightnessThreshold);
material.SetInt("HalfSampling", halfSampling ? 1 : 0);
material.SetInt("Orthographic", attachedCamera.orthographic ? 1 : 0);
if (useDownsampling)
{
ssaoDownsampled = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, RenderTextureFormat.ARGBHalf);
ssaoDownsampled.filterMode = FilterMode.Bilinear;
material.SetInt("Downsamp", 1);
Graphics.Blit(source, ssaoDownsampled, material, colorBleedAmount <= 0.0001f ? 1 : 0);
}
else
{
material.SetInt("Downsamp", 0);
Graphics.Blit(source, ssao1, material, colorBleedAmount <= 0.0001f ? 1 : 0);
}
RenderTexture.ReleaseTemporary(colorDownsampled1);
material.SetFloat("BlurDepthTolerance", 0.1f);
int bilateralBlurPass = attachedCamera.orthographic ? 6 : 2;
if (attachedCamera.orthographic)
{
material.SetFloat("Near", attachedCamera.nearClipPlane);
material.SetFloat("Far", attachedCamera.farClipPlane);
}
if (useDownsampling)
{
material.SetVector("Kernel", new Vector2(2.0f, 0.0f));
Graphics.Blit(ssaoDownsampled, ssao2, material, bilateralBlurPass);
RenderTexture.ReleaseTemporary(ssaoDownsampled);
material.SetVector("Kernel", new Vector2(0.0f, 2.0f));
Graphics.Blit(ssao2, ssao1, material, bilateralBlurPass);
material.SetVector("Kernel", new Vector2(2.0f, 0.0f));
Graphics.Blit(ssao1, ssao2, material, bilateralBlurPass);
material.SetVector("Kernel", new Vector2(0.0f, 2.0f));
Graphics.Blit(ssao2, ssao1, material, bilateralBlurPass);
}
else
{
material.SetVector("Kernel", new Vector2(1.0f, 0.0f));
Graphics.Blit(ssao1, ssao2, material, bilateralBlurPass);
material.SetVector("Kernel", new Vector2(0.0f, 1.0f));
Graphics.Blit(ssao2, ssao1, material, bilateralBlurPass);
material.SetVector("Kernel", new Vector2(1.0f, 0.0f));
Graphics.Blit(ssao1, ssao2, material, bilateralBlurPass);
material.SetVector("Kernel", new Vector2(0.0f, 1.0f));
Graphics.Blit(ssao2, ssao1, material, bilateralBlurPass);
}
RenderTexture.ReleaseTemporary(ssao2);
material.SetTexture("_SSAO", ssao1);
if (!visualizeSSAO)
{
Graphics.Blit(source, destination, material, 3);
} else
{
Graphics.Blit(source, destination, material, 5);
}
RenderTexture.ReleaseTemporary(ssao1);
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System;
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
// ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
// is stored as an Int16 internally to save space, but presented as a TimeSpan.
//
// The range is constrained so that both the represented clock time and the represented
// UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
// for actual UTC times, and a slightly constrained range on one end when an offset is
// present.
//
// This class should be substitutable for date time in most cases; so most operations
// effectively work on the clock time. However, the underlying UTC time is what counts
// for the purposes of identity, sorting and subtracting two instances.
//
//
// There are theoretically two date times stored, the UTC and the relative local representation
// or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
// for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
// out and for internal readability.
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateTimeOffset : IComparable, IFormattable, ISerializable, IDeserializationCallback,
IComparable<DateTimeOffset>, IEquatable<DateTimeOffset> {
// Constants
internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
internal const Int64 MinOffset = -MaxOffset;
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
// Instance Fields
private DateTime m_dateTime;
private Int16 m_offsetMinutes;
// Constructors
// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. For UTC and Unspecified kinds, creates a
// UTC instance with a zero offset. For local, extracts the local offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc) {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
// consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
// the offset corresponds to the local.
public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
if (dateTime.Kind == DateTimeKind.Local) {
if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), "offset");
}
}
else if (dateTime.Kind == DateTimeKind.Utc) {
if (offset != TimeSpan.Zero) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), "offset");
}
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond and offset
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond, Calendar and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
}
// Returns a DateTimeOffset representing the current date and time. The
// resolution of the returned value depends on the system timer. For
// Windows NT 3.5 and later the timer resolution is approximately 10ms,
// for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
// it is approximately 55ms.
//
public static DateTimeOffset Now {
get {
return new DateTimeOffset(DateTime.Now);
}
}
public static DateTimeOffset UtcNow {
get {
return new DateTimeOffset(DateTime.UtcNow);
}
}
public DateTime DateTime {
get {
return ClockDateTime;
}
}
public DateTime UtcDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
}
}
public DateTime LocalDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
return UtcDateTime.ToLocalTime();
}
}
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
public DateTimeOffset ToOffset(TimeSpan offset) {
return new DateTimeOffset((m_dateTime + offset).Ticks, offset);
}
// Instance Properties
// The clock or visible time represented. This is just a wrapper around the internal date because this is
// the chosen storage mechanism. Going through this helper is good for readability and maintainability.
// This should be used for display but not identity.
private DateTime ClockDateTime {
get {
return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}
// Returns the date part of this DateTimeOffset. The resulting value
// corresponds to this DateTimeOffset with the time-of-day part set to
// zero (midnight).
//
public DateTime Date {
get {
return ClockDateTime.Date;
}
}
// Returns the day-of-month part of this DateTimeOffset. The returned
// value is an integer between 1 and 31.
//
public int Day {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 31);
return ClockDateTime.Day;
}
}
// Returns the day-of-week part of this DateTimeOffset. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek DayOfWeek {
get {
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return ClockDateTime.DayOfWeek;
}
}
// Returns the day-of-year part of this DateTimeOffset. The returned value
// is an integer between 1 and 366.
//
public int DayOfYear {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 366); // leap year
return ClockDateTime.DayOfYear;
}
}
// Returns the hour part of this DateTimeOffset. The returned value is an
// integer between 0 and 23.
//
public int Hour {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 24);
return ClockDateTime.Hour;
}
}
// Returns the millisecond part of this DateTimeOffset. The returned value
// is an integer between 0 and 999.
//
public int Millisecond {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
return ClockDateTime.Millisecond;
}
}
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Minute {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Minute;
}
}
// Returns the month part of this DateTimeOffset. The returned value is an
// integer between 1 and 12.
//
public int Month {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
return ClockDateTime.Month;
}
}
public TimeSpan Offset {
get {
return new TimeSpan(0, m_offsetMinutes, 0);
}
}
// Returns the second part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Second {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Second;
}
}
// Returns the tick count for this DateTimeOffset. The returned value is
// the number of 100-nanosecond intervals that have elapsed since 1/1/0001
// 12:00am.
//
public long Ticks {
get {
return ClockDateTime.Ticks;
}
}
public long UtcTicks {
get {
return UtcDateTime.Ticks;
}
}
// Returns the time-of-day part of this DateTimeOffset. The returned value
// is a TimeSpan that indicates the time elapsed since midnight.
//
public TimeSpan TimeOfDay {
get {
return ClockDateTime.TimeOfDay;
}
}
// Returns the year part of this DateTimeOffset. The returned value is an
// integer between 1 and 9999.
//
public int Year {
get {
Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
return ClockDateTime.Year;
}
}
// Returns the DateTimeOffset resulting from adding the given
// TimeSpan to this DateTimeOffset.
//
public DateTimeOffset Add(TimeSpan timeSpan) {
return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// days to this DateTimeOffset. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddDays(double days) {
return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// hours to this DateTimeOffset. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddHours(double hours) {
return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
}
// Returns the DateTimeOffset resulting from the given number of
// milliseconds to this DateTimeOffset. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to this DateTimeOffset. The value
// argument is permitted to be negative.
//
public DateTimeOffset AddMilliseconds(double milliseconds) {
return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// minutes to this DateTimeOffset. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddMinutes(double minutes) {
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
public DateTimeOffset AddMonths(int months) {
return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// seconds to this DateTimeOffset. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddSeconds(double seconds) {
return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// 100-nanosecond ticks to this DateTimeOffset. The value argument
// is permitted to be negative.
//
public DateTimeOffset AddTicks(long ticks) {
return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// years to this DateTimeOffset. The result is computed by incrementing
// (or decrementing) the year part of this DateTimeOffset by value
// years. If the month and day of this DateTimeOffset is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of this DateTimeOffset.
//
public DateTimeOffset AddYears(int years) {
return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
}
// Compares two DateTimeOffset values, returning an integer that indicates
// their relationship.
//
public static int Compare(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
}
// Compares this DateTimeOffset to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTimeOffset, or otherwise an exception
// occurs. Null is considered less than any instance.
//
int IComparable.CompareTo(Object obj) {
if (obj == null) return 1;
if (!(obj is DateTimeOffset)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
}
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
if (utc < objUtc) return -1;
return 0;
}
public int CompareTo(DateTimeOffset other) {
DateTime otherUtc = other.UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > otherUtc) return 1;
if (utc < otherUtc) return -1;
return 0;
}
// Checks if this DateTimeOffset is equal to a given object. Returns
// true if the given object is a boxed DateTimeOffset and its value
// is equal to the value of this DateTimeOffset. Returns false
// otherwise.
//
public override bool Equals(Object obj) {
if (obj is DateTimeOffset) {
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
public bool Equals(DateTimeOffset other) {
return UtcDateTime.Equals(other.UtcDateTime);
}
public bool EqualsExact(DateTimeOffset other) {
//
// returns true when the ClockDateTime, Kind, and Offset match
//
// currently the Kind should always be Unspecified, but there is always the possibility that a future version
// of DateTimeOffset overloads the Kind field
//
return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
}
// Compares two DateTimeOffset values for equality. Returns true if
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
}
// Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
// a long representing the date and time as the number of
// 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
//
public static DateTimeOffset FromFileTime(long fileTime) {
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
// ----- SECTION: private serialization instance methods ----------------*
#if FEATURE_SERIALIZATION
void IDeserializationCallback.OnDeserialization(Object sender) {
try {
m_offsetMinutes = ValidateOffset(Offset);
m_dateTime = ValidateDate(ClockDateTime, Offset);
}
catch (ArgumentException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("DateTime", m_dateTime);
info.AddValue("OffsetMinutes", m_offsetMinutes);
}
DateTimeOffset(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16));
}
#endif
// Returns the hash code for this DateTimeOffset.
//
public override int GetHashCode() {
return UtcDateTime.GetHashCode();
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input) {
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) {
return Parse(input, formatProvider, DateTimeStyles.None);
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) {
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public TimeSpan Subtract(DateTimeOffset value) {
return UtcDateTime.Subtract(value.UtcDateTime);
}
public DateTimeOffset Subtract(TimeSpan value) {
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
public long ToFileTime() {
return UtcDateTime.ToFileTime();
}
public DateTimeOffset ToLocalTime() {
return ToLocalTime(false);
}
internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public String ToString(String format, IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public DateTimeOffset ToUniversalTime() {
return new DateTimeOffset(UtcDateTime);
}
public static Boolean TryParse(String input, out DateTimeOffset result) {
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
// Ensures the TimeSpan is valid to go in a DateTimeOffset.
private static Int16 ValidateOffset(TimeSpan offset) {
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), "offset");
}
if (ticks < MinOffset || ticks > MaxOffset) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_OffsetOutOfRange"));
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
// Ensures that the time and offset are in range.
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_UTCOutOfRange"));
}
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
}
private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) {
if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
}
if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
}
if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
}
Contract.EndContractBlock();
// RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatability with DateTime
style &= ~DateTimeStyles.RoundtripKind;
// AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
style &= ~DateTimeStyles.AssumeLocal;
return style;
}
// Operators
public static implicit operator DateTimeOffset (DateTime dateTime) {
return new DateTimeOffset(dateTime);
}
public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime - right.UtcDateTime;
}
public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime == right.UtcDateTime;
}
public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime != right.UtcDateTime;
}
public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime < right.UtcDateTime;
}
public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime <= right.UtcDateTime;
}
public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime > right.UtcDateTime;
}
public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime >= right.UtcDateTime;
}
}
}
| |
using ColossalFramework;
using ColossalFramework.Math;
using ICities;
using UnityEngine;
namespace FPSCamera
{
public class FPSCamera : MonoBehaviour
{
public delegate void OnCameraModeChanged(bool state);
public static OnCameraModeChanged onCameraModeChanged;
public delegate void OnUpdate();
public static OnUpdate onUpdate;
public static bool editorMode = false;
public static void Initialize(LoadMode mode)
{
var controller = GameObject.FindObjectOfType<CameraController>();
instance = controller.gameObject.AddComponent<FPSCamera>();
if (mode == LoadMode.LoadGame || mode == LoadMode.NewGame)
{
instance.gameObject.AddComponent<GamePanelExtender>();
instance.vehicleCamera = instance.gameObject.AddComponent<VehicleCamera>();
instance.citizenCamera = instance.gameObject.AddComponent<CitizenCamera>();
editorMode = false;
}
else
{
editorMode = true;
}
}
public static void Deinitialize()
{
Destroy(instance);
}
public static FPSCamera instance;
public static readonly string configPath = "FPSCameraConfig.xml";
public Configuration config;
private bool fpsModeEnabled = false;
private CameraController controller;
private Camera camera;
float rotationY = 0f;
private Vector3 mainCameraPosition;
private Quaternion mainCameraOrientation;
private SavedInputKey cameraMoveLeft;
private SavedInputKey cameraMoveRight;
private SavedInputKey cameraMoveForward;
private SavedInputKey cameraMoveBackward;
private SavedInputKey cameraZoomCloser;
private SavedInputKey cameraZoomAway;
public Component hideUIComponent = null;
public bool checkedForHideUI = false;
public VehicleCamera vehicleCamera;
public CitizenCamera citizenCamera;
public bool cityWalkthroughMode = false;
private float cityWalkthroughNextChangeTimer = 0.0f;
public float originalFieldOfView = 0.0f;
public FPSCameraUI ui;
void Start()
{
controller = FindObjectOfType<CameraController>();
camera = controller.GetComponent<Camera>();
originalFieldOfView = camera.fieldOfView;
config = Configuration.Deserialize(configPath);
if (config == null)
{
config = new Configuration();
}
SaveConfig();
mainCameraPosition = gameObject.transform.position;
mainCameraOrientation = gameObject.transform.rotation;
cameraMoveLeft = new SavedInputKey(Settings.cameraMoveLeft, Settings.gameSettingsFile, DefaultSettings.cameraMoveLeft, true);
cameraMoveRight = new SavedInputKey(Settings.cameraMoveRight, Settings.gameSettingsFile, DefaultSettings.cameraMoveRight, true);
cameraMoveForward = new SavedInputKey(Settings.cameraMoveForward, Settings.gameSettingsFile, DefaultSettings.cameraMoveForward, true);
cameraMoveBackward = new SavedInputKey(Settings.cameraMoveBackward, Settings.gameSettingsFile, DefaultSettings.cameraMoveBackward, true);
cameraZoomCloser = new SavedInputKey(Settings.cameraZoomCloser, Settings.gameSettingsFile, DefaultSettings.cameraZoomCloser, true);
cameraZoomAway = new SavedInputKey(Settings.cameraZoomAway, Settings.gameSettingsFile, DefaultSettings.cameraZoomAway, true);
mainCameraPosition = gameObject.transform.position;
mainCameraOrientation = gameObject.transform.rotation;
rotationY = -instance.transform.localEulerAngles.x;
var gameObjects = FindObjectsOfType<GameObject>();
foreach (var go in gameObjects)
{
var tmp = go.GetComponent("HideUI");
if (tmp != null)
{
hideUIComponent = tmp;
break;
}
}
checkedForHideUI = true;
ui = FPSCameraUI.Instance;
}
public void SaveConfig()
{
Configuration.Serialize(configPath, config);
}
void GUICheckbox(string label, ref bool state)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.ExpandWidth(false));
state = GUILayout.Toggle(state, "");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
private Matrix4x4 sliderOffsetMatrix = Matrix4x4.TRS(new Vector3(0.0f, 6.0f, 0.0f), Quaternion.identity, Vector3.one);
void GUISlider(string label, ref float state, float min, float max)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.ExpandWidth(false));
var oldMatrix = GUI.matrix;
GUI.matrix *= sliderOffsetMatrix;
state = GUILayout.HorizontalSlider(state, min, max);
GUI.matrix = oldMatrix;
GUILayout.Label(state.ToString("0.00"), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
}
public void SetFieldOfView(float fov)
{
config.fieldOfView = fov;
SaveConfig();
if (fpsModeEnabled)
{
camera.fieldOfView = fov;
}
}
private bool inModeTransition = false;
private Vector3 transitionTargetPosition = Vector3.zero;
private Quaternion transitionTargetOrientation = Quaternion.identity;
private Vector3 transitionStartPosition = Vector3.zero;
private Quaternion transitionStartOrientation = Quaternion.identity;
private float transitionT = 0.0f;
public void EnterWalkthroughMode()
{
cityWalkthroughMode = true;
cityWalkthroughNextChangeTimer = config.walkthroughModeTimer;
if (hideUIComponent != null && config.integrateHideUI)
{
hideUIComponent.SendMessage("Hide");
}
WalkthroughModeSwitchTarget();
FPSCameraUI.Instance.Hide();
}
public void ResetConfig()
{
config = new Configuration();
SaveConfig();
Destroy(FPSCameraUI.instance);
FPSCameraUI.instance = null;
ui = FPSCameraUI.Instance;
ui.Show();
}
public void SetMode(bool fpsMode)
{
instance.fpsModeEnabled = fpsMode;
if (instance.fpsModeEnabled)
{
camera.fieldOfView = config.fieldOfView;
instance.controller.enabled = false;
Cursor.visible = false;
instance.rotationY = -instance.transform.localEulerAngles.x;
}
else
{
if (!config.animateTransitions)
{
instance.controller.enabled = true;
}
camera.fieldOfView = originalFieldOfView;
Cursor.visible = true;
}
if (hideUIComponent != null && config.integrateHideUI)
{
if (instance.fpsModeEnabled)
{
hideUIComponent.SendMessage("Hide");
}
else
{
hideUIComponent.SendMessage("Show");
}
}
if (onCameraModeChanged != null)
{
onCameraModeChanged(fpsMode);
}
}
public static KeyCode GetToggleUIKey()
{
return instance.config.toggleFPSCameraHotkey;
}
public static bool IsEnabled()
{
return instance.fpsModeEnabled;
}
public ushort GetRandomVehicle()
{
var vmanager = VehicleManager.instance;
int skip = Random.Range(0, vmanager.m_vehicleCount - 1);
for (ushort i = 0; i < vmanager.m_vehicles.m_buffer.Length; i++)
{
if ((vmanager.m_vehicles.m_buffer[i].m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
{
continue;
}
if (vmanager.m_vehicles.m_buffer[i].Info.m_vehicleAI is CarTrailerAI)
{
continue;
}
if(skip > 0)
{
skip--;
continue;
}
return i;
}
for (ushort i = 0; i < vmanager.m_vehicles.m_buffer.Length; i++)
{
if ((vmanager.m_vehicles.m_buffer[i].m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) !=
Vehicle.Flags.Created)
{
continue;
}
if (vmanager.m_vehicles.m_buffer[i].Info.m_vehicleAI is CarTrailerAI)
{
continue;
}
return i;
}
return 0;
}
public uint GetRandomCitizenInstance()
{
var cmanager = CitizenManager.instance;
int skip = Random.Range(0, cmanager.m_instanceCount - 1);
for (uint i = 0; i < cmanager.m_instances.m_buffer.Length; i++)
{
if ((cmanager.m_instances.m_buffer[i].m_flags & (CitizenInstance.Flags.Created | CitizenInstance.Flags.Deleted)) != CitizenInstance.Flags.Created)
{
continue;
}
if (skip > 0)
{
skip--;
continue;
}
return cmanager.m_instances.m_buffer[i].m_citizen;
}
for (uint i = 0; i < cmanager.m_instances.m_buffer.Length; i++)
{
if ((cmanager.m_instances.m_buffer[i].m_flags & (CitizenInstance.Flags.Created | CitizenInstance.Flags.Deleted)) != CitizenInstance.Flags.Created)
{
continue;
}
return cmanager.m_instances.m_buffer[i].m_citizen;
}
return 0;
}
void WalkthroughModeSwitchTarget()
{
bool vehicleOrCitizen = Random.Range(0, 3) == 0;
if (!vehicleOrCitizen)
{
if (citizenCamera.following)
{
citizenCamera.StopFollowing();
}
var vehicle = GetRandomVehicle();
if (vehicle != 0)
{
vehicleCamera.SetFollowInstance(vehicle);
}
}
else
{
if (vehicleCamera.following)
{
vehicleCamera.StopFollowing();
}
var citizen = GetRandomCitizenInstance();
if (citizen != 0)
{
citizenCamera.SetFollowInstance(citizen);
}
}
}
void UpdateCityWalkthrough()
{
if (cityWalkthroughMode && !config.walkthroughModeManual)
{
cityWalkthroughNextChangeTimer -= Time.deltaTime;
if (cityWalkthroughNextChangeTimer <= 0.0f || !(citizenCamera.following || vehicleCamera.following))
{
cityWalkthroughNextChangeTimer = config.walkthroughModeTimer;
WalkthroughModeSwitchTarget();
}
}
else if (cityWalkthroughMode)
{
if (Input.GetMouseButtonDown(0))
{
WalkthroughModeSwitchTarget();
}
}
}
void UpdateCameras()
{
if (vehicleCamera != null && vehicleCamera.following && config.allowUserOffsetInVehicleCitizenMode)
{
if (cameraMoveForward.IsPressed())
{
vehicleCamera.userOffset += gameObject.transform.forward * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraMoveBackward.IsPressed())
{
vehicleCamera.userOffset -= gameObject.transform.forward * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
if (cameraMoveLeft.IsPressed())
{
vehicleCamera.userOffset -= gameObject.transform.right * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraMoveRight.IsPressed())
{
vehicleCamera.userOffset += gameObject.transform.right * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
if (cameraZoomAway.IsPressed())
{
vehicleCamera.userOffset -= gameObject.transform.up * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraZoomCloser.IsPressed())
{
vehicleCamera.userOffset += gameObject.transform.up * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
}
if (citizenCamera != null && citizenCamera.following && config.allowUserOffsetInVehicleCitizenMode)
{
if (cameraMoveForward.IsPressed())
{
citizenCamera.userOffset += gameObject.transform.forward * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraMoveBackward.IsPressed())
{
citizenCamera.userOffset -= gameObject.transform.forward * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
if (cameraMoveLeft.IsPressed())
{
citizenCamera.userOffset -= gameObject.transform.right * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraMoveRight.IsPressed())
{
citizenCamera.userOffset += gameObject.transform.right * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
if (cameraZoomAway.IsPressed())
{
citizenCamera.userOffset -= gameObject.transform.up * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
else if (cameraZoomCloser.IsPressed())
{
citizenCamera.userOffset += gameObject.transform.up * config.cameraMoveSpeed * 0.25f * Time.deltaTime;
}
}
}
void OnEscapePressed()
{
if (cityWalkthroughMode)
{
cityWalkthroughMode = false;
if (vehicleCamera != null && vehicleCamera.following)
{
vehicleCamera.StopFollowing();
}
if (citizenCamera != null && citizenCamera.following)
{
citizenCamera.StopFollowing();
}
if (hideUIComponent != null && config.integrateHideUI)
{
hideUIComponent.SendMessage("Show");
}
}
else if (vehicleCamera != null && vehicleCamera.following)
{
vehicleCamera.StopFollowing();
if (hideUIComponent != null && config.integrateHideUI)
{
hideUIComponent.SendMessage("Show");
}
}
else if (citizenCamera != null && citizenCamera.following)
{
citizenCamera.StopFollowing();
if (hideUIComponent != null && config.integrateHideUI)
{
hideUIComponent.SendMessage("Show");
}
}
else if (fpsModeEnabled)
{
if (config.animateTransitions && fpsModeEnabled)
{
inModeTransition = true;
transitionT = 0.0f;
if ((gameObject.transform.position - mainCameraPosition).magnitude <= 1.0f)
{
transitionT = 1.0f;
mainCameraOrientation = gameObject.transform.rotation;
}
transitionStartPosition = gameObject.transform.position;
transitionStartOrientation = gameObject.transform.rotation;
transitionTargetPosition = mainCameraPosition;
transitionTargetOrientation = mainCameraOrientation;
}
SetMode(!fpsModeEnabled);
}
}
void OnToggleCameraHotkeyPressed()
{
if (cityWalkthroughMode)
{
cityWalkthroughMode = false;
if (vehicleCamera.following)
{
vehicleCamera.StopFollowing();
}
if (citizenCamera.following)
{
citizenCamera.StopFollowing();
}
if (hideUIComponent != null && config.integrateHideUI)
{
hideUIComponent.SendMessage("Show");
}
}
else if (vehicleCamera != null && vehicleCamera.following)
{
vehicleCamera.StopFollowing();
}
else if (citizenCamera != null && citizenCamera.following)
{
citizenCamera.StopFollowing();
}
else
{
if (config.animateTransitions && fpsModeEnabled)
{
inModeTransition = true;
transitionT = 0.0f;
if ((gameObject.transform.position - mainCameraPosition).magnitude <= 1.0f)
{
transitionT = 1.0f;
mainCameraOrientation = gameObject.transform.rotation;
}
transitionStartPosition = gameObject.transform.position;
transitionStartOrientation = gameObject.transform.rotation;
transitionTargetPosition = mainCameraPosition;
transitionTargetOrientation = mainCameraOrientation;
}
SetMode(!fpsModeEnabled);
}
}
void Update()
{
if (onUpdate != null)
{
onUpdate();
}
UpdateCityWalkthrough();
UpdateCameras();
if (Input.GetKeyDown(KeyCode.Escape))
{
OnEscapePressed();
}
if (Input.GetKeyDown(config.toggleFPSCameraHotkey))
{
OnToggleCameraHotkeyPressed();
}
var pos = gameObject.transform.position;
float terrainY = TerrainManager.instance.SampleDetailHeight(gameObject.transform.position);
float waterY = TerrainManager.instance.WaterLevel(new Vector2(gameObject.transform.position.x, gameObject.transform.position.z));
terrainY = Mathf.Max(terrainY, waterY);
if (config.animateTransitions && inModeTransition)
{
transitionT += Time.deltaTime * config.animationSpeed;
gameObject.transform.position = Vector3.Slerp(transitionStartPosition, transitionTargetPosition, transitionT);
gameObject.transform.rotation = Quaternion.Slerp(transitionStartOrientation, transitionTargetOrientation, transitionT);
if (transitionT >= 1.0f)
{
inModeTransition = false;
if (!fpsModeEnabled)
{
instance.controller.enabled = true;
}
}
}
else if (fpsModeEnabled)
{
if (config.snapToGround)
{
Segment3 ray = new Segment3(gameObject.transform.position + new Vector3(0f, 1.5f, 0f), gameObject.transform.position + new Vector3(0f, -1000f, 0f));
Vector3 hitPos;
ushort nodeIndex;
ushort segmentIndex;
Vector3 hitPos2;
if (NetManager.instance.RayCast(null, ray, 0f, ItemClass.Service.Road, ItemClass.Service.PublicTransport, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos, out nodeIndex, out segmentIndex)
| NetManager.instance.RayCast(null, ray, 0f, ItemClass.Service.Beautification, ItemClass.Service.Water, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos2, out nodeIndex, out segmentIndex))
{
terrainY = Mathf.Max(terrainY, Mathf.Max(hitPos.y, hitPos2.y));
}
gameObject.transform.position = Vector3.Lerp(gameObject.transform.position, new Vector3(pos.x, terrainY + config.groundOffset, pos.z), 0.9f);
}
float speedFactor = 1.0f;
if (config.limitSpeedGround)
{
speedFactor *= Mathf.Sqrt(terrainY);
speedFactor = Mathf.Clamp(speedFactor, 1.0f, 256.0f);
}
if (Input.GetKey(config.goFasterHotKey))
{
speedFactor *= config.goFasterSpeedMultiplier;
}
if (cameraMoveForward.IsPressed())
{
gameObject.transform.position += gameObject.transform.forward * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
else if (cameraMoveBackward.IsPressed())
{
gameObject.transform.position -= gameObject.transform.forward * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
if (cameraMoveLeft.IsPressed())
{
gameObject.transform.position -= gameObject.transform.right * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
else if (cameraMoveRight.IsPressed())
{
gameObject.transform.position += gameObject.transform.right * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
if (cameraZoomAway.IsPressed())
{
gameObject.transform.position -= gameObject.transform.up * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
else if (cameraZoomCloser.IsPressed())
{
gameObject.transform.position += gameObject.transform.up * config.cameraMoveSpeed * speedFactor * Time.deltaTime;
}
if (Input.GetKey(config.showMouseHotkey))
{
Cursor.visible = true;
}
else
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * config.cameraRotationSensitivity;
rotationY += Input.GetAxis("Mouse Y") * config.cameraRotationSensitivity * (config.invertYAxis ? -1.0f : 1.0f);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
Cursor.visible = false;
}
camera.fieldOfView = config.fieldOfView;
camera.nearClipPlane = 1.0f;
}
else
{
mainCameraPosition = gameObject.transform.position;
mainCameraOrientation = gameObject.transform.rotation;
}
if (config.preventClipGround)
{
Segment3 ray = new Segment3(gameObject.transform.position + new Vector3(0f, 1.5f, 0f), gameObject.transform.position + new Vector3(0f, -1000f, 0f));
Vector3 hitPos;
ushort nodeIndex;
ushort segmentIndex;
Vector3 hitPos2;
if (NetManager.instance.RayCast(null, ray, 0f, ItemClass.Service.Road, ItemClass.Service.PublicTransport, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos, out nodeIndex, out segmentIndex)
| NetManager.instance.RayCast(null, ray, 0f, ItemClass.Service.Beautification, ItemClass.Service.Water, ItemClass.SubService.None, ItemClass.SubService.None, ItemClass.Layer.Default, ItemClass.Layer.None, NetNode.Flags.None, NetSegment.Flags.None, out hitPos2, out nodeIndex, out segmentIndex))
{
terrainY = Mathf.Max(terrainY, Mathf.Max(hitPos.y, hitPos2.y));
}
if (transform.position.y < terrainY + config.groundOffset)
{
transform.position = new Vector3(transform.position.x, terrainY + config.groundOffset, transform.position.z);
}
}
}
}
}
| |
using AutoMapper;
using ReMi.BusinessEntities.Plugins;
using ReMi.Common.Constants.ReleaseCalendar;
using ReMi.Common.Constants.ReleaseExecution;
using ReMi.Common.Utils;
using ReMi.Common.Utils.Enums;
using ReMi.Common.Utils.Repository;
using ReMi.DataAccess.Exceptions;
using ReMi.DataAccess.Exceptions.Configuration;
using ReMi.DataEntities.Metrics;
using ReMi.DataEntities.Products;
using ReMi.DataEntities.ReleaseCalendar;
using System;
using System.Collections.Generic;
using System.Linq;
using ReleaseTypeDescription = ReMi.BusinessEntities.ReleaseCalendar.ReleaseTypeDescription;
namespace ReMi.DataAccess.BusinessEntityGateways.ReleaseCalendar
{
public class ReleaseWindowGateway : BaseGateway, IReleaseWindowGateway
{
public IRepository<ReleaseWindow> ReleaseWindowRepository { get; set; }
public IRepository<Product> ProductRepository { get; set; }
public IRepository<Metric> MetricRepository { get; set; }
public IRepository<DataEntities.Auth.Account> AccountRepository { get; set; }
public IMappingEngine MappingEngine { get; set; }
public Func<IReleaseProductGateway> ReleaseProductGatewayFactory { get; set; }
public IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindowView> GetAllStartingInTimeRange(DateTime startTime, DateTime endTime)
{
if (startTime > endTime)
{
throw new ArgumentOutOfRangeException(string.Format("startTime ({0}) must be prior to endTime ({1})", startTime, endTime));
}
var dataResults = ReleaseWindowRepository
.GetAllSortedSatisfiedBy(
r => !r.Metrics.Any() ||
r.Metrics.Any(m => m.MetricType == MetricType.StartTime && m.ExecutedOn.HasValue && m.ExecutedOn.Value >= startTime && m.ExecutedOn.Value <= endTime),
q => q.OrderBy(r => r.Metrics.FirstOrDefault(m => m.MetricType == MetricType.StartTime && m.ExecutedOn.HasValue).ExecutedOn.Value))
.ToList();
return MappingEngine.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindowView>>(dataResults);
}
public IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow> GetAllByProduct(string product)
{
return MappingEngine
.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
ReleaseWindowRepository.GetAllSatisfiedBy(o => o.ReleaseProducts.Any(x => x.Product.Description == product)));
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow GetUpcomingRelease(string product)
{
var result = ReleaseWindowRepository
.GetAllSortedSatisfiedBy(
x => x.ReleaseProducts.Any(p => p.Product.Description == product)
&& x.Metrics.Any(m => m.MetricType == MetricType.Close && !m.ExecutedOn.HasValue),
q => q.OrderBy(r => r.StartTime))
.FirstOrDefault();
return MappingEngine.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(result);
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow GetCurrentRelease(string product)
{
var fromDate = SystemTime.Now.AddMinutes(15);
var current = SystemTime.Now;
var result = ReleaseWindowRepository.Entities
.Where(x => x.ReleaseProducts.Any(p => p.Product.Description == product))
.Where(x => x.Metrics.Any(m => m.MetricType == MetricType.StartTime && m.ExecutedOn.HasValue && m.ExecutedOn.Value <= fromDate))
.FirstOrDefault(x => x.Metrics.Any(m => m.MetricType == MetricType.EndTime && m.ExecutedOn.HasValue && m.ExecutedOn.Value >= current));
return MappingEngine.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(result);
}
public IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow> GetNearReleases(string product)
{
var productEntity = ProductRepository.GetSatisfiedBy(x => string.Equals(x.Description, product));
if (productEntity == null)
throw new ProductNotFoundException(product);
const int numberClosed = 2;
const int numberNonClosed = 3;
var releases = ReleaseWindowRepository
.GetAllSortedSatisfiedBy(x =>
x.ReleaseProducts.Any(o => o.Product.Description == product)
&& x.Metrics.Any(m => m.MetricType == MetricType.Close && m.ExecutedOn.HasValue),
q => q.OrderByDescending(r => r.StartTime))
.Take(numberClosed)
.ToList();
releases.AddRange(
ReleaseWindowRepository
.GetAllSortedSatisfiedBy(x =>
x.ReleaseProducts.Any(o => o.Product.Description == product)
&& (!x.Metrics.Any()
|| !x.Metrics.Any(m => m.MetricType == MetricType.Close && m.ExecutedOn.HasValue)),
q => q.OrderBy(r => r.StartTime))
.Take(numberNonClosed)
.ToList()
);
return MappingEngine.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(
releases.OrderBy(o => o.StartTime)
);
}
public IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow> GetExpiredReleases()
{
var endPeriod = SystemTime.Now;
var releases = ReleaseWindowRepository
.GetAllSatisfiedBy(x =>
x.Metrics.Any(m => m.MetricType == MetricType.EndTime && m.ExecutedOn.HasValue && m.ExecutedOn.Value < endPeriod)
&& x.Metrics.Any(m => m.MetricType == MetricType.Close && !m.ExecutedOn.HasValue));
return MappingEngine.Map<IEnumerable<ReleaseWindow>, IEnumerable<BusinessEntities.ReleaseCalendar.ReleaseWindow>>(releases);
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow FindFirstOverlappedRelease(string product,
DateTime periodStart, DateTime periodEnd)
{
return FindFirstOverlappedRelease(product, periodStart, periodEnd, Guid.Empty);
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow FindFirstOverlappedRelease(string product,
DateTime periodStart, DateTime periodEnd, Guid currentExternalId)
{
var maintenanceTypes = EnumDescriptionHelper.GetEnumDescriptions<ReleaseType, ReleaseTypeDescription>()
.Where(x => x.IsMaintenance)
.Select(x => x.Id)
.ToArray();
var foundReleases = ReleaseWindowRepository
.GetAllSatisfiedBy(
r => (
(
!r.Metrics.Any()
|| r.Metrics.Any(m => m.MetricType == MetricType.StartTime && m.ExecutedOn.HasValue && periodStart <= m.ExecutedOn.Value && periodEnd > m.ExecutedOn.Value)
|| r.Metrics.Any(m => m.MetricType == MetricType.EndTime && m.ExecutedOn.HasValue && periodStart < m.ExecutedOn.Value && periodEnd >= m.ExecutedOn.Value)
|| (
r.Metrics.Any(m => m.MetricType == MetricType.StartTime && m.ExecutedOn.HasValue && periodStart <= m.ExecutedOn.Value)
&& r.Metrics.Any(m => m.MetricType == MetricType.EndTime && m.ExecutedOn.HasValue && periodEnd >= m.ExecutedOn.Value)
)
)
&& !r.Metrics.Any(m => m.MetricType == MetricType.Close && m.ExecutedOn.HasValue)
&& r.ReleaseProducts.Any(x => x.Product.Description == product && x.Product.ReleaseTrack != ReleaseTrack.Automated)
&& (currentExternalId.Equals(Guid.Empty) || !r.ExternalId.Equals(currentExternalId))
))
.ToList();
var dataRelease = foundReleases.FirstOrDefault(r => !maintenanceTypes.Contains((int)r.ReleaseType));
return MappingEngine.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(dataRelease);
}
public BusinessEntities.ReleaseCalendar.ReleaseWindow GetByExternalId(Guid externalId, bool forceCheck = false, bool getReleaseNote = false)
{
var result = ReleaseWindowRepository.GetSatisfiedBy(r => r.ExternalId == externalId);
if (result == null && forceCheck)
throw new ReleaseWindowNotFoundException(externalId);
if (result == null) return null;
var retval = MappingEngine.Map<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>(result);
if (getReleaseNote && result.ReleaseNotes != null)
{
retval.ReleaseNotes = result.ReleaseNotes.ReleaseNotes;
retval.Issues = result.ReleaseNotes.Issues;
}
retval.Plugins = result.ReleaseProducts
.SelectMany(x => x.Product.PluginPackageConfiguration)
.Where(x => x.PluginId.HasValue)
.Select(x => x.Plugin)
.Distinct()
.Select(x => new PluginView
{
PluginType = x.PluginType,
PluginKey = x.Key,
PluginId = x.ExternalId
})
.ToArray();
return retval;
}
public void Create(BusinessEntities.ReleaseCalendar.ReleaseWindow releaseWindow, Guid creatorId)
{
var account = AccountRepository.GetSatisfiedBy(x => x.ExternalId == creatorId);
if (account == null) throw new AccountNotFoundException(creatorId);
var targetProducts = releaseWindow.Products.ToList();
var products = ProductRepository.GetAllSatisfiedBy(p => targetProducts.Contains(p.Description)).ToList();
if (products.IsNullOrEmpty())
{
throw new ProductNotFoundException(releaseWindow.Products);
}
if (products.Count != targetProducts.Count)
{
throw new ProductNotFoundException(targetProducts.Where(x => products.Any(p => p.Description == x)).ToArray());
}
Logger.DebugFormat("Found products: {0}", products.FormatElements());
var dataReleaseWindow = MappingEngine.Map<BusinessEntities.ReleaseCalendar.ReleaseWindow, ReleaseWindow>(releaseWindow);
dataReleaseWindow.ReleaseDecision = ReleaseDecision.NoGo;
dataReleaseWindow.CreatedOn = SystemTime.Now;
dataReleaseWindow.CreatedById = account.AccountId;
ReleaseWindowRepository.Insert(dataReleaseWindow);
using (var gateway = ReleaseProductGatewayFactory())
{
gateway.AssignProductsToRelease(releaseWindow.ExternalId, targetProducts);
}
}
public void Cancel(BusinessEntities.ReleaseCalendar.ReleaseWindow releaseWindow)
{
var entity = ReleaseWindowRepository.GetSatisfiedBy(row => row.ExternalId == releaseWindow.ExternalId);
ReleaseWindowRepository.Delete(entity);
}
public void Update(BusinessEntities.ReleaseCalendar.ReleaseWindow releaseWindow, bool updateOnlyDescription = false)
{
var targetProducts = releaseWindow.Products.ToList();
var products = ProductRepository.GetAllSatisfiedBy(p => targetProducts.Contains(p.Description)).ToList();
if (products == null)
{
throw new ProductNotFoundException(releaseWindow.Products);
}
if (products.Count != targetProducts.Count)
{
throw new ProductNotFoundException(targetProducts.Where(x => products.Any(p => p.Description == x)).ToArray());
}
var entity = ReleaseWindowRepository.GetSatisfiedBy(e => e.ExternalId == releaseWindow.ExternalId);
entity.Description = releaseWindow.Description;
if (!updateOnlyDescription)
{
entity.StartTime = releaseWindow.StartTime.ToUniversalTime();
entity.ReleaseType = releaseWindow.ReleaseType;
entity.RequiresDowntime = releaseWindow.RequiresDowntime;
entity.Sprint = releaseWindow.Sprint;
}
ReleaseWindowRepository.Update(entity);
using (var gateway = ReleaseProductGatewayFactory())
{
gateway.AssignProductsToRelease(releaseWindow.ExternalId, targetProducts);
}
}
public void CloseRelease(string releaseNotes, Guid releaseWindowId)
{
var release = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
if (release == null)
{
throw new ReleaseWindowNotFoundException(releaseWindowId);
}
if (release.ReleaseNotes == null)
{
release.ReleaseNotes = new ReleaseNote
{
ReleaseNotes = releaseNotes
};
}
else
{
release.ReleaseNotes.ReleaseNotes = releaseNotes;
}
if (!release.Metrics.Any() || release.Metrics.All(x => x.MetricType != MetricType.Close))
{
MetricRepository.Insert(new Metric
{
ExecutedOn = SystemTime.Now,
ExternalId = Guid.NewGuid(),
MetricType = MetricType.Close,
ReleaseWindowId = release.ReleaseWindowId
});
}
else
{
var metric =
MetricRepository.GetSatisfiedBy(x => x.ReleaseWindowId == release.ReleaseWindowId && x.MetricType == MetricType.Close);
metric.ExecutedOn = SystemTime.Now;
MetricRepository.Update(metric);
}
ReleaseWindowRepository.Update(release);
}
public void SaveIssues(BusinessEntities.ReleaseCalendar.ReleaseWindow window)
{
var release = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == window.ExternalId);
if (release == null)
{
throw new ReleaseWindowNotFoundException(window.ExternalId);
}
if (release.ReleaseNotes == null)
{
release.ReleaseNotes = new ReleaseNote
{
Issues = window.Issues
};
}
else
{
release.ReleaseNotes.Issues = window.Issues;
}
ReleaseWindowRepository.Update(release);
}
public void CloseFailedRelease(Guid releaseWindowId, string issues)
{
var releaseWindow = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
if (releaseWindow == null)
throw new ReleaseWindowNotFoundException(releaseWindowId);
if (releaseWindow.ReleaseNotes == null)
releaseWindow.ReleaseNotes = new ReleaseNote
{
Issues = issues
};
else
{
if (string.IsNullOrWhiteSpace(releaseWindow.ReleaseNotes.Issues))
releaseWindow.ReleaseNotes.Issues = issues;
else
releaseWindow.ReleaseNotes.Issues =
string.Format("{0}{1}{2}",
releaseWindow.ReleaseNotes.Issues.Trim().TrimEnd(Environment.NewLine.ToCharArray()),
Environment.NewLine + Environment.NewLine,
issues);
}
releaseWindow.IsFailed = true;
ReleaseWindowRepository.Update(releaseWindow);
var metrics = MetricRepository.GetAllSatisfiedBy(x => x.ReleaseWindow.ExternalId == releaseWindowId && !x.ExecutedOn.HasValue);
foreach (var metric in metrics)
{
metric.ExecutedOn = SystemTime.Now;
MetricRepository.Update(metric);
Logger.InfoFormat("Set metric as completed for failed release. ReleaseWindowId={0}, MetricId={1}, MetricType={2}",
releaseWindow.ExternalId, metric.MetricId, metric.MetricType);
}
}
public bool IsClosed(Guid releaseWindowId)
{
var release = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
if (release == null)
{
throw new ReleaseWindowNotFoundException(releaseWindowId);
}
return release.Metrics.Any() && release.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue);
}
public void UpdateReleaseDecision(Guid releaseWindowId, ReleaseDecision releaseDecision)
{
var releaseWindow = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
if (releaseWindow == null)
{
throw new ReleaseWindowNotFoundException(releaseWindowId);
}
releaseWindow.ReleaseDecision = releaseDecision;
ReleaseWindowRepository.Update(releaseWindow);
}
public void ApproveRelease(Guid releaseWindowId)
{
var release = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
if (release == null)
{
throw new ReleaseWindowNotFoundException(releaseWindowId);
}
if (!release.Metrics.Any() || release.Metrics.All(x => x.MetricType != MetricType.Approve))
{
MetricRepository.Insert(new Metric
{
ExecutedOn = SystemTime.Now,
ExternalId = Guid.NewGuid(),
MetricType = MetricType.Approve,
ReleaseWindowId = release.ReleaseWindowId
});
}
else
{
var metric =
MetricRepository.GetSatisfiedBy(x => x.ReleaseWindowId == release.ReleaseWindowId && x.MetricType == MetricType.Approve);
metric.ExecutedOn = SystemTime.Now;
MetricRepository.Update(metric);
}
}
public override void OnDisposing()
{
ReleaseWindowRepository.Dispose();
ProductRepository.Dispose();
MetricRepository.Dispose();
MappingEngine.Dispose();
base.OnDisposing();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Diagnostics;
using System.Security;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Runtime;
class AsyncMethodInvoker : IOperationInvoker
{
MethodInfo beginMethod;
MethodInfo endMethod;
InvokeBeginDelegate invokeBeginDelegate;
InvokeEndDelegate invokeEndDelegate;
int inputParameterCount;
int outputParameterCount;
public AsyncMethodInvoker(MethodInfo beginMethod, MethodInfo endMethod)
{
if (beginMethod == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("beginMethod"));
if (endMethod == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("endMethod"));
this.beginMethod = beginMethod;
this.endMethod = endMethod;
}
public MethodInfo BeginMethod
{
get { return this.beginMethod; }
}
public MethodInfo EndMethod
{
get { return this.endMethod; }
}
public bool IsSynchronous
{
get { return false; }
}
public object[] AllocateInputs()
{
return EmptyArray.Allocate(this.InputParameterCount);
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
internal static void CreateActivityInfo(ref ServiceModelActivity activity, ref Activity boundActivity)
{
if (DiagnosticUtility.ShouldUseActivity)
{
activity = ServiceModelActivity.CreateAsyncActivity();
TraceUtility.UpdateAsyncOperationContextWithActivity(activity);
boundActivity = ServiceModelActivity.BoundOperation(activity, true);
}
else if (TraceUtility.MessageFlowTracingOnly)
{
Guid activityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
if (activityId != Guid.Empty)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
else if (TraceUtility.ShouldPropagateActivity)
{
//Message flow tracing only scenarios use a light-weight ActivityID management logic
Guid activityId = ActivityIdHeader.ExtractActivityId(OperationContext.Current.IncomingMessage);
if (activityId != Guid.Empty)
{
boundActivity = Activity.CreateActivity(activityId);
}
TraceUtility.UpdateAsyncOperationContextWithActivity(activityId);
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
if (instance == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
if (inputs == null)
{
if (this.InputParameterCount > 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.InputParameterCount)));
}
else if (inputs.Length != this.InputParameterCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.InputParameterCount, inputs.Length)));
StartOperationInvokePerformanceCounters(this.beginMethod.Name.Substring(ServiceReflector.BeginMethodNamePrefix.Length));
IAsyncResult returnValue;
bool callFailed = true;
bool callFaulted = false;
ServiceModelActivity activity = null;
try
{
Activity boundActivity = null;
CreateActivityInfo(ref activity, ref boundActivity);
StartOperationInvokeTrace(this.beginMethod.Name);
using (boundActivity)
{
if (DiagnosticUtility.ShouldUseActivity)
{
string activityName = null;
if (this.endMethod == null)
{
activityName = SR.GetString(SR.ActivityExecuteMethod,
this.beginMethod.DeclaringType.FullName, this.beginMethod.Name);
}
else
{
activityName = SR.GetString(SR.ActivityExecuteAsyncMethod,
this.beginMethod.DeclaringType.FullName, this.beginMethod.Name,
this.endMethod.DeclaringType.FullName, this.endMethod.Name);
}
ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
}
returnValue = this.InvokeBeginDelegate(instance, inputs, callback, state);
callFailed = false;
}
}
catch (System.Security.SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
catch (Exception e)
{
TraceUtility.TraceUserCodeException(e, this.beginMethod);
if (e is FaultException)
{
callFaulted = true;
callFailed = false;
}
throw;
}
finally
{
ServiceModelActivity.Stop(activity);
// An exception during the InvokeBegin will not call InvokeEnd,
// so we complete the trace and performance counters here.
if (callFailed || callFaulted)
{
StopOperationInvokeTrace(callFailed, callFaulted, this.EndMethod.Name);
StopOperationInvokePerformanceCounters(callFailed, callFaulted, endMethod.Name.Substring(ServiceReflector.EndMethodNamePrefix.Length));
}
}
return returnValue;
}
internal static void GetActivityInfo(ref ServiceModelActivity activity, ref Activity boundOperation)
{
if (TraceUtility.MessageFlowTracingOnly)
{
if (null != OperationContext.Current)
{
Guid activityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
if (activityId != Guid.Empty)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
}
else if (DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivity)
{
object activityInfo = TraceUtility.ExtractAsyncOperationContextActivity();
if (activityInfo != null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
activity = activityInfo as ServiceModelActivity;
boundOperation = ServiceModelActivity.BoundOperation(activity, true);
}
else if (TraceUtility.ShouldPropagateActivity)
{
if (activityInfo is Guid)
{
Guid activityId = (Guid)activityInfo;
boundOperation = Activity.CreateActivity(activityId);
}
}
}
}
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
object returnVal;
if (instance == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
outputs = EmptyArray.Allocate(this.OutputParameterCount);
bool callFailed = true;
bool callFaulted = false;
ServiceModelActivity activity = null;
try
{
Activity boundOperation = null;
GetActivityInfo(ref activity, ref boundOperation);
using (boundOperation)
{
returnVal = this.InvokeEndDelegate(instance, outputs, result);
callFailed = false;
}
}
catch (SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
catch (FaultException)
{
callFaulted = true;
callFailed = false;
throw;
}
finally
{
ServiceModelActivity.Stop(activity);
StopOperationInvokeTrace(callFailed, callFaulted, this.endMethod.Name);
StopOperationInvokePerformanceCounters(callFailed, callFaulted, this.endMethod.Name.Substring(ServiceReflector.EndMethodNamePrefix.Length));
}
return returnVal;
}
internal static void StartOperationInvokeTrace(string methodName)
{
if (TD.OperationInvokedIsEnabled())
{
OperationContext context = OperationContext.Current;
EventTraceActivity eventTraceActivity = null;
if (context != null && context.IncomingMessage != null)
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(context.IncomingMessage);
}
if (TD.OperationInvokedIsEnabled())
{
TD.OperationInvoked(eventTraceActivity, methodName, TraceUtility.GetCallerInfo(OperationContext.Current));
}
if (TD.OperationCompletedIsEnabled() || TD.OperationFaultedIsEnabled() || TD.OperationFailedIsEnabled())
{
TraceUtility.UpdateAsyncOperationContextWithStartTime(eventTraceActivity, DateTime.UtcNow.Ticks);
}
}
}
internal static void StopOperationInvokeTrace(bool callFailed, bool callFaulted, string methodName)
{
if (!(TD.OperationCompletedIsEnabled() ||
TD.OperationFaultedIsEnabled() ||
TD.OperationFailedIsEnabled()))
{
return;
}
EventTraceActivity eventTraceActivity;
long startTime;
TraceUtility.ExtractAsyncOperationStartTime(out eventTraceActivity, out startTime);
long duration = TraceUtility.GetUtcBasedDurationForTrace(startTime);
if (callFailed)
{
if (TD.OperationFailedIsEnabled())
{
TD.OperationFailed(eventTraceActivity, methodName, duration);
}
}
else if (callFaulted)
{
if (TD.OperationFaultedIsEnabled())
{
TD.OperationFaulted(eventTraceActivity, methodName, duration);
}
}
else
{
if (TD.OperationCompletedIsEnabled())
{
TD.OperationCompleted(eventTraceActivity, methodName, duration);
}
}
}
internal static void StartOperationInvokePerformanceCounters(string methodName)
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.MethodCalled(methodName);
}
}
internal static void StopOperationInvokePerformanceCounters(bool callFailed, bool callFaulted, string methodName)
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
if (callFailed)
{
PerformanceCounters.MethodReturnedError(methodName);
}
else if (callFaulted)
{
PerformanceCounters.MethodReturnedFault(methodName);
}
else
{
PerformanceCounters.MethodReturnedSuccess(methodName);
}
}
}
InvokeBeginDelegate InvokeBeginDelegate
{
get
{
EnsureIsInitialized();
return invokeBeginDelegate;
}
}
InvokeEndDelegate InvokeEndDelegate
{
get
{
EnsureIsInitialized();
return invokeEndDelegate;
}
}
int InputParameterCount
{
get
{
EnsureIsInitialized();
return this.inputParameterCount;
}
}
int OutputParameterCount
{
get
{
EnsureIsInitialized();
return this.outputParameterCount;
}
}
void EnsureIsInitialized()
{
if (this.invokeBeginDelegate == null)
{
// Only pass locals byref because InvokerUtil may store temporary results in the byref.
// If two threads both reference this.count, temporary results may interact.
int inputParameterCount;
InvokeBeginDelegate invokeBeginDelegate = new InvokerUtil().GenerateInvokeBeginDelegate(this.beginMethod, out inputParameterCount);
this.inputParameterCount = inputParameterCount;
int outputParameterCount;
InvokeEndDelegate invokeEndDelegate = new InvokerUtil().GenerateInvokeEndDelegate(this.endMethod, out outputParameterCount);
this.outputParameterCount = outputParameterCount;
this.invokeEndDelegate = invokeEndDelegate;
this.invokeBeginDelegate = invokeBeginDelegate; // must set this last due to ----
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.PointOfService;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace PosPrinterSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario3_MultipleReceipt : Page
{
// Uncomment the following line if you need a pointer back to the MainPage.
// This value should be obtained in OnNavigatedTo in the e.Parameter argument
private MainPage rootPage;
PosPrinter printerInstance1 = null;
PosPrinter printerInstance2 = null;
ClaimedPosPrinter claimedPrinter1 = null;
ClaimedPosPrinter claimedPrinter2 = null;
bool IsAnImportantTransactionInstance1;
bool IsAnImportantTransactionInstance2;
public Scenario3_MultipleReceipt()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
ResetTheScenarioState();
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
ResetTheScenarioState();
}
async void FindReceiptPrinter_Click(object sender, RoutedEventArgs e)
{
await FindReceiptPrinterInstances();
}
/// <summary>
/// Claims printer instance 1
/// </summary>
async void Claim1_Click(object sender, RoutedEventArgs e)
{
await ClaimAndEnablePrinter1();
}
/// <summary>
/// Releases claim of printer instance 1
/// </summary>
void Release1_Click(object sender, RoutedEventArgs e)
{
if (claimedPrinter1 != null)
{
claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested;
claimedPrinter1.Dispose();
claimedPrinter1 = null;
rootPage.NotifyUser("Released claimed Instance 1", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Instance 1 not claimed to release", NotifyType.StatusMessage);
}
}
/// <summary>
/// Claims printer instance 2
/// </summary>
async void Claim2_Click(object sender, RoutedEventArgs e)
{
await ClaimAndEnablePrinter2();
}
/// <summary>
/// Releases claim of printer instance 2
/// </summary>
void Release2_Click(object sender, RoutedEventArgs e)
{
if (claimedPrinter2 != null)
{
claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested;
claimedPrinter2.Dispose();
claimedPrinter2 = null;
rootPage.NotifyUser("Released claimed Instance 2", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Instance 2 not claimed to release", NotifyType.StatusMessage);
}
}
/// <summary>
///Actual claim method task that claims and enables printer instance 1 asynchronously. It then adds the releasedevicerequested event handler as well to the claimed printer.
/// </summary>
private async Task<bool> ClaimAndEnablePrinter1()
{
if (printerInstance1 == null)
{
rootPage.NotifyUser("Cound not claim printer. Make sure you find printer first.", NotifyType.ErrorMessage);
return false;
}
if (claimedPrinter1 == null)
{
claimedPrinter1 = await printerInstance1.ClaimPrinterAsync();
if (claimedPrinter1 != null)
{
claimedPrinter1.ReleaseDeviceRequested += ClaimedPrinter1_ReleaseDeviceRequested;
rootPage.NotifyUser("Claimed Printer Instance 1", NotifyType.StatusMessage);
if (!await claimedPrinter1.EnableAsync())
{
rootPage.NotifyUser("Could not enable printer instance 1.", NotifyType.ErrorMessage);
}
else
{
return true;
}
}
else
{
rootPage.NotifyUser("Claim Printer instance 1 failed. Probably because instance 2 is holding on to it.", NotifyType.ErrorMessage);
}
}
return false;
}
/// <summary>
///Actual claim method task that claims and enables printer instance 2 asynchronously. It then adds the releasedevicerequested event handler as well to the claimed printer.
/// </summary>
private async Task<bool> ClaimAndEnablePrinter2()
{
if (printerInstance2 == null)
{
rootPage.NotifyUser("Cound not claim printer. Make sure you find printer first.", NotifyType.ErrorMessage);
return false;
}
if (printerInstance1 != null && claimedPrinter2 == null)
{
rootPage.NotifyUser("Trying to claim instance 2.", NotifyType.StatusMessage);
claimedPrinter2 = await printerInstance2.ClaimPrinterAsync();
if (claimedPrinter2 != null)
{
claimedPrinter2.ReleaseDeviceRequested += ClaimedPrinter2_ReleaseDeviceRequested;
rootPage.NotifyUser("Claimed Printer Instance 2", NotifyType.StatusMessage);
if (!await claimedPrinter2.EnableAsync())
{
rootPage.NotifyUser("Could not enable printer instance 2.", NotifyType.ErrorMessage);
}
else
{
return true;
}
}
else
{
rootPage.NotifyUser("Claim Printer instance 2 failed. Probably because instance 1 is holding on to it.", NotifyType.ErrorMessage);
}
}
return false;
}
/// <summary>
/// PosPrinter GetDeviceSelector gets the string format used to search for pos printer. This is then used to find any pos printers.
/// The method then takes the first printer id found and tries to create two instances for that printer.
/// </summary>
/// <returns></returns>
private async Task<bool> FindReceiptPrinterInstances()
{
if (printerInstance1 == null || printerInstance2 == null)
{
rootPage.NotifyUser("Finding printer", NotifyType.StatusMessage);
DeviceInformationCollection deviceCollection = await DeviceInformation.FindAllAsync(PosPrinter.GetDeviceSelector());
if (deviceCollection != null && deviceCollection.Count > 0)
{
DeviceInformation deviceInfo = deviceCollection[0];
printerInstance1 = await PosPrinter.FromIdAsync(deviceInfo.Id);
if (printerInstance1.Capabilities.Receipt.IsPrinterPresent)
{
rootPage.NotifyUser("Got Printer Instance 1 with Device Id : " + printerInstance1.DeviceId, NotifyType.StatusMessage);
printerInstance2 = await PosPrinter.FromIdAsync(deviceInfo.Id);
if (printerInstance2.Capabilities.Receipt.IsPrinterPresent)
{
rootPage.NotifyUser("Got Printer Instance 2 with Device Id : " + printerInstance2.DeviceId, NotifyType.StatusMessage);
}
return true;
}
else
{
rootPage.NotifyUser("Did not find a Receipt printer ", NotifyType.ErrorMessage);
return false;
}
}
else
{
rootPage.NotifyUser("No devices returned by FindAllAsync.", NotifyType.ErrorMessage);
return false;
}
}
return true;
}
/// <summary>
/// Reset all instances of claimed printer and remove event handlers.
/// </summary>
private void ResetTheScenarioState()
{
IsAnImportantTransactionInstance1 = true;
IsAnImportantTransactionInstance2 = false;
chkInstance1.IsChecked = true;
chkInstance2.IsChecked = false;
//Remove releasedevicerequested handler and dispose claimed printer object.
if (claimedPrinter1 != null)
{
claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested;
claimedPrinter1.Dispose();
claimedPrinter1 = null;
}
if (claimedPrinter2 != null)
{
claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested;
claimedPrinter2.Dispose();
claimedPrinter2 = null;
}
printerInstance1 = null;
printerInstance2 = null;
}
async void ClaimedPrinter1_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args)
{
if (IsAnImportantTransactionInstance1)
{
await sender.RetainDeviceAsync();
}
else
{
claimedPrinter1.ReleaseDeviceRequested -= ClaimedPrinter1_ReleaseDeviceRequested;
claimedPrinter1.Dispose();
claimedPrinter1 = null;
}
}
async void ClaimedPrinter2_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args)
{
if (IsAnImportantTransactionInstance2)
{
await sender.RetainDeviceAsync();
}
else
{
claimedPrinter2.ReleaseDeviceRequested -= ClaimedPrinter2_ReleaseDeviceRequested;
claimedPrinter2.Dispose();
claimedPrinter2 = null;
}
}
async void PrintLine1_Click(object sender, RoutedEventArgs e)
{
await PrintLine(txtPrintLine1.Text, claimedPrinter1);
}
async void PrintLine2_Click(object sender, RoutedEventArgs e)
{
await PrintLine(txtPrintLine2.Text, claimedPrinter2);
}
private async Task<bool> PrintLine(string message, ClaimedPosPrinter claimedPrinter)
{
if (claimedPrinter == null)
{
rootPage.NotifyUser("Claimed printer object is null. Cannot print.", NotifyType.ErrorMessage);
return false;
}
if (claimedPrinter.Receipt == null)
{
rootPage.NotifyUser("No receipt printer object in claimed printer.", NotifyType.ErrorMessage);
return false;
}
ReceiptPrintJob job = claimedPrinter.Receipt.CreateJob();
job.PrintLine(message);
if (await job.ExecuteAsync())
{
rootPage.NotifyUser("Printed line", NotifyType.StatusMessage);
return true;
}
rootPage.NotifyUser("Was not able to print line", NotifyType.StatusMessage);
return false;
}
private void EndScenario_Click(object sender, RoutedEventArgs e)
{
ResetTheScenarioState();
rootPage.NotifyUser("Disconnected Receipt Printer", NotifyType.StatusMessage);
}
private void chkInstance1_Checked(object sender, RoutedEventArgs e)
{
IsAnImportantTransactionInstance1 = true;
}
private void chkInstance2_Checked(object sender, RoutedEventArgs e)
{
IsAnImportantTransactionInstance2 = true;
}
private void chkInstance2_Unchecked(object sender, RoutedEventArgs e)
{
IsAnImportantTransactionInstance2 = false;
}
private void chkInstance1_Unchecked(object sender, RoutedEventArgs e)
{
IsAnImportantTransactionInstance1 = false;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace TestStack.BDDfy.Tests.Reporters
{
using System.Linq;
public class ReportTestData
{
private int _idCount;
public IEnumerable<Story> CreateTwoStoriesEachWithOneFailingScenarioAndOnePassingScenarioWithThreeStepsOfFiveMilliseconds()
{
var storyMetadata1 = new StoryMetadata(typeof(RegularAccountHolderStory), "As a person", "I want ice cream", "So that I can be happy", "Happiness");
var storyMetadata2 = new StoryMetadata(typeof(GoldAccountHolderStory), "As an account holder", "I want to withdraw cash", "So that I can get money when the bank is closed", "Account holder withdraws cash");
var stories = new List<Story>
{
new Story(storyMetadata1, GetScenarios(false, false)),
new Story(storyMetadata2, GetScenarios(true, false))
};
return stories;
}
public IEnumerable<Story> CreateMixContainingEachTypeOfOutcome()
{
var storyMetadata1 = new StoryMetadata(typeof(RegularAccountHolderStory), "As a person", "I want ice cream", "So that I can be happy", "Happiness");
var storyMetadata2 = new StoryMetadata(typeof(GoldAccountHolderStory), "As an account holder", "I want to withdraw cash", "So that I can get money when the bank is closed", "Account holder withdraws cash");
const StoryMetadata testThatReportWorksWithNoStory = null;
var stories = new List<Story>
{
new Story(storyMetadata1, GetOneOfEachScenarioResult()),
new Story(storyMetadata2, GetOneOfEachScenarioResult()),
new Story(testThatReportWorksWithNoStory, GetOneOfEachScenarioResult())
};
return stories;
}
public IEnumerable<Story> CreateMixContainingEachTypeOfOutcomeWithOneScenarioPerStory()
{
var storyMetadata1 = new StoryMetadata(typeof(RegularAccountHolderStory), "As a person", "I want ice cream", "So that I can be happy", "Happiness");
var storyMetadata2 = new StoryMetadata(typeof(GoldAccountHolderStory), "As an unhappy examples story", "I want to see failed steps", "So that I can diagnose what's wrong", "Unhappy examples");
var storyMetadata3 = new StoryMetadata(typeof(PlatinumAccountHolderStory), "As a happy examples story", "I want a clean report with examples", "So that the report is clean and readable", "Happy Examples");
const StoryMetadata testThatReportWorksWithNoStory = null;
var stories = new List<Story>
{
new Story(storyMetadata1, new Scenario(typeof(HappyPathScenario), GetHappyExecutionSteps(), "Happy Path Scenario [for Happiness]", new List<string>())),
new Story(storyMetadata1, new Scenario(typeof(SadPathScenario), GetFailingExecutionSteps(), "Sad Path Scenario [for Happiness]", new List<string>())),
new Story(storyMetadata1, new Scenario(typeof(SadPathScenario), GetInconclusiveExecutionSteps(), "Inconclusive Scenario [for Happiness]", new List<string>())),
new Story(storyMetadata1, new Scenario(typeof(SadPathScenario), GetNotImplementedExecutionSteps(), "Not Implemented Scenario [for Happiness]", new List<string>())),
new Story(testThatReportWorksWithNoStory, new Scenario(typeof(HappyPathScenario), GetHappyExecutionSteps(), "Happy Path Scenario [with no story]", new List<string>())),
new Story(testThatReportWorksWithNoStory, new Scenario(typeof(SadPathScenario), GetFailingExecutionSteps(), "Sad Path Scenario [with no story]", new List<string>())),
new Story(testThatReportWorksWithNoStory, new Scenario(typeof(SadPathScenario), GetInconclusiveExecutionSteps(), "Inconclusive Scenario [with no story]", new List<string>())),
new Story(testThatReportWorksWithNoStory, new Scenario(typeof(SadPathScenario), GetNotImplementedExecutionSteps(), "Not Implemented Scenario [with no story]", new List<string>())),
new Story(storyMetadata2, GetScenarios(true, true)),
new Story(storyMetadata3, GetScenarios(false, true)),
};
return stories;
}
public IEnumerable<Story> CreateTwoStoriesEachWithOneFailingScenarioAndOnePassingScenarioWithThreeStepsOfFiveMillisecondsAndEachHasTwoExamples()
{
var storyMetadata1 = new StoryMetadata(typeof(RegularAccountHolderStory), "As a person", "I want ice cream", "So that I can be happy", "Happiness");
var storyMetadata2 = new StoryMetadata(typeof(GoldAccountHolderStory), "As an account holder", "I want to withdraw cash", "So that I can get money when the bank is closed", "Account holder withdraws cash");
var stories = new List<Story>
{
new Story(storyMetadata1, GetScenarios(false, true)),
new Story(storyMetadata2, GetScenarios(true, true))
};
return stories;
}
private Scenario[] GetScenarios(bool includeFailingScenario, bool includeExamples)
{
var sadExecutionSteps = GetSadExecutionSteps().ToList();
if (includeFailingScenario)
{
var last = sadExecutionSteps.Last();
last.Result = Result.Failed;
try
{
throw new InvalidOperationException("Boom");
}
catch (Exception ex)
{
last.Exception = ex;
}
}
if (includeExamples)
{
var exampleId = _idCount++.ToString();
var exampleTable = new ExampleTable("sign", "action")
{
{"positive", "is"},
{"negative", "is not"}
};
var exampleExecutionSteps = GetExampleExecutionSteps().ToList();
if (includeFailingScenario)
{
var last = exampleExecutionSteps.Last();
last.Result = Result.Failed;
try
{
throw new InvalidOperationException("Boom\nWith\r\nNew lines");
}
catch (Exception ex)
{
last.Exception = ex;
}
}
return new List<Scenario>
{
new Scenario(exampleId, typeof(ExampleScenario), GetExampleExecutionSteps(), "Example Scenario", exampleTable.ElementAt(0), new List<string>()),
new Scenario(exampleId, typeof(ExampleScenario), exampleExecutionSteps, "Example Scenario", exampleTable.ElementAt(1), new List<string>())
}.ToArray();
}
return new List<Scenario>
{
new Scenario(typeof(HappyPathScenario), GetHappyExecutionSteps(), "Happy Path Scenario", new List<string>()),
new Scenario(typeof(SadPathScenario), sadExecutionSteps, "Sad Path Scenario", new List<string>())
}.ToArray();
}
private Scenario[] GetOneOfEachScenarioResult()
{
var scenarios = new List<Scenario>
{
new Scenario(typeof(HappyPathScenario), GetHappyExecutionSteps(), "Happy Path Scenario", new List<string>()),
new Scenario(typeof(SadPathScenario), GetSadExecutionSteps(), "Sad Path Scenario", new List<string>()),
new Scenario(typeof(SadPathScenario), GetInconclusiveExecutionSteps(), "Inconclusive Scenario", new List<string>()),
new Scenario(typeof(SadPathScenario), GetNotImplementedExecutionSteps(), "Not Implemented Scenario", new List<string>())
};
// override specific step results - ideally this class could be refactored to provide objectmother/builder interface
SetAllStepResults(scenarios[0].Steps, Result.Passed);
SetAllStepResults(scenarios[1].Steps, Result.Passed);
var last = scenarios[1].Steps.Last();
last.Result = Result.Failed;
try
{
throw new InvalidOperationException("Boom");
}
catch (Exception ex)
{
last.Exception = ex;
}
return scenarios.ToArray();
}
private List<Step> GetHappyExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a positive account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("Then money is dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
};
return steps;
}
private List<Step> GetExampleExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a <sign> account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("Then money <action> dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
};
return steps;
}
private List<Step> GetSadExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a negative account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
new Step(null, new StepTitle("Then no money is dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5), Result = Result.Passed},
};
return steps;
}
private List<Step> GetFailingExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a negative account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()),
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()),
new Step(null, new StepTitle("Then no money is dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()),
};
SetAllStepResults(steps, Result.Passed);
var last = steps.Last();
last.Result = Result.Failed;
try
{
throw new InvalidOperationException("Boom");
}
catch (Exception ex)
{
last.Exception = ex;
}
return steps;
}
private List<Step> GetInconclusiveExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a negative account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
new Step(null, new StepTitle("Then no money is dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
};
SetAllStepResults(steps, Result.Passed);
steps.Last().Result = Result.Inconclusive;
return steps;
}
private List<Step> GetNotImplementedExecutionSteps()
{
var steps = new List<Step>
{
new Step(null, new StepTitle("Given a negative account balance"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
new Step(null, new StepTitle("When the account holder requests money"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
new Step(null, new StepTitle("Then no money is dispensed"), true, ExecutionOrder.Assertion, true, new List<StepArgument>()) {Duration = new TimeSpan(0, 0, 0, 0, 5)},
};
SetAllStepResults(steps, Result.Passed);
steps.Last().Result = Result.NotImplemented;
return steps;
}
private void SetAllStepResults(IEnumerable<Step> steps, Result result)
{
foreach (var step in steps)
{
step.Result = result;
}
}
public class RegularAccountHolderStory { }
public class GoldAccountHolderStory { }
public class PlatinumAccountHolderStory { }
public class ExampleScenario
{
public void GivenA__sign__AccountBalance() { }
public void WhenTheAccountHolderRequestsMoney() { }
public void ThenMoney__action__Dispensed() { }
}
public class HappyPathScenario
{
public void GivenAPositiveAccountBalance() { }
public void WhenTheAccountHolderRequestsMoney() { }
public void ThenMoneyIsDispensed() { }
}
public class SadPathScenario
{
public void GivenANegativeAccountBalance() { }
public void WhenTheAccountHolderRequestsMoney() { }
public void ThenNoMoneyIsDispensed() { }
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.AccessControl;
using DiscUtils.Internal;
using DiscUtils.Streams;
namespace DiscUtils.Ntfs
{
internal sealed class SecurityDescriptors : IDiagnosticTraceable
{
// File consists of pairs of duplicate blocks (one after the other), providing
// redundancy. When a pair is full, the next pair is used.
private const int BlockSize = 0x40000;
private readonly File _file;
private readonly IndexView<HashIndexKey, HashIndexData> _hashIndex;
private readonly IndexView<IdIndexKey, IdIndexData> _idIndex;
private uint _nextId;
private long _nextSpace;
public SecurityDescriptors(File file)
{
_file = file;
_hashIndex = new IndexView<HashIndexKey, HashIndexData>(file.GetIndex("$SDH"));
_idIndex = new IndexView<IdIndexKey, IdIndexData>(file.GetIndex("$SII"));
foreach (KeyValuePair<IdIndexKey, IdIndexData> entry in _idIndex.Entries)
{
if (entry.Key.Id > _nextId)
{
_nextId = entry.Key.Id;
}
long end = entry.Value.SdsOffset + entry.Value.SdsLength;
if (end > _nextSpace)
{
_nextSpace = end;
}
}
if (_nextId == 0)
{
_nextId = 256;
}
else
{
_nextId++;
}
_nextSpace = MathUtilities.RoundUp(_nextSpace, 16);
}
public void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + "SECURITY DESCRIPTORS");
using (Stream s = _file.OpenStream(AttributeType.Data, "$SDS", FileAccess.Read))
{
byte[] buffer = StreamUtilities.ReadExact(s, (int)s.Length);
foreach (KeyValuePair<IdIndexKey, IdIndexData> entry in _idIndex.Entries)
{
int pos = (int)entry.Value.SdsOffset;
SecurityDescriptorRecord rec = new SecurityDescriptorRecord();
if (!rec.Read(buffer, pos))
{
break;
}
string secDescStr = "--unknown--";
if (rec.SecurityDescriptor[0] != 0)
{
RawSecurityDescriptor sd = new RawSecurityDescriptor(rec.SecurityDescriptor, 0);
secDescStr = sd.GetSddlForm(AccessControlSections.All);
}
writer.WriteLine(indent + " SECURITY DESCRIPTOR RECORD");
writer.WriteLine(indent + " Hash: " + rec.Hash);
writer.WriteLine(indent + " Id: " + rec.Id);
writer.WriteLine(indent + " File Offset: " + rec.OffsetInFile);
writer.WriteLine(indent + " Size: " + rec.EntrySize);
writer.WriteLine(indent + " Value: " + secDescStr);
}
}
}
public static SecurityDescriptors Initialize(File file)
{
file.CreateIndex("$SDH", 0, AttributeCollationRule.SecurityHash);
file.CreateIndex("$SII", 0, AttributeCollationRule.UnsignedLong);
file.CreateStream(AttributeType.Data, "$SDS");
return new SecurityDescriptors(file);
}
public RawSecurityDescriptor GetDescriptorById(uint id)
{
IdIndexData data;
if (_idIndex.TryGetValue(new IdIndexKey(id), out data))
{
return ReadDescriptor(data).Descriptor;
}
return null;
}
public uint AddDescriptor(RawSecurityDescriptor newDescriptor)
{
// Search to see if this is a known descriptor
SecurityDescriptor newDescObj = new SecurityDescriptor(newDescriptor);
uint newHash = newDescObj.CalcHash();
byte[] newByteForm = new byte[newDescObj.Size];
newDescObj.WriteTo(newByteForm, 0);
foreach (KeyValuePair<HashIndexKey, HashIndexData> entry in _hashIndex.FindAll(new HashFinder(newHash)))
{
SecurityDescriptor stored = ReadDescriptor(entry.Value);
byte[] storedByteForm = new byte[stored.Size];
stored.WriteTo(storedByteForm, 0);
if (Utilities.AreEqual(newByteForm, storedByteForm))
{
return entry.Value.Id;
}
}
long offset = _nextSpace;
// Write the new descriptor to the end of the existing descriptors
SecurityDescriptorRecord record = new SecurityDescriptorRecord();
record.SecurityDescriptor = newByteForm;
record.Hash = newHash;
record.Id = _nextId;
// If we'd overflow into our duplicate block, skip over it to the
// start of the next block
if ((offset + record.Size) / BlockSize % 2 == 1)
{
_nextSpace = MathUtilities.RoundUp(offset, BlockSize * 2);
offset = _nextSpace;
}
record.OffsetInFile = offset;
byte[] buffer = new byte[record.Size];
record.WriteTo(buffer, 0);
using (Stream s = _file.OpenStream(AttributeType.Data, "$SDS", FileAccess.ReadWrite))
{
s.Position = _nextSpace;
s.Write(buffer, 0, buffer.Length);
s.Position = BlockSize + _nextSpace;
s.Write(buffer, 0, buffer.Length);
}
// Make the next descriptor land at the end of this one
_nextSpace = MathUtilities.RoundUp(_nextSpace + buffer.Length, 16);
_nextId++;
// Update the indexes
HashIndexData hashIndexData = new HashIndexData();
hashIndexData.Hash = record.Hash;
hashIndexData.Id = record.Id;
hashIndexData.SdsOffset = record.OffsetInFile;
hashIndexData.SdsLength = (int)record.EntrySize;
HashIndexKey hashIndexKey = new HashIndexKey();
hashIndexKey.Hash = record.Hash;
hashIndexKey.Id = record.Id;
_hashIndex[hashIndexKey] = hashIndexData;
IdIndexData idIndexData = new IdIndexData();
idIndexData.Hash = record.Hash;
idIndexData.Id = record.Id;
idIndexData.SdsOffset = record.OffsetInFile;
idIndexData.SdsLength = (int)record.EntrySize;
IdIndexKey idIndexKey = new IdIndexKey();
idIndexKey.Id = record.Id;
_idIndex[idIndexKey] = idIndexData;
_file.UpdateRecordInMft();
return record.Id;
}
private SecurityDescriptor ReadDescriptor(IndexData data)
{
using (Stream s = _file.OpenStream(AttributeType.Data, "$SDS", FileAccess.Read))
{
s.Position = data.SdsOffset;
byte[] buffer = StreamUtilities.ReadExact(s, data.SdsLength);
SecurityDescriptorRecord record = new SecurityDescriptorRecord();
record.Read(buffer, 0);
return new SecurityDescriptor(new RawSecurityDescriptor(record.SecurityDescriptor, 0));
}
}
internal abstract class IndexData
{
public uint Hash;
public uint Id;
public int SdsLength;
public long SdsOffset;
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[Data-Hash:{0},Id:{1},SdsOffset:{2},SdsLength:{3}]",
Hash, Id, SdsOffset, SdsLength);
}
}
internal sealed class HashIndexKey : IByteArraySerializable
{
public uint Hash;
public uint Id;
public int Size
{
get { return 8; }
}
public int ReadFrom(byte[] buffer, int offset)
{
Hash = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0);
Id = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 4);
return 8;
}
public void WriteTo(byte[] buffer, int offset)
{
EndianUtilities.WriteBytesLittleEndian(Hash, buffer, offset + 0);
EndianUtilities.WriteBytesLittleEndian(Id, buffer, offset + 4);
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[Key-Hash:{0},Id:{1}]", Hash, Id);
}
}
internal sealed class HashIndexData : IndexData, IByteArraySerializable
{
public int Size
{
get { return 0x14; }
}
public int ReadFrom(byte[] buffer, int offset)
{
Hash = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x00);
Id = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x04);
SdsOffset = EndianUtilities.ToInt64LittleEndian(buffer, offset + 0x08);
SdsLength = EndianUtilities.ToInt32LittleEndian(buffer, offset + 0x10);
return 0x14;
}
public void WriteTo(byte[] buffer, int offset)
{
EndianUtilities.WriteBytesLittleEndian(Hash, buffer, offset + 0x00);
EndianUtilities.WriteBytesLittleEndian(Id, buffer, offset + 0x04);
EndianUtilities.WriteBytesLittleEndian(SdsOffset, buffer, offset + 0x08);
EndianUtilities.WriteBytesLittleEndian(SdsLength, buffer, offset + 0x10);
////Array.Copy(new byte[] { (byte)'I', 0, (byte)'I', 0 }, 0, buffer, offset + 0x14, 4);
}
}
internal sealed class IdIndexKey : IByteArraySerializable
{
public uint Id;
public IdIndexKey() {}
public IdIndexKey(uint id)
{
Id = id;
}
public int Size
{
get { return 4; }
}
public int ReadFrom(byte[] buffer, int offset)
{
Id = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0);
return 4;
}
public void WriteTo(byte[] buffer, int offset)
{
EndianUtilities.WriteBytesLittleEndian(Id, buffer, offset + 0);
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[Key-Id:{0}]", Id);
}
}
internal sealed class IdIndexData : IndexData, IByteArraySerializable
{
public int Size
{
get { return 0x14; }
}
public int ReadFrom(byte[] buffer, int offset)
{
Hash = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x00);
Id = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0x04);
SdsOffset = EndianUtilities.ToInt64LittleEndian(buffer, offset + 0x08);
SdsLength = EndianUtilities.ToInt32LittleEndian(buffer, offset + 0x10);
return 0x14;
}
public void WriteTo(byte[] buffer, int offset)
{
EndianUtilities.WriteBytesLittleEndian(Hash, buffer, offset + 0x00);
EndianUtilities.WriteBytesLittleEndian(Id, buffer, offset + 0x04);
EndianUtilities.WriteBytesLittleEndian(SdsOffset, buffer, offset + 0x08);
EndianUtilities.WriteBytesLittleEndian(SdsLength, buffer, offset + 0x10);
}
}
private class HashFinder : IComparable<HashIndexKey>
{
private readonly uint _toMatch;
public HashFinder(uint toMatch)
{
_toMatch = toMatch;
}
public int CompareTo(HashIndexKey other)
{
return CompareTo(other.Hash);
}
public int CompareTo(uint otherHash)
{
if (_toMatch < otherHash)
{
return -1;
}
if (_toMatch > otherHash)
{
return 1;
}
return 0;
}
}
}
}
| |
// <copyright file="BatchedEventsTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
namespace DirectoryWatcherSample.Test
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class BatchedEventsTest
{
[TestMethod]
public void AddBeforeSubscribe()
{
BatchedEvents<string> events = new BatchedEvents<string>(() => Task.CompletedTask);
Action act = () => events.Add("item1", new TimePoint(1));
act.Should().NotThrow();
}
[TestMethod]
public void AddOneAndComplete()
{
TaskCompletionSource<bool> pending = new TaskCompletionSource<bool>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Task);
List<string> batches = new List<string>();
events.Subscribe("item1", i => batches.Add(i));
events.Add("item1", new TimePoint(1));
batches.Should().BeEmpty();
pending.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("item1");
}
[TestMethod]
public void AddTwoAndComplete()
{
TaskCompletionSource<bool> pending = new TaskCompletionSource<bool>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Task);
List<string> batches = new List<string>();
events.Subscribe("item1", i => batches.Add(i));
events.Add("item1", new TimePoint(1));
events.Add("item1", new TimePoint(2));
batches.Should().BeEmpty();
pending.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("item1");
}
[TestMethod]
public void AddOneAndCompleteTwice()
{
Queue<TaskCompletionSource<bool>> pending = new Queue<TaskCompletionSource<bool>>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Dequeue().Task);
List<string> batches = new List<string>();
TaskCompletionSource<bool> pending1 = new TaskCompletionSource<bool>();
TaskCompletionSource<bool> pending2 = new TaskCompletionSource<bool>();
pending.Enqueue(pending1);
pending.Enqueue(pending2);
events.Subscribe("item1", i => batches.Add(i));
events.Add("item1", new TimePoint(1));
batches.Should().BeEmpty();
pending1.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("item1");
batches.Clear();
events.Add("item1", new TimePoint(2));
batches.Should().BeEmpty();
pending2.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("item1");
}
[TestMethod]
public void AddTwoDifferentBatches()
{
Queue<TaskCompletionSource<bool>> pending = new Queue<TaskCompletionSource<bool>>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Dequeue().Task);
List<string> batches = new List<string>();
TaskCompletionSource<bool> pending1 = new TaskCompletionSource<bool>();
TaskCompletionSource<bool> pending2 = new TaskCompletionSource<bool>();
pending.Enqueue(pending1);
pending.Enqueue(pending2);
events.Subscribe("item1", i => batches.Add("A:" + i));
events.Subscribe("item2", i => batches.Add("B:" + i));
events.Add("item1", new TimePoint(1));
events.Add("item2", new TimePoint(1));
batches.Should().BeEmpty();
pending1.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("A:item1");
batches.Clear();
pending2.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("B:item2");
}
[TestMethod]
public void SubscribeAndDispose()
{
BatchedEvents<string> events = new BatchedEvents<string>(() => Task.CompletedTask);
IDisposable sub = events.Subscribe("item1", i => { });
Action act = () => sub.Dispose();
act.Should().NotThrow();
}
[TestMethod]
public void SubscribeThenAddAndDispose()
{
TaskCompletionSource<bool> pending = new TaskCompletionSource<bool>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Task);
IDisposable sub = events.Subscribe("item1", i => { });
events.Add("item1", new TimePoint(1));
Action act = () => sub.Dispose();
act.Should().NotThrow();
}
[TestMethod]
public void DisposeAfterCreate()
{
BatchedEvents<string> events = new BatchedEvents<string>(() => Task.CompletedTask);
Action act = () => events.Dispose();
act.Should().NotThrow();
}
[TestMethod]
public void SubscribeAndAddTwoThenDisposeOneAndComplete()
{
Queue<TaskCompletionSource<bool>> pending = new Queue<TaskCompletionSource<bool>>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Dequeue().Task);
List<string> batches = new List<string>();
TaskCompletionSource<bool> pending1 = new TaskCompletionSource<bool>();
TaskCompletionSource<bool> pending2 = new TaskCompletionSource<bool>();
pending.Enqueue(pending1);
pending.Enqueue(pending2);
IDisposable sub1 = events.Subscribe("item1", i => batches.Add("A:" + i));
events.Subscribe("item2", i => batches.Add("B:" + i));
events.Add("item1", new TimePoint(1));
events.Add("item2", new TimePoint(1));
batches.Should().BeEmpty();
sub1.Dispose();
pending1.SetResult(true);
batches.Should().BeEmpty();
pending2.SetResult(true);
batches.Should().ContainSingle().Which.Should().Be("B:item2");
}
[TestMethod]
public void SubscribeAndAddTwoThenDisposeAllAndComplete()
{
Queue<TaskCompletionSource<bool>> pending = new Queue<TaskCompletionSource<bool>>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Dequeue().Task);
List<string> batches = new List<string>();
TaskCompletionSource<bool> pending1 = new TaskCompletionSource<bool>();
TaskCompletionSource<bool> pending2 = new TaskCompletionSource<bool>();
pending.Enqueue(pending1);
pending.Enqueue(pending2);
IDisposable sub1 = events.Subscribe("item1", i => batches.Add("A:" + i));
events.Subscribe("item2", i => batches.Add("B:" + i));
events.Add("item1", new TimePoint(1));
events.Add("item2", new TimePoint(1));
batches.Should().BeEmpty();
events.Dispose();
pending1.SetResult(true);
batches.Should().BeEmpty();
pending2.SetResult(true);
batches.Should().BeEmpty();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteTablesOperations operations.
/// </summary>
internal partial class RouteTablesOperations : IServiceOperations<NetworkClient>, IRouteTablesOperations
{
/// <summary>
/// Initializes a new instance of the RouteTablesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteTablesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </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<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_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 (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteTable>();
_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<RouteTable>(_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>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteTable> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all route tables in 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<IPage<RouteTable>>> ListWithHttpMessagesAsync(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-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables").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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_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 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or updates a route table in a specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update route table operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_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 = Microsoft.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RouteTable>();
_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<RouteTable>(_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all route tables in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RouteTable>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_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 System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace BMGFramework
{
public class GraphicsManager
{
public const int FPS = 60;
private int _width, _height;
private Matrix _projection_matrix;
private Matrix _view_matrix;
private Engine _engine;
public SpriteBatch SpriteBatch { get { return _sprite_batch; } }
public GraphicsDevice GraphicsDevice { get { return _graphics_device; } }
private SpriteBatch _sprite_batch;
private ContentManager _content_manager;
private GraphicsDevice _graphics_device;
private GraphicsDeviceManager _graphics_device_manager;
private RenderTarget2D _render_target;
private BasicEffect _line_effect;
public Dictionary<string, SpriteSheet> SpriteSheets = new Dictionary<string, SpriteSheet>();
public Dictionary<string, Effect> Effects = new Dictionary<string, Effect>();
public int ZoomLevel { get; private set; }
public GraphicsManager(Engine engine, ContentManager contentManager, GraphicsDevice graphicsDevice, GraphicsDeviceManager graphicsDeviceManager, int width, int height, int initialZoom = 1)
{
_engine = engine;
_width = width;
_height = height;
ZoomLevel = initialZoom;
_content_manager = contentManager;
_graphics_device = graphicsDevice;
_graphics_device_manager = graphicsDeviceManager;
_view_matrix = new Matrix(
1f, 0, 0, 0,
0, -1f, 0, 0,
0, 0, -1f, 0,
0, 0, 0, 1f
);
_projection_matrix = Matrix.CreateOrthographicOffCenter(0, width, -height, 0, 0, 1);
_line_effect = new BasicEffect(_graphics_device)
{
Alpha = 1f,
VertexColorEnabled = true,
TextureEnabled = false,
World = Matrix.Identity,
View = _view_matrix,
Projection = _projection_matrix,
};
_sprite_batch = new SpriteBatch(_graphics_device);
_render_target = new RenderTarget2D(_graphics_device, width, height);
_graphics_device.BlendState = BlendState.AlphaBlend;
ResizeWindow();
}
public void ResizeWindow()
{
int width = _width * ZoomLevel;
int height = _height * ZoomLevel;
try
{
_graphics_device_manager.PreferredBackBufferWidth = width;
_graphics_device_manager.PreferredBackBufferHeight = height;
_graphics_device_manager.ApplyChanges();
}
catch(Exception e)
{
_engine.Logger?.Warning("Failed to resize window: " + e.Message);
}
}
public void SetZoomLevel(int zoom)
{
ZoomLevel = zoom;
ResizeWindow();
_engine.SaveConfig("Zoom", ZoomLevel.ToString());
}
public void LoadSprite(string name, int spriteWidth, int spriteHeight)
{
Texture2D texture = _content_manager.Load<Texture2D>("Graphics/" + name);
SpriteSheets.Add(
name,
new SpriteSheet(
name,
texture,
spriteWidth, spriteHeight,
CreateBasicEffect(texture)
)
);
}
public void LoadEffect(string name)
{
Effect effect = _content_manager.Load<Effect>("Effects/" + name);
Effects.Add(
name,
effect
);
}
public BasicEffect CreateBasicEffect(Texture2D texture)
{
return new BasicEffect(_graphics_device)
{
World = Matrix.Identity,
View = _view_matrix,
Projection = _projection_matrix,
Texture = texture,
TextureEnabled = true,
};
}
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="spriteSheet"></param>
/// <param name="text"></param>
/// <param name="characterOffset"></param>
/// <returns>How many rows of text were rendered.</returns>
public int DrawText(int x, int y, SpriteSheet spriteSheet, string text, int characterOffset = 0, int xSpacing = 1, int ySpacing = 1)
{
int col = 0;
int row = 0;
for(int i = 0; i < text.Length; i++, col++)
{
int c = text[i];
if(c == 10 || c == 13)
{
col = -1;
row++;
}
else
DrawSprite(x + col * (spriteSheet.SpriteWidth + xSpacing), y + row * (spriteSheet.SpriteHeight + ySpacing), spriteSheet, c - characterOffset);
}
return row;
}
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="spriteSheetName"></param>
/// <param name="text"></param>
/// <param name="characterOffset"></param>
/// <returns>How many rows of text were rendered.</returns>
public int DrawText(int x, int y, string spriteSheetName, string text, int characterOffset = 0, int xSpacing = 1, int ySpacing = 1)
{
return DrawText(x, y, SpriteSheets[spriteSheetName], text, characterOffset, xSpacing, ySpacing);
}
public void DrawSprite(double x, double y, Camera c, SpriteSheet spriteSheet, int spriteIndex)
{
DrawSprite(
(int)(x - c.X), (int)(y - c.Y),
spriteSheet.SpriteWidth, spriteSheet.SpriteHeight,
spriteSheet,
spriteIndex
);
}
public void DrawSprite(int x, int y, SpriteSheet spriteSheet, int spriteIndex)
{
DrawSprite(
x, y,
spriteSheet.SpriteWidth, spriteSheet.SpriteHeight,
spriteSheet,
spriteIndex
);
}
public void DrawSprite(int x, int y, string spriteSheetName, int spriteIndex)
{
SpriteSheet spriteSheet = SpriteSheets[spriteSheetName];
DrawSprite(
x, y,
spriteSheet.SpriteWidth, spriteSheet.SpriteHeight,
spriteSheet,
spriteIndex
);
}
public void DrawSprite(int x, int y, int width, int height, SpriteSheet spriteSheet, int spriteIndex)
{
int spriteX = spriteIndex % spriteSheet.Columns;
int spriteY = spriteIndex / spriteSheet.Columns;
float spriteXWidth = 1 / (float)spriteSheet.Columns;
float spriteYHeight = 1 / (float)spriteSheet.Rows;
float spriteXOffset = spriteX * spriteXWidth;
float spriteYOffset = spriteY * spriteYHeight;
foreach (EffectPass pass in spriteSheet.Effect.CurrentTechnique.Passes)
{
pass.Apply();
_graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionTexture[]
{
new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(spriteXOffset, spriteYOffset)),
new VertexPositionTexture(new Vector3(x + width, y, 0), new Vector2(spriteXOffset + spriteXWidth, spriteYOffset)),
new VertexPositionTexture(new Vector3(x, y + height, 0), new Vector2(spriteXOffset, spriteYOffset + spriteYHeight)),
new VertexPositionTexture(new Vector3(x + width, y + height, 0), new Vector2(spriteXOffset + spriteXWidth, spriteYOffset + spriteYHeight)),
}, 0, 2, VertexPositionTexture.VertexDeclaration);
}
}
public void DrawBasicEffect(int x, int y, BasicEffect e)
{
int width = e.Texture.Width;
int height = e.Texture.Height;
foreach (EffectPass pass in e.CurrentTechnique.Passes)
{
pass.Apply();
_graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionTexture[]
{
new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(0, 0)),
new VertexPositionTexture(new Vector3(x + width, y, 0), new Vector2(1, 0)),
new VertexPositionTexture(new Vector3(x, y + height, 0), new Vector2(0, 1)),
new VertexPositionTexture(new Vector3(x + width, y + height, 0), new Vector2(1, 1)),
}, 0, 2, VertexPositionTexture.VertexDeclaration);
}
}
public void DrawTiledSprite(int x, int y, int width, int height, string spriteSheetName, float offsetX = 0, float offsetY = 0)
{
DrawTiledSprite(x, y, width, height, SpriteSheets[spriteSheetName], offsetX, offsetY);
}
public void DrawTiledSprite(int x, int y, int width, int height, SpriteSheet spriteSheet, float offsetX = 0, float offsetY = 0)
{
int spriteWidth = spriteSheet.SpriteWidth;
int spriteHeight = spriteSheet.SpriteHeight;
foreach (EffectPass pass in spriteSheet.Effect.CurrentTechnique.Passes)
{
pass.Apply();
_graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionTexture[]
{
new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(offsetX, offsetY)),
new VertexPositionTexture(new Vector3(x + width, y, 0), new Vector2(offsetX + (float)width / spriteWidth, offsetY)),
new VertexPositionTexture(new Vector3(x, y + height, 0), new Vector2(offsetX, offsetY + (float)height / spriteHeight)),
new VertexPositionTexture(new Vector3(x + width, y + height, 0), new Vector2(offsetX + (float)width / spriteWidth, offsetY + (float)height / spriteHeight)),
}, 0, 2, VertexPositionTexture.VertexDeclaration);
}
}
public void DrawRectangleWire(int x1, int y1, int w, int h, Color color)
{
DrawLine(x1, y1, x1, y1 + h - 1, color);
DrawLine(x1, y1, x1 + w - 1, y1, color);
DrawLine(x1 + w - 1, y1, x1 + w - 1, y1 + h - 1, color);
DrawLine(x1, y1 + h - 1, x1 + w, y1 + h - 1, color); // no -1 on the width here, because we need to finally hit the bottom-right pixel
}
public void DrawRectangle(int x1, int y1, int w, int h, Color color)
{
if (w == 0 || h == 0) return;
int x2 = x1 + w;
int y2 = y1 + h;
_line_effect.CurrentTechnique.Passes[0].Apply();
_graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionColor[]
{
new VertexPositionColor(new Vector3(x1 + 0.5f, y1 + 0.5f, 0), color),
new VertexPositionColor(new Vector3(x2 + 0.5f, y1 + 0.5f, 0), color),
new VertexPositionColor(new Vector3(x1 + 0.5f, y2 + 0.5f, 0), color),
new VertexPositionColor(new Vector3(x2 + 0.5f, y2 + 0.5f, 0), color),
}, 0, 2);
}
public void DrawLine(float x1, float y1, float x2, float y2, Color color)
{
_line_effect.CurrentTechnique.Passes[0].Apply();
_graphics_device.DrawUserPrimitives(PrimitiveType.LineList, new VertexPositionColor[]
{
new VertexPositionColor(new Vector3(x1 + 0.5f, y1 + 0.5f, 0), color),
new VertexPositionColor(new Vector3(x2 + 0.5f, y2 + 0.5f, 0), color),
}, 0, 1);
}
public delegate void DrawFunction(Engine e);
public void ClearScreen(Color c)
{
_graphics_device.Clear(c);
}
public Effect ScreenEffect;
public void DrawScene(Engine engine, DrawFunction drawScene)
{
// render scene
_graphics_device.SetRenderTarget(_render_target);
_graphics_device.RasterizerState = new RasterizerState()
{
CullMode = CullMode.None
};
_graphics_device.BlendState = BlendState.AlphaBlend;
drawScene(engine);
// draw scene to window
_graphics_device.SetRenderTarget(null);
_sprite_batch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap, null, null, ScreenEffect);
_sprite_batch.Draw(_render_target, new Rectangle(0, 0, _width * ZoomLevel, _height * ZoomLevel), Color.White);
_sprite_batch.End();
}
public Texture2D GetClippedScreenshot(int x, int y, int w, int h)
{
Rectangle clipper = new Rectangle(x, y, w, h);
Texture2D clip = new Texture2D(_graphics_device, w, h);
Color[] data = new Color[w * h];
_render_target.GetData(0, clipper, data, 0, data.Length);
clip.SetData(data);
return clip;
}
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Data;
using Avalonia.Data.Core;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Base class for avalonia properties.
/// </summary>
public abstract class AvaloniaProperty : IEquatable<AvaloniaProperty>, IPropertyInfo
{
/// <summary>
/// Represents an unset property value.
/// </summary>
public static readonly object UnsetValue = new UnsetValueType();
private static int s_nextId;
private readonly PropertyMetadata _defaultMetadata;
private readonly Dictionary<Type, PropertyMetadata> _metadata;
private readonly Dictionary<Type, PropertyMetadata> _metadataCache = new Dictionary<Type, PropertyMetadata>();
private bool _hasMetadataOverrides;
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="valueType">The type of the property's value.</param>
/// <param name="ownerType">The type of the class that registers the property.</param>
/// <param name="metadata">The property metadata.</param>
/// <param name="notifying">A <see cref="Notifying"/> callback.</param>
protected AvaloniaProperty(
string name,
Type valueType,
Type ownerType,
PropertyMetadata metadata,
Action<IAvaloniaObject, bool> notifying = null)
{
Contract.Requires<ArgumentNullException>(name != null);
Contract.Requires<ArgumentNullException>(valueType != null);
Contract.Requires<ArgumentNullException>(ownerType != null);
Contract.Requires<ArgumentNullException>(metadata != null);
if (name.Contains("."))
{
throw new ArgumentException("'name' may not contain periods.");
}
_metadata = new Dictionary<Type, PropertyMetadata>();
Name = name;
PropertyType = valueType;
OwnerType = ownerType;
Notifying = notifying;
Id = s_nextId++;
_metadata.Add(ownerType, metadata);
_defaultMetadata = metadata;
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
/// </summary>
/// <param name="source">The direct property to copy.</param>
/// <param name="ownerType">The new owner type.</param>
/// <param name="metadata">Optional overridden metadata.</param>
protected AvaloniaProperty(
AvaloniaProperty source,
Type ownerType,
PropertyMetadata metadata)
{
Contract.Requires<ArgumentNullException>(source != null);
Contract.Requires<ArgumentNullException>(ownerType != null);
_metadata = new Dictionary<Type, PropertyMetadata>();
Name = source.Name;
PropertyType = source.PropertyType;
OwnerType = ownerType;
Notifying = source.Notifying;
Id = source.Id;
_defaultMetadata = source._defaultMetadata;
// Properties that have different owner can't use fast path for metadata.
_hasMetadataOverrides = true;
if (metadata != null)
{
_metadata.Add(ownerType, metadata);
}
}
/// <summary>
/// Gets the name of the property.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the type of the property's value.
/// </summary>
public Type PropertyType { get; }
/// <summary>
/// Gets the type of the class that registered the property.
/// </summary>
public Type OwnerType { get; }
/// <summary>
/// Gets a value indicating whether the property inherits its value.
/// </summary>
public virtual bool Inherits => false;
/// <summary>
/// Gets a value indicating whether this is an attached property.
/// </summary>
public virtual bool IsAttached => false;
/// <summary>
/// Gets a value indicating whether this is a direct property.
/// </summary>
public virtual bool IsDirect => false;
/// <summary>
/// Gets a value indicating whether this is a readonly property.
/// </summary>
public virtual bool IsReadOnly => false;
/// <summary>
/// Gets an observable that is fired when this property changes on any
/// <see cref="AvaloniaObject"/> instance.
/// </summary>
/// <value>
/// An observable that is fired when this property changes on any
/// <see cref="AvaloniaObject"/> instance.
/// </value>
public IObservable<AvaloniaPropertyChangedEventArgs> Changed => GetChanged();
/// <summary>
/// Gets a method that gets called before and after the property starts being notified on an
/// object.
/// </summary>
/// <remarks>
/// When a property changes, change notifications are sent to all property subscribers;
/// for example via the <see cref="AvaloniaProperty.Changed"/> observable and and the
/// <see cref="AvaloniaObject.PropertyChanged"/> event. If this callback is set for a property,
/// then it will be called before and after these notifications take place. The bool argument
/// will be true before the property change notifications are sent and false afterwards. This
/// callback is intended to support Control.IsDataContextChanging.
/// </remarks>
public Action<IAvaloniaObject, bool> Notifying { get; }
/// <summary>
/// Gets the integer ID that represents this property.
/// </summary>
internal int Id { get; }
/// <summary>
/// Provides access to a property's binding via the <see cref="AvaloniaObject"/>
/// indexer.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
public static IndexerDescriptor operator !(AvaloniaProperty property)
{
return new IndexerDescriptor
{
Priority = BindingPriority.LocalValue,
Property = property,
};
}
/// <summary>
/// Provides access to a property's template binding via the <see cref="AvaloniaObject"/>
/// indexer.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
public static IndexerDescriptor operator ~(AvaloniaProperty property)
{
return new IndexerDescriptor
{
Priority = BindingPriority.TemplatedParent,
Property = property,
};
}
/// <summary>
/// Tests two <see cref="AvaloniaProperty"/>s for equality.
/// </summary>
/// <param name="a">The first property.</param>
/// <param name="b">The second property.</param>
/// <returns>True if the properties are equal, otherwise false.</returns>
public static bool operator ==(AvaloniaProperty a, AvaloniaProperty b)
{
if (object.ReferenceEquals(a, b))
{
return true;
}
else if (((object)a == null) || ((object)b == null))
{
return false;
}
else
{
return a.Equals(b);
}
}
/// <summary>
/// Tests two <see cref="AvaloniaProperty"/>s for inequality.
/// </summary>
/// <param name="a">The first property.</param>
/// <param name="b">The second property.</param>
/// <returns>True if the properties are equal, otherwise false.</returns>
public static bool operator !=(AvaloniaProperty a, AvaloniaProperty b)
{
return !(a == b);
}
/// <summary>
/// Registers a <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
/// <typeparam name="TValue">The type of the property's value.</typeparam>
/// <param name="name">The name of the property.</param>
/// <param name="defaultValue">The default value of the property.</param>
/// <param name="inherits">Whether the property inherits its value.</param>
/// <param name="defaultBindingMode">The default binding mode for the property.</param>
/// <param name="validate">A value validation callback.</param>
/// <param name="coerce">A value coercion callback.</param>
/// <param name="notifying">
/// A method that gets called before and after the property starts being notified on an
/// object; the bool argument will be true before and false afterwards. This callback is
/// intended to support IsDataContextChanging.
/// </param>
/// <returns>A <see cref="StyledProperty{TValue}"/></returns>
public static StyledProperty<TValue> Register<TOwner, TValue>(
string name,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Func<TValue, bool> validate = null,
Func<IAvaloniaObject, TValue, TValue> coerce = null,
Action<IAvaloniaObject, bool> notifying = null)
where TOwner : IAvaloniaObject
{
Contract.Requires<ArgumentNullException>(name != null);
var metadata = new StyledPropertyMetadata<TValue>(
defaultValue,
defaultBindingMode: defaultBindingMode,
coerce: coerce);
var result = new StyledProperty<TValue>(
name,
typeof(TOwner),
metadata,
inherits,
validate,
notifying);
AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
return result;
}
/// <summary>
/// Registers an attached <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
/// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
/// <typeparam name="TValue">The type of the property's value.</typeparam>
/// <param name="name">The name of the property.</param>
/// <param name="defaultValue">The default value of the property.</param>
/// <param name="inherits">Whether the property inherits its value.</param>
/// <param name="defaultBindingMode">The default binding mode for the property.</param>
/// <param name="validate">A value validation callback.</param>
/// <param name="coerce">A value coercion callback.</param>
/// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
public static AttachedProperty<TValue> RegisterAttached<TOwner, THost, TValue>(
string name,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Func<TValue, bool> validate = null,
Func<IAvaloniaObject, TValue, TValue> coerce = null)
where THost : IAvaloniaObject
{
Contract.Requires<ArgumentNullException>(name != null);
var metadata = new StyledPropertyMetadata<TValue>(
defaultValue,
defaultBindingMode: defaultBindingMode,
coerce: coerce);
var result = new AttachedProperty<TValue>(name, typeof(TOwner), metadata, inherits, validate);
var registry = AvaloniaPropertyRegistry.Instance;
registry.Register(typeof(TOwner), result);
registry.RegisterAttached(typeof(THost), result);
return result;
}
/// <summary>
/// Registers an attached <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
/// <typeparam name="TValue">The type of the property's value.</typeparam>
/// <param name="name">The name of the property.</param>
/// <param name="ownerType">The type of the class that is registering the property.</param>
/// <param name="defaultValue">The default value of the property.</param>
/// <param name="inherits">Whether the property inherits its value.</param>
/// <param name="defaultBindingMode">The default binding mode for the property.</param>
/// <param name="validate">A value validation callback.</param>
/// <param name="coerce">A value coercion callback.</param>
/// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
public static AttachedProperty<TValue> RegisterAttached<THost, TValue>(
string name,
Type ownerType,
TValue defaultValue = default(TValue),
bool inherits = false,
BindingMode defaultBindingMode = BindingMode.OneWay,
Func<TValue, bool> validate = null,
Func<IAvaloniaObject, TValue, TValue> coerce = null)
where THost : IAvaloniaObject
{
Contract.Requires<ArgumentNullException>(name != null);
var metadata = new StyledPropertyMetadata<TValue>(
defaultValue,
defaultBindingMode: defaultBindingMode,
coerce: coerce);
var result = new AttachedProperty<TValue>(name, ownerType, metadata, inherits, validate);
var registry = AvaloniaPropertyRegistry.Instance;
registry.Register(ownerType, result);
registry.RegisterAttached(typeof(THost), result);
return result;
}
/// <summary>
/// Registers a direct <see cref="AvaloniaProperty"/>.
/// </summary>
/// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
/// <typeparam name="TValue">The type of the property's value.</typeparam>
/// <param name="name">The name of the property.</param>
/// <param name="getter">Gets the current value of the property.</param>
/// <param name="setter">Sets the value of the property.</param>
/// <param name="unsetValue">The value to use when the property is cleared.</param>
/// <param name="defaultBindingMode">The default binding mode for the property.</param>
/// <param name="enableDataValidation">
/// Whether the property is interested in data validation.
/// </param>
/// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
public static DirectProperty<TOwner, TValue> RegisterDirect<TOwner, TValue>(
string name,
Func<TOwner, TValue> getter,
Action<TOwner, TValue> setter = null,
TValue unsetValue = default(TValue),
BindingMode defaultBindingMode = BindingMode.OneWay,
bool enableDataValidation = false)
where TOwner : IAvaloniaObject
{
Contract.Requires<ArgumentNullException>(name != null);
Contract.Requires<ArgumentNullException>(getter != null);
var metadata = new DirectPropertyMetadata<TValue>(
unsetValue: unsetValue,
defaultBindingMode: defaultBindingMode,
enableDataValidation: enableDataValidation);
var result = new DirectProperty<TOwner, TValue>(
name,
getter,
setter,
metadata);
AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
return result;
}
/// <summary>
/// Returns a binding accessor that can be passed to <see cref="AvaloniaObject"/>'s []
/// operator to initiate a binding.
/// </summary>
/// <returns>A <see cref="IndexerDescriptor"/>.</returns>
/// <remarks>
/// The ! and ~ operators are short forms of this.
/// </remarks>
public IndexerDescriptor Bind()
{
return new IndexerDescriptor
{
Property = this,
};
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
var p = obj as AvaloniaProperty;
return p != null && Equals(p);
}
/// <inheritdoc/>
public bool Equals(AvaloniaProperty other)
{
return other != null && Id == other.Id;
}
/// <inheritdoc/>
public override int GetHashCode()
{
return Id;
}
/// <summary>
/// Gets the property metadata for the specified type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <returns>
/// The property metadata.
/// </returns>
public PropertyMetadata GetMetadata<T>() where T : IAvaloniaObject
{
return GetMetadata(typeof(T));
}
/// <summary>
/// Gets the property metadata for the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The property metadata.
/// </returns>
///
public PropertyMetadata GetMetadata(Type type)
{
if (!_hasMetadataOverrides)
{
return _defaultMetadata;
}
return GetMetadataWithOverrides(type);
}
/// <summary>
/// Checks whether the <paramref name="value"/> is valid for the property.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>True if the value is valid, otherwise false.</returns>
public bool IsValidValue(object value)
{
return TypeUtilities.TryConvertImplicit(PropertyType, value, out value);
}
/// <summary>
/// Gets the string representation of the property.
/// </summary>
/// <returns>The property's string representation.</returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Uses the visitor pattern to resolve an untyped property to a typed property.
/// </summary>
/// <typeparam name="TData">The type of user data passed.</typeparam>
/// <param name="vistor">The visitor which will accept the typed property.</param>
/// <param name="data">The user data to pass.</param>
public abstract void Accept<TData>(IAvaloniaPropertyVisitor<TData> vistor, ref TData data)
where TData : struct;
/// <summary>
/// Routes an untyped ClearValue call to a typed call.
/// </summary>
/// <param name="o">The object instance.</param>
internal abstract void RouteClearValue(IAvaloniaObject o);
/// <summary>
/// Routes an untyped GetValue call to a typed call.
/// </summary>
/// <param name="o">The object instance.</param>
internal abstract object RouteGetValue(IAvaloniaObject o);
/// <summary>
/// Routes an untyped GetBaseValue call to a typed call.
/// </summary>
/// <param name="o">The object instance.</param>
/// <param name="maxPriority">The maximum priority for the value.</param>
internal abstract object RouteGetBaseValue(IAvaloniaObject o, BindingPriority maxPriority);
/// <summary>
/// Routes an untyped SetValue call to a typed call.
/// </summary>
/// <param name="o">The object instance.</param>
/// <param name="value">The value.</param>
/// <param name="priority">The priority.</param>
/// <returns>
/// An <see cref="IDisposable"/> if setting the property can be undone, otherwise null.
/// </returns>
internal abstract IDisposable RouteSetValue(
IAvaloniaObject o,
object value,
BindingPriority priority);
/// <summary>
/// Routes an untyped Bind call to a typed call.
/// </summary>
/// <param name="o">The object instance.</param>
/// <param name="source">The binding source.</param>
/// <param name="priority">The priority.</param>
internal abstract IDisposable RouteBind(
IAvaloniaObject o,
IObservable<BindingValue<object>> source,
BindingPriority priority);
internal abstract void RouteInheritanceParentChanged(AvaloniaObject o, IAvaloniaObject oldParent);
/// <summary>
/// Overrides the metadata for the property on the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="metadata">The metadata.</param>
protected void OverrideMetadata(Type type, PropertyMetadata metadata)
{
Contract.Requires<ArgumentNullException>(type != null);
Contract.Requires<ArgumentNullException>(metadata != null);
if (_metadata.ContainsKey(type))
{
throw new InvalidOperationException(
$"Metadata is already set for {Name} on {type}.");
}
var baseMetadata = GetMetadata(type);
metadata.Merge(baseMetadata, this);
_metadata.Add(type, metadata);
_metadataCache.Clear();
_hasMetadataOverrides = true;
}
protected abstract IObservable<AvaloniaPropertyChangedEventArgs> GetChanged();
private PropertyMetadata GetMetadataWithOverrides(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
{
return result;
}
Type currentType = type;
while (currentType != null)
{
if (_metadata.TryGetValue(currentType, out result))
{
_metadataCache[type] = result;
return result;
}
currentType = currentType.BaseType;
}
_metadataCache[type] = _defaultMetadata;
return _defaultMetadata;
}
bool IPropertyInfo.CanGet => true;
bool IPropertyInfo.CanSet => true;
object IPropertyInfo.Get(object target) => ((AvaloniaObject)target).GetValue(this);
void IPropertyInfo.Set(object target, object value) => ((AvaloniaObject)target).SetValue(this, value);
}
/// <summary>
/// Class representing the <see cref="AvaloniaProperty.UnsetValue"/>.
/// </summary>
public sealed class UnsetValueType
{
internal UnsetValueType() { }
/// <summary>
/// Returns the string representation of the <see cref="AvaloniaProperty.UnsetValue"/>.
/// </summary>
/// <returns>The string "(unset)".</returns>
public override string ToString() => "(unset)";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.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>
/// LogProfilesOperations operations.
/// </summary>
internal partial class LogProfilesOperations : IServiceOperations<MonitorManagementClient>, ILogProfilesOperations
{
/// <summary>
/// Initializes a new instance of the LogProfilesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LogProfilesOperations(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>
/// Deletes the log profile.
/// </summary>
/// <param name='logProfileName'>
/// The name of the log profile.
/// </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 logProfileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (logProfileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName");
}
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("logProfileName", logProfileName);
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}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString();
_url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName));
_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 != 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 the log profile.
/// </summary>
/// <param name='logProfileName'>
/// The name of the log profile.
/// </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<LogProfileResource>> GetWithHttpMessagesAsync(string logProfileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (logProfileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName");
}
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("logProfileName", logProfileName);
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}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString();
_url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName));
_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 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<LogProfileResource>();
_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<LogProfileResource>(_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>
/// Create or update a log profile in Azure Monitoring REST API.
/// </summary>
/// <param name='logProfileName'>
/// The name of the log profile.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LogProfileResource>> CreateOrUpdateWithHttpMessagesAsync(string logProfileName, LogProfileResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (logProfileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName");
}
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("logProfileName", logProfileName);
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}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString();
_url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName));
_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)
{
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<LogProfileResource>();
_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<LogProfileResource>(_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>
/// Updates an existing LogProfilesResource. To update other fields use the
/// CreateOrUpdate method.
/// </summary>
/// <param name='logProfileName'>
/// The name of the log profile.
/// </param>
/// <param name='logProfilesResource'>
/// Parameters supplied to the operation.
/// </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<LogProfileResource>> UpdateWithHttpMessagesAsync(string logProfileName, LogProfileResourcePatch logProfilesResource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (logProfileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "logProfileName");
}
if (logProfilesResource == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "logProfilesResource");
}
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("logProfileName", logProfileName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("logProfilesResource", logProfilesResource);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles/{logProfileName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{logProfileName}", System.Uri.EscapeDataString(logProfileName));
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("PATCH");
_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(logProfilesResource != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(logProfilesResource, 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)
{
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<LogProfileResource>();
_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<LogProfileResource>(_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 log profiles.
/// </summary>
/// <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<LogProfileResource>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
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("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/microsoft.insights/logprofiles").ToString();
_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<LogProfileResource>>();
_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<LogProfileResource>>(_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 UnityEngine;
using System.Collections;
public class Vec3 {
#region Member Variables
private float _x, _y, _z;
#endregion
#region Properties
public float x {
get { return _x; }
set { _x = value; }
}
public float y {
get { return _y; }
set { _y = value; }
}
public float z {
get { return _z; }
set { _z = value; }
}
#endregion
#region Constructors
public Vec3() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vec3(float v) {
this.x = v;
this.y = v;
this.z = v;
}
public Vec3(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vec3(Vec2 vec) {
this.x = vec.x;
this.y = vec.y;
this.z = 0;
}
public Vec3(Vec2 vec, float z) {
this.x = vec.x;
this.y = vec.y;
this.z = z;
}
public Vec3(Vec3 vec) {
this.x = vec.x;
this.y = vec.y;
this.z = vec.z;
}
#endregion
#region Methods
public float Length() {
return Mathf.Sqrt((x * x) + (y * y) + (z * z));
}
public float Length2() {
return (x * x) + (y * y) + (z * z);
}
public Vec3 Normalize() {
float len = Length();
this.x /= len;
this.y /= len;
this.z /= len;
return this;
}
public float Dot(Vec3 vec) {
return (x * vec.x) + (y * vec.y) + (z * vec.z);
}
public Vec3 Cross(Vec3 vec) {
return new Vec3((x * vec.z) - (z * vec.x),
(z * vec.x) - (x * vec.z),
(x * vec.y) - (y * vec.x));
}
public float Distance(Vec3 vec) {
return (vec - this).Length();
}
public float Distance2(Vec3 vec) {
return (vec - this).Length2();
}
public bool Approximately(Vec3 vec) {
return Mathf.Approximately(x, vec.x)
&& Mathf.Approximately(y, vec.y)
&& Mathf.Approximately(z, vec.z);
}
public override bool Equals(object obj) {
Vec3 vec = obj as Vec3;
if (vec == null) {
return false;
}
return this == vec;
}
public override int GetHashCode() {
unchecked
{
int hash = 17;
hash = hash * 23 + x.GetHashCode();
hash = hash * 23 + y.GetHashCode();
hash = hash * 23 + z.GetHashCode();
return hash;
}
}
public override string ToString()
{
return typeof(Vec3).Name + "<x=" + x + ",y=" + y + ",z=" + z + ">";
}
#endregion
#region Operator Overloads
public static Vec3 operator +(Vec3 l, Vec3 r) {
return new Vec3(l.x + r.x, l.y + r.y, l.z + r.z);
}
public static Vec3 operator +(Vector3 l, Vec3 r) {
return new Vec3(l.x + r.x, l.y + r.y, l.z + r.z);
}
public static Vec3 operator +(Vec3 l, Vector3 r) {
return new Vec3(l.x + r.x, l.y + r.y, l.z + r.z);
}
public static Vec3 operator +(Vec3 l, float r) {
return new Vec3(l.x + r, l.y + r, l.z + r);
}
public static Vec3 operator +(float l, Vec3 r) {
return new Vec3(l + r.x, l + r.y, l + r.z);
}
public static Vec3 operator -(Vec3 l, Vec3 r) {
return new Vec3(l.x - r.x, l.y - r.y, l.z - r.z);
}
public static Vec3 operator -(Vector3 l, Vec3 r) {
return new Vec3(l.x - r.x, l.y - r.y, l.z - r.z);
}
public static Vec3 operator -(Vec3 l, Vector3 r) {
return new Vec3(l.x - r.x, l.y - r.y, l.z - r.z);
}
public static Vec3 operator -(Vec3 l, float r) {
return new Vec3(l.x - r, l.y - r, l.z - r);
}
public static Vec3 operator -(float l, Vec3 r) {
return new Vec3(l - r.x, l - r.y, l - r.z);
}
public static Vec3 operator *(Vec3 l, Vec3 r) {
return new Vec3(l.x * r.x, l.y * r.y, l.z * r.z);
}
public static Vec3 operator *(Vector3 l, Vec3 r) {
return new Vec3(l.x * r.x, l.y * r.y, l.z * r.z);
}
public static Vec3 operator *(Vec3 l, Vector3 r) {
return new Vec3(l.x * r.x, l.y * r.y, l.z * r.z);
}
public static Vec3 operator *(Vec3 l, float r) {
return new Vec3(l.x * r, l.y * r, l.z * r);
}
public static Vec3 operator *(float l, Vec3 r) {
return new Vec3(l * r.x, l * r.y, l * r.z);
}
public static Vec3 operator /(Vec3 l, Vec3 r) {
return new Vec3(l.x / r.x, l.y / r.y, l.z / r.z);
}
public static Vec3 operator /(Vector3 l, Vec3 r) {
return new Vec3(l.x / r.x, l.y / r.y, l.z / r.z);
}
public static Vec3 operator /(Vec3 l, Vector3 r) {
return new Vec3(l.x / r.x, l.y / r.y, l.z / r.z);
}
public static Vec3 operator /(Vec3 l, float r) {
return new Vec3(l.x / r, l.y / r, l.z / r);
}
public static Vec3 operator /(float l, Vec3 r) {
return new Vec3(l / r.x, l / r.y, l / r.z);
}
public static bool operator ==(Vec3 l, Vec3 r) {
return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);
}
public static bool operator ==(Vector3 l, Vec3 r) {
return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);
}
public static bool operator ==(Vec3 l, Vector3 r) {
return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);
}
public static bool operator !=(Vec3 l, Vec3 r) {
return (l.x != r.x) || (l.y != r.y) || (l.z != r.z);
}
public static bool operator !=(Vector3 l, Vec3 r) {
return (l.x != r.x) || (l.y != r.y) || (l.z != r.z);
}
public static bool operator !=(Vec3 l, Vector3 r) {
return (l.x != r.x) || (l.y != r.y) || (l.z != r.z);
}
#endregion
#region Conversion Operator Overloads
public static explicit operator Vec3(Vector2 vec) {
return new Vec3(vec.x, vec.y, 0);
}
public static explicit operator Vector2(Vec3 vec) {
return new Vector2(vec.x, vec.y);
}
public static implicit operator Vec3(Vector3 vec) {
return new Vec3(vec.x, vec.y, vec.z);
}
public static implicit operator Vector3(Vec3 vec) {
return new Vector3(vec.x, vec.y, vec.z);
}
public static explicit operator Vec3(Vec2 vec) {
return new Vec3(vec.x, vec.y, 0);
}
public static explicit operator Vec2(Vec3 vec) {
return new Vec2(vec.x, vec.y);
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using NCabinet.Exceptions;
using NCabinet.Inspection;
using NCabinet.Monitor;
using NCabinet.Settings;
using NCabinet.Tools;
namespace NCabinet
{
/// <summary>
/// The core cache manager
/// </summary>
public partial class CacheManager : ICacheManager
{
// Private members
private static readonly object _groupLock = new object();
private static ICacheProvider _cache;
private static bool _monitoringEnabled;
private static MonitorIndex _monitorIndex;
private string Name { get; set; }
private string Description { get; set; }
private string Group { get; set; }
private DateTime? Expiration { get; set; }
private TimeSpan? SlidingExpiration { get; set; }
public static MonitorIndex Monitor
{
get
{
if (_monitoringEnabled == false)
throw new MonitoringNotEnabledException();
return _monitorIndex;
}
}
// Constructors
public CacheManager() { }
public CacheManager(CacheOptions options)
{
if (options == null)
return;
Name = options.Name;
Description = options.Description;
Expiration = options.Expires;
SlidingExpiration = options.KeepAlive;
}
/// <summary>
/// Sets the cache provider for all cache manager instances
/// </summary>
/// <param name="provider">The cache provider to use</param>
internal static void SetProvider(ICacheProvider provider)
{
if (_cache != null)
throw new ExistingProviderException();
_cache = provider;
}
/// <summary>
/// Turns on tracking of cache operations needed for monitoring.
/// </summary>
internal static void EnableMonitoring()
{
_monitoringEnabled = true;
_monitorIndex = new MonitorIndex();
}
/// <summary>
/// Apply settings for all cache manager objects
/// </summary>
/// <param name="action">An action containing the desired setup expressions</param>
public static void Initialize(Action<IInitializationExpression> action)
{
lock (typeof(CacheManager))
{
var expression = new InitializationExpression();
action(expression);
}
}
/// <summary>
/// Returns true if a valid cache provider has been set
/// </summary>
public static bool IsReady
{
get { return _cache != null; }
}
/// <summary>
/// Shorthand for creating a new cache manager object
/// </summary>
/// <param name="options">Cache settings</param>
/// <returns>A new cache manager object</returns>
public static CacheManager Create(CacheOptions options = null)
{
return new CacheManager(options);
}
/// <summary>
/// Sets optional information that will be stored alongside any values returned
/// by the cache manager. This can be used for monitoring.
/// </summary>
/// <param name="name">An optional name of the cache call</param>
/// <param name="description">An optional description of the cache call</param>
/// <returns>A new cache manager with the desired information appended</returns>
public CacheManager Info(string name = null, string description = null)
{
var clone = Clone();
clone.Name = name;
clone.Description = description;
return clone;
}
/// <summary>
/// Tells the cache manager to group any objects that are returned within a
/// named group. This can be used for removing multiple elements in one operation.
/// </summary>
/// <param name="keys">The group identifier</param>
/// <returns>A new cache manager object that will group returned objects</returns>
public CacheManager GroupBy(params string[] keys)
{
var clone = Clone();
clone.Group = KeyBuilder.Build(keys);
return clone;
}
/// <summary>
/// Sets a finite expiration time for the objects returned by the cache manager.
/// </summary>
/// <param name="expiration">The time returned objects will expire</param>
/// <returns>A new cache manager holding the expiration settings</returns>
public CacheManager Expires(DateTime expiration)
{
var clone = Clone();
clone.Expiration = expiration;
return clone;
}
/// <summary>
/// Sets a finite expiration time for the objects returned by the cache manager.
/// </summary>
/// <param name="count">The number of time elements until the object expires</param>
/// <param name="interval">The type of time element used</param>
/// <returns>A new cache manager holding the expiration settings</returns>
public CacheManager Expires(int count, ExpirationInterval interval)
{
DateTime expiration;
switch (interval)
{
case ExpirationInterval.Milliseconds: expiration = DateTime.Now.AddMilliseconds(count); break;
case ExpirationInterval.Seconds: expiration = DateTime.Now.AddSeconds(count); break;
case ExpirationInterval.Minutes: expiration = DateTime.Now.AddMinutes(count); break;
case ExpirationInterval.Hours: expiration = DateTime.Now.AddHours(count); break;
case ExpirationInterval.Days: expiration = DateTime.Now.AddDays(count); break;
default: throw new InvalidExpirationIntervalException();
}
var clone = Clone();
clone.Expiration = expiration;
return clone;
}
/// <summary>
/// Sets a sliding window expiration period. The object will be kept in the cache
/// for as long as it is retrieved again within the timespan provided.
/// </summary>
/// <param name="sliding">The timespan to keep the cached object alive for</param>
/// <returns>A new cache manager holding the keep alive settings</returns>
public CacheManager KeepAlive(TimeSpan sliding)
{
var clone = Clone();
clone.SlidingExpiration = sliding;
return clone;
}
/// <summary>
/// Sets a sliding window expiration period. The object will be kept in the cache
/// for as long as it is retrieved again within the timespan provided.
/// </summary>
/// <param name="count">The number of time elements the object will be kept in cache for</param>
/// <param name="interval">The type of time element used</param>
/// <returns>A new cache manager holding the keep alive settings</returns>
public CacheManager KeepAlive(int count, ExpirationInterval interval)
{
TimeSpan sliding;
switch (interval)
{
case ExpirationInterval.Milliseconds: sliding = new TimeSpan(0, 0, 0, 0, count); break;
case ExpirationInterval.Seconds: sliding = new TimeSpan(0, 0, 0, count, 0); break;
case ExpirationInterval.Minutes: sliding = new TimeSpan(0, 0, count, 0, 0); break;
case ExpirationInterval.Hours: sliding = new TimeSpan(0, count, 0, 0, 0); break;
case ExpirationInterval.Days: sliding = new TimeSpan(count, 0, 0, 0, 0); break;
default: throw new InvalidExpirationIntervalException();
}
var clone = Clone();
clone.SlidingExpiration = sliding;
return clone;
}
/// <summary>
/// Creates a new cache manager object with exactly the same
/// properties as the current one.
/// </summary>
/// <returns></returns>
public CacheManager Clone()
{
return new CacheManager() { Name = Name, Description = Description, Group = Group, Expiration = Expiration, SlidingExpiration = SlidingExpiration };
}
// Wrappers for this with 1-15 arguments are located in the CacheManagerExtensions.cs file
/// <summary>
/// Returns a value from the cache based on the provided arguments and information about the calling method.
/// If the item is not found in the cache it is loaded from the callback provided and added to the cache before
/// being returned to the caller.
/// </summary>
private TOut Get<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut>(Func<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut> callback, TIn1 i1, TIn2 i2, TIn3 i3, TIn4 i4, TIn5 i5, TIn6 i6, TIn7 i7, TIn8 i8, TIn9 i9, TIn10 i10, TIn11 i11, TIn12 i12, TIn13 i13, TIn14 i14, TIn15 i15, TIn16 i16, MethodInfo callerInfo)
{
var n = typeof (NoKey);
var keys = new List<object>();
if (typeof(TIn1) != n) keys.Add(i1);
if (typeof(TIn2) != n) keys.Add(i2);
if (typeof(TIn3) != n) keys.Add(i3);
if (typeof(TIn4) != n) keys.Add(i4);
if (typeof(TIn5) != n) keys.Add(i5);
if (typeof(TIn6) != n) keys.Add(i6);
if (typeof(TIn7) != n) keys.Add(i7);
if (typeof(TIn8) != n) keys.Add(i8);
if (typeof(TIn9) != n) keys.Add(i9);
if (typeof(TIn10) != n) keys.Add(i10);
if (typeof(TIn11) != n) keys.Add(i11);
if (typeof(TIn12) != n) keys.Add(i12);
if (typeof(TIn13) != n) keys.Add(i13);
if (typeof(TIn14) != n) keys.Add(i14);
if (typeof(TIn15) != n) keys.Add(i15);
if (typeof(TIn16) != n) keys.Add(i16);
var type = typeof(TOut);
var caller = CallAnalyzer.GetCallbackInfo(callerInfo);
var key = KeyBuilder.Build(type, caller, keys.ToArray());
var value = _cache.Get(key);
if (value == null)
{
value = callback(i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16);
if (value == null)
return default(TOut);
var cacheItem = new CacheItem();
cacheItem.Value = value;
cacheItem.Key = key;
cacheItem.Namespace = caller.Namespace;
cacheItem.Method = cacheItem.Method;
cacheItem.Name = Name;
cacheItem.Description = Description;
cacheItem.Loaded = DateTime.Now;
_cache.Put(key, cacheItem);
AddToGroup(key);
if (_monitoringEnabled)
_monitorIndex.Add(key, cacheItem);
return (TOut)value;
}
var output = value as CacheItem;
if (output == null)
throw new IllegalCacheItemException();
return output.Value is TOut ? (TOut)output.Value : default(TOut);
}
/// <summary>
/// Returns a value from the cache based on the provided arguments and information about the calling method.
/// If the item is not found in the cache it is loaded from the callback provided and added to the cache before
/// being returned to the caller.
/// </summary>
public T Get<T>(Callback<T> callback, params object[] parameters)
{
var type = typeof(T);
var caller = CallAnalyzer.GetCallerInfo();
var key = KeyBuilder.Build(type, caller, parameters);
var value = _cache.Get(key);
if (value == null)
{
value = callback(parameters);
if (value == null)
return default(T);
var cacheItem = new CacheItem();
cacheItem.Value = value;
cacheItem.Key = key;
cacheItem.Namespace = caller.Namespace;
cacheItem.Method = cacheItem.Method;
cacheItem.Name = Name;
cacheItem.Description = Description;
cacheItem.Loaded = DateTime.Now;
_cache.Put(key, cacheItem);
AddToGroup(key);
if (_monitoringEnabled)
_monitorIndex.Add(key, cacheItem);
return (T)value;
}
var output = value as CacheItem;
if (output == null)
throw new IllegalCacheItemException();
return output.Value is T ? (T)output.Value : default(T);
}
/// <summary>
/// Loads an element from the cache based on the provided arguments
/// </summary>
public T Get<T>(params object[] parameters)
{
var type = typeof(T);
var key = KeyBuilder.Build(type, null, parameters);
var value = _cache.Get(key);
if (value == null)
return default(T);
var output = value as CacheItem;
if (output == null)
throw new IllegalCacheItemException();
return output.Value is T ? (T)output.Value : default(T);
}
/// <summary>
/// Adds an object to the cache. The cache key is generated from the
/// provided key paremeters.
/// </summary>
/// <param name="value">The object to add to cache</param>
/// <param name="parameters">Elements for building the cache key</param>
public void Put(object value, params object[] parameters)
{
if (value == null)
return;
var type = value.GetType();
var caller = CallAnalyzer.GetCallerInfo();
var key = KeyBuilder.Build(type, null, parameters);
var cacheItem = new CacheItem();
cacheItem.Value = value;
cacheItem.Key = key;
cacheItem.Namespace = caller.Namespace;
cacheItem.Method = cacheItem.Method;
cacheItem.Name = Name;
cacheItem.Description = Description;
cacheItem.Loaded = DateTime.Now;
_cache.Put(key, cacheItem);
AddToGroup(key);
if (_monitoringEnabled)
_monitorIndex.Add(key, cacheItem);
}
/// <summary>
/// Adds a cache key to the cache managers group.
/// </summary>
/// <param name="key">The key to group</param>
private void AddToGroup(string key)
{
if (String.IsNullOrEmpty(Group))
return;
lock (_groupLock)
{
var keys = _cache.Get(Group) as List<string> ?? new List<string>();
if (!keys.Contains(key))
keys.Add(key);
_cache.Put(Group, keys);
}
}
// Wrappers for this with 1-15 arguments are located in the CacheManagerExtensions.cs file
/// <summary>
/// Removes an item from the cache based on the exact arguments that were used to get it in the first place.
/// </summary>
private void Remove<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut>(Func<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut> callback, TIn1 i1, TIn2 i2, TIn3 i3, TIn4 i4, TIn5 i5, TIn6 i6, TIn7 i7, TIn8 i8, TIn9 i9, TIn10 i10, TIn11 i11, TIn12 i12, TIn13 i13, TIn14 i14, TIn15 i15, TIn16 i16, MethodInfo callerInfo)
{
var n = typeof(NoKey);
var keys = new List<object>();
if (typeof(TIn1) != n) keys.Add(i1);
if (typeof(TIn2) != n) keys.Add(i2);
if (typeof(TIn3) != n) keys.Add(i3);
if (typeof(TIn4) != n) keys.Add(i4);
if (typeof(TIn5) != n) keys.Add(i5);
if (typeof(TIn6) != n) keys.Add(i6);
if (typeof(TIn7) != n) keys.Add(i7);
if (typeof(TIn8) != n) keys.Add(i8);
if (typeof(TIn9) != n) keys.Add(i9);
if (typeof(TIn10) != n) keys.Add(i10);
if (typeof(TIn11) != n) keys.Add(i11);
if (typeof(TIn12) != n) keys.Add(i12);
if (typeof(TIn13) != n) keys.Add(i13);
if (typeof(TIn14) != n) keys.Add(i14);
if (typeof(TIn15) != n) keys.Add(i15);
if (typeof(TIn16) != n) keys.Add(i16);
var type = typeof (TOut);
var caller = CallAnalyzer.GetCallbackInfo(callerInfo);
var key = KeyBuilder.Build(type, caller, keys.ToArray());
_cache.Remove(key);
if (_monitoringEnabled)
_monitorIndex.Remove(key);
}
/// <summary>
/// Removes an item from cache
/// </summary>
/// <typeparam name="T">The type of the item</typeparam>
/// <param name="callback">The callback used for getting the item</param>
/// <param name="parameters">The parameters provided when getting the item</param>
public void Remove<T>(Callback<T> callback, params object[] parameters)
{
var type = typeof(T);
var caller = CallAnalyzer.GetCallerInfo();
var key = KeyBuilder.Build(type, caller, parameters);
_cache.Remove(key);
if (_monitoringEnabled)
_monitorIndex.Remove(key);
}
/// <summary>
/// Removes an element from the cache based on the provided key elements.
/// </summary>
/// <param name="parameters">The elements used to build the key.</param>
public void Remove<T>(params object[] parameters)
{
var type = typeof(T);
var key = KeyBuilder.Build(type, null, parameters);
_cache.Remove(key);
if (_monitoringEnabled)
_monitorIndex.Remove(key);
}
/// <summary>
/// Iterates through all cache items belonging to a group and removes each of them.
/// </summary>
/// <param name="keys">The group identifier</param>
public void RemoveGroup(params string[] keys)
{
var key = KeyBuilder.Build(keys);
lock (_groupLock)
{
var removable = _cache.Get(key) as List<string>;
if (removable == null)
return;
foreach (var remove in removable)
{
_cache.Remove(remove);
if (_monitoringEnabled)
_monitorIndex.Remove(remove);
}
}
}
/// <summary>
/// Checks if an item exists in the cache
/// </summary>
/// <typeparam name="T">The type of the item</typeparam>
/// <param name="parameters">The keys identifying the item</param>
/// <returns>True if the item exists</returns>
public bool Exists<T>(params object[] parameters)
{
var type = typeof(T);
var key = KeyBuilder.Build(type, null, parameters);
return _cache.Exists(key);
}
/// <summary>
/// Checks if an item exists in the cache
/// </summary>
/// <typeparam name="T">The type of the item</typeparam>
/// <param name="callback">The callback used for getting the item</param>
/// <param name="parameters">The parameters provided for getting the item</param>
/// <returns>True if the item exists</returns>
public bool Exists<T>(Callback<T> callback, params object[] parameters)
{
var type = typeof(T);
var caller = CallAnalyzer.GetCallerInfo();
var key = KeyBuilder.Build(type, caller, parameters);
return _cache.Exists(key);
}
/// <summary>
/// Checks if an item exists in cache
/// </summary>
/// <returns>True if the item exists</returns>
private bool Exists<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut>(Func<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TIn7, TIn8, TIn9, TIn10, TIn11, TIn12, TIn13, TIn14, TIn15, TIn16, TOut> callback, TIn1 i1, TIn2 i2, TIn3 i3, TIn4 i4, TIn5 i5, TIn6 i6, TIn7 i7, TIn8 i8, TIn9 i9, TIn10 i10, TIn11 i11, TIn12 i12, TIn13 i13, TIn14 i14, TIn15 i15, TIn16 i16, MethodInfo callerInfo)
{
var n = typeof(NoKey);
var keys = new List<object>();
if (typeof(TIn1) != n) keys.Add(i1);
if (typeof(TIn2) != n) keys.Add(i2);
if (typeof(TIn3) != n) keys.Add(i3);
if (typeof(TIn4) != n) keys.Add(i4);
if (typeof(TIn5) != n) keys.Add(i5);
if (typeof(TIn6) != n) keys.Add(i6);
if (typeof(TIn7) != n) keys.Add(i7);
if (typeof(TIn8) != n) keys.Add(i8);
if (typeof(TIn9) != n) keys.Add(i9);
if (typeof(TIn10) != n) keys.Add(i10);
if (typeof(TIn11) != n) keys.Add(i11);
if (typeof(TIn12) != n) keys.Add(i12);
if (typeof(TIn13) != n) keys.Add(i13);
if (typeof(TIn14) != n) keys.Add(i14);
if (typeof(TIn15) != n) keys.Add(i15);
if (typeof(TIn16) != n) keys.Add(i16);
var type = typeof(TOut);
var caller = CallAnalyzer.GetCallbackInfo(callerInfo);
var key = KeyBuilder.Build(type, caller, keys.ToArray());
return _cache.Exists(key);
}
/// <summary>
/// Removes everything from cache
/// </summary>
public void Flush()
{
_cache.Flush();
if (_monitoringEnabled)
_monitorIndex.Flush();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
#endregion
namespace VectorRumble
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
/// <remarks>Based on a class in the Game State Management sample.</remarks>
public abstract class GameScreen
{
#region Properties
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup = false;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 255 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public byte TransitionAlpha
{
get { return (byte)(255 - TransitionPosition * 255); }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
bool isExiting = false;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
ScreenManager screenManager;
#endregion
#region Initialization
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is going away to die, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if ((transitionPosition <= 0) || (transitionPosition >= 1))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputState input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime) { }
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
#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.
/******************************************************************************
* 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 TestNotZAndNotCInt32()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanTwoComparisonOpTest__TestNotZAndNotCInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int32);
private const int Op2ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private BooleanTwoComparisonOpTest__DataTable<Int32, Int32> _dataTable;
static BooleanTwoComparisonOpTest__TestNotZAndNotCInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestNotZAndNotCInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<Int32, Int32>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt32();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "")
{
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));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiContrib.Formatting.Xlsx.Sample.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*****************************************************************************
*
* Copyright(c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution.If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com.By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
****************************************************************************/
/*****************************************************************************
* XSharp.BV
* Based on IronStudio/IronPythonTools/IronPythonTools/Navigation
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using Microsoft.VisualStudio.Shell;
namespace XSharp.LanguageService
{
internal class HierarchyEventArgs : EventArgs
{
private uint itemId;
private string fileName;
private IVsTextLines buffer;
public HierarchyEventArgs(uint itemId, string canonicalName)
{
this.itemId = itemId;
this.fileName = canonicalName;
}
/// <summary>
/// Fullpath of the FileName associated with the ItemId
/// </summary>
public string CanonicalName
{
get { return fileName; }
}
/// <summary>
/// Unique Id of the Item (File) in the Hierarchy it belongs to
/// </summary>
public uint ItemID
{
get { return itemId; }
}
public IVsTextLines TextBuffer
{
get { return buffer; }
set { buffer = value; }
}
}
internal class HierarchyListener : IVsHierarchyEvents, IDisposable
{
private IVsHierarchy hierarchy;
private uint cookie;
public HierarchyListener(IVsHierarchy hierarchy)
{
if (null == hierarchy)
{
throw new ArgumentNullException("The hierarchy to listen cannot be null");
}
this.hierarchy = hierarchy;
}
#region Public Methods
public bool IsListening
{
get { return (0 != cookie); }
}
public void StartListening()
{
// The listener has already been registered in the Hierachy eventHandler list
if (0 != cookie)
{
return;
}
// Register to receive any event that append to the hierarchy
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (hierarchy != null)
{
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
hierarchy.AdviseHierarchyEvents(this, out cookie));
}
});
//
//if (doInitialScan)
{
InternalScanHierarchy(VSConstants.VSITEMID_ROOT);
}
}
public void StopListening()
{
InternalStopListening(true);
}
#endregion
#region IDisposable Members
public void Dispose()
{
InternalStopListening(false);
cookie = 0;
hierarchy = null;
}
#endregion
#region Public Events
private EventHandler<HierarchyEventArgs> onItemAdded;
public event EventHandler<HierarchyEventArgs> OnAddItem
{
add { onItemAdded += value; }
remove { onItemAdded -= value; }
}
private EventHandler<HierarchyEventArgs> onItemDeleted;
public event EventHandler<HierarchyEventArgs> OnDeleteItem
{
add { onItemDeleted += value; }
remove { onItemDeleted -= value; }
}
#endregion
#region IVsHierarchyEvents Members
public int OnInvalidateIcon(IntPtr hicon)
{
// Do Nothing.
return VSConstants.S_OK;
}
public int OnInvalidateItems(uint itemidParent)
{
// TODO: Find out if this event is needed.
Debug.WriteLine("--> OnInvalidateItems");
return VSConstants.S_OK;
}
public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded)
{
// Check if the item is a PRG file.
Debug.WriteLine("--> OnItemAdded");
string name = getItemName(itemidAdded);
// if (!IsPrgFile(itemidAdded, out name))
//{
// return VSConstants.S_OK;
//}
// This item is a PRG file, so we can notify that it is added to the hierarchy.
if (null != onItemAdded)
{
HierarchyEventArgs args = new HierarchyEventArgs(itemidAdded, name);
onItemAdded(hierarchy, args);
}
return VSConstants.S_OK;
}
public int OnItemDeleted(uint itemid)
{
Debug.WriteLine("--> OnItemDeleted");
// Notify that the item is deleted only if it is a PRG file.
string name = getItemName(itemid);
//if (! IsPrgFile(itemid, out name))
//{
// return VSConstants.S_OK;
//}
if (null != onItemDeleted)
{
HierarchyEventArgs args = new HierarchyEventArgs(itemid, name);
onItemDeleted(hierarchy, args);
}
return VSConstants.S_OK;
}
public int OnItemsAppended(uint itemidParent)
{
// TODO: Find out what this event is about.
Debug.WriteLine("--> OnItemsAppended");
return VSConstants.S_OK;
}
public int OnPropertyChanged(uint itemid, int propid, uint flags)
{
// Do Nothing.
return VSConstants.S_OK;
}
#endregion
private bool InternalStopListening(bool throwOnError)
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if ((null == hierarchy) || (0 == cookie))
{
return false;
}
int hr = hierarchy.UnadviseHierarchyEvents(cookie);
if (throwOnError)
{
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr);
}
cookie = 0;
return Microsoft.VisualStudio.ErrorHandler.Succeeded(hr);
});
}
/// <summary>
/// Based in ItemId, check if the item is a file.
/// Then check if it ends with ".prg"
/// Retrieve its FullName
/// </summary>
/// <param name="itemId"></param>
/// <param name="canonicalName"></param>
/// <returns></returns>
private bool IsPrgFile(uint itemId, out string canonicalName)
{
// Find out if this item is a physical file.
canonicalName = getItemName(itemId);
string extension = System.IO.Path.GetExtension(canonicalName);
return (0 == string.Compare(extension, ".prg", StringComparison.OrdinalIgnoreCase));
}
private string getItemName(uint itemId)
{
Guid typeGuid = Guid.Empty;
int hr = VSConstants.S_OK;
try
{
if (hierarchy == null)
return string.Empty;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
hr = hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid);
});
}
catch (System.Runtime.InteropServices.COMException)
{
//For WPF Projects, they will throw an exception when trying to access this property if the
//guid is empty. These are caught and ignored here.
}
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) ||
VSConstants.GUID_ItemType_PhysicalFile != typeGuid)
{
// It is not a file, we can exit now.
return string.Empty;
}
//hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_Name, out var name);
// This item is a file; find if it is a PRG file.
string canonicalName = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
hr = hierarchy.GetCanonicalName(itemId, out canonicalName);
});
return canonicalName;
}
/// <summary>
/// Do a recursive walk on the hierarchy to find all the PRG files in it.
/// It will generate an event for every file found.
/// </summary>
private void InternalScanHierarchy(uint itemId)
{
uint currentItem = itemId;
while (VSConstants.VSITEMID_NIL != currentItem)
{
// If this item is a PRG file, then send the add item event.
string itemName = getItemName(itemId);
// IsPrgFile(currentItem, out itemName);
if ((null != onItemAdded) && ! string.IsNullOrEmpty(itemName))
{
HierarchyEventArgs args = new HierarchyEventArgs(currentItem, itemName);
onItemAdded(hierarchy, args);
}
// NOTE: At the moment we skip the nested hierarchies, so here we look for the
// children of this node.
// Before looking at the children we have to make sure that the enumeration has not
// side effects to avoid unexpected behavior.
bool canScanSubitems = true;
int hr = 0;
object propertyValue = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
hr = hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_HasEnumerationSideEffects, out propertyValue);
});
if (VSConstants.S_OK == hr && propertyValue is bool ok)
{
canScanSubitems = !ok;
}
// If it is allow to look at the sub-items of the current one, lets do it.
if (canScanSubitems)
{
object child = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
hr = hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_FirstChild, out child);
});
if (VSConstants.S_OK == hr)
{
// There is a sub-item, call this same function on it.
InternalScanHierarchy(GetItemId(child));
}
}
// Move the current item to its first visible sibling.
object sibling = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (hierarchy != null)
hr = hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_NextSibling, out sibling);
});
if (VSConstants.S_OK != hr)
{
currentItem = VSConstants.VSITEMID_NIL;
}
else
{
currentItem = GetItemId(sibling);
}
}
}
/// <summary>
/// Gets the item id.
/// </summary>
/// <param name="variantValue">VARIANT holding an itemid.</param>
/// <returns>Item Id of the concerned node</returns>
private static uint GetItemId(object variantValue)
{
if (variantValue == null) return VSConstants.VSITEMID_NIL;
if (variantValue is int) return (uint)(int)variantValue;
if (variantValue is uint) return (uint)variantValue;
if (variantValue is short) return (uint)(short)variantValue;
if (variantValue is ushort) return (uint)(ushort)variantValue;
if (variantValue is long) return (uint)(long)variantValue;
return VSConstants.VSITEMID_NIL;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
** PURPOSE: Helpers for XML input & output
**
===========================================================*/
namespace System.Security.Util {
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using PermissionState = System.Security.Permissions.PermissionState;
using BindingFlags = System.Reflection.BindingFlags;
using Assembly = System.Reflection.Assembly;
using System.Threading;
using System.Globalization;
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.Contracts;
internal static class XMLUtil
{
//
// Warning: Element constructors have side-effects on their
// third argument.
//
private const String BuiltInPermission = "System.Security.Permissions.";
public static SecurityElement
NewPermissionElement (IPermission ip)
{
return NewPermissionElement (ip.GetType ().FullName) ;
}
public static SecurityElement
NewPermissionElement (String name)
{
SecurityElement ecr = new SecurityElement( "Permission" );
ecr.AddAttribute( "class", name );
return ecr;
}
public static void
AddClassAttribute( SecurityElement element, Type type, String typename )
{
// Replace any quotes with apostrophes so that we can include quoted materials
// within classnames. Notably the assembly name member 'loc' uses a quoted string.
// NOTE: this makes assumptions as to what reflection is expecting for a type string
// it will need to be updated if reflection changes what it wants.
if ( typename == null )
typename = type.FullName;
Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) );
}
internal static bool ParseElementForAssemblyIdentification(SecurityElement el,
out String className,
out String assemblyName, // for example "WindowsBase"
out String assemblyVersion)
{
className = null;
assemblyName = null;
assemblyVersion = null;
String fullClassName = el.Attribute( "class" );
if (fullClassName == null)
{
return false;
}
if (fullClassName.IndexOf('\'') >= 0)
{
fullClassName = fullClassName.Replace( '\'', '\"' );
}
int commaIndex = fullClassName.IndexOf( ',' );
int namespaceClassNameLength;
// If the classname is tagged with assembly information, find where
// the assembly information begins.
if (commaIndex == -1)
{
return false;
}
namespaceClassNameLength = commaIndex;
className = fullClassName.Substring(0, namespaceClassNameLength);
String assemblyFullName = fullClassName.Substring(commaIndex + 1);
AssemblyName an = new AssemblyName(assemblyFullName);
assemblyName = an.Name;
assemblyVersion = an.Version.ToString();
return true;
}
private static bool
ParseElementForObjectCreation( SecurityElement el,
String requiredNamespace,
out String className,
out int classNameStart,
out int classNameLength )
{
className = null;
classNameStart = 0;
classNameLength = 0;
int requiredNamespaceLength = requiredNamespace.Length;
String fullClassName = el.Attribute( "class" );
if (fullClassName == null)
{
throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) );
}
if (fullClassName.IndexOf('\'') >= 0)
{
fullClassName = fullClassName.Replace( '\'', '\"' );
}
if (!PermissionToken.IsMscorlibClassName( fullClassName ))
{
return false;
}
int commaIndex = fullClassName.IndexOf( ',' );
int namespaceClassNameLength;
// If the classname is tagged with assembly information, find where
// the assembly information begins.
if (commaIndex == -1)
{
namespaceClassNameLength = fullClassName.Length;
}
else
{
namespaceClassNameLength = commaIndex;
}
// Only if the length of the class name is greater than the namespace info
// on our requiredNamespace do we continue
// with our check.
if (namespaceClassNameLength > requiredNamespaceLength)
{
// Make sure we are in the required namespace.
if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal))
{
className = fullClassName;
classNameLength = namespaceClassNameLength - requiredNamespaceLength;
classNameStart = requiredNamespaceLength;
return true;
}
}
return false;
}
public static IPermission
CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures)
{
if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) )
throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ;
Contract.EndContractBlock();
String className;
int classNameLength;
int classNameStart;
if (!ParseElementForObjectCreation( el,
BuiltInPermission,
out className,
out classNameStart,
out classNameLength ))
{
goto USEREFLECTION;
}
// We have a built in permission, figure out which it is.
// UIPermission
// FileIOPermission
// SecurityPermission
// PrincipalPermission
// ReflectionPermission
// FileDialogPermission
// EnvironmentPermission
// GacIdentityPermission
// UrlIdentityPermission
// SiteIdentityPermission
// ZoneIdentityPermission
// KeyContainerPermission
// UnsafeForHostPermission
// HostProtectionPermission
// StrongNameIdentityPermission
// RegistryPermission
// PublisherIdentityPermission
switch (classNameLength)
{
case 12:
// UIPermission
if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UIPermission( permState );
else
goto USEREFLECTION;
case 16:
// FileIOPermission
if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FileIOPermission( permState );
else
goto USEREFLECTION;
case 18:
// RegistryPermission
// SecurityPermission
if (className[classNameStart] == 'R')
{
if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new RegistryPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new SecurityPermission( permState );
else
goto USEREFLECTION;
}
case 20:
// ReflectionPermission
// FileDialogPermission
if (className[classNameStart] == 'R')
{
if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ReflectionPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new FileDialogPermission( permState );
else
goto USEREFLECTION;
}
case 21:
// EnvironmentPermission
// UrlIdentityPermission
// GacIdentityPermission
if (className[classNameStart] == 'E')
{
if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new EnvironmentPermission( permState );
else
goto USEREFLECTION;
}
else if (className[classNameStart] == 'U')
{
if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new UrlIdentityPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new GacIdentityPermission( permState );
else
goto USEREFLECTION;
}
case 22:
// SiteIdentityPermission
// ZoneIdentityPermission
// KeyContainerPermission
if (className[classNameStart] == 'S')
{
if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new SiteIdentityPermission( permState );
else
goto USEREFLECTION;
}
else if (className[classNameStart] == 'Z')
{
if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new ZoneIdentityPermission( permState );
else
goto USEREFLECTION;
}
else
{
if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new KeyContainerPermission( permState );
else
goto USEREFLECTION;
}
case 24:
// HostProtectionPermission
if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new HostProtectionPermission( permState );
else
goto USEREFLECTION;
case 28:
// StrongNameIdentityPermission
if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new StrongNameIdentityPermission( permState );
else
goto USEREFLECTION;
default:
goto USEREFLECTION;
}
USEREFLECTION:
Object[] objs = new Object[1];
objs[0] = permState;
Type permClass = null;
IPermission perm = null;
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
permClass = GetClassFromElement(el, ignoreTypeLoadFailures);
if (permClass == null)
return null;
if (!(typeof(IPermission).IsAssignableFrom(permClass)))
throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") );
perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null );
return perm;
}
internal static Type
GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures)
{
String className = el.Attribute( "class" );
if (className == null)
{
if (ignoreTypeLoadFailures)
return null;
else
throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") );
}
if (ignoreTypeLoadFailures)
{
try
{
return Type.GetType(className, false, false);
}
catch (SecurityException)
{
return null;
}
}
else
return Type.GetType(className, true, false);
}
public static bool
IsPermissionElement (IPermission ip,
SecurityElement el)
{
if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission"))
return false;
return true;
}
public static bool
IsUnrestricted (SecurityElement el)
{
String sUnrestricted = el.Attribute( "Unrestricted" );
if (sUnrestricted == null)
return false;
return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" );
}
public static String BitFieldEnumToString( Type type, Object value )
{
int iValue = (int)value;
if (iValue == 0)
return Enum.GetName( type, 0 );
StringBuilder result = StringBuilderCache.Acquire();
bool first = true;
int flag = 0x1;
for (int i = 1; i < 32; ++i)
{
if ((flag & iValue) != 0)
{
String sFlag = Enum.GetName( type, flag );
if (sFlag == null)
continue;
if (!first)
{
result.Append( ", " );
}
result.Append( sFlag );
first = false;
}
flag = flag << 1;
}
return StringBuilderCache.GetStringAndRelease(result);
}
}
}
| |
// 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.Globalization;
using System.Reflection;
using Gallio.Common.Collections;
using System.Security;
/*
* This compilation unit contains MethodBase overrides that must be duplicated for each
* of the unresolved reflection types because C# does not support multiple inheritance.
*/
#if DOTNET40
namespace Gallio.Common.Reflection.Impl.DotNet40
#else
namespace Gallio.Common.Reflection.Impl.DotNet20
#endif
{
internal static class UnresolvedMethodBase
{
public static ParameterInfo[] ResolveParameters(IList<IParameterInfo> parameters)
{
return GenericCollectionUtils.ConvertAllToArray<IParameterInfo, ParameterInfo>(parameters,
delegate(IParameterInfo parameter) { return parameter.Resolve(false); });
}
}
internal partial class UnresolvedConstructorInfo
{
public override MethodAttributes Attributes
{
get { return adapter.MethodAttributes; }
}
public override CallingConventions CallingConvention
{
get { return CallingConventions.Any; }
}
public override bool ContainsGenericParameters
{
get { return false; }
}
public override bool IsGenericMethod
{
get { return false; }
}
public override bool IsGenericMethodDefinition
{
get { return false; }
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotSupportedException("Cannot get method handle of unresolved constructor."); }
}
public override Type[] GetGenericArguments()
{
return Type.EmptyTypes;
}
#if DOTNET40
[SecuritySafeCritical]
#endif
public override MethodBody GetMethodBody()
{
throw new NotSupportedException("Cannot get method body of unresolved constructor.");
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return MethodImplAttributes.ForwardRef;
}
public override ParameterInfo[] GetParameters()
{
return UnresolvedMethodBase.ResolveParameters(adapter.Parameters);
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters,
CultureInfo culture)
{
throw new NotSupportedException("Cannot invoke unresolved constructor.");
}
#region .Net 4.0 Only
#if DOTNET40
public override bool IsSecurityCritical
{
get { return false; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
#endif
#endregion
}
internal partial class UnresolvedMethodInfo
{
public override MethodAttributes Attributes
{
get { return adapter.MethodAttributes; }
}
public override CallingConventions CallingConvention
{
get { return CallingConventions.Any; }
}
public override bool ContainsGenericParameters
{
get { return adapter.ContainsGenericParameters; }
}
public override bool IsGenericMethod
{
get { return adapter.IsGenericMethod; }
}
public override bool IsGenericMethodDefinition
{
get { return adapter.IsGenericMethodDefinition; }
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotSupportedException("Cannot get method handle of unresolved method."); }
}
public override Type[] GetGenericArguments()
{
return GenericCollectionUtils.ConvertAllToArray<ITypeInfo, Type>(adapter.GenericArguments,
delegate(ITypeInfo parameter) { return parameter.Resolve(false); });
}
#if DOTNET40
[SecuritySafeCritical]
#endif
public override MethodBody GetMethodBody()
{
throw new NotSupportedException("Cannot get method body of unresolved method.");
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return MethodImplAttributes.ForwardRef;
}
public override ParameterInfo[] GetParameters()
{
return UnresolvedMethodBase.ResolveParameters(adapter.Parameters);
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters,
CultureInfo culture)
{
throw new NotSupportedException("Cannot invoke unresolved method.");
}
#region .Net 4.0 Only
#if DOTNET40
public override bool IsSecurityCritical
{
get { return false; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Azure.Messaging.ServiceBus.Tests.Sender
{
public class SenderLiveTests : ServiceBusLiveTestBase
{
[Test]
public async Task SendConnStringWithSharedKey()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendConnStringWithSignature()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions();
var audience = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName);
var connectionString = TestEnvironment.BuildConnectionStringWithSharedAccessSignature(scope.QueueName, audience);
await using var sender = new ServiceBusClient(connectionString, options).CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendToken()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential);
var sender = client.CreateSender(scope.QueueName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendConnectionTopic()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
[Test]
public async Task SendTopicSession()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage("sessionId"));
}
}
[Test]
public async Task CanSendAMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
ServiceBusMessageBatch messageBatch = ServiceBusTestUtilities.AddMessages(batch, 3);
await sender.SendMessagesAsync(messageBatch);
}
}
[Test]
public async Task SendingEmptyBatchDoesNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CanSendAnEmptyBodyMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
batch.TryAddMessage(new ServiceBusMessage(Array.Empty<byte>()));
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CannotSendLargerThanMaximumSize()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch.
ServiceBusMessage message = new ServiceBusMessage(new byte[batch.MaxSizeInBytes + 10]);
Assert.That(async () => await sender.SendMessageAsync(message), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessageSizeExceeded));
}
}
[Test]
public async Task TryAddReturnsFalseIfSizeExceed()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch. Because this will be used for the
// message body, leave some padding for the conversion and batch envelope.
var padding = 500;
var size = (batch.MaxSizeInBytes - padding);
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[size])), Is.True, "A message was rejected by the batch; all messages should be accepted.");
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[padding + 1])), Is.False, "A message was rejected by the batch; message size exceed.");
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task ClientProperties()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.AreEqual(scope.QueueName, sender.EntityPath);
Assert.AreEqual(TestEnvironment.FullyQualifiedNamespace, sender.FullyQualifiedNamespace);
}
}
[Test]
public async Task Schedule()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var seq = await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
Assert.AreEqual(ServiceBusMessageState.Scheduled, msg.State);
await sender.CancelScheduledMessageAsync(seq);
msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
}
[Test]
public async Task ScheduleMultipleArray()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
Assert.AreEqual(ServiceBusMessageState.Scheduled, msg.State);
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: sequenceNums);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty array
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Array.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleList()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
Assert.AreEqual(ServiceBusMessageState.Scheduled, msg.State);
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>(sequenceNums));
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty list
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleEnumerable()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
Assert.AreEqual(ServiceBusMessageState.Scheduled, msg.State);
}
// use an enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: GetEnumerable());
IEnumerable<long> GetEnumerable()
{
foreach (long seq in sequenceNums)
{
yield return seq;
}
}
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Enumerable.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task CloseSenderShouldNotCloseConnection()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNum = await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), scheduleTime);
await sender.DisposeAsync(); // shouldn't close connection, but should close send link
Assert.That(async () => await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage()), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.ScheduleMessageAsync(ServiceBusTestUtilities.GetMessage(), default), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.CancelScheduledMessageAsync(sequenceNum), Throws.InstanceOf<ObjectDisposedException>());
// receive should still work
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(sequenceNum);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
}
[Test]
public async Task CreateSenderWithoutParentReference()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
}
}
}
[Test]
public async Task SendSessionMessageToNonSessionfulEntityShouldNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
// this is apparently supported. The session is ignored by the service but can be used
// as additional app data. Not recommended.
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage("sessionId"));
var receiver = client.CreateReceiver(scope.QueueName);
var msg = await receiver.ReceiveMessageAsync();
Assert.AreEqual("sessionId", msg.SessionId);
}
}
[Test]
public async Task SendNonSessionMessageToSessionfulEntityShouldThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.That(
async () => await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage()),
Throws.InstanceOf<InvalidOperationException>());
}
}
[Test]
public async Task CanSendReceivedMessage()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var client = new ServiceBusClient(
TestEnvironment.FullyQualifiedNamespace,
TestEnvironment.Credential);
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
var messageCt = 10;
IEnumerable<ServiceBusMessage> messages = ServiceBusTestUtilities.GetMessages(messageCt);
await sender.SendMessagesAsync(messages);
var receiver = client.CreateReceiver(scope.QueueName, new ServiceBusReceiverOptions()
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
});
var remainingMessages = messageCt;
IList<ServiceBusReceivedMessage> receivedMessages = new List<ServiceBusReceivedMessage>();
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(messageCt))
{
remainingMessages--;
receivedMessages.Add(msg);
}
}
foreach (ServiceBusReceivedMessage msg in receivedMessages)
{
await sender.SendMessageAsync(new ServiceBusMessage(msg));
}
var messageEnum = receivedMessages.GetEnumerator();
remainingMessages = messageCt;
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(remainingMessages))
{
remainingMessages--;
messageEnum.MoveNext();
Assert.AreEqual(messageEnum.Current.MessageId, msg.MessageId);
}
}
Assert.AreEqual(0, remainingMessages);
}
}
[Test]
public async Task CreateBatchThrowsIftheEntityDoesNotExist()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var connectionString = TestEnvironment.BuildConnectionStringForEntity("FakeEntity");
await using var client = new ServiceBusClient(connectionString);
ServiceBusSender sender = client.CreateSender("FakeEntity");
Assert.That(async () => await sender.CreateMessageBatchAsync(), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));
}
}
[Test]
public async Task CreateBatchReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
using var batch = await sender.CreateMessageBatchAsync();
// Close the client and attempt to create another batch.
await client.DisposeAsync();
Assert.That(async () => await sender.CreateMessageBatchAsync(),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task SendMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
using var batch = ServiceBusTestUtilities.AddMessages((await sender.CreateMessageBatchAsync()), 5);
await sender.SendMessagesAsync(batch);
// Close the client and attempt to send another message batch.
using var anotherBatch = ServiceBusTestUtilities.AddMessages((await sender.CreateMessageBatchAsync()), 5);
await client.DisposeAsync();
Assert.That(async () => await sender.SendMessagesAsync(anotherBatch),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task ScheduleMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
// Close the client and attempt to schedule another set of messages.
await client.DisposeAsync();
Assert.That(async () => await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task CancelScheduledMessagesReactsToClosingTheClient()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var sequenceNumbers = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await sender.CancelScheduledMessagesAsync(sequenceNumbers);
// Close the client and attempt to cancel another set of scheduled messages.
sequenceNumbers = await sender.ScheduleMessagesAsync(ServiceBusTestUtilities.GetMessages(5), scheduleTime);
await client.DisposeAsync();
Assert.That(async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers),
Throws.InstanceOf<ObjectDisposedException>().And.Property(nameof(ObjectDisposedException.ObjectName)).EqualTo(nameof(ServiceBusConnection)));
}
}
[Test]
public async Task CancellingSendDoesNotBlockSubsequentSends()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(20));
Assert.That(
async () => await sender.SendMessagesAsync(ServiceBusTestUtilities.GetMessages(300), cancellationTokenSource.Token),
Throws.InstanceOf<TaskCanceledException>());
var start = DateTime.UtcNow;
await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
var end = DateTime.UtcNow;
Assert.Less(end - start, TimeSpan.FromSeconds(5));
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/17/2009 3:33:10 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections.Generic;
using System.Drawing;
namespace DotSpatial.Controls
{
public class SoutherlandHodgman
{
const int BOUND_RIGHT = 0;
const int BOUND_TOP = 1;
const int BOUND_LEFT = 2;
const int BOUND_BOTTOM = 3;
const int X = 0;
const int Y = 1;
Rectangle _drawingBounds = new Rectangle(-32000, -32000, 64000, 64000);
/// <summary>
/// Create SoutherlandHodgman polygon clipper with clipping rectangle
/// </summary>
/// <param name="clipRect"></param>
public SoutherlandHodgman(Rectangle clipRect)
{
_drawingBounds = clipRect;
}
/// <summary>
/// Create southerlandHodgman polygon clipper with default clipping rectangle
/// </summary>
public SoutherlandHodgman()
{
ClippingRectangle = new Rectangle(-32000, -32000, 64000, 64000);
}
/// <summary>
/// Get or set the clipping rectangle used in subsequent Clip calls.
/// </summary>
public Rectangle ClippingRectangle
{
get { return _drawingBounds; }
set { _drawingBounds = value; }
}
/// <summary>
/// Calculates the Southerland-Hodgman clip using the actual drawing coordinates.
/// This hopefully will be much faster than NTS which seems unncessarilly slow to calculate.
/// http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965
/// </summary>
/// <param name="points"></param>
/// <returns>A modified list of points that has been clipped to the drawing bounds</returns>
public List<PointF> Clip(List<PointF> points)
{
List<PointF> result = points;
for (int direction = 0; direction < 4; direction++)
{
result = ClipDirection(result, direction);
}
return result;
}
private List<PointF> ClipDirection(IEnumerable<PointF> points, int direction)
{
bool previousInside = true;
List<PointF> result = new List<PointF>();
PointF previous = PointF.Empty;
foreach (PointF point in points)
{
bool inside = IsInside(point, direction);
if (previousInside && inside)
{
// both points are inside, so simply add the current point
result.Add(point);
previous = point;
}
if (previousInside && inside == false)
{
if (previous.IsEmpty == false)
{
// crossing the boundary going out, so insert the intersection instead
result.Add(BoundIntersection(previous, point, direction));
}
previous = point;
}
if (previousInside == false && inside)
{
// crossing the boundary going in, so insert the intersection AND the new point
result.Add(BoundIntersection(previous, point, direction));
result.Add(point);
previous = point;
}
if (previousInside == false && inside == false)
{
previous = point;
}
previousInside = inside;
}
// be sure to close the polygon if it is not closed
if (result.Count > 0)
{
if (result[0].X != result[result.Count - 1].X || result[0].Y != result[result.Count - 1].Y)
{
result.Add(new PointF(result[0].X, result[0].Y));
}
}
return result;
}
private bool IsInside(PointF point, int direction)
{
switch (direction)
{
case BOUND_RIGHT:
if (point.X <= _drawingBounds.Right) return true;
return false;
case BOUND_LEFT:
if (point.X >= _drawingBounds.Left) return true;
return false;
case BOUND_TOP:
if (point.Y >= _drawingBounds.Top) return true;
return false;
case BOUND_BOTTOM:
if (point.Y <= _drawingBounds.Bottom) return true;
return false;
}
return false;
}
private PointF BoundIntersection(PointF start, PointF end, int direction)
{
PointF result = new PointF();
switch (direction)
{
case BOUND_RIGHT:
result.X = _drawingBounds.Right;
result.Y = start.Y + (end.Y - start.Y) * (_drawingBounds.Right - start.X) / (end.X - start.X);
break;
case BOUND_LEFT:
result.X = _drawingBounds.Left;
result.Y = start.Y + (end.Y - start.Y) * (_drawingBounds.Left - start.X) / (end.X - start.X);
break;
case BOUND_TOP:
result.Y = _drawingBounds.Top;
result.X = start.X + (end.X - start.X) * (_drawingBounds.Top - start.Y) / (end.Y - start.Y);
break;
case BOUND_BOTTOM:
result.Y = _drawingBounds.Bottom;
result.X = start.X + (end.X - start.X) * (_drawingBounds.Bottom - start.Y) / (end.Y - start.Y);
break;
}
return result;
}
/// <summary>
/// Calculates the Southerland-Hodgman clip using the actual drawing coordinates.
/// This specific overload works with arrays of doubles instead of PointF structures.
/// This hopefully will be much faster than NTS which seems unncessarilly slow to calculate.
/// http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965
/// </summary>
/// <param name="vertexValues">The list of arrays of doubles where the X index is 0 and the Y index is 1.</param>
/// <returns>A modified list of points that has been clipped to the drawing bounds</returns>
public List<double[]> Clip(List<double[]> vertexValues)
{
List<double[]> result = vertexValues;
for (int direction = 0; direction < 4; direction++)
{
result = ClipDirection(result, direction);
}
return result;
}
private List<double[]> ClipDirection(IEnumerable<double[]> points, int direction)
{
bool previousInside = true;
List<double[]> result = new List<double[]>();
double[] previous = new double[2];
bool isFirst = true;
foreach (double[] point in points)
{
bool inside = IsInside(point, direction);
if (previousInside && inside)
{
// both points are inside, so simply add the current point
result.Add(point);
previous = point;
}
if (previousInside && inside == false)
{
if (isFirst == false)
{
// crossing the boundary going out, so insert the intersection instead
result.Add(BoundIntersection(previous, point, direction));
}
previous = point;
}
if (previousInside == false && inside)
{
// crossing the boundary going in, so insert the intersection AND the new point
result.Add(BoundIntersection(previous, point, direction));
result.Add(point);
previous = point;
}
if (previousInside == false && inside == false)
{
previous = point;
}
isFirst = false;
previousInside = inside;
}
// be sure to close the polygon if it is not closed
if (result.Count > 0)
{
if (result[0][X] != result[result.Count - 1][X] || result[0][Y] != result[result.Count - 1][Y])
{
result.Add(new[] { result[0][X], result[0][Y] });
}
}
return result;
}
private bool IsInside(double[] point, int direction)
{
switch (direction)
{
case BOUND_RIGHT:
if (point[X] <= _drawingBounds.Right) return true;
return false;
case BOUND_LEFT:
if (point[X] >= _drawingBounds.Left) return true;
return false;
case BOUND_TOP:
if (point[Y] >= _drawingBounds.Top) return true;
return false;
case BOUND_BOTTOM:
if (point[Y] <= _drawingBounds.Bottom) return true;
return false;
}
return false;
}
private double[] BoundIntersection(double[] start, double[] end, int direction)
{
double[] result = new double[2];
switch (direction)
{
case BOUND_RIGHT:
result[X] = _drawingBounds.Right;
result[Y] = start[Y] + (end[Y] - start[Y]) * (_drawingBounds.Right - start[X]) / (end[X] - start[X]);
break;
case BOUND_LEFT:
result[X] = _drawingBounds.Left;
result[Y] = start[Y] + (end[Y] - start[Y]) * (_drawingBounds.Left - start[X]) / (end[X] - start[X]);
break;
case BOUND_TOP:
result[Y] = _drawingBounds.Top;
result[X] = start[X] + (end[X] - start[X]) * (_drawingBounds.Top - start[Y]) / (end[Y] - start[Y]);
break;
case BOUND_BOTTOM:
result[Y] = _drawingBounds.Bottom;
result[X] = start[X] + (end[X] - start[X]) * (_drawingBounds.Bottom - start[Y]) / (end[Y] - start[Y]);
break;
}
return result;
}
}
}
| |
using System;
using System.IO;
using Microsoft.Build.Construction;
namespace GodotSharpTools.Project
{
public static class ProjectGenerator
{
const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}";
const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}";
public static string GenCoreApiProject(string dir, string[] compileItems)
{
string path = Path.Combine(dir, CoreApiProject + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(CoreApiProject, out mainGroup);
mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml"));
mainGroup.SetProperty("RootNamespace", "Godot");
mainGroup.SetProperty("ProjectGuid", CoreApiProjectGuid);
GenAssemblyInfoFile(root, dir, CoreApiProject,
new string[] { "[assembly: InternalsVisibleTo(\"" + EditorApiProject + "\")]" },
new string[] { "System.Runtime.CompilerServices" });
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static string GenEditorApiProject(string dir, string coreApiHintPath, string[] compileItems)
{
string path = Path.Combine(dir, EditorApiProject + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(EditorApiProject, out mainGroup);
mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml"));
mainGroup.SetProperty("RootNamespace", "Godot");
mainGroup.SetProperty("ProjectGuid", EditorApiProjectGuid);
GenAssemblyInfoFile(root, dir, EditorApiProject);
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
var coreApiRef = root.AddItem("Reference", CoreApiProject);
coreApiRef.AddMetadata("HintPath", coreApiHintPath);
coreApiRef.AddMetadata("Private", "False");
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static string GenGameProject(string dir, string name, string[] compileItems)
{
string path = Path.Combine(dir, name + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(name, out mainGroup);
mainGroup.SetProperty("OutputPath", Path.Combine(".mono", "temp", "bin", "$(Configuration)"));
mainGroup.SetProperty("BaseIntermediateOutputPath", Path.Combine(".mono", "temp", "obj"));
mainGroup.SetProperty("IntermediateOutputPath", Path.Combine("$(BaseIntermediateOutputPath)", "$(Configuration)"));
var toolsGroup = root.AddPropertyGroup();
toolsGroup.Condition = " '$(Configuration)|$(Platform)' == 'Tools|AnyCPU' ";
toolsGroup.AddProperty("DebugSymbols", "true");
toolsGroup.AddProperty("DebugType", "portable");
toolsGroup.AddProperty("Optimize", "false");
toolsGroup.AddProperty("DefineConstants", "DEBUG;TOOLS;");
toolsGroup.AddProperty("ErrorReport", "prompt");
toolsGroup.AddProperty("WarningLevel", "4");
toolsGroup.AddProperty("ConsolePause", "false");
var coreApiRef = root.AddItem("Reference", CoreApiProject);
coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", CoreApiProject + ".dll"));
coreApiRef.AddMetadata("Private", "False");
var editorApiRef = root.AddItem("Reference", EditorApiProject);
editorApiRef.Condition = " '$(Configuration)' == 'Tools' ";
editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", EditorApiProject + ".dll"));
editorApiRef.AddMetadata("Private", "False");
GenAssemblyInfoFile(root, dir, name);
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static void GenAssemblyInfoFile(ProjectRootElement root, string dir, string name, string[] assemblyLines = null, string[] usingDirectives = null)
{
string propertiesDir = Path.Combine(dir, "Properties");
if (!Directory.Exists(propertiesDir))
Directory.CreateDirectory(propertiesDir);
string usingDirectivesText = string.Empty;
if (usingDirectives != null)
{
foreach (var usingDirective in usingDirectives)
usingDirectivesText += "\nusing " + usingDirective + ";";
}
string assemblyLinesText = string.Empty;
if (assemblyLines != null)
{
foreach (var assemblyLine in assemblyLines)
assemblyLinesText += string.Join("\n", assemblyLines) + "\n";
}
string content = string.Format(assemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText);
string assemblyInfoFile = Path.Combine(propertiesDir, "AssemblyInfo.cs");
File.WriteAllText(assemblyInfoFile, content);
root.AddItem("Compile", assemblyInfoFile.RelativeToPath(dir).Replace("/", "\\"));
}
public static ProjectRootElement CreateLibraryProject(string name, out ProjectPropertyGroupElement mainGroup)
{
var root = ProjectRootElement.Create();
root.DefaultTargets = "Build";
mainGroup = root.AddPropertyGroup();
mainGroup.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
mainGroup.AddProperty("Platform", "AnyCPU").Condition = " '$(Platform)' == '' ";
mainGroup.AddProperty("ProjectGuid", "{" + Guid.NewGuid().ToString().ToUpper() + "}");
mainGroup.AddProperty("OutputType", "Library");
mainGroup.AddProperty("OutputPath", Path.Combine("bin", "$(Configuration)"));
mainGroup.AddProperty("RootNamespace", name);
mainGroup.AddProperty("AssemblyName", name);
mainGroup.AddProperty("TargetFrameworkVersion", "v4.5");
var debugGroup = root.AddPropertyGroup();
debugGroup.Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ";
debugGroup.AddProperty("DebugSymbols", "true");
debugGroup.AddProperty("DebugType", "portable");
debugGroup.AddProperty("Optimize", "false");
debugGroup.AddProperty("DefineConstants", "DEBUG;");
debugGroup.AddProperty("ErrorReport", "prompt");
debugGroup.AddProperty("WarningLevel", "4");
debugGroup.AddProperty("ConsolePause", "false");
var releaseGroup = root.AddPropertyGroup();
releaseGroup.Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ";
releaseGroup.AddProperty("DebugType", "portable");
releaseGroup.AddProperty("Optimize", "true");
releaseGroup.AddProperty("ErrorReport", "prompt");
releaseGroup.AddProperty("WarningLevel", "4");
releaseGroup.AddProperty("ConsolePause", "false");
// References
var referenceGroup = root.AddItemGroup();
referenceGroup.AddItem("Reference", "System");
root.AddImport(Path.Combine("$(MSBuildBinPath)", "Microsoft.CSharp.targets").Replace("/", "\\"));
return root;
}
private static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
{
var group = elem.AddItemGroup();
foreach (var item in items)
{
group.AddItem(groupName, item);
}
}
public const string CoreApiProject = "GodotSharp";
public const string EditorApiProject = "GodotSharpEditor";
private const string assemblyInfoTemplate =
@"using System.Reflection;{0}
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle(""{1}"")]
[assembly: AssemblyDescription("""")]
[assembly: AssemblyConfiguration("""")]
[assembly: AssemblyCompany("""")]
[assembly: AssemblyProduct("""")]
[assembly: AssemblyCopyright("""")]
[assembly: AssemblyTrademark("""")]
[assembly: AssemblyCulture("""")]
// The assembly version has the format ""{{Major}}.{{Minor}}.{{Build}}.{{Revision}}"".
// The form ""{{Major}}.{{Minor}}.*"" will automatically update the build and revision,
// and ""{{Major}}.{{Minor}}.{{Build}}.*"" will update just the revision.
[assembly: AssemblyVersion(""1.0.*"")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("""")]
{2}";
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using KitchenPC.Context;
using KitchenPC.Recipes;
using log4net;
namespace KitchenPC.Modeler
{
/// <summary>
/// Represents a modeling session for a given user with a given pantry.
/// This object can be re-used (or cached) while the user changes modeling preferences and remodels.
/// </summary>
public class ModelingSession
{
const int MAX_SUGGESTIONS = 15;
const double COOLING_RATE = 0.9999;
const float MISSING_ING_PUNISH = 5.0f;
const float NEW_ING_PUNISH = 2.0f;
const float EMPTY_RECIPE_AMOUNT = 0.50f;
readonly Random random = new Random();
readonly IngredientNode[] pantryIngredients;
readonly Dictionary<IngredientNode, float?> pantryAmounts;
readonly List<IngredientNode> ingBlacklist;
readonly Dictionary<RecipeNode, byte> ratings;
readonly bool[] favTags; //Truth table of fav tags
readonly int[] favIngs; //Array of top 5 fav ings by id
readonly RecipeTags AllowedTags; //Copy of profile
Dictionary<IngredientNode, IngredientUsage> totals; //Hold totals for each scoring round so we don't have to reallocate map every time
readonly DBSnapshot db;
readonly IKPCContext context;
readonly IUserProfile profile;
public static ILog Log = LogManager.GetLogger(typeof (ModelingSession));
/// <summary>
/// Create a ModelingSession instance.
/// </summary>
/// <param name="context">KitchenPC context used for this modeling session.</param>
/// <param name="db">Object containing all available recipes, ratings, and trend information.</param>
/// <param name="profile">Object containing user specific information, such as pantry and user ratings.</param>
public ModelingSession(IKPCContext context, DBSnapshot db, IUserProfile profile)
{
this.db = db;
this.context = context;
this.profile = profile;
this.favTags = new bool[RecipeTag.NUM_TAGS];
this.favIngs = new int[profile.FavoriteIngredients.Length];
if (profile.Pantry != null && profile.Pantry.Length == 0) //Empty pantries must be null, not zero items
{
throw new EmptyPantryException();
}
if (profile.AllowedTags != null)
{
AllowedTags = profile.AllowedTags;
}
if (profile.Pantry != null)
{
pantryAmounts = new Dictionary<IngredientNode, float?>();
foreach (var item in profile.Pantry)
{
var node = this.db.FindIngredient(item.IngredientId);
//If an ingredient isn't used by any recipe, there's no reason for it to be in the pantry.
if (node == null)
{
continue;
}
//If an ingredient exists, but doesn't have any link to any allowed tags, there's no reason for it to be in the pantry.
if (AllowedTags != null && (node.AvailableTags & AllowedTags) == 0)
{
continue;
}
if (pantryAmounts.ContainsKey(node))
{
throw new DuplicatePantryItemException();
}
pantryAmounts.Add(node, item.Amt);
}
if (pantryAmounts.Keys.Count == 0)
{
throw new ImpossibleQueryException();
}
pantryIngredients = pantryAmounts.Keys.ToArray();
}
if (profile.FavoriteIngredients != null)
{
var i = 0;
foreach (var ing in profile.FavoriteIngredients)
{
var node = this.db.FindIngredient(ing);
favIngs[i] = node.Key;
}
}
if (profile.FavoriteTags != null)
{
foreach (var tag in profile.FavoriteTags)
{
this.favTags[tag.Value] = true;
}
}
if (profile.BlacklistedIngredients != null)
{
ingBlacklist = new List<IngredientNode>();
foreach (var ing in profile.BlacklistedIngredients)
{
var node = this.db.FindIngredient(ing);
ingBlacklist.Add(node);
}
}
if (profile.Ratings != null)
{
ratings = new Dictionary<RecipeNode, byte>(profile.Ratings.Length);
foreach (var r in profile.Ratings)
{
var n = this.db.FindRecipe(r.RecipeId);
ratings.Add(n, r.Rating);
}
}
else
{
ratings = new Dictionary<RecipeNode, byte>(0);
}
}
/// <summary>
/// Generates a model with the specified number of recipes and returns the recipe IDs in the optimal order.
/// </summary>
/// <param name="recipes">Number of recipes to generate</param>
/// <param name="scale">Scale indicating importance of optimal ingredient usage vs. user trend usage. 1 indicates ignore user trends, return most efficient set of recipes. 5 indicates ignore pantry and generate recipes user is most likely to rate high.</param>
/// <returns>An array up to size "recipes" containing recipes from DBSnapshot.</returns>
public Model Generate(int recipes, byte scale)
{
if (recipes > MAX_SUGGESTIONS)
{
throw new ArgumentException("Modeler can only generate " + MAX_SUGGESTIONS.ToString() + " recipes at a time.");
}
var temperature = 10000.0;
double deltaScore = 0;
const double absoluteTemperature = 0.00001;
totals = new Dictionary<IngredientNode, IngredientUsage>(IngredientNode.NextKey);
var currentSet = new RecipeNode[recipes]; //current set of recipes
var nextSet = new RecipeNode[recipes]; //set to compare with current
InitSet(currentSet); //Initialize with n random recipes
var score = GetScore(currentSet, scale); //Check initial score
var timer = new Stopwatch();
timer.Start();
while (temperature > absoluteTemperature)
{
nextSet = GetNextSet(currentSet); //Swap out a random recipe with another one from the available pool
deltaScore = GetScore(nextSet, scale) - score;
//if the new set has a smaller score (good thing)
//or if the new set has a higher score but satisfies Boltzman condition then accept the set
if ((deltaScore < 0) || (score > 0 && Math.Exp(-deltaScore/temperature) > random.NextDouble()))
{
nextSet.CopyTo(currentSet, 0);
score += deltaScore;
}
//cool down the temperature
temperature *= COOLING_RATE;
}
timer.Stop();
Log.InfoFormat("Generating set of {0} recipes took {1}ms.", recipes, timer.ElapsedMilliseconds);
return new Model(currentSet, profile.Pantry, score);
}
/// <summary>Takes a model generated from the modeling engine and loads necessary data from the database to deliver relevance to a user interface.</summary>
/// <param name="model">Model from modeling engine</param>
/// <returns>CompiledModel object which contains full recipe information about the provided set.</returns>
public CompiledModel Compile(Model model)
{
var results = new CompiledModel();
var recipes = context.ReadRecipes(model.RecipeIds, ReadRecipeOptions.None);
results.RecipeIds = model.RecipeIds;
results.Pantry = model.Pantry;
results.Briefs = recipes.Select(r => { return new RecipeBrief(r); }).ToArray();
results.Recipes = recipes.Select(r => new SuggestedRecipe
{
Id = r.Id,
Ingredients = context.AggregateRecipes(r.Id).ToArray()
}).ToArray();
return results;
}
/// <summary>
/// Judges a set of recipes based on a scale and its efficiency with regards to the current pantry. The lower the score, the better.
/// </summary>
double GetScore(RecipeNode[] currentSet, byte scale)
{
double wasted = 0; //Add 1.0 for ingredients that don't exist in pantry, add percentage of leftover otherwise
float avgRating = 0; //Average rating for all recipes in the set (0-4)
float tagPoints = 0; //Point for each tag that's one of our favorites
float tagTotal = 0; //Total number of tags in all recipes
float ingPoints = 0; //Point for each ing that's one of our favorites
float ingTotal = 0; //Total number of ingrediets in all recipes
for (var i = 0; i < currentSet.Length; i++)
{
var recipe = currentSet[i];
var ingredients = (IngredientUsage[]) recipe.Ingredients;
//Add points for any favorite tags this recipe uses
tagTotal += recipe.Tags.Length;
ingTotal += ingredients.Length;
for (var t = 0; t < recipe.Tags.Length; t++) //TODO: Use bitmasks for storing recipe tags and fav tags, then count bits
{
if (favTags[t])
{
tagPoints++;
}
}
byte realRating; //Real rating is the user's rating, else the public rating, else 3.
if (!ratings.TryGetValue(recipe, out realRating))
{
realRating = (recipe.Rating == 0) ? (byte) 3 : recipe.Rating; //if recipe has no ratings, use average rating of 3.
}
avgRating += (realRating - 1);
for (var j = 0; j < ingredients.Length; j++)
{
var ingredient = ingredients[j];
//Add points for any favorite ingredients this recipe uses
var ingKey = ingredient.Ingredient.Key;
for (var k = 0; k < favIngs.Length; k++) //For loop is actually faster than 5 "if" statements
{
if (favIngs[k] == ingKey)
{
ingPoints++;
break;
}
}
IngredientUsage curUsage;
var fContains = totals.TryGetValue(ingredient.Ingredient, out curUsage);
if (!fContains)
{
curUsage = new IngredientUsage();
curUsage.Amt = ingredient.Amt;
totals.Add(ingredient.Ingredient, curUsage);
}
else
{
curUsage.Amt += ingredient.Amt;
}
}
}
if (profile.Pantry != null) //If profile has a pantry, figure out how much of it is wasted
{
//For each pantry ingredient that we're not using, punish the score by MISSING_ING_PUNISH amount.
var pEnum = pantryAmounts.GetEnumerator();
while (pEnum.MoveNext())
{
if (!totals.ContainsKey(pEnum.Current.Key))
{
wasted += MISSING_ING_PUNISH;
}
}
var e = totals.GetEnumerator();
while (e.MoveNext())
{
var curKey = e.Current.Key;
float? have;
if (pantryAmounts.TryGetValue(curKey, out have)) //We have this in our pantry
{
if (!have.HasValue) //We have this in our pantry, but no amount is specified - So we "act" like we have whatever we need
{
continue;
}
if (!e.Current.Value.Amt.HasValue) //This recipe doesn't specify an amount - So we "act" like we use half of what we have
{
wasted += EMPTY_RECIPE_AMOUNT;
continue;
}
var need = e.Current.Value.Amt.Value;
var ratio = 1 - ((have.Value - need)/have.Value); //Percentage of how much you're using of what you have
if (ratio > 1) //If you need more than you have, add the excess ratio to the waste but don't go over the punishment for not having the ingredient at all
{
wasted += Math.Min(ratio, NEW_ING_PUNISH);
}
else
{
wasted += (1 - ratio);
}
}
else
{
wasted += NEW_ING_PUNISH; //For each ingredient this meal set needs that we don't have, increment by NEW_ING_PUNISH
}
}
}
double worstScore, trendScore, efficiencyScore;
if (profile.Pantry == null) //No pantry, efficiency is defined by the overlap of ingredients across recipes
{
efficiencyScore = totals.Keys.Count/ingTotal;
}
else //Efficiency is defined by how efficient the pantry ingredients are utilized
{
worstScore = ((totals.Keys.Count*NEW_ING_PUNISH) + (profile.Pantry.Length*MISSING_ING_PUNISH)); //Worst possible efficiency score
efficiencyScore = (wasted/worstScore);
}
avgRating /= currentSet.Length;
trendScore = 1 - ((((avgRating/4)*4) + (tagPoints/tagTotal) + (ingPoints/ingTotal))/6);
totals.Clear();
if (scale == 1)
return efficiencyScore;
else if (scale == 2)
return (efficiencyScore + efficiencyScore + trendScore)/3;
else if (scale == 3)
return (efficiencyScore + trendScore)/2;
else if (scale == 4)
return (efficiencyScore + trendScore + trendScore)/3;
else if (scale == 5)
return trendScore;
return 0;
}
/// <summary>
/// Initializes currentSet with random recipes from the available recipe pool.
/// </summary>
void InitSet(RecipeNode[] currentSet)
{
var inUse = new List<Guid>(currentSet.Length);
for (var i = 0; i < currentSet.Length; i++)
{
RecipeNode g;
var timeout = 0;
do
{
g = Fish();
if (++timeout > 100) //Ok we've tried 100 times to find a recipe not already in this set, there just isn't enough data to work with for this query
{
throw new ImpossibleQueryException(); //TODO: Maybe we can lower the demanded meals and return what we do have
}
} while (inUse.Contains(g.RecipeId));
inUse.Add(g.RecipeId);
currentSet[i] = g;
}
}
/// <summary>
/// Swap out a random recipe with another one from the available pool
/// </summary>
RecipeNode[] GetNextSet(RecipeNode[] currentSet)
{
var rndIndex = random.Next(currentSet.Length);
var existingRecipe = currentSet[rndIndex];
RecipeNode newRecipe;
var timeout = 0;
while (true)
{
if (++timeout > 100) //We've tried 100 times to replace a recipe in this set, but cannot find anything that isn't already in this set.
{
throw new ImpossibleQueryException(); //TODO: If this is the only set of n which match that query, we've solved it - just return this set as final!
}
newRecipe = Fish();
if (newRecipe == existingRecipe)
{
continue;
}
var fFound = false;
for (var i = 0; i < currentSet.Length; i++)
{
if (newRecipe == currentSet[i])
{
fFound = true;
break;
}
}
if (!fFound)
{
break;
}
}
var retSet = new RecipeNode[currentSet.Length];
currentSet.CopyTo(retSet, 0);
retSet[rndIndex] = newRecipe;
return retSet;
}
/// <summary>
/// Finds a random recipe in the available recipe pool
/// </summary>
/// <returns></returns>
RecipeNode Fish()
{
RecipeNode recipeNode;
if (pantryIngredients == null) //No pantry, fish through Recipe index
{
int rnd;
var tag = (AllowedTags == null) ? random.Next(RecipeTag.NUM_TAGS) : AllowedTags[random.Next(AllowedTags.Length)].Value;
var recipesByTag = db.FindRecipesByTag(tag);
if (recipesByTag == null || recipesByTag.Length == 0) //Nothing in that tag
return Fish();
rnd = random.Next(recipesByTag.Length);
recipeNode = recipesByTag[rnd];
}
else //Fish through random pantry ingredient
{
var rndIng = random.Next(pantryIngredients.Length);
var ingNode = pantryIngredients[rndIng];
RecipeNode[] recipes;
if (AllowedTags != null && AllowedTags.Length > 0)
{
if ((AllowedTags & ingNode.AvailableTags) == 0) //Does this ingredient have any allowed tags?
{
return Fish(); //No - Find something else
}
//Pick random tag from allowed tags (since this set is smaller, better to guess an available tag)
while (true)
{
var t = random.Next(AllowedTags.Length); //NOTE: Next will NEVER return MaxValue, so we don't subtract 1 from Length!
var rndTag = AllowedTags[t];
recipes = ingNode.RecipesByTag[rndTag.Value] as RecipeNode[];
if (recipes != null)
{
break;
}
}
}
else //Just pick a random available tag
{
var rndTag = random.Next(ingNode.AvailableTags.Length);
var tag = ingNode.AvailableTags[rndTag];
recipes = ingNode.RecipesByTag[tag.Value] as RecipeNode[];
}
var rndRecipe = random.Next(recipes.Length);
recipeNode = recipes[rndRecipe];
}
//If there's a blacklist, make sure no ingredients are blacklisted otherwise try again
if (this.ingBlacklist != null)
{
var ingredients = (IngredientUsage[]) recipeNode.Ingredients;
for (var i = 0; i < ingredients.Length; i++)
{
if (this.ingBlacklist.Contains(ingredients[i].Ingredient))
{
return Fish();
}
}
}
//Discard if this recipe is to be avoided
if (profile.AvoidRecipe.HasValue && profile.AvoidRecipe.Value.Equals(recipeNode.RecipeId))
return Fish();
return recipeNode;
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "CS_GetEventConditionAttributes_Response", IsSet = false)]
public class CS_GetEventConditionAttributes_Response : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(CS_GetEventConditionAttributes_Response));
private DisplayEnhancementChoiceType displayEnhancement_;
private GroupPriorityOverrideChoiceType groupPriorityOverride_;
private bool groupPriorityOverride_present;
private ICollection<ObjectName> listOfReferencingECL_;
private bool listOfReferencingECL_present;
[ASN1Element(Name = "groupPriorityOverride", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)]
public GroupPriorityOverrideChoiceType GroupPriorityOverride
{
get
{
return groupPriorityOverride_;
}
set
{
groupPriorityOverride_ = value;
groupPriorityOverride_present = true;
}
}
[ASN1SequenceOf(Name = "listOfReferencingECL", IsSetOf = false)]
[ASN1Element(Name = "listOfReferencingECL", IsOptional = true, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ICollection<ObjectName> ListOfReferencingECL
{
get
{
return listOfReferencingECL_;
}
set
{
listOfReferencingECL_ = value;
listOfReferencingECL_present = true;
}
}
[ASN1Element(Name = "displayEnhancement", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public DisplayEnhancementChoiceType DisplayEnhancement
{
get
{
return displayEnhancement_;
}
set
{
displayEnhancement_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isGroupPriorityOverridePresent()
{
return groupPriorityOverride_present;
}
public bool isListOfReferencingECLPresent()
{
return listOfReferencingECL_present;
}
[ASN1PreparedElement]
[ASN1Choice(Name = "displayEnhancement")]
public class DisplayEnhancementChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DisplayEnhancementChoiceType));
private long index_;
private bool index_selected;
private NullObject noEnhancement_;
private bool noEnhancement_selected;
private string string_;
private bool string_selected;
[ASN1String(Name = "",
StringType = UniversalTags.VisibleString, IsUCS = false)]
[ASN1Element(Name = "string", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public string String
{
get
{
return string_;
}
set
{
selectString(value);
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "index", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public long Index
{
get
{
return index_;
}
set
{
selectIndex(value);
}
}
[ASN1Null(Name = "noEnhancement")]
[ASN1Element(Name = "noEnhancement", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public NullObject NoEnhancement
{
get
{
return noEnhancement_;
}
set
{
selectNoEnhancement(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isStringSelected()
{
return string_selected;
}
public void selectString(string val)
{
string_ = val;
string_selected = true;
index_selected = false;
noEnhancement_selected = false;
}
public bool isIndexSelected()
{
return index_selected;
}
public void selectIndex(long val)
{
index_ = val;
index_selected = true;
string_selected = false;
noEnhancement_selected = false;
}
public bool isNoEnhancementSelected()
{
return noEnhancement_selected;
}
public void selectNoEnhancement()
{
selectNoEnhancement(new NullObject());
}
public void selectNoEnhancement(NullObject val)
{
noEnhancement_ = val;
noEnhancement_selected = true;
string_selected = false;
index_selected = false;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "groupPriorityOverride")]
public class GroupPriorityOverrideChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(GroupPriorityOverrideChoiceType));
private Priority priority_;
private bool priority_selected;
private NullObject undefined_;
private bool undefined_selected;
[ASN1Element(Name = "priority", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Priority Priority
{
get
{
return priority_;
}
set
{
selectPriority(value);
}
}
[ASN1Null(Name = "undefined")]
[ASN1Element(Name = "undefined", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public NullObject Undefined
{
get
{
return undefined_;
}
set
{
selectUndefined(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isPrioritySelected()
{
return priority_selected;
}
public void selectPriority(Priority val)
{
priority_ = val;
priority_selected = true;
undefined_selected = false;
}
public bool isUndefinedSelected()
{
return undefined_selected;
}
public void selectUndefined()
{
selectUndefined(new NullObject());
}
public void selectUndefined(NullObject val)
{
undefined_ = val;
undefined_selected = true;
priority_selected = false;
}
}
}
}
| |
namespace XenAdmin.Dialogs.OptionsPages
{
partial class ConnectionOptionsPage
{
/// <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)
{
validationToolTip.Dispose();
if (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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectionOptionsPage));
this.ConnectionTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.TimeoutGroupBox = new XenAdmin.Controls.DecentGroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.ConnectionTimeoutLabel = new System.Windows.Forms.Label();
this.TimeOutLabel = new System.Windows.Forms.Label();
this.ConnectionTimeoutNud = new System.Windows.Forms.NumericUpDown();
this.SecondsLabel = new System.Windows.Forms.Label();
this.ProxyGroupBox = new XenAdmin.Controls.DecentGroupBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.BypassForServersCheckbox = new System.Windows.Forms.CheckBox();
this.ProxyPasswordTextBox = new System.Windows.Forms.TextBox();
this.ProxyUsernameLabel = new System.Windows.Forms.Label();
this.ProxyUsernameTextBox = new System.Windows.Forms.TextBox();
this.ProxyPasswordLabel = new System.Windows.Forms.Label();
this.AuthenticationCheckBox = new System.Windows.Forms.CheckBox();
this.ProxyAddressLabel = new System.Windows.Forms.Label();
this.UseProxyRadioButton = new System.Windows.Forms.RadioButton();
this.DirectConnectionRadioButton = new System.Windows.Forms.RadioButton();
this.UseIERadioButton = new System.Windows.Forms.RadioButton();
this.ProxyAddressTextBox = new System.Windows.Forms.TextBox();
this.ProxyPortTextBox = new System.Windows.Forms.TextBox();
this.ProxyPortLabel = new System.Windows.Forms.Label();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.DigestRadioButton = new System.Windows.Forms.RadioButton();
this.AuthenticationMethodLabel = new System.Windows.Forms.Label();
this.BasicRadioButton = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.ConnectionTableLayoutPanel.SuspendLayout();
this.TimeoutGroupBox.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ConnectionTimeoutNud)).BeginInit();
this.ProxyGroupBox.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.SuspendLayout();
//
// ConnectionTableLayoutPanel
//
resources.ApplyResources(this.ConnectionTableLayoutPanel, "ConnectionTableLayoutPanel");
this.ConnectionTableLayoutPanel.Controls.Add(this.TimeoutGroupBox, 0, 2);
this.ConnectionTableLayoutPanel.Controls.Add(this.ProxyGroupBox, 0, 1);
this.ConnectionTableLayoutPanel.Controls.Add(this.label1, 0, 0);
this.ConnectionTableLayoutPanel.Name = "ConnectionTableLayoutPanel";
//
// TimeoutGroupBox
//
resources.ApplyResources(this.TimeoutGroupBox, "TimeoutGroupBox");
this.TimeoutGroupBox.Controls.Add(this.tableLayoutPanel2);
this.TimeoutGroupBox.Name = "TimeoutGroupBox";
this.TimeoutGroupBox.TabStop = false;
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.ConnectionTimeoutLabel, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.TimeOutLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.ConnectionTimeoutNud, 1, 1);
this.tableLayoutPanel2.Controls.Add(this.SecondsLabel, 2, 1);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// ConnectionTimeoutLabel
//
resources.ApplyResources(this.ConnectionTimeoutLabel, "ConnectionTimeoutLabel");
this.ConnectionTimeoutLabel.Name = "ConnectionTimeoutLabel";
//
// TimeOutLabel
//
resources.ApplyResources(this.TimeOutLabel, "TimeOutLabel");
this.tableLayoutPanel2.SetColumnSpan(this.TimeOutLabel, 3);
this.TimeOutLabel.Name = "TimeOutLabel";
//
// ConnectionTimeoutNud
//
resources.ApplyResources(this.ConnectionTimeoutNud, "ConnectionTimeoutNud");
this.ConnectionTimeoutNud.Maximum = new decimal(new int[] {
2147483,
0,
0,
0});
this.ConnectionTimeoutNud.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.ConnectionTimeoutNud.Name = "ConnectionTimeoutNud";
this.ConnectionTimeoutNud.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// SecondsLabel
//
resources.ApplyResources(this.SecondsLabel, "SecondsLabel");
this.SecondsLabel.Name = "SecondsLabel";
//
// ProxyGroupBox
//
resources.ApplyResources(this.ProxyGroupBox, "ProxyGroupBox");
this.ProxyGroupBox.Controls.Add(this.tableLayoutPanel1);
this.ProxyGroupBox.Name = "ProxyGroupBox";
this.ProxyGroupBox.TabStop = false;
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.BypassForServersCheckbox, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.ProxyPasswordTextBox, 7, 6);
this.tableLayoutPanel1.Controls.Add(this.ProxyUsernameLabel, 2, 6);
this.tableLayoutPanel1.Controls.Add(this.ProxyUsernameTextBox, 3, 6);
this.tableLayoutPanel1.Controls.Add(this.ProxyPasswordLabel, 5, 6);
this.tableLayoutPanel1.Controls.Add(this.AuthenticationCheckBox, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.ProxyAddressLabel, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.UseProxyRadioButton, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.DirectConnectionRadioButton, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.UseIERadioButton, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.ProxyAddressTextBox, 3, 3);
this.tableLayoutPanel1.Controls.Add(this.ProxyPortTextBox, 6, 3);
this.tableLayoutPanel1.Controls.Add(this.ProxyPortLabel, 5, 3);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel3, 2, 8);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// BypassForServersCheckbox
//
resources.ApplyResources(this.BypassForServersCheckbox, "BypassForServersCheckbox");
this.tableLayoutPanel1.SetColumnSpan(this.BypassForServersCheckbox, 7);
this.BypassForServersCheckbox.Name = "BypassForServersCheckbox";
this.BypassForServersCheckbox.UseVisualStyleBackColor = true;
this.BypassForServersCheckbox.CheckedChanged += new System.EventHandler(this.GeneralProxySettingsChanged);
//
// ProxyPasswordTextBox
//
resources.ApplyResources(this.ProxyPasswordTextBox, "ProxyPasswordTextBox");
this.ProxyPasswordTextBox.Name = "ProxyPasswordTextBox";
this.ProxyPasswordTextBox.UseSystemPasswordChar = true;
this.ProxyPasswordTextBox.TextChanged += new System.EventHandler(this.ProxyAuthenticationSettingsChanged);
//
// ProxyUsernameLabel
//
resources.ApplyResources(this.ProxyUsernameLabel, "ProxyUsernameLabel");
this.tableLayoutPanel1.SetColumnSpan(this.ProxyUsernameLabel, 2);
this.ProxyUsernameLabel.Name = "ProxyUsernameLabel";
//
// ProxyUsernameTextBox
//
resources.ApplyResources(this.ProxyUsernameTextBox, "ProxyUsernameTextBox");
this.ProxyUsernameTextBox.Name = "ProxyUsernameTextBox";
this.ProxyUsernameTextBox.TextChanged += new System.EventHandler(this.ProxyAuthenticationSettingsChanged);
//
// ProxyPasswordLabel
//
resources.ApplyResources(this.ProxyPasswordLabel, "ProxyPasswordLabel");
this.tableLayoutPanel1.SetColumnSpan(this.ProxyPasswordLabel, 2);
this.ProxyPasswordLabel.Name = "ProxyPasswordLabel";
//
// AuthenticationCheckBox
//
resources.ApplyResources(this.AuthenticationCheckBox, "AuthenticationCheckBox");
this.tableLayoutPanel1.SetColumnSpan(this.AuthenticationCheckBox, 7);
this.AuthenticationCheckBox.Name = "AuthenticationCheckBox";
this.AuthenticationCheckBox.UseVisualStyleBackColor = true;
this.AuthenticationCheckBox.CheckedChanged += new System.EventHandler(this.AuthenticationCheckBox_CheckedChanged);
//
// ProxyAddressLabel
//
resources.ApplyResources(this.ProxyAddressLabel, "ProxyAddressLabel");
this.tableLayoutPanel1.SetColumnSpan(this.ProxyAddressLabel, 2);
this.ProxyAddressLabel.Name = "ProxyAddressLabel";
//
// UseProxyRadioButton
//
resources.ApplyResources(this.UseProxyRadioButton, "UseProxyRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.UseProxyRadioButton, 8);
this.UseProxyRadioButton.Name = "UseProxyRadioButton";
this.UseProxyRadioButton.TabStop = true;
this.UseProxyRadioButton.UseVisualStyleBackColor = true;
//
// DirectConnectionRadioButton
//
resources.ApplyResources(this.DirectConnectionRadioButton, "DirectConnectionRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.DirectConnectionRadioButton, 8);
this.DirectConnectionRadioButton.Name = "DirectConnectionRadioButton";
this.DirectConnectionRadioButton.TabStop = true;
this.DirectConnectionRadioButton.UseVisualStyleBackColor = true;
//
// UseIERadioButton
//
resources.ApplyResources(this.UseIERadioButton, "UseIERadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.UseIERadioButton, 8);
this.UseIERadioButton.Name = "UseIERadioButton";
this.UseIERadioButton.TabStop = true;
this.UseIERadioButton.UseVisualStyleBackColor = true;
//
// ProxyAddressTextBox
//
resources.ApplyResources(this.ProxyAddressTextBox, "ProxyAddressTextBox");
this.tableLayoutPanel1.SetColumnSpan(this.ProxyAddressTextBox, 2);
this.ProxyAddressTextBox.Name = "ProxyAddressTextBox";
this.ProxyAddressTextBox.TextChanged += new System.EventHandler(this.GeneralProxySettingsChanged);
//
// ProxyPortTextBox
//
resources.ApplyResources(this.ProxyPortTextBox, "ProxyPortTextBox");
this.tableLayoutPanel1.SetColumnSpan(this.ProxyPortTextBox, 2);
this.ProxyPortTextBox.Name = "ProxyPortTextBox";
this.ProxyPortTextBox.TextChanged += new System.EventHandler(this.GeneralProxySettingsChanged);
//
// ProxyPortLabel
//
resources.ApplyResources(this.ProxyPortLabel, "ProxyPortLabel");
this.ProxyPortLabel.Name = "ProxyPortLabel";
//
// tableLayoutPanel3
//
resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3");
this.tableLayoutPanel1.SetColumnSpan(this.tableLayoutPanel3, 6);
this.tableLayoutPanel3.Controls.Add(this.DigestRadioButton, 2, 0);
this.tableLayoutPanel3.Controls.Add(this.AuthenticationMethodLabel, 0, 0);
this.tableLayoutPanel3.Controls.Add(this.BasicRadioButton, 1, 0);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
//
// DigestRadioButton
//
resources.ApplyResources(this.DigestRadioButton, "DigestRadioButton");
this.DigestRadioButton.Name = "DigestRadioButton";
this.DigestRadioButton.UseVisualStyleBackColor = true;
this.DigestRadioButton.CheckedChanged += new System.EventHandler(this.ProxyAuthenticationSettingsChanged);
//
// AuthenticationMethodLabel
//
resources.ApplyResources(this.AuthenticationMethodLabel, "AuthenticationMethodLabel");
this.AuthenticationMethodLabel.Name = "AuthenticationMethodLabel";
//
// BasicRadioButton
//
resources.ApplyResources(this.BasicRadioButton, "BasicRadioButton");
this.BasicRadioButton.Name = "BasicRadioButton";
this.BasicRadioButton.UseVisualStyleBackColor = true;
this.BasicRadioButton.CheckedChanged += new System.EventHandler(this.ProxyAuthenticationSettingsChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// ConnectionOptionsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.ConnectionTableLayoutPanel);
this.Name = "ConnectionOptionsPage";
this.ConnectionTableLayoutPanel.ResumeLayout(false);
this.ConnectionTableLayoutPanel.PerformLayout();
this.TimeoutGroupBox.ResumeLayout(false);
this.TimeoutGroupBox.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ConnectionTimeoutNud)).EndInit();
this.ProxyGroupBox.ResumeLayout(false);
this.ProxyGroupBox.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel ConnectionTableLayoutPanel;
private XenAdmin.Controls.DecentGroupBox TimeoutGroupBox;
private System.Windows.Forms.NumericUpDown ConnectionTimeoutNud;
private System.Windows.Forms.Label TimeOutLabel;
private System.Windows.Forms.Label ConnectionTimeoutLabel;
private System.Windows.Forms.Label SecondsLabel;
private XenAdmin.Controls.DecentGroupBox ProxyGroupBox;
private System.Windows.Forms.RadioButton DirectConnectionRadioButton;
private System.Windows.Forms.TextBox ProxyAddressTextBox;
private System.Windows.Forms.RadioButton UseProxyRadioButton;
private System.Windows.Forms.TextBox ProxyPortTextBox;
private System.Windows.Forms.Label ProxyAddressLabel;
private System.Windows.Forms.RadioButton UseIERadioButton;
private System.Windows.Forms.Label ProxyPortLabel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox AuthenticationCheckBox;
private System.Windows.Forms.CheckBox BypassForServersCheckbox;
private System.Windows.Forms.TextBox ProxyPasswordTextBox;
private System.Windows.Forms.Label ProxyUsernameLabel;
private System.Windows.Forms.TextBox ProxyUsernameTextBox;
private System.Windows.Forms.Label ProxyPasswordLabel;
private System.Windows.Forms.RadioButton BasicRadioButton;
private System.Windows.Forms.Label AuthenticationMethodLabel;
private System.Windows.Forms.RadioButton DigestRadioButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO; //TextWriter
using System.Text; //Encoding
namespace Microsoft.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// TraceLevel
//
////////////////////////////////////////////////////////////////
public enum TraceLevel
{
None,
Info,
Default,
Debug,
All,
}
////////////////////////////////////////////////////////////////
// TestLog
//
////////////////////////////////////////////////////////////////
public class TestLog
{
//Data
private static ITestLog s_pinternal;
private static TraceLevel s_plevel = TraceLevel.Default;
private static TestLogAssertHandler s_passerthandler = null;
//Accessors
public static ITestLog Internal
{
set
{
s_pinternal = value;
}
get
{
return s_pinternal;
}
}
public static TraceLevel Level
{
get { return s_plevel; }
set { s_plevel = value; }
}
public static TestLogAssertHandler AssertHandler
{
get { return s_passerthandler; }
}
internal static void Dispose()
{
//Reset the info.
s_pinternal = null;
s_passerthandler = null;
}
//Helpers
public static string NewLine
{
get { return "\n"; }
}
public static bool WillTrace(TraceLevel level)
{
return (s_plevel >= level);
}
public static void Write(object value)
{
Write(TestLogFlags.Text, StringEx.ToString(value));
}
public static void WriteLine(object value)
{
WriteLine(TestLogFlags.Text, StringEx.ToString(value));
}
public static void WriteLine()
{
WriteLine(TestLogFlags.Text, null);
}
public static void Write(string text)
{
Write(TestLogFlags.Text, text);
}
public static void Write(string text, params object[] args)
{
//Delegate
Write(TestLogFlags.Text, String.Format(text, args));
}
public static void WriteLine(string text)
{
WriteLine(TestLogFlags.Text, text);
}
public static void WriteLine(string text, params object[] args)
{
//Delegate
WriteLine(String.Format(text, args));
}
public static void Write(char[] value)
{
WriteLine(TestLogFlags.Text, new string(value));
}
public static void WriteLine(char[] value)
{
WriteLine(TestLogFlags.Text, new string(value));
}
public static void WriteXml(string text)
{
Write(TestLogFlags.Xml, text);
}
public static void WriteRaw(string text)
{
Write(TestLogFlags.Raw, text);
}
public static void WriteIgnore(string text)
{
Write(TestLogFlags.Ignore, text);
}
public static void WriteLineIgnore(string text)
{
WriteLine(TestLogFlags.Ignore, text);
}
public static void Write(TestLogFlags flags, string text)
{
if (Internal != null)
Internal.Write(flags, FixupXml(text));
else
Console.Write(text);
}
public static void WriteLine(TestLogFlags flags, string text)
{
if (Internal != null)
Internal.WriteLine(flags, FixupXml(text));
else
Console.WriteLine(text);
}
public static void Trace(String value)
{
Trace(TraceLevel.Default, value);
}
public static void TraceLine(String value)
{
TraceLine(TraceLevel.Default, value);
}
public static void TraceLine()
{
TraceLine(TraceLevel.Default, null);
}
public static void Trace(TraceLevel level, String value)
{
if (WillTrace(level))
Write(TestLogFlags.Trace | TestLogFlags.Ignore, value);
}
public static void TraceLine(TraceLevel level, String value)
{
if (WillTrace(level))
Write(TestLogFlags.Trace | TestLogFlags.Ignore, value + TestLog.NewLine);
}
public static void TraceLine(TraceLevel level)
{
TraceLine(level, null);
}
public static bool Compare(bool equal, string message)
{
if (equal)
return true;
return Compare(false, true, message);
}
public static bool Compare(object actual, object expected, string message)
{
if (InternalEquals(actual, expected))
return true;
//Compare not only compares but throws - so your test stops processing
//This way processing stops upon the first error, so you don't have to check return
//values or validate values afterwards. If you have other items to do, then use the
//TestLog.Equals instead of TestLog.Compare
throw new TestFailedException(message, actual, expected, null);
}
public static bool Compare(object actual, object expected1, object expected2, string message)
{
if (InternalEquals(actual, expected1) || InternalEquals(actual, expected2))
return true;
//Compare not only compares but throws - so your test stops processing
//This way processing stops upon the first error, so you don't have to check return
//values or validate values afterwards. If you have other items to do, then use the
//TestLog.Equals instead of TestLog.Compare
throw new TestFailedException(message, actual, expected2, null);
}
public static bool Equals(object actual, object expected, string message)
{
//Equals is identical to Compare, except that Equals doesn't throw.
//i.e. the test wants to record the failure and continue to do other things
if (InternalEquals(actual, expected))
return true;
TestLog.Error(TestResult.Failed, actual, expected, null, message, new Exception().StackTrace, null, 0);
return false;
}
public static bool Warning(bool equal, string message)
{
return Warning(equal, true, message, null);
}
public static bool Warning(object actual, object expected, string message)
{
return Warning(actual, expected, message, null);
}
public static bool Warning(object actual, object expected, string message, Exception inner)
{
//See if these are equal
bool equal = InternalEquals(actual, expected);
if (equal)
return true;
try
{
throw new TestWarningException(message, actual, expected, inner);
}
catch (Exception e)
{
//Warning should continue - not halt test progress
TestLog.HandleException(e);
return false;
}
}
public static bool Skip(string message)
{
//Delegate
return Skip(true, message);
}
public static bool Skip(bool skip, string message)
{
if (skip)
throw new TestSkippedException(message);
return false;
}
internal static bool InternalEquals(object actual, object expected)
{
//Handle null comparison
if (actual == null && expected == null)
return true;
else if (actual == null || expected == null)
return false;
//Otherwise
return expected.Equals(actual);
}
public static void Error(TestResult result, object actual, object expected, string source, string message, string stack, String filename, int lineno)
{
//Log the error
if (Internal != null)
{
Internal.Error(result,
TestLogFlags.Text, //flags
StringEx.Format(actual), //actual
StringEx.Format(expected), //expected
source, //source
message, //message
stack, //stack
filename, //filename
lineno //line
);
}
else
{
//We call IError::Compare, which logs the error AND increments the error count...
Console.WriteLine("Message:\t" + message);
Console.WriteLine("Source:\t\t" + source);
Console.WriteLine("Expected:\t" + expected);
Console.WriteLine("Received:\t" + actual);
Console.WriteLine("Details:" + TestLog.NewLine + stack);
Console.WriteLine("File:\t\t" + filename);
Console.WriteLine("Line:\t\t" + lineno);
}
}
public static TestResult HandleException(Exception e)
{
TestResult result = TestResult.Failed;
Exception inner = e;
if (!(inner is TestException) ||
((inner as TestException).Result != TestResult.Skipped &&
(inner as TestException).Result != TestResult.Passed &&
(inner as TestException).Result != TestResult.Warning))
inner = e; //start over so we do not loose the stack trace
while (inner != null)
{
String source = inner.Source;
//Message
String message = inner.Message;
if (inner != e)
message = "Inner Exception -> " + message;
//Expected / Actual
Object actual = inner.GetType();
Object expected = null;
String details = inner.StackTrace;
String filename = null;
int line = 0;
if (inner is TestException)
{
TestException testinner = (TestException)inner;
//Setup more meaningful info
actual = testinner.Actual;
expected = testinner.Expected;
result = testinner.Result;
switch (result)
{
case TestResult.Passed:
case TestResult.Skipped:
WriteLine(message);
return result;
}
}
//Log
TestLog.Error(result, actual, expected, source, message, details, filename, line);
//Next
inner = inner.InnerException;
}
return result;
}
private static String FixupXml(String value)
{
bool escapeXmlStuff = false;
if (value == null) return null;
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
switch (value[i])
{
case '&':
if (escapeXmlStuff) b.Append("&"); else b.Append('&');
break;
case '<':
if (escapeXmlStuff) b.Append("<"); else b.Append('<');
break;
case '>':
if (escapeXmlStuff) b.Append(">"); else b.Append('>');
break;
case '"':
if (escapeXmlStuff) b.Append("""); else b.Append('"');
break;
case '\'':
if (escapeXmlStuff) b.Append("'"); else b.Append('\'');
break;
case '\t':
b.Append('\t');
break;
case '\r':
b.Append('\r');
break;
case '\n':
b.Append('\n');
break;
default:
if ((value[i] < 0x20) || value[i] > 0x80)
{
b.Append(PrintUnknownCharacter(value[i]));
}
else
{
b.Append(value[i]);
}
break;
}
}
return b.ToString();
}
private static string PrintUnknownCharacter(char ch)
{
int number = ch;
string result = string.Empty;
if (number == 0)
{
result = "0";
}
while (number > 0)
{
int n = number % 16;
number = number / 16;
if (n < 10)
{
result = (char)(n + (int)'0') + result;
}
else
{
result = (char)(n - 10 + (int)'A') + result;
}
}
return "px" + result + "p";
}
}
////////////////////////////////////////////////////////////////
// TestLogWriter
//
////////////////////////////////////////////////////////////////
public class TestLogWriter : TextWriter
{
//Data
protected TestLogFlags pflags = TestLogFlags.Text;
//Constructor
public TestLogWriter(TestLogFlags flags)
{
pflags = flags;
}
//Overrides
public override void Write(char ch)
{
//A subclass must minimally implement the Write(Char) method.
Write(ch.ToString());
}
public override void Write(string text)
{
//Delegate
TestLog.Write(pflags, text);
}
public override void Write(char[] ch)
{
//Note: This is a workaround the TextWriter::Write(char[]) that incorrectly
//writes 1 char at a time, which means \r\n is written sperately and then gets fixed
//up to be two carriage returns!
if (ch != null)
{
StringBuilder builder = new StringBuilder(ch.Length);
builder.Append(ch);
Write(builder.ToString());
}
}
public override void WriteLine(string strText)
{
Write(strText + this.NewLine);
}
public override void WriteLine()
{
//Writes a line terminator to the text stream.
//The default line terminator is a carriage return followed by a line feed ("\r\n"),
//but this value can be changed using the NewLine property.
Write(this.NewLine);
}
public override Encoding Encoding
{
get { return Encoding.Unicode; }
}
}
////////////////////////////////////////////////////////////////
// TestLogAssertHandler
//
////////////////////////////////////////////////////////////////
public class TestLogAssertHandler
{
//Data
protected bool pshouldthrow = false;
//Constructor
public TestLogAssertHandler()
{
}
//Accessors
public virtual bool ShouldThrow
{
get { return pshouldthrow; }
set { pshouldthrow = value; }
}
//Overloads
public void Fail(string message, string details)
{
//Handle the assert, treat it as an error.
Exception e = new TestException(TestResult.Assert, message, details, null, null);
e.Source = "Debug.Assert";
//Note: We don't throw the exception (by default), since we want to continue on Asserts
//(as many of them are benign or simply a valid runtime error).
if (this.ShouldThrow)
throw e;
TestLog.Error(TestResult.Assert, details, null, "Debug.Assert", message, new Exception().StackTrace, null, 0);
}
public void Write(string strText)
{
}
public void WriteLine(string strText)
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using Microsoft.Win32.SafeHandles;
using Xunit;
[Collection("CreateViewStream")]
public class CreateViewStream : MMFTestBase
{
private static readonly String s_fileNameForLargeCapacity = "CreateViewStream_MMF_ForLargeCapacity.txt";
[Fact]
public static void CreateViewStreamTestCases()
{
bool bResult = false;
CreateViewStream test = new CreateViewStream();
try
{
bResult = test.runTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main.ToString());
}
Assert.True(bResult, "One or more test cases failed.");
}
public bool runTest()
{
try
{
////////////////////////////////////////////////////////////////////////
// CreateViewStream()
////////////////////////////////////////////////////////////////////////
long defaultCapacity = SystemInfoHelpers.GetPageSize();
MemoryMappedFileAccess defaultAccess = MemoryMappedFileAccess.ReadWrite;
String fileContents = String.Empty;
// Verify default values
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname101", 100))
{
VerifyCreateViewStream("Loc101", mmf, defaultCapacity, defaultAccess, fileContents);
}
// default length is full MMF
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname102", defaultCapacity * 2))
{
VerifyCreateViewStream("Loc102", mmf, defaultCapacity * 2, defaultAccess, fileContents);
}
// if MMF is read-only, default access throws
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname103", 100, MemoryMappedFileAccess.Read))
{
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc103", mmf);
}
////////////////////////////////////////////////////////////////////////
// CreateViewStream(long, long)
////////////////////////////////////////////////////////////////////////
// capacity
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname200", defaultCapacity * 2))
{
// 0
VerifyCreateViewStream("Loc201", mmf, 0, 0, defaultCapacity * 2, defaultAccess, fileContents);
// >0
VerifyCreateViewStream("Loc202", mmf, 100, 0, defaultCapacity * 2 - 100, defaultAccess, fileContents);
// >pagesize
VerifyCreateViewStream("Loc203", mmf, defaultCapacity + 100, 0, defaultCapacity - 100, defaultAccess, fileContents);
// <0
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc204", mmf, -1, 0);
// =MMF capacity
VerifyCreateViewStream("Loc205", mmf, defaultCapacity * 2, 0, 0, defaultAccess, fileContents);
// >MMF capacity
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc206", mmf, defaultCapacity * 2 + 1, 0);
}
// size
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname410", defaultCapacity * 2))
{
// 0
VerifyCreateViewStream("Loc211", mmf, 1000, 0, defaultCapacity * 2 - 1000, defaultAccess, fileContents);
// >0, <pagesize
VerifyCreateViewStream("Loc212", mmf, 100, 1000, 1000, defaultAccess, fileContents);
// =pagesize
VerifyCreateViewStream("Loc213", mmf, 100, defaultCapacity, defaultCapacity, defaultAccess, fileContents);
// >pagesize
VerifyCreateViewStream("Loc214", mmf, 100, defaultCapacity + 1000, defaultCapacity + 1000, defaultAccess, fileContents);
// <0
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc215", mmf, 0, -1);
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc216", mmf, 0, -2);
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc217", mmf, 0, Int64.MinValue);
// offset+size = MMF capacity
VerifyCreateViewStream("Loc218", mmf, 0, defaultCapacity * 2, defaultCapacity * 2, defaultAccess, fileContents);
VerifyCreateViewStream("Loc219", mmf, defaultCapacity, defaultCapacity, defaultCapacity, defaultAccess, fileContents);
VerifyCreateViewStream("Loc220", mmf, defaultCapacity * 2 - 1, 1, 1, defaultAccess, fileContents);
// offset+size > MMF capacity
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc221", mmf, 0, defaultCapacity * 2 + 1);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc222", mmf, 1, defaultCapacity * 2);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc223", mmf, defaultCapacity, defaultCapacity + 1);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc224", mmf, defaultCapacity * 2, 1);
// Int64.MaxValue - cannot exceed local address space
if (IntPtr.Size == 4)
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc225", mmf, 0, Int64.MaxValue);
else // 64-bit machine
VerifyCreateViewStreamException<IOException>("Loc225b", mmf, 0, Int64.MaxValue); // valid but too large
}
////////////////////////////////////////////////////////////////////////
// CreateViewStream(long, long, MemoryMappedFileAccess)
////////////////////////////////////////////////////////////////////////
// [] offset
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname400", defaultCapacity * 2))
{
// 0
VerifyCreateViewStream("Loc401", mmf, 0, 0, defaultAccess, defaultCapacity * 2, defaultAccess, fileContents);
// >0
VerifyCreateViewStream("Loc402", mmf, 100, 0, defaultAccess, defaultCapacity * 2 - 100, defaultAccess, fileContents);
// >pagesize
VerifyCreateViewStream("Loc403", mmf, defaultCapacity + 100, 0, defaultAccess, defaultCapacity - 100, defaultAccess, fileContents);
// <0
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc404", mmf, -1, 0, defaultAccess);
// =MMF capacity
VerifyCreateViewStream("Loc405", mmf, defaultCapacity * 2, 0, defaultAccess, 0, defaultAccess, fileContents);
// >MMF capacity
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc406", mmf, defaultCapacity * 2 + 1, 0, defaultAccess);
}
// size
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname410", defaultCapacity * 2))
{
// 0
VerifyCreateViewStream("Loc411", mmf, 1000, 0, defaultAccess, defaultCapacity * 2 - 1000, defaultAccess, fileContents);
// >0, <pagesize
VerifyCreateViewStream("Loc412", mmf, 100, 1000, defaultAccess, 1000, defaultAccess, fileContents);
// =pagesize
VerifyCreateViewStream("Loc413", mmf, 100, defaultCapacity, defaultAccess, defaultCapacity, defaultAccess, fileContents);
// >pagesize
VerifyCreateViewStream("Loc414", mmf, 100, defaultCapacity + 1000, defaultAccess, defaultCapacity + 1000, defaultAccess, fileContents);
// <0
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc415", mmf, 0, -1, defaultAccess);
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc416", mmf, 0, -2, defaultAccess);
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc417", mmf, 0, Int64.MinValue, defaultAccess);
// offset+size = MMF capacity
VerifyCreateViewStream("Loc418", mmf, 0, defaultCapacity * 2, defaultAccess, defaultCapacity * 2, defaultAccess, fileContents);
VerifyCreateViewStream("Loc419", mmf, defaultCapacity, defaultCapacity, defaultAccess, defaultCapacity, defaultAccess, fileContents);
VerifyCreateViewStream("Loc420", mmf, defaultCapacity * 2 - 1, 1, defaultAccess, 1, defaultAccess, fileContents);
// offset+size > MMF capacity
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc421", mmf, 0, defaultCapacity * 2 + 1, defaultAccess);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc422", mmf, 1, defaultCapacity * 2, defaultAccess);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc423", mmf, defaultCapacity, defaultCapacity + 1, defaultAccess);
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc424", mmf, defaultCapacity * 2, 1, defaultAccess);
// Int64.MaxValue - cannot exceed local address space
if (IntPtr.Size == 4)
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc425", mmf, 0, Int64.MaxValue, defaultAccess);
else // 64-bit machine
VerifyCreateViewStreamException<IOException>("Loc425b", mmf, 0, Int64.MaxValue, defaultAccess); // valid but too large
}
// [] access
MemoryMappedFileAccess[] accessList;
// existing file is ReadWriteExecute
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname431", 1000, MemoryMappedFileAccess.ReadWriteExecute))
{
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.Write,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStream("Loc431_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents);
}
}
// existing file is ReadExecute
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname432", 1000, MemoryMappedFileAccess.ReadExecute))
{
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.CopyOnWrite,
MemoryMappedFileAccess.ReadExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStream("Loc432_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents);
}
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Write,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc432_" + access, mmf, 0, 0, access);
}
}
// existing file is CopyOnWrite
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname433", 1000, MemoryMappedFileAccess.CopyOnWrite))
{
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.CopyOnWrite,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStream("Loc433_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents);
}
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Write,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc433_" + access, mmf, 0, 0, access);
}
}
// existing file is ReadWrite
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname434", 1000, MemoryMappedFileAccess.ReadWrite))
{
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.Write,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStream("Loc434_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents);
}
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc434_" + access, mmf, 0, 0, access);
}
}
// existing file is Read
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname435", 1000, MemoryMappedFileAccess.Read))
{
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.CopyOnWrite,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStream("Loc435_" + access, mmf, 0, 0, access, defaultCapacity, access, fileContents);
}
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Write,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStreamException<UnauthorizedAccessException>("Loc435_" + access, mmf, 0, 0, access);
}
}
// invalid enum value
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("CVS_mapname436", 1000, MemoryMappedFileAccess.ReadWrite))
{
accessList = new MemoryMappedFileAccess[] {
(MemoryMappedFileAccess)(-1),
(MemoryMappedFileAccess)(6),
};
foreach (MemoryMappedFileAccess access in accessList)
{
VerifyCreateViewStreamException<ArgumentOutOfRangeException>("Loc436_" + ((int)access), mmf, 0, 0, access);
}
}
// File-backed MemoryMappedFile size should not be constrained to size of system's logical address space
TestLargeCapacity();
/// END TEST CASES
if (iCountErrors == 0)
{
return true;
}
else
{
Console.WriteLine("FAiL! iCountErrors==" + iCountErrors);
return false;
}
}
catch (Exception ex)
{
Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex);
return false;
}
}
private void TestLargeCapacity()
{
try
{
// Prepare the test file
using (FileStream fs = File.Open(s_fileNameForLargeCapacity, FileMode.CreateNew)) { }
// 2^31-1, 2^31, 2^31+1, 2^32-1, 2^32, 2^32+1
Int64[] capacities = { 2147483647, 2147483648, 2147483649, 4294967295, 4294967296, 4294967297 };
foreach (Int64 capacity in capacities)
{
RunTestLargeCapacity(capacity);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Unexpected exception in TestLargeCapacity: {0}", ex.ToString());
}
finally
{
if (File.Exists(s_fileNameForLargeCapacity))
{
File.Delete(s_fileNameForLargeCapacity);
}
}
}
private void RunTestLargeCapacity(Int64 capacity)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(s_fileNameForLargeCapacity, FileMode.Open, "RunTestLargeCapacity", capacity))
{
try
{
// mapping all; this should fail for 32-bit
using (MemoryMappedViewStream viewStream =
mmf.CreateViewStream(0, capacity, MemoryMappedFileAccess.ReadWrite))
{
if (IntPtr.Size == 4)
{
iCountErrors++;
Console.WriteLine("Err440! Not throwing expected ArgumentOutOfRangeException for capacity " + capacity);
}
}
}
catch (ArgumentOutOfRangeException aore)
{
if (IntPtr.Size != 4)
{
iCountErrors++;
Console.WriteLine("Err441! Shouldn't get ArgumentOutOfRangeException on 64-bit: {0}", aore.ToString());
}
else if (capacity < UInt32.MaxValue)
{
iCountErrors++;
Console.WriteLine("Err442! Expected IOExc but got ArgOutOfRangeExc");
}
else
{
// Got expected ArgumentOutOfRangeException
}
}
catch (IOException ioex)
{
if (IntPtr.Size != 4)
{
iCountErrors++;
Console.WriteLine("Err443! Shouldn't get IOException on 64-bit: {0}", ioex.ToString());
}
else if (capacity > UInt32.MaxValue)
{
Console.WriteLine("Err444! Expected ArgOutOfRangeExc but got IOExc: {0}", ioex.ToString());
}
else
{
// Got expected IOException
}
}
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err445! Got unexpected exception: {0}", ex.ToString());
}
}
/// START HELPER FUNCTIONS
public void VerifyCreateViewStream(String strLoc, MemoryMappedFile mmf, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents)
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream())
{
Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc);
VerifyAccess(strLoc, view, expectedAccess);
VerifyContents(strLoc, view, expectedContents);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateViewStreamException<EXCTYPE>(String strLoc, MemoryMappedFile mmf) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream())
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateViewStream(String strLoc, MemoryMappedFile mmf, long offset, long size, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents)
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream(offset, size))
{
Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc);
VerifyAccess(strLoc, view, expectedAccess);
VerifyContents(strLoc, view, expectedContents);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateViewStreamException<EXCTYPE>(String strLoc, MemoryMappedFile mmf, long offset, long size) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream(offset, size))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateViewStream(String strLoc, MemoryMappedFile mmf, long offset, long size, MemoryMappedFileAccess access, long expectedCapacity, MemoryMappedFileAccess expectedAccess, String expectedContents)
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream(offset, size, access))
{
Eval(expectedCapacity, view.Capacity, "ERROR, {0}: Wrong capacity", strLoc);
VerifyAccess(strLoc, view, expectedAccess);
VerifyContents(strLoc, view, expectedContents);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateViewStreamException<EXCTYPE>(String strLoc, MemoryMappedFile mmf, long offset, long size, MemoryMappedFileAccess access) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedViewStream view = mmf.CreateViewStream(offset, size, access))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
void VerifyAccess(String strLoc, MemoryMappedViewStream view, MemoryMappedFileAccess expectedAccess)
{
try
{
bool expectedRead = ((expectedAccess == MemoryMappedFileAccess.Read) ||
(expectedAccess == MemoryMappedFileAccess.CopyOnWrite) ||
(expectedAccess == MemoryMappedFileAccess.ReadWrite) ||
(expectedAccess == MemoryMappedFileAccess.ReadExecute) ||
(expectedAccess == MemoryMappedFileAccess.ReadWriteExecute));
bool expectedWrite = ((expectedAccess == MemoryMappedFileAccess.Write) ||
(expectedAccess == MemoryMappedFileAccess.CopyOnWrite) ||
(expectedAccess == MemoryMappedFileAccess.ReadWrite) ||
(expectedAccess == MemoryMappedFileAccess.ReadWriteExecute));
Eval(expectedRead, view.CanRead, "ERROR, {0}, CanRead was wrong", strLoc);
Eval(expectedWrite, view.CanWrite, "ERROR, {0}, CanWrite was wrong", strLoc);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}, Unexpected exception, {1}", strLoc, ex);
}
}
void VerifyContents(String strLoc, MemoryMappedViewStream view, String expectedContents)
{
}
}
| |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2011 Embarcadero Technologies, Inc.
//
//*******************************************************
using System;
namespace Embarcadero.Datasnap.WindowsPhone7
{
/**
* This class extends DBXValue and overrides the setter and getter methods of
* DBXValue to allows to set and get specified types
*/
public class DBXWritableValue : DBXValue {
/**
* It clears internal structure with defaults.
*/
public override void Clear() {
booleanValue = false;
INT32Value = 0;
UINT32Value = 0;
INT64Value = 0;
UINT64Value = 0;
stringValue = "";
singleValue = 0;
doubleValue = 0;
dateTimeValue = DateTime.MinValue;
streamValue = null;
objectValue = null;
jsonValueValue = null;
bcdValue = 0;
DBXValueValue = null;
TimeStampValue = DateTime.MinValue;
}
public override string ToString()
{
return base.ToString();
}
/**
* Return as DBXDataTypes
*/
public override int GetAsTDBXDate() {
checkCurrentDBXType(DBXDataTypes.DateType);
return this.INT32Value;
}
/**
* Set as DBXDataTypes
*/
public override void SetAsTDBXDate(int Value)
{
this.INT32Value = Value;
setDBXType(DBXDataTypes.DateType);
}
/**
* Set as JsonValueType
*/
public override void SetAsJSONValue(TJSONValue Value)
{
jsonValueValue = Value;
setDBXType(DBXDataTypes.JsonValueType);
}
/**
* Return as JsonValueType
*/
public override TJSONValue GetAsJSONValue()
{
checkCurrentDBXType(DBXDataTypes.JsonValueType);
return jsonValueValue;
}
/**
* Set as BinaryBlobType
*/
public override void SetAsStream(TStream Value)
{
streamValue = Value;
setDBXType(DBXDataTypes.BinaryBlobType);
}
/**
* Return as BinaryBlobType
*/
public override TStream GetAsStream()
{
checkCurrentDBXType(DBXDataTypes.BinaryBlobType);
return streamValue;
}
/**
* Return as UInt64Type
*/
public override long GetAsUInt64()
{
checkCurrentDBXType(DBXDataTypes.UInt64Type);
return UINT64Value;
}
/**
* Return as UInt32Type
*/
public override long GetAsUInt32()
{
checkCurrentDBXType(DBXDataTypes.UInt32Type);
return UINT32Value;
}
/**
* Set as TableType
*/
public override void SetAsTable(TableType Value)
{
objectValue = (Object) Value;
setDBXType(DBXDataTypes.TableType);
}
/**
* Return as TableType
*/
public override Object GetAsTable()
{
checkCurrentDBXType(DBXDataTypes.TableType);
return objectValue;
}
public static Double CurrencyRound(double value) {
Double bd = Math.Round(value, DBXDefaultFormatter.CURRENCYDECIMALPLACE);
return bd;
}
public DBXWritableValue() : base()
{
}
protected override void throwInvalidValue()
{
throw new DBXException("Invalid value for param");
}
/**
* Set as String
*/
public override void SetAsAnsiString(String value) {
SetAsString(value);
}
/**
* Return as WideStringType
*/
public override String GetAsAnsiString()
{
checkCurrentDBXType(DBXDataTypes.WideStringType);
return stringValue;
}
/**
* Set as BooleanType
*/
public override void SetAsBoolean(bool Value)
{
this.booleanValue = Value;
setDBXType(DBXDataTypes.BooleanType);
}
/**
* Set as UInt8Type
*/
public override void SetAsUInt8(int Value)
{
if (Value >= 0 && Value <= 255) {
this.INT32Value = Value;
setDBXType(DBXDataTypes.UInt8Type);
} else
throwInvalidValue();
}
/**
* Set as Int8Type
*/
public override void SetAsInt8(int Value)
{
if (Value >= -127 && Value <= 128) {
this.INT32Value = Value;
setDBXType(DBXDataTypes.Int8Type);
} else
throwInvalidValue();
}
/**
* Set as UInt16Type
*/
public override void SetAsUInt16(int Value)
{
if (Value >= 0 && Value <= 65535) {
this.INT32Value = Value;
setDBXType(DBXDataTypes.UInt16Type);
} else
throwInvalidValue();
}
/**
* Set as Int16Type
*/
public override void SetAsInt16(int Value)
{
if (Value >= -32768 && Value <= 32767) {
this.INT32Value = Value;
setDBXType(DBXDataTypes.Int16Type);
} else
throwInvalidValue();
}
/**
* Set as Int32Type
*/
public override void SetAsInt32(int Value)
{
if (Value >= -2147483648 && Value <= 2147483647) {
this.INT32Value = Value;
setDBXType(DBXDataTypes.Int32Type);
} else
throwInvalidValue();
}
/**
* Set as Int64Type
*/
public override void SetAsInt64(long Value)
{
if (Value >= -9223372036854775808L && Value <= 9223372036854775807L) {
this.INT64Value = Value;
setDBXType(DBXDataTypes.Int64Type);
} else
throwInvalidValue();
}
/**
* Set as WideStringType
*/
public override void SetAsString(String Value)
{
this.stringValue = Value;
setDBXType(DBXDataTypes.WideStringType);
}
/**
* Set as SingleType
*/
public override void SetAsSingle(float Value)
{
this.singleValue = Value;
setDBXType(DBXDataTypes.SingleType);
}
/**
* Set as DoubleType
*/
public override void SetAsDouble(double Value)
{
this.doubleValue = Value;
setDBXType(DBXDataTypes.DoubleType);
}
/**
* Set as DateType
*/
public override void SetAsDate(DateTime Value) {
this.dateTimeValue = Value;
setDBXType(DBXDataTypes.DateType);
}
/**
* Set as TimeType
*/
public override void SetAsTime(DateTime Value)
{
this.dateTimeValue = Value;
setDBXType(DBXDataTypes.TimeType);
}
/**
* Set as DateTimeType
*/
public override void SetAsDateTime(DateTime Value)
{
this.dateTimeValue = Value;
setDBXType(DBXDataTypes.DateTimeType);
}
/**
* Set as TimeStampType
*/
public override void SetAsTimeStamp(DateTime Value)
{
this.TimeStampValue = Value;
setDBXType(DBXDataTypes.TimeStampType);
}
/**
* Set as BcdType
*/
public override void SetAsBcd(double Value)
{
this.bcdValue = Value;
setDBXType(DBXDataTypes.BcdType);
}
/**
* Set as CurrencyType
*/
public override void SetAsCurrency(double Value)
{
this.doubleValue = Value;
setDBXType(DBXDataTypes.CurrencyType);
}
/**
* Set as UInt32Type
*/
public void SetAsUInt32(long Value) {
if (Value >= 0 && Value <= 4294967295L) {
this.UINT32Value = Value;
setDBXType(DBXDataTypes.UInt32Type);
} else
throwInvalidValue();
}
/**
* Set as UInt64Type
*/
public override void SetAsUInt64(long Value)
{
this.UINT64Value = Value;
setDBXType(DBXDataTypes.UInt64Type);
}
protected override void checkCurrentDBXType(int value)
{
if (value != CurrentDBXType)
throw new DBXException("Incorrect type in DBXValue");
}
/**
* Return as BooleanType
*/
public override bool GetAsBoolean()
{
checkCurrentDBXType(DBXDataTypes.BooleanType);
return this.booleanValue;
}
/**
* Return as UInt8Type
*/
public override int GetAsUInt8()
{
checkCurrentDBXType(DBXDataTypes.UInt8Type);
return this.INT32Value;
}
/**
* Return as Int8Type
*/
public override int GetAsInt8()
{
checkCurrentDBXType(DBXDataTypes.Int8Type);
return this.INT32Value;
}
/**
* Return as UInt16Type
*/
public override int GetAsUInt16()
{
checkCurrentDBXType(DBXDataTypes.UInt16Type);
return this.INT32Value;
}
/**
* Return as Int16Type
*/
public override int GetAsInt16()
{
checkCurrentDBXType(DBXDataTypes.Int16Type);
return this.INT32Value;
}
/**
* Return as Int32Type
*/
public override int GetAsInt32()
{
checkCurrentDBXType(DBXDataTypes.Int32Type);
return this.INT32Value;
}
/**
* Return as Int64Type
*/
public override long GetAsInt64()
{
checkCurrentDBXType(DBXDataTypes.Int64Type);
return this.INT64Value;
}
/**
* Return as WideStringType
*/
public override String GetAsString() {
checkCurrentDBXType(DBXDataTypes.WideStringType);
return this.stringValue;
}
/**
* Return as SingleType
*/
public override float GetAsSingle()
{
checkCurrentDBXType(DBXDataTypes.SingleType);
return this.singleValue;
}
/**
* Return as DoubleType
*/
public override double GetAsDouble()
{
setDBXType(DBXDataTypes.DoubleType);
return this.doubleValue;
}
/**
* Return as DateType
*/
public override DateTime GetAsDate()
{
checkCurrentDBXType(DBXDataTypes.DateType);
return this.dateTimeValue;
}
/**
* Return as TimeType
*/
public override DateTime GetAsTime()
{
checkCurrentDBXType(DBXDataTypes.TimeType);
return this.dateTimeValue;
}
/**
* Return as DateTimeType
*/
public override DateTime GetAsDateTime()
{
checkCurrentDBXType(DBXDataTypes.DateTimeType);
return this.dateTimeValue;
}
/**
* Return as TimeStampType
*/
public override DateTime GetAsTimeStamp()
{
checkCurrentDBXType(DBXDataTypes.TimeStampType);
return this.TimeStampValue;
}
/**
* Return as CurrencyType
*/
public override double GetAsCurrency()
{
checkCurrentDBXType(DBXDataTypes.CurrencyType);
return this.doubleValue;
}
/**
* Return as BcdType
*/
public override double GetAsBcd()
{
checkCurrentDBXType(DBXDataTypes.BcdType);
return this.bcdValue;
}
/**
* Return as TimeType
*/
public override int GetAsTDBXTime()
{
checkCurrentDBXType(DBXDataTypes.TimeType);
return this.INT32Value;
}
/**
* Set as TimeType
*/
public override void SetAsTDBXTime(int Value)
{
this.INT32Value = Value;
setDBXType(DBXDataTypes.TimeType);
}
/**
* Set as BlobType
*/
public override void SetAsBlob(TStream value)
{
this.objectValue = value;
setDBXType(DBXDataTypes.BlobType);
}
/**
* Return as BlobType
*/
public override TStream GetAsBlob()
{
checkCurrentDBXType(DBXDataTypes.BlobType);
return (TStream) this.objectValue;
}
// ********** DBXValueType ******************************
public override void SetAsDBXValue(DBXValue Value) {
setDBXType(Value.getDBXType());
isSimpleValueType = true;
DBXValueValue = Value;
}
/**
* Return as DBXValueValue
*/
public override DBXValue GetAsDBXValue() {
if (!isSimpleValueType)
throw new DBXException("Invalid DBX type");
return this.DBXValueValue;
}
/**
* Set null a DBXValue based on its TypeName
*/
public override void SetTDBXNull(String TypeName) {
if (TypeName.Equals("TDBXStringValue")) {
TDBXStringValue v = new TDBXStringValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXAnsiCharsValue")) {
TDBXAnsiCharsValue v = new TDBXAnsiCharsValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXAnsiStringValue")) {
TDBXAnsiStringValue v = new TDBXAnsiStringValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXSingleValue")) {
TDBXSingleValue v = new TDBXSingleValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXWideStringValue")) {
TDBXWideStringValue v = new TDBXWideStringValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXDateValue")) {
TDBXDateValue v = new TDBXDateValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXTimeValue")) {
TDBXTimeValue v = new TDBXTimeValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXBooleanValue")) {
TDBXBooleanValue v = new TDBXBooleanValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXDoubleValue")) {
TDBXDoubleValue v = new TDBXDoubleValue();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXInt64Value")) {
TDBXInt64Value v = new TDBXInt64Value();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXInt32Value")) {
TDBXInt32Value v = new TDBXInt32Value();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXInt16Value")) {
TDBXInt16Value v = new TDBXInt16Value();
v.setNull();
SetAsDBXValue(v);
} else if (TypeName.Equals("TDBXInt8Value")) {
TDBXInt8Value v = new TDBXInt8Value();
v.setNull();
SetAsDBXValue(v);
}
else if (TypeName.Equals("TDBXStreamValue"))
{
TDBXStreamValue v = new TDBXStreamValue();
v.setNull();
SetAsDBXValue(v);
}
else if (TypeName.Equals("TDBXReaderValue"))
{
TDBXReaderValue v = new TDBXReaderValue();
v.setNull();
SetAsDBXValue(v);
}
}
}
}
| |
namespace System.Net.Mail
{
using System;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.Net.Configuration;
using System.Threading;
using System.Threading.Tasks;
using System.Security;
using System.Security.Permissions;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Net.NetworkInformation;
using System.Runtime.Versioning;
using System.Text;
using System.Globalization;
public delegate void SendCompletedEventHandler(object sender, AsyncCompletedEventArgs e);
public enum SmtpDeliveryMethod {
Network,
SpecifiedPickupDirectory,
#if !FEATURE_PAL
PickupDirectoryFromIis
#endif
}
// EAI Settings
public enum SmtpDeliveryFormat {
SevenBit = 0, // Legacy
International = 1, // SMTPUTF8 - Email Address Internationalization (EAI)
}
public class SmtpClient : IDisposable {
string host;
int port;
bool inCall;
bool cancelled;
bool timedOut;
string targetName = null;
SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network;
SmtpDeliveryFormat deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
string pickupDirectoryLocation = null;
SmtpTransport transport;
MailMessage message; //required to prevent premature finalization
MailWriter writer;
MailAddressCollection recipients;
SendOrPostCallback onSendCompletedDelegate;
Timer timer;
static volatile MailSettingsSectionGroupInternal mailConfiguration;
ContextAwareResult operationCompletedResult = null;
AsyncOperation asyncOp = null;
static AsyncCallback _ContextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
static int defaultPort = 25;
internal string clientDomain = null;
bool disposed = false;
// true if the host and port change between calls to send or GetServicePoint
bool servicePointChanged = false;
ServicePoint servicePoint = null;
// (async only) For when only some recipients fail. We still send the e-mail to the others.
SmtpFailedRecipientException failedRecipientException;
// ports above this limit are invalid
const int maxPortValue = 65535;
public event SendCompletedEventHandler SendCompleted;
public SmtpClient() {
if (Logging.On) Logging.Enter(Logging.Web, "SmtpClient", ".ctor", "");
try {
Initialize();
} finally {
if (Logging.On) Logging.Exit(Logging.Web, "SmtpClient", ".ctor", this);
}
}
public SmtpClient(string host) {
if (Logging.On) Logging.Enter(Logging.Web, "SmtpClient", ".ctor", "host=" + host);
try {
this.host = host;
Initialize();
} finally {
if (Logging.On) Logging.Exit(Logging.Web, "SmtpClient", ".ctor", this);
}
}
//?? should port throw or just default on 0?
public SmtpClient(string host, int port) {
if (Logging.On) Logging.Enter(Logging.Web, "SmtpClient", ".ctor", "host=" + host + ", port=" + port);
try {
if (port < 0) {
throw new ArgumentOutOfRangeException("port");
}
this.host = host;
this.port = port;
Initialize();
} finally {
if (Logging.On) Logging.Exit(Logging.Web, "SmtpClient", ".ctor", this);
}
}
void Initialize() {
if (port == defaultPort || port == 0) {
new SmtpPermission(SmtpAccess.Connect).Demand();
}
else {
new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
}
transport = new SmtpTransport(this);
if (Logging.On) Logging.Associate(Logging.Web, this, transport);
onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
if (MailConfiguration.Smtp != null)
{
if (MailConfiguration.Smtp.Network != null)
{
if (host == null || host.Length == 0) {
host = MailConfiguration.Smtp.Network.Host;
}
if (port == 0) {
port = MailConfiguration.Smtp.Network.Port;
}
transport.Credentials = MailConfiguration.Smtp.Network.Credential;
transport.EnableSsl = MailConfiguration.Smtp.Network.EnableSsl;
if (MailConfiguration.Smtp.Network.TargetName != null)
targetName = MailConfiguration.Smtp.Network.TargetName;
// If the config file contains a domain to be used for the
// domain element in the client's EHLO or HELO message,
// use it.
//
// We do not validate whether the domain specified is valid.
// It is up to the administrators or user to use the right
// value for their scenario.
//
// Note: per section 4.1.4 of RFC2821, the domain element of
// the HELO/EHLO should be used for logging purposes. An
// SMTP server should not decide to route an email based on
// this value.
clientDomain = MailConfiguration.Smtp.Network.ClientDomain;
}
deliveryFormat = MailConfiguration.Smtp.DeliveryFormat;
deliveryMethod = MailConfiguration.Smtp.DeliveryMethod;
if (MailConfiguration.Smtp.SpecifiedPickupDirectory != null)
pickupDirectoryLocation = MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
}
if (host != null && host.Length != 0) {
host = host.Trim();
}
if (port == 0) {
port = defaultPort;
}
if (this.targetName == null)
targetName = "SMTPSVC/" + host;
if (clientDomain == null) {
// We use the local host name as the default client domain
// for the client's EHLO or HELO message. This limits the
// information about the host that we share. Additionally, the
// FQDN is not available to us or useful to the server (internal
// machine connecting to public server).
// SMTP RFC's require ASCII only host names in the HELO/EHLO message.
string clientDomainRaw = IPGlobalProperties.InternalGetIPGlobalProperties().HostName;
IdnMapping mapping = new IdnMapping();
try
{
clientDomainRaw = mapping.GetAscii(clientDomainRaw);
}
catch (ArgumentException) { }
// For some inputs GetAscii may fail (bad Unicode, etc). If that happens
// we must strip out any non-ASCII characters.
// If we end up with no characters left, we use the string "LocalHost". This
// matches Outlook behavior.
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < clientDomainRaw.Length; i++) {
ch = clientDomainRaw[i];
if ((ushort)ch <= 0x7F)
sb.Append(ch);
}
if (sb.Length > 0)
clientDomain = sb.ToString();
else
clientDomain = "LocalHost";
}
}
public string Host {
get {
return host;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value == String.Empty)
{
throw new ArgumentException(SR.GetString(SR.net_emptystringset), "value");
}
value = value.Trim();
if (value != host)
{
host = value;
servicePointChanged = true;
}
}
}
public int Port {
get {
return port;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
if (value <= 0) {
throw new ArgumentOutOfRangeException("value");
}
if (value != defaultPort) {
new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
}
if (value != port) {
port = value;
servicePointChanged = true;
}
}
}
public bool UseDefaultCredentials {
get {
return (transport.Credentials is SystemNetworkCredential) ? true : false;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
transport.Credentials = value ? CredentialCache.DefaultNetworkCredentials : null;
}
}
public ICredentialsByHost Credentials {
get {
return transport.Credentials;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
transport.Credentials = value;
}
}
public int Timeout {
get {
return transport.Timeout;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
transport.Timeout = value;
}
}
public ServicePoint ServicePoint {
get {
CheckHostAndPort();
if (servicePoint == null || servicePointChanged) {
servicePoint = ServicePointManager.FindServicePoint(host, port);
// servicePoint is now correct for current host and port
servicePointChanged = false;
}
return servicePoint;
}
}
public SmtpDeliveryMethod DeliveryMethod {
get {
return deliveryMethod;
}
set {
deliveryMethod = value;
}
}
// Should we use EAI formats?
public SmtpDeliveryFormat DeliveryFormat {
get {
return deliveryFormat;
}
set {
deliveryFormat = value;
}
}
public string PickupDirectoryLocation {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
return pickupDirectoryLocation;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
set {
pickupDirectoryLocation = value;
}
}
/// <summary>
/// <para>Set to true if we need SSL</para>
/// </summary>
public bool EnableSsl {
get {
return transport.EnableSsl;
}
set {
transport.EnableSsl = value;
}
}
/// <summary>
/// Certificates used by the client for establishing an SSL connection with the server.
/// </summary>
public X509CertificateCollection ClientCertificates {
get {
return transport.ClientCertificates;
}
}
public string TargetName {
set { this.targetName = value; }
get { return this.targetName; }
}
private bool ServerSupportsEai {
get {
return transport.ServerSupportsEai;
}
}
private bool IsUnicodeSupported() {
if (DeliveryMethod == SmtpDeliveryMethod.Network) {
return (ServerSupportsEai && (DeliveryFormat == SmtpDeliveryFormat.International));
}
else { // Pickup directories
return (DeliveryFormat == SmtpDeliveryFormat.International);
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal MailWriter GetFileMailWriter(string pickupDirectory)
{
if (Logging.On) Logging.PrintInfo(Logging.Web, "SmtpClient.Send() pickupDirectory=" + pickupDirectory);
if (!Path.IsPathRooted(pickupDirectory))
throw new SmtpException(SR.GetString(SR.SmtpNeedAbsolutePickupDirectory));
string filename;
string pathAndFilename;
while (true) {
filename = Guid.NewGuid().ToString() + ".eml";
pathAndFilename = Path.Combine(pickupDirectory, filename);
if (!File.Exists(pathAndFilename))
break;
}
FileStream fileStream = new FileStream(pathAndFilename, FileMode.CreateNew);
return new MailWriter(fileStream);
}
protected void OnSendCompleted(AsyncCompletedEventArgs e)
{
if (SendCompleted != null) {
SendCompleted(this, e);
}
}
void SendCompletedWaitCallback(object operationState) {
OnSendCompleted((AsyncCompletedEventArgs)operationState);
}
public void Send(string from, string recipients, string subject, string body) {
if (disposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
//validation happends in MailMessage constructor
MailMessage mailMessage = new MailMessage(from, recipients, subject, body);
Send(mailMessage);
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public void Send(MailMessage message) {
if (Logging.On) Logging.Enter(Logging.Web, this, "Send", message);
if (disposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
try {
if (Logging.On) Logging.PrintInfo(Logging.Web, this, "Send", "DeliveryMethod=" + DeliveryMethod.ToString());
if (Logging.On) Logging.Associate(Logging.Web, this, message);
SmtpFailedRecipientException recipientException = null;
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.net_inasync));
}
if (message == null) {
throw new ArgumentNullException("message");
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
MailAddressCollection recipients = new MailAddressCollection();
if (message.From == null) {
throw new InvalidOperationException(SR.GetString(SR.SmtpFromRequired));
}
if (message.To != null) {
foreach (MailAddress address in message.To) {
recipients.Add(address);
}
}
if (message.Bcc != null) {
foreach (MailAddress address in message.Bcc) {
recipients.Add(address);
}
}
if (message.CC != null) {
foreach (MailAddress address in message.CC) {
recipients.Add(address);
}
}
if (recipients.Count == 0) {
throw new InvalidOperationException(SR.GetString(SR.SmtpRecipientRequired));
}
transport.IdentityRequired = false; // everything completes on the same thread.
try {
InCall = true;
timedOut = false;
timer = new Timer(new TimerCallback(this.TimeOutCallback), null, Timeout, Timeout);
bool allowUnicode = false;
string pickupDirectory = PickupDirectoryLocation;
MailWriter writer;
switch (DeliveryMethod) {
#if !FEATURE_PAL
case SmtpDeliveryMethod.PickupDirectoryFromIis:
pickupDirectory = IisPickupDirectory.GetPickupDirectory();
goto case SmtpDeliveryMethod.SpecifiedPickupDirectory;
#endif // !FEATURE_PAL
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
if (EnableSsl)
throw new SmtpException(SR.GetString(SR.SmtpPickupDirectoryDoesnotSupportSsl));
allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = GetFileMailWriter(pickupDirectory);
break;
case SmtpDeliveryMethod.Network:
default:
GetConnection();
// Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = transport.SendMail(message.Sender ?? message.From, recipients,
message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
break;
}
this.message = message;
message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
writer.Close();
transport.ReleaseConnection();
//throw if we couldn't send to any of the recipients
if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null) {
throw recipientException;
}
}
catch (Exception e) {
if (Logging.On) Logging.Exception(Logging.Web, this, "Send", e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal) {
throw;
}
Abort();
if (timedOut) {
throw new SmtpException(SR.GetString(SR.net_timeout));
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.GetString(SR.SmtpSendMailFailure), e);
}
finally {
InCall = false;
if (timer != null) {
timer.Dispose();
}
}
} finally {
if (Logging.On) Logging.Exit(Logging.Web, this, "Send", null);
}
}
[HostProtection(ExternalThreading = true)]
public void SendAsync(string from, string recipients, string subject, string body, object userToken) {
if (disposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
SendAsync(new MailMessage(from, recipients, subject, body), userToken);
}
[HostProtection(ExternalThreading = true)]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public void SendAsync(MailMessage message, object userToken) {
if (disposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
if (Logging.On) Logging.Enter(Logging.Web, this, "SendAsync", "DeliveryMethod=" + DeliveryMethod.ToString());
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync Transport#" + ValidationHelper.HashString(transport));
try {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.net_inasync));
}
if (message == null) {
throw new ArgumentNullException("message");
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
recipients = new MailAddressCollection();
if (message.From == null) {
throw new InvalidOperationException(SR.GetString(SR.SmtpFromRequired));
}
if (message.To != null) {
foreach (MailAddress address in message.To) {
recipients.Add(address);
}
}
if (message.Bcc != null) {
foreach (MailAddress address in message.Bcc) {
recipients.Add(address);
}
}
if (message.CC != null) {
foreach (MailAddress address in message.CC) {
recipients.Add(address);
}
}
if (recipients.Count == 0) {
throw new InvalidOperationException(SR.GetString(SR.SmtpRecipientRequired));
}
try {
InCall = true;
cancelled = false;
this.message = message;
string pickupDirectory = PickupDirectoryLocation;
#if !FEATURE_PAL
CredentialCache cache;
// Skip token capturing if no credentials are used or they don't include a default one.
// Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
transport.IdentityRequired = Credentials != null && (Credentials is SystemNetworkCredential || (cache = Credentials as CredentialCache) == null || cache.IsDefaultInCache);
#endif // !FEATURE_PAL
asyncOp = AsyncOperationManager.CreateOperation(userToken);
switch (DeliveryMethod) {
#if !FEATURE_PAL
case SmtpDeliveryMethod.PickupDirectoryFromIis:
pickupDirectory = IisPickupDirectory.GetPickupDirectory();
goto case SmtpDeliveryMethod.SpecifiedPickupDirectory;
#endif // !FEATURE_PAL
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
{
if (EnableSsl)
throw new SmtpException(SR.GetString(SR.SmtpPickupDirectoryDoesnotSupportSsl));
writer = GetFileMailWriter(pickupDirectory);
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
message.Send(writer, true, allowUnicode);
if (writer != null)
writer.Close();
transport.ReleaseConnection();
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, asyncOp.UserSuppliedState);
InCall = false;
asyncOp.PostOperationCompleted(onSendCompletedDelegate, eventArgs);
break;
}
case SmtpDeliveryMethod.Network:
default:
operationCompletedResult = new ContextAwareResult(transport.IdentityRequired, true, null, this, _ContextSafeCompleteCallback);
lock (operationCompletedResult.StartPostingAsyncOp())
{
GlobalLog.Print("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync calling BeginConnect. Transport#" + ValidationHelper.HashString(transport));
transport.BeginGetConnection(ServicePoint, operationCompletedResult, ConnectCallback, operationCompletedResult);
operationCompletedResult.FinishPostingAsyncOp();
}
break;
}
}
catch (Exception e) {
InCall = false;
if (Logging.On) Logging.Exception(Logging.Web, this, "Send", e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal) {
throw;
}
Abort();
if (timedOut) {
throw new SmtpException(SR.GetString(SR.net_timeout));
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.GetString(SR.SmtpSendMailFailure), e);
}
} finally {
if (Logging.On) Logging.Exit(Logging.Web, this, "SendAsync", null);
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync");
}
}
public void SendAsyncCancel() {
if (disposed) {
throw new ObjectDisposedException(this.GetType().FullName);
}
if (Logging.On) Logging.Enter(Logging.Web, this, "SendAsyncCancel", null);
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsyncCancel");
try {
if (!InCall || cancelled) {
return;
}
cancelled = true;
Abort();
} finally {
if (Logging.On) Logging.Exit(Logging.Web, this, "SendAsyncCancel", null);
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsyncCancel");
}
}
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public Task SendMailAsync(string from, string recipients, string subject, string body)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message);
}
[HostProtection(ExternalThreading = true)]
public Task SendMailAsync(MailMessage message)
{
// Create a TaskCompletionSource to represent the operation
var tcs = new TaskCompletionSource<object>();
// Register a handler that will transfer completion results to the TCS Task
SendCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, handler);
this.SendCompleted += handler;
// Start the async operation.
try { this.SendAsync(message, tcs); }
catch
{
this.SendCompleted -= handler;
throw;
}
// Return the task to represent the asynchronous operation
return tcs.Task;
}
private void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler)
{
if (e.UserState == tcs)
{
try { this.SendCompleted -= handler; }
finally
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(null);
}
}
}
//*********************************
// private methods
//********************************
internal bool InCall {
get {
return inCall;
}
set {
inCall = value;
}
}
internal static MailSettingsSectionGroupInternal MailConfiguration {
get {
if (mailConfiguration == null) {
mailConfiguration = MailSettingsSectionGroupInternal.GetSection();
}
return mailConfiguration;
}
}
void CheckHostAndPort() {
if (host == null || host.Length == 0) {
throw new InvalidOperationException(SR.GetString(SR.UnspecifiedHost));
}
if (port <= 0 || port > maxPortValue) {
throw new InvalidOperationException(SR.GetString(SR.InvalidPort));
}
}
void TimeOutCallback(object state) {
if (!timedOut) {
timedOut = true;
Abort();
}
}
void Complete(Exception exception, IAsyncResult result) {
ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete");
try {
if (cancelled) {
//any exceptions were probably caused by cancellation, clear it.
exception = null;
Abort();
}
// An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
{
GlobalLog.Print("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete Exception: " + exception.ToString());
Abort();
if (!(exception is SmtpException)) {
exception = new SmtpException(SR.GetString(SR.SmtpSendMailFailure), exception);
}
}
else {
if (writer != null) {
try {
writer.Close();
}
// Close may result in a DataStopCommand and the server may return error codes at this time.
catch (SmtpException se) {
exception = se;
}
}
transport.ReleaseConnection();
}
}
finally {
operationCompletedResult.InvokeCallback(exception);
}
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete");
}
static void ContextSafeCompleteCallback(IAsyncResult ar)
{
ContextAwareResult result = (ContextAwareResult)ar;
SmtpClient client = (SmtpClient)ar.AsyncState;
Exception exception = result.Result as Exception;
AsyncOperation asyncOp = client.asyncOp;
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client.cancelled, asyncOp.UserSuppliedState);
client.InCall = false;
client.failedRecipientException = null; // Reset before the next send.
asyncOp.PostOperationCompleted(client.onSendCompletedDelegate, eventArgs);
}
void SendMessageCallback(IAsyncResult result) {
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendMessageCallback");
try {
message.EndSend(result);
// If some recipients failed but not others, throw AFTER sending the message.
Complete(failedRecipientException, result);
}
catch (Exception e) {
Complete(e, result);
}
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendMessageCallback");
}
void SendMailCallback(IAsyncResult result) {
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendMailCallback");
try {
writer = transport.EndSendMail(result);
// If some recipients failed but not others, send the e-mail anyways, but then return the
// "Non-fatal" exception reporting the failures. The [....] code path does it this way.
// Fatal exceptions would have thrown above at transport.EndSendMail(...)
SendMailAsyncResult sendResult = (SendMailAsyncResult)result;
// Save these and throw them later in SendMessageCallback, after the message has sent.
failedRecipientException = sendResult.GetFailedRecipientException();
}
catch (Exception e)
{
Complete(e, result);
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendMailCallback");
return;
}
try {
if (cancelled) {
Complete(null, result);
}
else {
message.BeginSend(writer, DeliveryMethod != SmtpDeliveryMethod.Network,
ServerSupportsEai, new AsyncCallback(SendMessageCallback), result.AsyncState);
}
}
catch (Exception e) {
Complete(e, result);
}
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendMailCallback");
}
void ConnectCallback(IAsyncResult result) {
GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::ConnectCallback");
try {
transport.EndGetConnection(result);
if (cancelled) {
Complete(null, result);
}
else {
// Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
transport.BeginSendMail(message.Sender ?? message.From, recipients,
message.BuildDeliveryStatusNotificationString(), allowUnicode,
new AsyncCallback(SendMailCallback), result.AsyncState);
}
}
catch (Exception e) {
Complete(e, result);
}
GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::ConnectCallback");
}
// After we've estabilished a connection and initilized ServerSupportsEai,
// check all the addresses for one that contains unicode in the username/localpart.
// The localpart is the only thing we cannot succesfully downgrade.
private void ValidateUnicodeRequirement(MailMessage message,
MailAddressCollection recipients, bool allowUnicode)
{
// Check all recipients, to, from, sender, bcc, cc, etc...
// GetSmtpAddress will throw if !allowUnicode and the username contains non-ascii
foreach (MailAddress address in recipients)
{
address.GetSmtpAddress(allowUnicode);
}
if (message.Sender != null)
{
message.Sender.GetSmtpAddress(allowUnicode);
}
message.From.GetSmtpAddress(allowUnicode);
}
void GetConnection() {
if (!transport.IsConnected) {
transport.GetConnection(ServicePoint);
}
}
void Abort() {
try {
transport.Abort();
}
catch {
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing && !disposed ) {
if (InCall && !cancelled) {
cancelled = true;
Abort();
}
if ((transport != null) && (servicePoint != null)) {
transport.CloseIdleConnections(servicePoint);
}
if (timer != null) {
timer.Dispose();
}
disposed = true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
private int _acceptedFileDescriptor;
private int _socketAddressSize;
private SocketFlags _receivedFlags;
internal int? SendPacketsDescriptorCount { get { return null; } }
private void InitializeInternals()
{
// No-op for *nix.
}
private void FreeInternals(bool calledFromFinalizer)
{
// No-op for *nix.
}
private void SetupSingleBuffer()
{
// No-op for *nix.
}
private void SetupMultipleBuffers()
{
// No-op for *nix.
}
private void SetupSendPacketsElements()
{
// No-op for *nix.
}
private void InnerComplete()
{
// No-op for *nix.
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
_acceptedFileDescriptor = -1;
}
private void AcceptCompletionCallback(int acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
{
// TODO: receive bytes on socket if requested
_acceptedFileDescriptor = acceptedFileDescriptor;
Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer);
_acceptAddressBufferCount = socketAddressSize;
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred)
{
Debug.Assert(acceptHandle == null);
bytesTransferred = 0;
return handle.AsyncContext.AcceptAsync(_buffer ?? _acceptBuffer, _acceptAddressBufferCount / 2, AcceptCompletionCallback);
}
private void InnerStartOperationConnect()
{
// No-op for *nix.
}
private void ConnectCompletionCallback(SocketError socketError)
{
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
bytesTransferred = 0;
return handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
}
private void InnerStartOperationDisconnect()
{
throw new PlatformNotSupportedException();
}
private void TransferCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
{
Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer);
_socketAddressSize = socketAddressSize;
_receivedFlags = receivedFlags;
CompletionCallback(bytesTransferred, socketError);
}
private void InnerStartOperationReceive()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveAsync(_bufferList, _socketFlags, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveFrom()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveMessageFrom()
{
_receiveMessageFromPacketInfo = default(IPPacketInformation);
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
{
Debug.Assert(_socketAddress != null);
Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);
_socketAddressSize = socketAddressSize;
_receivedFlags = receivedFlags;
_receiveMessageFromPacketInfo = ipPacketInformation;
CompletionCallback(bytesTransferred, errorCode);
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
bytesTransferred = 0;
return handle.AsyncContext.ReceiveMessageFromAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, isIPv4, isIPv6, ReceiveMessageFromCompletionCallback);
}
private void InnerStartOperationSend()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred)
{
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, _socketFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendAsync(_bufferList, _socketFlags, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
throw new PlatformNotSupportedException();
}
private void InnerStartOperationSendTo()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred)
{
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendToAsync(_bufferList, _socketFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
internal void LogBuffer(int size)
{
// TODO: implement?
}
internal void LogSendPacketsBuffers(int size)
{
throw new PlatformNotSupportedException();
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
_acceptSocket = _currentSocket.CreateAcceptSocket(
SafeCloseSocket.CreateSocket(_acceptedFileDescriptor),
_currentSocket._rightEndPoint.Create(remoteSocketAddress));
return SocketError.Success;
}
private SocketError FinishOperationConnect()
{
// No-op for *nix.
return SocketError.Success;
}
private unsafe int GetSocketAddressSize()
{
return _socketAddressSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
// No-op for *nix.
}
private void FinishOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
private void CompletionCallback(int bytesTransferred, SocketError socketError)
{
// TODO: plumb SocketFlags through TransferOperation
if (socketError == SocketError.Success)
{
FinishOperationSuccess(socketError, bytesTransferred, _receivedFlags);
}
else
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
FinishOperationAsyncFailure(socketError, bytesTransferred, _receivedFlags);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace Flatbox.RegularExpressions.Tests
{
public class RegexReplaceTests
{
public static IEnumerable<object[]> Replace_String_TestData()
{
yield return new object[] { @"[^ ]+\s(?<time>)", "08/10/99 16:00", "${time}", RegexOptions.None, 14, 0, "16:00" };
yield return new object[] { "icrosoft", "MiCrOsOfT", "icrosoft", RegexOptions.IgnoreCase, 9, 0, "Microsoft" };
yield return new object[] { "dog", "my dog has fleas", "CAT", RegexOptions.IgnoreCase, 16, 0, "my CAT has fleas" };
yield return new object[] { @"D\.(.+)", "D.Bau", "David $1", RegexOptions.None, 5, 0, "David Bau" };
yield return new object[] { "a", "aaaaa", "b", RegexOptions.None, 2, 0, "bbaaa" };
yield return new object[] { "a", "aaaaa", "b", RegexOptions.None, 2, 3, "aaabb" };
// Replace with group numbers
yield return new object[] { "([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z])))))))))))))))", "abcdefghiklmnop", "$15", RegexOptions.None, 15, 0, "p" };
yield return new object[] { "([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z])))))))))))))))", "abcdefghiklmnop", "$3", RegexOptions.None, 15, 0, "cdefghiklmnop" };
// Stress
string pattern = string.Empty;
for (int i = 0; i < 1000; i++)
pattern += "([a-z]";
for (int i = 0; i < 1000; i++)
pattern += ")";
string input = string.Empty;
for (int i = 0; i < 200; i++)
input += "abcde";
yield return new object[] { pattern, input, "$1000", RegexOptions.None, input.Length, 0, "e" };
string expected = string.Empty;
for (int i = 0; i < 200; i++)
expected += "abcde";
yield return new object[] { pattern, input, "$1", RegexOptions.None, input.Length, 0, expected };
// Undefined group
yield return new object[] { "([a_z])(.+)", "abc", "$3", RegexOptions.None, 3, 0, "$3" };
// Valid cases
yield return new object[] { @"(?<cat>cat)\s*(?<dog>dog)", "cat dog", "${cat}est ${dog}est", RegexOptions.None, 7, 0, "catest dogest" };
yield return new object[] { @"(?<cat>cat)\s*(?<dog>dog)", "slkfjsdcat dogkljeah", "START${cat}dogcat${dog}END", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<512>cat)\s*(?<256>dog)", "slkfjsdcat dogkljeah", "START${512}dogcat${256}END", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "START${256}dogcat${512}END", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<512>cat)\s*(?<256>dog)", "slkfjsdcat dogkljeah", "STARTcat$256$512dogEND", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat$512$256dogEND", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(hello)cat\s+dog(world)", "hellocat dogworld", "$1$$$2", RegexOptions.None, 19, 0, "hello$world" };
yield return new object[] { @"(hello)\s+(world)", "What the hello world goodby", "$&, how are you?", RegexOptions.None, 27, 0, "What the hello world, how are you? goodby" };
yield return new object[] { @"(hello)\s+(world)", "What the hello world goodby", "$`cookie are you doing", RegexOptions.None, 27, 0, "What the What the cookie are you doing goodby" };
yield return new object[] { @"(cat)\s+(dog)", "before textcat dogafter text", ". This is the $' and ", RegexOptions.None, 28, 0, "before text. This is the after text and after text" };
yield return new object[] { @"(cat)\s+(dog)", "before textcat dogafter text", ". The following should be dog and it is $+. ", RegexOptions.None, 28, 0, "before text. The following should be dog and it is dog. after text" };
yield return new object[] { @"(cat)\s+(dog)", "before textcat dogafter text", ". The following should be the entire string '$_'. ", RegexOptions.None, 28, 0, "before text. The following should be the entire string 'before textcat dogafter text'. after text" };
yield return new object[] { @"(hello)\s+(world)", "START hello world END", "$2 $1 $1 $2 $3$4", RegexOptions.None, 24, 0, "START world hello hello world $3$4 END" };
yield return new object[] { @"(hello)\s+(world)", "START hello world END", "$2 $1 $1 $2 $123$234", RegexOptions.None, 24, 0, "START world hello hello world $123$234 END" };
yield return new object[] { @"(d)(o)(g)(\s)(c)(a)(t)(\s)(h)(a)(s)", "My dog cat has fleas.", "$01$02$03$04$05$06$07$08$09$10$11", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline, 21, 0, "My dog cat has fleas." };
yield return new object[] { @"(d)(o)(g)(\s)(c)(a)(t)(\s)(h)(a)(s)", "My dog cat has fleas.", "$05$06$07$04$01$02$03$08$09$10$11", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline, 21, 0, "My cat dog has fleas." };
// ECMAScript
yield return new object[] { @"(?<512>cat)\s*(?<256>dog)", "slkfjsdcat dogkljeah", "STARTcat${256}${512}dogEND", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat${512}${256}dogEND", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<1>cat)\s*(?<2>dog)", "slkfjsdcat dogkljeah", "STARTcat$2$1dogEND", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<2>cat)\s*(?<1>dog)", "slkfjsdcat dogkljeah", "STARTcat$1$2dogEND", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<512>cat)\s*(?<256>dog)", "slkfjsdcat dogkljeah", "STARTcat$256$512dogEND", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "START${256}dogcat${512}END", RegexOptions.ECMAScript, 20, 0, "slkfjsdSTARTcatdogcatdogENDkljeah" };
yield return new object[] { @"(hello)\s+world", "START hello world END", "$234 $1 $1 $234 $3$4", RegexOptions.ECMAScript, 24, 0, "START $234 hello hello $234 $3$4 END" };
yield return new object[] { @"(hello)\s+(world)", "START hello world END", "$2 $1 $1 $2 $3$4", RegexOptions.ECMAScript, 24, 0, "START world hello hello world $3$4 END" };
yield return new object[] { @"(hello)\s+(world)", "START hello world END", "$2 $1 $1 $2 $123$234", RegexOptions.ECMAScript, 24, 0, "START world hello hello world hello23world34 END" };
yield return new object[] { @"(?<12>hello)\s+(world)", "START hello world END", "$1 $12 $12 $1 $123$134", RegexOptions.ECMAScript, 24, 0, "START world hello hello world hello3world34 END" };
yield return new object[] { @"(?<123>hello)\s+(?<23>world)", "START hello world END", "$23 $123 $123 $23 $123$234", RegexOptions.ECMAScript, 24, 0, "START world hello hello world helloworld4 END" };
yield return new object[] { @"(?<123>hello)\s+(?<234>world)", "START hello world END", "$234 $123 $123 $234 $123456$234567", RegexOptions.ECMAScript, 24, 0, "START world hello hello world hello456world567 END" };
yield return new object[] { @"(d)(o)(g)(\s)(c)(a)(t)(\s)(h)(a)(s)", "My dog cat has fleas.", "$01$02$03$04$05$06$07$08$09$10$11", RegexOptions.CultureInvariant | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline, 21, 0, "My dog cat has fleas." };
yield return new object[] { @"(d)(o)(g)(\s)(c)(a)(t)(\s)(h)(a)(s)", "My dog cat has fleas.", "$05$06$07$04$01$02$03$08$09$10$11", RegexOptions.CultureInvariant | RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline, 21, 0, "My cat dog has fleas." };
// Error cases
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat$512$", RegexOptions.None, 20, 0, "slkfjsdSTARTcatdog$kljeah" };
yield return new object[] { @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat$2048$1024dogEND", RegexOptions.None, 20, 0, "slkfjsdSTARTcat$2048$1024dogENDkljeah" };
yield return new object[] { @"(?<cat>cat)\s*(?<dog>dog)", "slkfjsdcat dogkljeah", "START${catTWO}dogcat${dogTWO}END", RegexOptions.None, 20, 0, "slkfjsdSTART${catTWO}dogcat${dogTWO}ENDkljeah" };
// RightToLeft
yield return new object[] { @"foo\s+", "0123456789foo4567890foo ", "bar", RegexOptions.RightToLeft, 32, 32, "0123456789foo4567890bar" };
yield return new object[] { @"\d", "0123456789foo4567890foo ", "#", RegexOptions.RightToLeft, 17, 32, "##########foo#######foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", "#", RegexOptions.RightToLeft, 7, 32, "0123456789foo#######foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", "#", RegexOptions.RightToLeft, 0, 32, "0123456789foo4567890foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", "#", RegexOptions.RightToLeft, -1, 32, "##########foo#######foo " };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$0", RegexOptions.RightToLeft, -1, 10, "abc123def!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$1", RegexOptions.RightToLeft, -1, 10, "abc1!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$2", RegexOptions.RightToLeft, -1, 10, "abc2!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$3", RegexOptions.RightToLeft, -1, 10, "abc3!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$4", RegexOptions.RightToLeft, -1, 10, "abc$4!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$$", RegexOptions.RightToLeft, -1, 10, "abc$!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$&", RegexOptions.RightToLeft, -1, 10, "abc123def!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$`", RegexOptions.RightToLeft, -1, 10, "abcabc!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$'", RegexOptions.RightToLeft, -1, 10, "abc!!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$+", RegexOptions.RightToLeft, -1, 10, "abc3!" };
yield return new object[] { "([1-9])([1-9])([1-9])def", "abc123def!", "$_", RegexOptions.RightToLeft, -1, 10, "abcabc123def!!" };
}
[Theory]
[MemberData(nameof(Replace_String_TestData))]
public void Replace(string pattern, string input, string replacement, RegexOptions options, int count, int start, string expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, count);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Replace(string, string) or Replace(string, string, string)
Assert.Equal(expected, new Regex(pattern).Replace(input, replacement));
Assert.Equal(expected, Regex.Replace(input, pattern, replacement));
}
if (isDefaultStart)
{
// Use Replace(string, string, string, int)
Assert.Equal(expected, new Regex(pattern).Replace(input, replacement, count));
}
// Use Replace(string, string, int, int)
Assert.Equal(expected, new Regex(pattern).Replace(input, replacement, count, start));
}
if (isDefaultStart && isDefaultCount)
{
// Use Replace(string, string) or Replace(string, string, string, RegexOptions)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, replacement));
Assert.Equal(expected, Regex.Replace(input, pattern, replacement, options));
}
if (isDefaultStart)
{
// Use Replace(string, string, string, int)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, replacement, count));
}
// Use Replace(string, string, int, int)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, replacement, count, start));
}
public static IEnumerable<object[]> Replace_MatchEvaluator_TestData()
{
yield return new object[] { "(Big|Small)", "Big mountain", new MatchEvaluator(MatchEvaluator1), RegexOptions.None, 12, 0, "Huge mountain" };
yield return new object[] { "(Big|Small)", "Small village", new MatchEvaluator(MatchEvaluator1), RegexOptions.None, 13, 0, "Tiny village" };
if ("i".ToUpper() == "I")
{
yield return new object[] { "(Big|Small)", "bIG horse", new MatchEvaluator(MatchEvaluator1), RegexOptions.IgnoreCase, 9, 0, "Huge horse" };
}
yield return new object[] { "(Big|Small)", "sMaLl dog", new MatchEvaluator(MatchEvaluator1), RegexOptions.IgnoreCase, 9, 0, "Tiny dog" };
yield return new object[] { ".+", "XSP_TEST_FAILURE", new MatchEvaluator(MatchEvaluator2), RegexOptions.None, 16, 0, "SUCCESS" };
yield return new object[] { "[abcabc]", "abcabc", new MatchEvaluator(MatchEvaluator3), RegexOptions.None, 6, 0, "ABCABC" };
yield return new object[] { "[abcabc]", "abcabc", new MatchEvaluator(MatchEvaluator3), RegexOptions.None, 3, 0, "ABCabc" };
yield return new object[] { "[abcabc]", "abcabc", new MatchEvaluator(MatchEvaluator3), RegexOptions.None, 3, 2, "abCABc" };
// Regression test:
// Regex treating Devanagari matra characters as matching "\b"
// Unicode characters in the "Mark, NonSpacing" Category, U+0902=Devanagari sign anusvara, U+0947=Devanagri vowel sign E
string boldInput = "\u092f\u0939 \u0915\u0930 \u0935\u0939 \u0915\u0930\u0947\u0902 \u0939\u0948\u0964";
string boldExpected = "\u092f\u0939 <b>\u0915\u0930</b> \u0935\u0939 <b>\u0915\u0930\u0947\u0902</b> \u0939\u0948\u0964";
yield return new object[] { @"\u0915\u0930.*?\b", boldInput, new MatchEvaluator(MatchEvaluatorBold), RegexOptions.CultureInvariant | RegexOptions.Singleline, boldInput.Length, 0, boldExpected };
// RighToLeft
yield return new object[] { @"foo\s+", "0123456789foo4567890foo ", new MatchEvaluator(MatchEvaluatorBar), RegexOptions.RightToLeft, 32, 32, "0123456789foo4567890bar" };
yield return new object[] { @"\d", "0123456789foo4567890foo ", new MatchEvaluator(MatchEvaluatorPoundSign), RegexOptions.RightToLeft, 17, 32, "##########foo#######foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", new MatchEvaluator(MatchEvaluatorPoundSign), RegexOptions.RightToLeft, 7, 32, "0123456789foo#######foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", new MatchEvaluator(MatchEvaluatorPoundSign), RegexOptions.RightToLeft, 0, 32, "0123456789foo4567890foo " };
yield return new object[] { @"\d", "0123456789foo4567890foo ", new MatchEvaluator(MatchEvaluatorPoundSign), RegexOptions.RightToLeft, -1, 32, "##########foo#######foo " };
}
[Theory]
[MemberData(nameof(Replace_MatchEvaluator_TestData))]
public void Replace(string pattern, string input, MatchEvaluator evaluator, RegexOptions options, int count, int start, string expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, count);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Replace(string, MatchEvaluator) or Replace(string, string, MatchEvaluator)
Assert.Equal(expected, new Regex(pattern).Replace(input, evaluator));
Assert.Equal(expected, Regex.Replace(input, pattern, evaluator));
}
if (isDefaultStart)
{
// Use Replace(string, MatchEvaluator, string, int)
Assert.Equal(expected, new Regex(pattern).Replace(input, evaluator, count));
}
// Use Replace(string, MatchEvaluator, int, int)
Assert.Equal(expected, new Regex(pattern).Replace(input, evaluator, count, start));
}
if (isDefaultStart && isDefaultCount)
{
// Use Replace(string, MatchEvaluator) or Replace(string, MatchEvaluator, RegexOptions)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, evaluator));
Assert.Equal(expected, Regex.Replace(input, pattern, evaluator, options));
}
if (isDefaultStart)
{
// Use Replace(string, MatchEvaluator, string, int)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, evaluator, count));
}
// Use Replace(string, MatchEvaluator, int, int)
Assert.Equal(expected, new Regex(pattern, options).Replace(input, evaluator, count, start));
}
[Fact]
public void Replace_NoMatch()
{
string input = "";
Assert.Same(input, Regex.Replace(input, "no-match", "replacement"));
Assert.Same(input, Regex.Replace(input, "no-match", new MatchEvaluator(MatchEvaluator1)));
}
[Fact]
public void Replace_Invalid()
{
// Input is null
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", "replacement"));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", "replacement", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", "replacement", RegexOptions.None, TimeSpan.FromMilliseconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, "replacement"));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, "replacement", 0));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, "replacement", 0, 0));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", new MatchEvaluator(MatchEvaluator1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", new MatchEvaluator(MatchEvaluator1), RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Replace(null, "pattern", new MatchEvaluator(MatchEvaluator1), RegexOptions.None, TimeSpan.FromMilliseconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, new MatchEvaluator(MatchEvaluator1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, new MatchEvaluator(MatchEvaluator1), 0));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Replace(null, new MatchEvaluator(MatchEvaluator1), 0, 0));
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, "replacement"));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, "replacement", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, "replacement", RegexOptions.None, TimeSpan.FromMilliseconds(1)));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, new MatchEvaluator(MatchEvaluator1)));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, new MatchEvaluator(MatchEvaluator1), RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Replace("input", null, new MatchEvaluator(MatchEvaluator1), RegexOptions.None, TimeSpan.FromMilliseconds(1)));
// Replacement is null
AssertExtensions.Throws<ArgumentNullException>("replacement", () => Regex.Replace("input", "pattern", (string)null));
AssertExtensions.Throws<ArgumentNullException>("replacement", () => Regex.Replace("input", "pattern", (string)null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("replacement", () => Regex.Replace("input", "pattern", (string)null, RegexOptions.None, TimeSpan.FromMilliseconds(1)));
AssertExtensions.Throws<ArgumentNullException>("replacement", () => new Regex("pattern").Replace("input", (string)null));
AssertExtensions.Throws<ArgumentNullException>("replacement", () => new Regex("pattern").Replace("input", (string)null, 0));
AssertExtensions.Throws<ArgumentNullException>("replacement", () => new Regex("pattern").Replace("input", (string)null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => Regex.Replace("input", "pattern", (MatchEvaluator)null));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => Regex.Replace("input", "pattern", (MatchEvaluator)null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => Regex.Replace("input", "pattern", (MatchEvaluator)null, RegexOptions.None, TimeSpan.FromMilliseconds(1)));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => new Regex("pattern").Replace("input", (MatchEvaluator)null));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => new Regex("pattern").Replace("input", (MatchEvaluator)null, 0));
AssertExtensions.Throws<ArgumentNullException>("evaluator", () => new Regex("pattern").Replace("input", (MatchEvaluator)null, 0, 0));
// Count is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => new Regex("pattern").Replace("input", "replacement", -2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => new Regex("pattern").Replace("input", "replacement", -2, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => new Regex("pattern").Replace("input", new MatchEvaluator(MatchEvaluator1), -2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => new Regex("pattern").Replace("input", new MatchEvaluator(MatchEvaluator1), -2, 0));
// Start is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Replace("input", "replacement", 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Replace("input", new MatchEvaluator(MatchEvaluator1), 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Replace("input", "replacement", 0, 6));
AssertExtensions.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Replace("input", new MatchEvaluator(MatchEvaluator1), 0, 6));
}
public static string MatchEvaluator1(Match match) => match.Value.ToLower() == "big" ? "Huge": "Tiny";
public static string MatchEvaluator2(Match match) => "SUCCESS";
public static string MatchEvaluator3(Match match)
{
if (match.Value == "a" || match.Value == "b" || match.Value == "c")
return match.Value.ToUpperInvariant();
return string.Empty;
}
public static string MatchEvaluatorBold(Match match) => string.Format("<b>{0}</b>", match.Value);
private static string MatchEvaluatorBar(Match match) => "bar";
private static string MatchEvaluatorPoundSign(Match match) => "#";
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
public class CloseTest : ClientWebSocketTestBase
{
public CloseTest(ITestOutputHelper output) : base(output) { }
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ServerInitiatedClose_Success(Uri server)
{
const string closeWebSocketMetaCommand = ".close";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
_output.WriteLine("SendAsync starting.");
await cws.SendAsync(
WebSocketData.GetBufferFromText(closeWebSocketMetaCommand),
WebSocketMessageType.Text,
true,
cts.Token);
_output.WriteLine("SendAsync done.");
var recvBuffer = new byte[256];
_output.WriteLine("ReceiveAsync starting.");
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(new ArraySegment<byte>(recvBuffer), cts.Token);
_output.WriteLine("ReceiveAsync done.");
// Verify received server-initiated close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, recvResult.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, recvResult.CloseStatusDescription);
// Verify current websocket state as CloseReceived which indicates only partial close.
Assert.Equal(WebSocketState.CloseReceived, cws.State);
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
// Send back close message to acknowledge server-initiated close.
_output.WriteLine("CloseAsync starting.");
await cws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, string.Empty, cts.Token);
_output.WriteLine("CloseAsync done.");
Assert.Equal(WebSocketState.Closed, cws.State);
// Verify that there is no follow-up echo close message back from the server by
// making sure the close code and message are the same as from the first server close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ClientInitiatedClose_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Assert.Equal(WebSocketState.Open, cws.State);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_InvalidMessageType";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLength_Success(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength + 1);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidCloseStatusDescription",
closeDescription,
CloseDescriptionMaxLength);
var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); });
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionHasUnicode_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_Containing\u016Cnicode.";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(true, String.IsNullOrEmpty(cws.CloseStatusDescription));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri server)
{
string message = "Hello WebSockets!";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
string closeDescription = "CloseOutputAsync_Client_InvalidPayloadData";
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Need a short delay as per WebSocket rfc6455 section 5.5.1 there isn't a requirement to receive any
// data fragments after a close has been sent. The delay allows the received data fragment to be
// available before calling close. The WinRT MessageWebSocket implementation doesn't allow receiving
// after a call to Close.
await Task.Delay(100);
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
// Should be able to receive the message echoed by the server.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(message.Length, recvResult.Count);
segmentRecv = new ArraySegment<byte>(segmentRecv.Array, 0, recvResult.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(segmentRecv));
Assert.Equal(null, recvResult.CloseStatus);
Assert.Equal(null, recvResult.CloseStatusDescription);
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ServerInitiated_CanSend(Uri server)
{
string message = "Hello WebSockets!";
var expectedCloseStatus = WebSocketCloseStatus.NormalClosure;
var expectedCloseDescription = ".shutdown";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".shutdown"),
WebSocketMessageType.Text,
true,
cts.Token);
// Should be able to receive a shutdown message.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(0, recvResult.Count);
Assert.Equal(expectedCloseStatus, recvResult.CloseStatus);
Assert.Equal(expectedCloseDescription, recvResult.CloseStatusDescription);
// Verify WebSocket state
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.CloseReceived, cws.State);
// Should be able to send.
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Cannot change the close status/description with the final close.
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
var closeDescription = "CloseOutputAsync_Client_Description";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
}
}
[ActiveIssue(20362, TargetFrameworkMonikers.NetFramework)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_DuringConcurrentReceiveAsync_ExpectedStates(Uri server)
{
var receiveBuffer = new byte[1024];
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
// Issue a receive but don't wait for it.
var t = cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
Assert.False(t.IsCompleted);
Assert.Equal(WebSocketState.Open, cws.State);
// Send a close frame. After this completes, the state could be CloseSent if we haven't
// yet received the server response close frame, or it could be CloseReceived if we have.
await cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Assert.True(
cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived,
$"Expected CloseSent or CloseReceived, got {cws.State}");
// Then wait for the receive. After this completes, the state is most likely CloseReceived,
// however there is a race condition between the our realizing that the send has completed
// and a fast server sending back a close frame, such that we could end up noticing the
// receive completion before we notice the send completion.
WebSocketReceiveResult r = await t;
Assert.Equal(WebSocketMessageType.Close, r.MessageType);
Assert.True(
cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived,
$"Expected CloseSent or CloseReceived, got {cws.State}");
// Then close
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Assert.Equal(WebSocketState.Closed, cws.State);
// Another close should fail
await Assert.ThrowsAsync<WebSocketException>(() => cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_DuringConcurrentReceiveAsync_ExpectedStates(Uri server)
{
var receiveBuffer = new byte[1024];
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var t = cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
Assert.False(t.IsCompleted);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
// There is a race condition in the above. If the ReceiveAsync receives the sent close message from the server,
// then it will complete successfully and the socket will close successfully. If the CloseAsync receive the sent
// close message from the server, then the receive async will end up getting aborted along with the socket.
try
{
await t;
Assert.Equal(WebSocketState.Closed, cws.State);
}
catch (OperationCanceledException)
{
Assert.Equal(WebSocketState.Aborted, cws.State);
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
/// <summary>
/// Represents an iCalendar period of time.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class Period :
EncodableDataType,
IPeriod
{
#region Private Fields
private IDateTime m_StartTime;
private IDateTime m_EndTime;
private TimeSpan m_Duration;
private bool m_MatchesDateOnly;
#endregion
#region Constructors
public Period()
{
}
public Period(IDateTime occurs) : this(occurs, default(TimeSpan)) { }
public Period(IDateTime start, IDateTime end) : this()
{
StartTime = start;
if (end != null)
{
EndTime = end;
Duration = end.Subtract(start);
}
}
public Period(IDateTime start, TimeSpan duration)
: this()
{
StartTime = start;
if (duration != default(TimeSpan))
{
Duration = duration;
EndTime = start.Add(duration);
}
}
#endregion
#region Overrides
public override void CopyFrom(ICopyable obj)
{
base.CopyFrom(obj);
IPeriod p = obj as IPeriod;
if (p != null)
{
StartTime = p.StartTime;
EndTime = p.EndTime;
Duration = p.Duration;
MatchesDateOnly = p.MatchesDateOnly;
}
}
public override bool Equals(object obj)
{
if (obj is IPeriod)
{
IPeriod p = (IPeriod)obj;
if (MatchesDateOnly || p.MatchesDateOnly)
{
return
StartTime.Value.Date == p.StartTime.Value.Date &&
(
EndTime == null ||
p.EndTime == null ||
EndTime.Value.Date.Equals(p.EndTime.Value.Date)
);
}
else
{
return
StartTime.Equals(p.StartTime) &&
(
EndTime == null ||
p.EndTime == null ||
EndTime.Equals(p.EndTime)
);
}
}
return false;
}
public override int GetHashCode()
{
return StartTime.GetHashCode() ^ EndTime.GetHashCode();
}
public override string ToString()
{
PeriodSerializer periodSerializer = new PeriodSerializer();
return periodSerializer.SerializeToString(this);
}
#endregion
#region Private Methods
private void ExtrapolateTimes()
{
if (EndTime == null && StartTime != null && Duration != default(TimeSpan))
EndTime = StartTime.Add(Duration);
else if (Duration == default(TimeSpan) && StartTime != null && EndTime != null)
Duration = EndTime.Subtract(StartTime);
else if (StartTime == null && Duration != default(TimeSpan) && EndTime != null)
StartTime = EndTime.Subtract(Duration);
}
#endregion
#region IPeriod Members
virtual public IDateTime StartTime
{
get { return m_StartTime; }
set
{
m_StartTime = value;
ExtrapolateTimes();
}
}
virtual public IDateTime EndTime
{
get { return m_EndTime; }
set
{
m_EndTime = value;
ExtrapolateTimes();
}
}
virtual public TimeSpan Duration
{
get { return m_Duration; }
set
{
if (!object.Equals(m_Duration, value))
{
m_Duration = value;
ExtrapolateTimes();
}
}
}
/// <summary>
/// When true, comparisons between this and other <see cref="Period"/>
/// objects are matched against the date only, and
/// not the date-time combination.
/// </summary>
virtual public bool MatchesDateOnly
{
get { return m_MatchesDateOnly; }
set { m_MatchesDateOnly = value; }
}
virtual public bool Contains(IDateTime dt)
{
// Start time is inclusive
if (dt != null &&
StartTime != null &&
StartTime.LessThanOrEqual(dt))
{
// End time is exclusive
if (EndTime == null || EndTime.GreaterThan(dt))
return true;
}
return false;
}
virtual public bool CollidesWith(IPeriod period)
{
if (period != null &&
(
(period.StartTime != null && Contains(period.StartTime)) ||
(period.EndTime != null && Contains(period.EndTime))
))
{
return true;
}
return false;
}
#endregion
#region IComparable Members
public int CompareTo(IPeriod p)
{
if (p == null)
throw new ArgumentNullException("p");
else if (Equals(p))
return 0;
else if (StartTime.LessThan(p.StartTime))
return -1;
else if (StartTime.GreaterThanOrEqual(p.StartTime))
return 1;
throw new Exception("An error occurred while comparing Period values.");
}
#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.
//
namespace System.Reflection
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
//
// Invocation cached flags. Those are used in unmanaged code as well
// so be careful if you change them
//
[Flags]
internal enum INVOCATION_FLAGS : uint
{
INVOCATION_FLAGS_UNKNOWN = 0x00000000,
INVOCATION_FLAGS_INITIALIZED = 0x00000001,
// it's used for both method and field to signify that no access is allowed
INVOCATION_FLAGS_NO_INVOKE = 0x00000002,
INVOCATION_FLAGS_NEED_SECURITY = 0x00000004,
// Set for static ctors and ctors on abstract types, which
// can be invoked only if the "this" object is provided (even if it's null).
INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008,
// because field and method are different we can reuse the same bits
// method
INVOCATION_FLAGS_IS_CTOR = 0x00000010,
INVOCATION_FLAGS_RISKY_METHOD = 0x00000020,
INVOCATION_FLAGS_NON_W8P_FX_API = 0x00000040,
INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080,
INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100,
// field
INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010,
INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020,
// temporary flag used for flagging invocation of method vs ctor
// this flag never appears on the instance m_invocationFlag and is simply
// passed down from within ConstructorInfo.Invoke()
INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000,
}
[Serializable]
public abstract class MethodBase : MemberInfo
{
#region Static Members
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
Type declaringType = m.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"),
m, declaringType.GetGenericTypeDefinition()));
return m;
}
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo());
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static MethodBase GetCurrentMethod()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark);
}
#endregion
#region Constructor
protected MethodBase() { }
#endregion
public static bool operator ==(MethodBase left, MethodBase right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null)
return false;
MethodInfo method1, method2;
ConstructorInfo constructor1, constructor2;
if ((method1 = left as MethodInfo) != null && (method2 = right as MethodInfo) != null)
return method1 == method2;
else if ((constructor1 = left as ConstructorInfo) != null && (constructor2 = right as ConstructorInfo) != null)
return constructor1 == constructor2;
return false;
}
public static bool operator !=(MethodBase left, MethodBase right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region Internal Members
// used by EE
private IntPtr GetMethodDesc() { return MethodHandle.Value; }
#if FEATURE_APPX
#endif
#endregion
#region Public Abstract\Virtual Members
internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters(); }
[System.Diagnostics.Contracts.Pure]
public abstract ParameterInfo[] GetParameters();
public virtual MethodImplAttributes MethodImplementationFlags
{
get
{
return GetMethodImplementationFlags();
}
}
public abstract MethodImplAttributes GetMethodImplementationFlags();
public abstract RuntimeMethodHandle MethodHandle { get; }
public abstract MethodAttributes Attributes { get; }
public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } }
public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual bool IsGenericMethodDefinition { get { return false; } }
public virtual bool ContainsGenericParameters { get { return false; } }
public virtual bool IsGenericMethod { get { return false; } }
public virtual bool IsSecurityCritical { get { throw new NotImplementedException(); } }
public virtual bool IsSecuritySafeCritical { get { throw new NotImplementedException(); } }
public virtual bool IsSecurityTransparent { get { throw new NotImplementedException(); } }
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object Invoke(Object obj, Object[] parameters)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return Invoke(obj, BindingFlags.Default, null, parameters, null);
}
public bool IsPublic { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } }
public bool IsPrivate { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } }
public bool IsFamily { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } }
public bool IsAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } }
public bool IsFamilyAndAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } }
public bool IsFamilyOrAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } }
public bool IsStatic { get { return (Attributes & MethodAttributes.Static) != 0; } }
public bool IsFinal
{
get { return (Attributes & MethodAttributes.Final) != 0; }
}
public bool IsVirtual
{
get { return (Attributes & MethodAttributes.Virtual) != 0; }
}
public bool IsHideBySig { get { return (Attributes & MethodAttributes.HideBySig) != 0; } }
public bool IsAbstract { get { return (Attributes & MethodAttributes.Abstract) != 0; } }
public bool IsSpecialName { get { return (Attributes & MethodAttributes.SpecialName) != 0; } }
public bool IsConstructor
{
get
{
// To be backward compatible we only return true for instance RTSpecialName ctors.
return (this is ConstructorInfo &&
!IsStatic &&
((Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName));
}
}
public virtual MethodBody GetMethodBody()
{
throw new InvalidOperationException();
}
#endregion
#region Internal Methods
// helper method to construct the string representation of the parameter list
internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization)
{
StringBuilder sbParamList = new StringBuilder();
string comma = "";
for (int i = 0; i < parameterTypes.Length; i++)
{
Type t = parameterTypes[i];
sbParamList.Append(comma);
string typeName = t.FormatTypeName(serialization);
// Legacy: Why use "ByRef" for by ref parameters? What language is this?
// VB uses "ByRef" but it should precede (not follow) the parameter name.
// Why don't we just use "&"?
if (t.IsByRef && !serialization)
{
sbParamList.Append(typeName.TrimEnd('&'));
sbParamList.Append(" ByRef");
}
else
{
sbParamList.Append(typeName);
}
comma = ", ";
}
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
sbParamList.Append(comma);
sbParamList.Append("...");
}
return sbParamList.ToString();
}
internal string FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig());
}
}
internal string FormatNameAndSig()
{
return FormatNameAndSig(false);
}
internal virtual string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
internal virtual Type[] GetParameterTypes()
{
ParameterInfo[] paramInfo = GetParametersNoCopy();
Type[] parameterTypes = new Type[paramInfo.Length];
for (int i = 0; i < paramInfo.Length; i++)
parameterTypes[i] = paramInfo[i].ParameterType;
return parameterTypes;
}
internal Object[] CheckArguments(Object[] parameters, Binder binder,
BindingFlags invokeAttr, CultureInfo culture, Signature sig)
{
// copy the arguments in a different array so we detach from any user changes
Object[] copyOfParameters = new Object[parameters.Length];
ParameterInfo[] p = null;
for (int i = 0; i < parameters.Length; i++)
{
Object arg = parameters[i];
RuntimeType argRT = sig.Arguments[i];
if (arg == Type.Missing)
{
if (p == null)
p = GetParametersNoCopy();
if (p[i].DefaultValue == System.DBNull.Value)
throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"), nameof(parameters));
arg = p[i].DefaultValue;
}
copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
}
return copyOfParameters;
}
#endregion
}
}
| |
namespace Loon.Action.Avg.Drama
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using Loon.Java.Collections;
using Loon.Utils;
using Loon.Core;
using Loon.Java;
public abstract class Conversion : Expression
{
private const int MAX_LENGTH = 128;
public const int STACK_VARIABLE = 11;
public const int STACK_RAND = -1;
public const int STACK_NUM = 0;
public const int PLUS = 1;
public const int MINUS = 2;
public const int MULTIPLE = 3;
public const int DIVISION = 4;
public const int MODULO = 5;
internal Exps exp = new Exps();
internal static bool IsCondition(string s)
{
if (s.Equals("==", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else if (s.Equals("!=", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else if (s.Equals(">=", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else if (s.Equals("<=", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else if (s.Equals(">", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
else if (s.Equals("<", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
internal static bool IsOperator(char c)
{
switch (c)
{
case '+':
return true;
case '-':
return true;
case '*':
return true;
case '/':
return true;
case '<':
return true;
case '>':
return true;
case '=':
return true;
case '%':
return true;
case '!':
return true;
}
return false;
}
public static string UpdateOperator(string context)
{
if (context != null
&& (context.StartsWith("\"") || context.StartsWith("'")))
{
return context;
}
int size = context.Length;
StringBuilder sbr = new StringBuilder(size * 2);
char[] chars = context.ToCharArray();
bool notFlag = false;
bool operators;
for (int i = 0; i < size; i++)
{
if (chars[i] == '"' || chars[i] == '\'')
{
notFlag = !notFlag;
}
if (notFlag)
{
sbr.Append(chars[i]);
continue;
}
if (chars[i] == ' ')
{
if (i > 0 && chars[i - 1] != ' ')
{
sbr.Append(FLAG);
}
}
else
{
operators = IsOperator(chars[i]);
if (i > 0)
{
if (operators && !IsOperator(chars[i - 1]))
{
if (chars[i - 1] != ' ')
{
sbr.Append(FLAG);
}
}
}
sbr.Append(chars[i]);
if (i < size - 1)
{
if (operators && !IsOperator(chars[i + 1]))
{
if (chars[i + 1] != ' ')
{
sbr.Append(FLAG);
}
}
}
}
}
return sbr.ToString().Trim();
}
public static IList SplitToList(string strings, string tag)
{
return Arrays.AsList(StringUtils.Split(strings, tag));
}
public class Exps : LRelease
{
private Dictionary<string, Compute> computes = new Dictionary<string, Compute>();
private char[] expChr;
private bool Exp(string exp)
{
return exp.IndexOf("+") != -1 || exp.IndexOf("-") != -1
|| exp.IndexOf("*") != -1 || exp.IndexOf("/") != -1
|| exp.IndexOf("%") != -1;
}
public float Parse(object v)
{
return Parse((string)v);
}
public float Parse(string v)
{
if (!Exp(v))
{
if (MathUtils.IsNan(v))
{
return float.Parse(v);
}
else
{
throw new RuntimeException(v + " not parse !");
}
}
return Eval(v);
}
private void EvalFloatValue(Compute compute, int stIdx, int lgt,
float sign)
{
if (expChr[stIdx] == '$')
{
string label = new string(expChr, stIdx + 1, lgt - 1);
if (label.Equals("rand", StringComparison.InvariantCultureIgnoreCase))
{
compute.Push(0, STACK_RAND);
}
else
{
int idx;
try
{
idx = int.Parse(label) - 1;
}
catch
{
compute.Push(0, STACK_NUM);
return;
}
compute.Push(0, STACK_VARIABLE + idx);
}
}
else
{
try
{
float idx = float.Parse(new string(expChr, stIdx, lgt));
compute.Push(idx * sign, STACK_NUM);
}
catch
{
compute.Push(0, STACK_NUM);
}
}
}
private void EvalExp(Compute compute, int stIdx, int edIdx)
{
int[] op = new int[] { -1, -1 };
while (expChr[stIdx] == '(' && expChr[edIdx - 1] == ')')
{
stIdx++;
edIdx--;
}
for (int i = edIdx - 1; i >= stIdx; i--)
{
char c = expChr[i];
if (c == ')')
{
do
{
i--;
} while (expChr[i] != '(');
}
else if (op[0] < 0 && (c == '*' || c == '/' || c == '%'))
{
op[0] = i;
}
else if (c == '+' || c == '-')
{
op[1] = i;
break;
}
}
if (op[1] < 0)
{
if (op[0] < 0)
{
EvalFloatValue(compute, stIdx, edIdx - stIdx, 1);
}
else
{
switch (expChr[op[0]])
{
case '*':
EvalExp(compute, stIdx, op[0]);
EvalExp(compute, op[0] + 1, edIdx);
compute.SetOperator(MULTIPLE);
break;
case '/':
EvalExp(compute, stIdx, op[0]);
EvalExp(compute, op[0] + 1, edIdx);
compute.SetOperator(DIVISION);
break;
case '%':
EvalExp(compute, stIdx, op[0]);
EvalExp(compute, op[0] + 1, edIdx);
compute.SetOperator(MODULO);
break;
}
}
}
else
{
if (op[1] == stIdx)
{
switch (expChr[op[1]])
{
case '-':
EvalFloatValue(compute, stIdx + 1, edIdx - stIdx - 1,
-1);
break;
case '+':
EvalFloatValue(compute, stIdx + 1, edIdx - stIdx - 1, 1);
break;
}
}
else
{
switch (expChr[op[1]])
{
case '+':
EvalExp(compute, stIdx, op[1]);
EvalExp(compute, op[1] + 1, edIdx);
compute.SetOperator(PLUS);
break;
case '-':
EvalExp(compute, stIdx, op[1]);
EvalExp(compute, op[1] + 1, edIdx);
compute.SetOperator(MINUS);
break;
}
}
}
}
public float Eval(string exp)
{
Compute compute = (Compute)CollectionUtils.Get(computes, exp);
if (compute == null)
{
expChr = new char[exp.Length];
int ecIdx = 0;
bool skip = false;
StringBuilder buf = new StringBuilder(exp);
int depth = 0;
bool balance = true;
char ch;
for (int i = 0; i < buf.Length; i++)
{
ch = buf[i];
switch (ch)
{
case ' ':
case '\n':
skip = true;
break;
case ')':
depth--;
if (depth < 0)
balance = false;
break;
case '(':
depth++;
break;
}
if (skip)
{
skip = false;
}
else
{
expChr[ecIdx] = ch;
ecIdx++;
}
}
if (depth != 0 || !balance)
{
return 0;
}
compute = new Compute();
EvalExp(compute, 0, ecIdx);
CollectionUtils.Put(computes, exp, compute);
}
return compute.Calc();
}
private class Compute
{
private float[] num = new float[MAX_LENGTH];
private int[] opr = new int[MAX_LENGTH];
private int idx;
private float[] stack = new float[MAX_LENGTH];
public Compute()
{
idx = 0;
}
private float CalcOp(int op, float n1, float n2)
{
switch (op)
{
case PLUS:
return n1 + n2;
case MINUS:
return n1 - n2;
case MULTIPLE:
return n1 * n2;
case DIVISION:
return n1 / n2;
case MODULO:
return n1 % n2;
}
return 0;
}
public void SetOperator(int op)
{
if (idx >= MAX_LENGTH)
{
return;
}
if (opr[idx - 1] == STACK_NUM && opr[idx - 2] == STACK_NUM)
{
num[idx - 2] = CalcOp(op, num[idx - 2], num[idx - 1]);
idx--;
}
else
{
opr[idx] = op;
idx++;
}
}
public void Push(float nm, int vr)
{
if (idx >= MAX_LENGTH)
{
return;
}
num[idx] = nm;
opr[idx] = vr;
idx++;
}
public float Calc()
{
int stkIdx = 0;
for (int i = 0; i < idx; i++)
{
switch (opr[i])
{
case STACK_NUM:
stack[stkIdx] = num[i];
stkIdx++;
break;
case STACK_RAND:
stack[stkIdx] = (float)LSystem.random.NextDouble();
stkIdx++;
break;
default:
if (opr[i] >= STACK_VARIABLE)
{
stkIdx++;
}
else
{
stack[stkIdx - 2] = CalcOp(opr[i],
stack[stkIdx - 2], stack[stkIdx - 1]);
stkIdx--;
}
break;
}
}
return stack[0];
}
}
public void Dispose()
{
if (computes != null)
{
computes.Clear();
}
}
}
}
}
| |
using System;
using Shouldly;
using Spk.Common.Helpers.Guard;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Spk.Common.Tests.Helpers.Guard
{
public partial class ArgumentGuardTests
{
public class GuardIsGreaterThanOrEqualTo_double
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
double argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
double argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_float
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
float argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
float argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_decimal
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
decimal argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
decimal argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_short
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
short argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
short argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_int
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
int argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
int argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_long
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
[InlineData(-1230, -1231)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
long argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
[InlineData(-1231, -1230)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
long argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_ushort
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
ushort argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
ushort argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
public class GuardIsGreaterThanOrEqualTo_uint
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
public void GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
uint argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
uint argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
public class GuardIsGreaterThanOrEqualTo_ulong
{
[Theory]
[InlineData(2, 1)]
[InlineData(2, 2)]
public void
GuardIsGreaterThanOrEqualTo_ShouldReturnUnalteredValue_WhenArgumentIsGreaterThanOrEqualToTarget(
ulong argument,
double target)
{
var result = argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument));
result.ShouldBe(argument);
}
[Theory]
[InlineData(1, 2)]
public void GuardIsGreaterThanOrEqualTo_ShouldThrow_WhenArgumentIsNotGreaterThanTarget(
ulong argument,
double target)
{
Assert.Throws<ArgumentOutOfRangeException>(
nameof(argument),
() => { argument.GuardIsGreaterThanOrEqualTo(target, nameof(argument)); });
}
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcmv = Google.Cloud.Monitoring.V3;
using sys = System;
namespace Google.Cloud.Monitoring.V3
{
/// <summary>Resource name for the <c>Service</c> resource.</summary>
public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName>
{
/// <summary>The possible contents of <see cref="ServiceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/services/{service}</c>.</summary>
ProjectService = 1,
/// <summary>A resource name with pattern <c>organizations/{organization}/services/{service}</c>.</summary>
OrganizationService = 2,
/// <summary>A resource name with pattern <c>folders/{folder}/services/{service}</c>.</summary>
FolderService = 3,
}
private static gax::PathTemplate s_projectService = new gax::PathTemplate("projects/{project}/services/{service}");
private static gax::PathTemplate s_organizationService = new gax::PathTemplate("organizations/{organization}/services/{service}");
private static gax::PathTemplate s_folderService = new gax::PathTemplate("folders/{folder}/services/{service}");
/// <summary>Creates a <see cref="ServiceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ServiceName"/> with the pattern <c>projects/{project}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromProjectService(string projectId, string serviceId) =>
new ServiceName(ResourceNameType.ProjectService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Creates a <see cref="ServiceName"/> with the pattern <c>organizations/{organization}/services/{service}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromOrganizationService(string organizationId, string serviceId) =>
new ServiceName(ResourceNameType.OrganizationService, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Creates a <see cref="ServiceName"/> with the pattern <c>folders/{folder}/services/{service}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromFolderService(string folderId, string serviceId) =>
new ServiceName(ResourceNameType.FolderService, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/services/{service}</c>.
/// </returns>
public static string Format(string projectId, string serviceId) => FormatProjectService(projectId, serviceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/services/{service}</c>.
/// </returns>
public static string FormatProjectService(string projectId, string serviceId) =>
s_projectService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>organizations/{organization}/services/{service}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>organizations/{organization}/services/{service}</c>.
/// </returns>
public static string FormatOrganizationService(string organizationId, string serviceId) =>
s_organizationService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>folders/{folder}/services/{service}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>folders/{folder}/services/{service}</c>.
/// </returns>
public static string FormatFolderService(string folderId, string serviceId) =>
s_folderService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/services/{service}</c></description></item>
/// <item><description><c>organizations/{organization}/services/{service}</c></description></item>
/// <item><description><c>folders/{folder}/services/{service}</c></description></item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName) => Parse(serviceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/services/{service}</c></description></item>
/// <item><description><c>organizations/{organization}/services/{service}</c></description></item>
/// <item><description><c>folders/{folder}/services/{service}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName, bool allowUnparsed) =>
TryParse(serviceName, allowUnparsed, out ServiceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/services/{service}</c></description></item>
/// <item><description><c>organizations/{organization}/services/{service}</c></description></item>
/// <item><description><c>folders/{folder}/services/{service}</c></description></item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceName, out ServiceName result) => TryParse(serviceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/services/{service}</c></description></item>
/// <item><description><c>organizations/{organization}/services/{service}</c></description></item>
/// <item><description><c>folders/{folder}/services/{service}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceName, bool allowUnparsed, out ServiceName result)
{
gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName));
gax::TemplatedResourceName resourceName;
if (s_projectService.TryParseName(serviceName, out resourceName))
{
result = FromProjectService(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationService.TryParseName(serviceName, out resourceName))
{
result = FromOrganizationService(resourceName[0], resourceName[1]);
return true;
}
if (s_folderService.TryParseName(serviceName, out resourceName))
{
result = FromFolderService(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string serviceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
ServiceId = serviceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern
/// <c>projects/{project}/services/{service}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
public ServiceName(string projectId, string serviceId) : this(ResourceNameType.ProjectService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Service</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ServiceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectService: return s_projectService.Expand(ProjectId, ServiceId);
case ResourceNameType.OrganizationService: return s_organizationService.Expand(OrganizationId, ServiceId);
case ResourceNameType.FolderService: return s_folderService.Expand(FolderId, ServiceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ServiceName);
/// <inheritdoc/>
public bool Equals(ServiceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceName a, ServiceName b) => !(a == b);
}
/// <summary>Resource name for the <c>ServiceLevelObjective</c> resource.</summary>
public sealed partial class ServiceLevelObjectiveName : gax::IResourceName, sys::IEquatable<ServiceLevelObjectiveName>
{
/// <summary>The possible contents of <see cref="ServiceLevelObjectiveName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
ProjectServiceServiceLevelObjective = 1,
/// <summary>
/// A resource name with pattern
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
OrganizationServiceServiceLevelObjective = 2,
/// <summary>
/// A resource name with pattern
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
FolderServiceServiceLevelObjective = 3,
}
private static gax::PathTemplate s_projectServiceServiceLevelObjective = new gax::PathTemplate("projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}");
private static gax::PathTemplate s_organizationServiceServiceLevelObjective = new gax::PathTemplate("organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}");
private static gax::PathTemplate s_folderServiceServiceLevelObjective = new gax::PathTemplate("folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}");
/// <summary>Creates a <see cref="ServiceLevelObjectiveName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ServiceLevelObjectiveName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceLevelObjectiveName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceLevelObjectiveName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids.
/// </returns>
public static ServiceLevelObjectiveName FromProjectServiceServiceLevelObjective(string projectId, string serviceId, string serviceLevelObjectiveId) =>
new ServiceLevelObjectiveName(ResourceNameType.ProjectServiceServiceLevelObjective, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids.
/// </returns>
public static ServiceLevelObjectiveName FromOrganizationServiceServiceLevelObjective(string organizationId, string serviceId, string serviceLevelObjectiveId) =>
new ServiceLevelObjectiveName(ResourceNameType.OrganizationServiceServiceLevelObjective, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids.
/// </returns>
public static ServiceLevelObjectiveName FromFolderServiceServiceLevelObjective(string folderId, string serviceId, string serviceLevelObjectiveId) =>
new ServiceLevelObjectiveName(ResourceNameType.FolderServiceServiceLevelObjective, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </returns>
public static string Format(string projectId, string serviceId, string serviceLevelObjectiveId) =>
FormatProjectServiceServiceLevelObjective(projectId, serviceId, serviceLevelObjectiveId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </returns>
public static string FormatProjectServiceServiceLevelObjective(string projectId, string serviceId, string serviceLevelObjectiveId) =>
s_projectServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </returns>
public static string FormatOrganizationServiceServiceLevelObjective(string organizationId, string serviceId, string serviceLevelObjectiveId) =>
s_organizationServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>.
/// </returns>
public static string FormatFolderServiceServiceLevelObjective(string folderId, string serviceId, string serviceLevelObjectiveId) =>
s_folderServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceLevelObjectiveName"/> if successful.</returns>
public static ServiceLevelObjectiveName Parse(string serviceLevelObjectiveName) =>
Parse(serviceLevelObjectiveName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ServiceLevelObjectiveName"/> if successful.</returns>
public static ServiceLevelObjectiveName Parse(string serviceLevelObjectiveName, bool allowUnparsed) =>
TryParse(serviceLevelObjectiveName, allowUnparsed, out ServiceLevelObjectiveName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceLevelObjectiveName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceLevelObjectiveName, out ServiceLevelObjectiveName result) =>
TryParse(serviceLevelObjectiveName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceLevelObjectiveName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string serviceLevelObjectiveName, bool allowUnparsed, out ServiceLevelObjectiveName result)
{
gax::GaxPreconditions.CheckNotNull(serviceLevelObjectiveName, nameof(serviceLevelObjectiveName));
gax::TemplatedResourceName resourceName;
if (s_projectServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName))
{
result = FromProjectServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_organizationServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName))
{
result = FromOrganizationServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_folderServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName))
{
result = FromFolderServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceLevelObjectiveName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceLevelObjectiveName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string serviceId = null, string serviceLevelObjectiveId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
ServiceId = serviceId;
ServiceLevelObjectiveId = serviceLevelObjectiveId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceLevelObjectiveName"/> class from the component parts of
/// pattern <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceLevelObjectiveId">
/// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ServiceLevelObjectiveName(string projectId, string serviceId, string serviceLevelObjectiveId) : this(ResourceNameType.ProjectServiceServiceLevelObjective, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Service</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ServiceId { get; }
/// <summary>
/// The <c>ServiceLevelObjective</c> ID. May be <c>null</c>, depending on which resource name is contained by
/// this instance.
/// </summary>
public string ServiceLevelObjectiveId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectServiceServiceLevelObjective: return s_projectServiceServiceLevelObjective.Expand(ProjectId, ServiceId, ServiceLevelObjectiveId);
case ResourceNameType.OrganizationServiceServiceLevelObjective: return s_organizationServiceServiceLevelObjective.Expand(OrganizationId, ServiceId, ServiceLevelObjectiveId);
case ResourceNameType.FolderServiceServiceLevelObjective: return s_folderServiceServiceLevelObjective.Expand(FolderId, ServiceId, ServiceLevelObjectiveId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ServiceLevelObjectiveName);
/// <inheritdoc/>
public bool Equals(ServiceLevelObjectiveName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceLevelObjectiveName a, ServiceLevelObjectiveName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceLevelObjectiveName a, ServiceLevelObjectiveName b) => !(a == b);
}
public partial class Service
{
/// <summary>
/// <see cref="gcmv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceName.TryParse(Name, out gcmv::ServiceName service))
{
return service;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class ServiceLevelObjective
{
/// <summary>
/// <see cref="gcmv::ServiceLevelObjectiveName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceLevelObjectiveName ServiceLevelObjectiveName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceLevelObjectiveName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceLevelObjectiveName.TryParse(Name, out gcmv::ServiceLevelObjectiveName serviceLevelObjective))
{
return serviceLevelObjective;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
}
| |
using J2N.Threading.Atomic;
using Lucene.Net.Index;
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Codecs.Lucene42
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using BlockPackedReader = Lucene.Net.Util.Packed.BlockPackedReader;
using ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput;
using BytesRef = Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using CorruptIndexException = Lucene.Net.Index.CorruptIndexException;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using DocValues = Lucene.Net.Index.DocValues;
using DocValuesType = Lucene.Net.Index.DocValuesType;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IBits = Lucene.Net.Util.IBits;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using Int32sRef = Lucene.Net.Util.Int32sRef;
using IOUtils = Lucene.Net.Util.IOUtils;
using MonotonicBlockPackedReader = Lucene.Net.Util.Packed.MonotonicBlockPackedReader;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using PagedBytes = Lucene.Net.Util.PagedBytes;
using PositiveInt32Outputs = Lucene.Net.Util.Fst.PositiveInt32Outputs;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using Util = Lucene.Net.Util.Fst.Util;
/// <summary>
/// Reader for <see cref="Lucene42DocValuesFormat"/>.
/// </summary>
internal class Lucene42DocValuesProducer : DocValuesProducer
{
// metadata maps (just file pointers and minimal stuff)
private readonly IDictionary<int, NumericEntry> numerics;
private readonly IDictionary<int, BinaryEntry> binaries;
private readonly IDictionary<int, FSTEntry> fsts;
private readonly IndexInput data;
private readonly int version;
// ram instances we have already loaded
private readonly IDictionary<int, NumericDocValues> numericInstances = new Dictionary<int, NumericDocValues>();
private readonly IDictionary<int, BinaryDocValues> binaryInstances = new Dictionary<int, BinaryDocValues>();
private readonly IDictionary<int, FST<long?>> fstInstances = new Dictionary<int, FST<long?>>();
private readonly int maxDoc;
private readonly AtomicInt64 ramBytesUsed;
internal const sbyte NUMBER = 0;
internal const sbyte BYTES = 1;
internal const sbyte FST = 2;
internal const int BLOCK_SIZE = 4096;
internal const sbyte DELTA_COMPRESSED = 0;
internal const sbyte TABLE_COMPRESSED = 1;
internal const sbyte UNCOMPRESSED = 2;
internal const sbyte GCD_COMPRESSED = 3;
internal const int VERSION_START = 0;
internal const int VERSION_GCD_COMPRESSION = 1;
internal const int VERSION_CHECKSUM = 2;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
internal Lucene42DocValuesProducer(SegmentReadState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension)
{
maxDoc = state.SegmentInfo.DocCount;
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
// read in the entries from the metadata file.
ChecksumIndexInput @in = state.Directory.OpenChecksumInput(metaName, state.Context);
bool success = false;
ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOfInstance(this.GetType()));
try
{
version = CodecUtil.CheckHeader(@in, metaCodec, VERSION_START, VERSION_CURRENT);
numerics = new Dictionary<int, NumericEntry>();
binaries = new Dictionary<int, BinaryEntry>();
fsts = new Dictionary<int, FSTEntry>();
ReadFields(@in, state.FieldInfos);
if (version >= VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(@in);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(@in);
#pragma warning restore 612, 618
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(@in);
}
else
{
IOUtils.DisposeWhileHandlingException(@in);
}
}
success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
data = state.Directory.OpenInput(dataName, state.Context);
int version2 = CodecUtil.CheckHeader(data, dataCodec, VERSION_START, VERSION_CURRENT);
if (version != version2)
{
throw new CorruptIndexException("Format versions mismatch");
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this.data);
}
}
}
private void ReadFields(IndexInput meta, FieldInfos infos)
{
int fieldNumber = meta.ReadVInt32();
while (fieldNumber != -1)
{
// check should be: infos.fieldInfo(fieldNumber) != null, which incorporates negative check
// but docvalues updates are currently buggy here (loading extra stuff, etc): LUCENE-5616
if (fieldNumber < 0)
{
// trickier to validate more: because we re-use for norms, because we use multiple entries
// for "composite" types like sortedset, etc.
throw new CorruptIndexException("Invalid field number: " + fieldNumber + ", input=" + meta);
}
int fieldType = meta.ReadByte();
if (fieldType == NUMBER)
{
var entry = new NumericEntry();
entry.Offset = meta.ReadInt64();
entry.Format = (sbyte)meta.ReadByte();
switch (entry.Format)
{
case DELTA_COMPRESSED:
case TABLE_COMPRESSED:
case GCD_COMPRESSED:
case UNCOMPRESSED:
break;
default:
throw new CorruptIndexException("Unknown format: " + entry.Format + ", input=" + meta);
}
if (entry.Format != UNCOMPRESSED)
{
entry.PackedInt32sVersion = meta.ReadVInt32();
}
numerics[fieldNumber] = entry;
}
else if (fieldType == BYTES)
{
BinaryEntry entry = new BinaryEntry();
entry.Offset = meta.ReadInt64();
entry.NumBytes = meta.ReadInt64();
entry.MinLength = meta.ReadVInt32();
entry.MaxLength = meta.ReadVInt32();
if (entry.MinLength != entry.MaxLength)
{
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
}
binaries[fieldNumber] = entry;
}
else if (fieldType == FST)
{
FSTEntry entry = new FSTEntry();
entry.Offset = meta.ReadInt64();
entry.NumOrds = meta.ReadVInt64();
fsts[fieldNumber] = entry;
}
else
{
throw new CorruptIndexException("invalid entry type: " + fieldType + ", input=" + meta);
}
fieldNumber = meta.ReadVInt32();
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
lock (this)
{
NumericDocValues instance;
if (!numericInstances.TryGetValue(field.Number, out instance) || instance == null)
{
instance = LoadNumeric(field);
numericInstances[field.Number] = instance;
}
return instance;
}
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity()
{
if (version >= VERSION_CHECKSUM)
{
CodecUtil.ChecksumEntireFile(data);
}
}
private NumericDocValues LoadNumeric(FieldInfo field)
{
NumericEntry entry = numerics[field.Number];
data.Seek(entry.Offset);
switch (entry.Format)
{
case TABLE_COMPRESSED:
int size = data.ReadVInt32();
if (size > 256)
{
throw new CorruptIndexException("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + data);
}
var decode = new long[size];
for (int i = 0; i < decode.Length; i++)
{
decode[i] = data.ReadInt64();
}
int formatID = data.ReadVInt32();
int bitsPerValue = data.ReadVInt32();
PackedInt32s.Reader ordsReader = PackedInt32s.GetReaderNoHeader(data, PackedInt32s.Format.ById(formatID), entry.PackedInt32sVersion, maxDoc, bitsPerValue);
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(decode) + ordsReader.RamBytesUsed());
return new NumericDocValuesAnonymousInnerClassHelper(decode, ordsReader);
case DELTA_COMPRESSED:
int blockSize = data.ReadVInt32();
var reader = new BlockPackedReader(data, entry.PackedInt32sVersion, blockSize, maxDoc, false);
ramBytesUsed.AddAndGet(reader.RamBytesUsed());
return reader;
case UNCOMPRESSED:
byte[] bytes = new byte[maxDoc];
data.ReadBytes(bytes, 0, bytes.Length);
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(bytes));
return new NumericDocValuesAnonymousInnerClassHelper2(this, bytes);
case GCD_COMPRESSED:
long min = data.ReadInt64();
long mult = data.ReadInt64();
int quotientBlockSize = data.ReadVInt32();
BlockPackedReader quotientReader = new BlockPackedReader(data, entry.PackedInt32sVersion, quotientBlockSize, maxDoc, false);
ramBytesUsed.AddAndGet(quotientReader.RamBytesUsed());
return new NumericDocValuesAnonymousInnerClassHelper3(min, mult, quotientReader);
default:
throw new InvalidOperationException();
}
}
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
private readonly long[] decode;
private readonly PackedInt32s.Reader ordsReader;
public NumericDocValuesAnonymousInnerClassHelper(long[] decode, PackedInt32s.Reader ordsReader)
{
this.decode = decode;
this.ordsReader = ordsReader;
}
public override long Get(int docID)
{
return decode[(int)ordsReader.Get(docID)];
}
}
private class NumericDocValuesAnonymousInnerClassHelper2 : NumericDocValues
{
private readonly byte[] bytes;
public NumericDocValuesAnonymousInnerClassHelper2(Lucene42DocValuesProducer outerInstance, byte[] bytes)
{
this.bytes = bytes;
}
public override long Get(int docID)
{
return (sbyte)bytes[docID];
}
}
private class NumericDocValuesAnonymousInnerClassHelper3 : NumericDocValues
{
private readonly long min;
private readonly long mult;
private readonly BlockPackedReader quotientReader;
public NumericDocValuesAnonymousInnerClassHelper3(long min, long mult, BlockPackedReader quotientReader)
{
this.min = min;
this.mult = mult;
this.quotientReader = quotientReader;
}
public override long Get(int docID)
{
return min + mult * quotientReader.Get(docID);
}
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
lock (this)
{
BinaryDocValues instance;
if (!binaryInstances.TryGetValue(field.Number, out instance) || instance == null)
{
instance = LoadBinary(field);
binaryInstances[field.Number] = instance;
}
return instance;
}
}
private BinaryDocValues LoadBinary(FieldInfo field)
{
BinaryEntry entry = binaries[field.Number];
data.Seek(entry.Offset);
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, entry.NumBytes);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
if (entry.MinLength == entry.MaxLength)
{
int fixedLength = entry.MinLength;
ramBytesUsed.AddAndGet(bytes.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper(bytesReader, fixedLength);
}
else
{
MonotonicBlockPackedReader addresses = new MonotonicBlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, maxDoc, false);
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + addresses.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper2(bytesReader, addresses);
}
}
private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly int fixedLength;
public BinaryDocValuesAnonymousInnerClassHelper(PagedBytes.Reader bytesReader, int fixedLength)
{
this.bytesReader = bytesReader;
this.fixedLength = fixedLength;
}
public override void Get(int docID, BytesRef result)
{
bytesReader.FillSlice(result, fixedLength * (long)docID, fixedLength);
}
}
private class BinaryDocValuesAnonymousInnerClassHelper2 : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly MonotonicBlockPackedReader addresses;
public BinaryDocValuesAnonymousInnerClassHelper2(PagedBytes.Reader bytesReader, MonotonicBlockPackedReader addresses)
{
this.bytesReader = bytesReader;
this.addresses = addresses;
}
public override void Get(int docID, BytesRef result)
{
long startAddress = docID == 0 ? 0 : addresses.Get(docID - 1);
long endAddress = addresses.Get(docID);
bytesReader.FillSlice(result, startAddress, (int)(endAddress - startAddress));
}
}
public override SortedDocValues GetSorted(FieldInfo field)
{
FSTEntry entry = fsts[field.Number];
FST<long?> instance;
lock (this)
{
if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null)
{
data.Seek(entry.Offset);
instance = new FST<long?>(data, PositiveInt32Outputs.Singleton);
ramBytesUsed.AddAndGet(instance.GetSizeInBytes());
fstInstances[field.Number] = instance;
}
}
var docToOrd = GetNumeric(field);
var fst = instance;
// per-thread resources
var @in = fst.GetBytesReader();
var firstArc = new FST.Arc<long?>();
var scratchArc = new FST.Arc<long?>();
var scratchInts = new Int32sRef();
var fstEnum = new BytesRefFSTEnum<long?>(fst);
return new SortedDocValuesAnonymousInnerClassHelper(entry, docToOrd, fst, @in, firstArc, scratchArc, scratchInts, fstEnum);
}
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
private readonly FSTEntry entry;
private readonly NumericDocValues docToOrd;
private readonly FST<long?> fst;
private readonly FST.BytesReader @in;
private readonly FST.Arc<long?> firstArc;
private readonly FST.Arc<long?> scratchArc;
private readonly Int32sRef scratchInts;
private readonly BytesRefFSTEnum<long?> fstEnum;
public SortedDocValuesAnonymousInnerClassHelper(FSTEntry entry, NumericDocValues docToOrd, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum)
{
this.entry = entry;
this.docToOrd = docToOrd;
this.fst = fst;
this.@in = @in;
this.firstArc = firstArc;
this.scratchArc = scratchArc;
this.scratchInts = scratchInts;
this.fstEnum = fstEnum;
}
public override int GetOrd(int docID)
{
return (int)docToOrd.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
try
{
@in.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts);
result.Bytes = new byte[output.Length];
result.Offset = 0;
result.Length = 0;
Util.ToBytesRef(output, result);
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override int LookupTerm(BytesRef key)
{
try
{
BytesRefFSTEnum.InputOutput<long?> o = fstEnum.SeekCeil(key);
if (o == null)
{
return -ValueCount - 1;
}
else if (o.Input.Equals(key))
{
return (int)o.Output.GetValueOrDefault();
}
else
{
return (int)-o.Output.GetValueOrDefault() - 1;
}
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override int ValueCount => (int)entry.NumOrds;
public override TermsEnum GetTermsEnum()
{
return new FSTTermsEnum(fst);
}
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
FSTEntry entry = fsts[field.Number];
if (entry.NumOrds == 0)
{
return DocValues.EMPTY_SORTED_SET; // empty FST!
}
FST<long?> instance;
lock (this)
{
if (!fstInstances.TryGetValue(field.Number, out instance) || instance == null)
{
data.Seek(entry.Offset);
instance = new FST<long?>(data, PositiveInt32Outputs.Singleton);
ramBytesUsed.AddAndGet(instance.GetSizeInBytes());
fstInstances[field.Number] = instance;
}
}
BinaryDocValues docToOrds = GetBinary(field);
FST<long?> fst = instance;
// per-thread resources
var @in = fst.GetBytesReader();
var firstArc = new FST.Arc<long?>();
var scratchArc = new FST.Arc<long?>();
var scratchInts = new Int32sRef();
var fstEnum = new BytesRefFSTEnum<long?>(fst);
var @ref = new BytesRef();
var input = new ByteArrayDataInput();
return new SortedSetDocValuesAnonymousInnerClassHelper(entry, docToOrds, fst, @in, firstArc, scratchArc, scratchInts, fstEnum, @ref, input);
}
private class SortedSetDocValuesAnonymousInnerClassHelper : SortedSetDocValues
{
private readonly FSTEntry entry;
private readonly BinaryDocValues docToOrds;
private readonly FST<long?> fst;
private readonly FST.BytesReader @in;
private readonly FST.Arc<long?> firstArc;
private readonly FST.Arc<long?> scratchArc;
private readonly Int32sRef scratchInts;
private readonly BytesRefFSTEnum<long?> fstEnum;
private readonly BytesRef @ref;
private readonly ByteArrayDataInput input;
public SortedSetDocValuesAnonymousInnerClassHelper(FSTEntry entry, BinaryDocValues docToOrds, FST<long?> fst, FST.BytesReader @in, FST.Arc<long?> firstArc, FST.Arc<long?> scratchArc, Int32sRef scratchInts, BytesRefFSTEnum<long?> fstEnum, BytesRef @ref, ByteArrayDataInput input)
{
this.entry = entry;
this.docToOrds = docToOrds;
this.fst = fst;
this.@in = @in;
this.firstArc = firstArc;
this.scratchArc = scratchArc;
this.scratchInts = scratchInts;
this.fstEnum = fstEnum;
this.@ref = @ref;
this.input = input;
}
private long currentOrd;
public override long NextOrd()
{
if (input.Eof)
{
return NO_MORE_ORDS;
}
else
{
currentOrd += input.ReadVInt64();
return currentOrd;
}
}
public override void SetDocument(int docID)
{
docToOrds.Get(docID, @ref);
input.Reset(@ref.Bytes, @ref.Offset, @ref.Length);
currentOrd = 0;
}
public override void LookupOrd(long ord, BytesRef result)
{
try
{
@in.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, @in, firstArc, scratchArc, scratchInts);
result.Bytes = new byte[output.Length];
result.Offset = 0;
result.Length = 0;
Lucene.Net.Util.Fst.Util.ToBytesRef(output, result);
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override long LookupTerm(BytesRef key)
{
try
{
var o = fstEnum.SeekCeil(key);
if (o == null)
{
return -ValueCount - 1;
}
else if (o.Input.Equals(key))
{
return (int)o.Output.GetValueOrDefault();
}
else
{
return -o.Output.GetValueOrDefault() - 1;
}
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
public override long ValueCount => entry.NumOrds;
public override TermsEnum GetTermsEnum()
{
return new FSTTermsEnum(fst);
}
}
public override IBits GetDocsWithField(FieldInfo field)
{
if (field.DocValuesType == DocValuesType.SORTED_SET)
{
return DocValues.DocsWithValue(GetSortedSet(field), maxDoc);
}
else
{
return new Lucene.Net.Util.Bits.MatchAllBits(maxDoc);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
data.Dispose();
}
}
internal class NumericEntry
{
internal long Offset { get; set; }
internal sbyte Format { get; set; }
/// <summary>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
internal int PackedInt32sVersion { get; set; }
}
internal class BinaryEntry
{
internal long Offset { get; set; }
internal long NumBytes { get; set; }
internal int MinLength { get; set; }
internal int MaxLength { get; set; }
/// <summary>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
internal int PackedInt32sVersion { get; set; }
internal int BlockSize { get; set; }
}
internal class FSTEntry
{
internal long Offset { get; set; }
internal long NumOrds { get; set; }
}
// exposes FSTEnum directly as a TermsEnum: avoids binary-search next()
internal class FSTTermsEnum : TermsEnum
{
internal readonly BytesRefFSTEnum<long?> @in;
// this is all for the complicated seek(ord)...
// maybe we should add a FSTEnum that supports this operation?
internal readonly FST<long?> fst;
internal readonly FST.BytesReader bytesReader;
internal readonly FST.Arc<long?> firstArc = new FST.Arc<long?>();
internal readonly FST.Arc<long?> scratchArc = new FST.Arc<long?>();
internal readonly Int32sRef scratchInts = new Int32sRef();
internal readonly BytesRef scratchBytes = new BytesRef();
internal FSTTermsEnum(FST<long?> fst)
{
this.fst = fst;
@in = new BytesRefFSTEnum<long?>(fst);
bytesReader = fst.GetBytesReader();
}
public override BytesRef Next()
{
var io = @in.Next();
if (io == null)
{
return null;
}
else
{
return io.Input;
}
}
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override SeekStatus SeekCeil(BytesRef text)
{
if (@in.SeekCeil(text) == null)
{
return SeekStatus.END;
}
else if (Term.Equals(text))
{
// TODO: add SeekStatus to FSTEnum like in https://issues.apache.org/jira/browse/LUCENE-3729
// to remove this comparision?
return SeekStatus.FOUND;
}
else
{
return SeekStatus.NOT_FOUND;
}
}
public override bool SeekExact(BytesRef text)
{
if (@in.SeekExact(text) == null)
{
return false;
}
else
{
return true;
}
}
public override void SeekExact(long ord)
{
// TODO: would be better to make this simpler and faster.
// but we dont want to introduce a bug that corrupts our enum state!
bytesReader.Position = 0;
fst.GetFirstArc(firstArc);
Int32sRef output = Lucene.Net.Util.Fst.Util.GetByOutput(fst, ord, bytesReader, firstArc, scratchArc, scratchInts);
scratchBytes.Bytes = new byte[output.Length];
scratchBytes.Offset = 0;
scratchBytes.Length = 0;
Lucene.Net.Util.Fst.Util.ToBytesRef(output, scratchBytes);
// TODO: we could do this lazily, better to try to push into FSTEnum though?
@in.SeekExact(scratchBytes);
}
public override BytesRef Term => @in.Current.Input;
public override long Ord => @in.Current.Output.GetValueOrDefault();
public override int DocFreq => throw new NotSupportedException();
public override long TotalTermFreq => throw new NotSupportedException();
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
throw new NotSupportedException();
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
throw new NotSupportedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RestBus.Client
{
public class RequestCookieCollection : IDictionary<string, string>
{
RequestHeaders headers;
public RequestCookieCollection(RequestHeaders requestHeaders)
{
if (requestHeaders == null) throw new ArgumentNullException("requestHeaders");
headers = requestHeaders;
}
public void Add(string key, string value)
{
if(String.IsNullOrEmpty(key))
{
throw new InvalidOperationException("Cookie key cannot be null or empty");
}
CheckCharacters(key, true);
CheckCharacters(value, false);
var cookies = GetCookies();
int index = cookies.FindIndex(c => c.Key == key);
if (index >= 0)
{
cookies.RemoveAt(index);
}
cookies.Add(new KeyValuePair<string, string>(key, value));
SetCookies(cookies);
}
public bool ContainsKey(string key)
{
var cookies = GetCookies();
return cookies.Any(c => c.Key == key);
}
public ICollection<string> Keys
{
get {
var cookies = GetCookies();
List<string> keys = new List<string>();
foreach(var cookie in cookies)
{
keys.Add(cookie.Key);
}
return keys;
}
}
public bool Remove(string key)
{
var cookies = GetCookies();
int index = cookies.FindIndex(c => c.Key == key);
if (index >= 0)
{
cookies.RemoveAt(index);
SetCookies(cookies);
return true;
}
return false;
}
public bool TryGetValue(string key, out string value)
{
var cookies = GetCookies();
var found = cookies.Where(c => c.Key == key);
if (found.Any())
{
value = found.First().Value;
return true;
}
value = null;
return false;
}
public ICollection<string> Values
{
get {
var cookies = GetCookies();
List<string> values = new List<string>();
foreach (var cookie in cookies)
{
values.Add(cookie.Value);
}
return values;
}
}
public string this[string key]
{
get
{
var cookies = GetCookies();
int index = cookies.FindIndex(c => c.Key == key);
if (index >= 0)
{
return cookies[index].Value;
}
return null;
}
set
{
Add(key, value);
}
}
public void Add(KeyValuePair<string, string> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
var cookies = GetCookies();
cookies.Clear();
SetCookies(cookies);
}
public bool Contains(KeyValuePair<string, string> item)
{
var cookies = GetCookies();
foreach (var cookie in cookies)
{
if (item.Key == cookie.Key && item.Value == cookie.Value)
{
return true;
}
}
return false;
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
var cookies = GetCookies();
if ((array.Length - arrayIndex) < cookies.Count)
{
throw new InvalidOperationException("target array is smaller than cookie collection");
}
for (int i = 0; i < cookies.Count; i++)
{
array[i + arrayIndex] = cookies[i];
}
}
public int Count
{
get
{
var cookies = GetCookies();
return cookies.Count;
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<string, string> item)
{
var cookies = GetCookies();
int index = cookies.FindIndex(c => c.Key == item.Key && c.Value == item.Value);
if (index >= 0)
{
cookies.RemoveAt(index);
SetCookies(cookies);
return true;
}
return false;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
var cookies = GetCookies();
return cookies.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
var cookies = GetCookies();
return cookies.GetEnumerator();
}
List<KeyValuePair<string, string>> GetCookies()
{
List<KeyValuePair<string, string>> cookies = new List<KeyValuePair<string, string>>();
IEnumerable<string> existing;
if (headers.TryGetValues("Cookie", out existing))
{
string[] kv;
foreach (var cookie in existing)
{
if (cookie != null)
{
kv = cookie.Split(new char[] { '=' }, 2);
if (kv.Length > 1)
{
cookies.Add(new KeyValuePair<string,string>(kv[0], kv[1]));
}
}
}
}
return cookies;
}
void SetCookies(List<KeyValuePair<string, string>> cookies)
{
//Remove any existing Cookie header
IEnumerable<string> existing;
if (headers.TryGetValues("Cookie", out existing))
{
headers.Remove("Cookie");
}
//Build cookie string
StringBuilder sb = new StringBuilder();
for( int i = 0; i < cookies.Count; i++)
{
CheckCharacters(cookies[i].Key, true);
CheckCharacters(cookies[i].Value, false);
sb.Append(cookies[i].Key);
sb.Append('=');
sb.Append(cookies[i].Value);
if (i != cookies.Count - 1)
{
sb.Append("; ");
}
}
headers.Add("Cookie", sb.ToString());
}
void CheckCharacters(string value, bool checkForEqualsSign)
{
if (value == null) return;
if (value.IndexOfAny(new char[] { ';', ',', ' ', '\r', '\n', '\t' }) >= 0)
{
throw new InvalidOperationException("Invalid characters in cookie string");
}
if (checkForEqualsSign)
{
if (value.IndexOfAny(new char[] { '=' }) >= 0)
{
throw new InvalidOperationException("Invalid characters in cookie string");
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderPreservingPipeliningMergeHelper.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Linq.Parallel
{
/// <summary>
/// A merge helper that yields results in a streaming fashion, while still ensuring correct output
/// ordering. This merge only works if each producer task generates outputs in the correct order,
/// i.e. with an Increasing (or Correct) order index.
///
/// The merge creates DOP producer tasks, each of which will be writing results into a separate
/// buffer.
///
/// The consumer always waits until each producer buffer contains at least one element. If we don't
/// have one element from each producer, we cannot yield the next element. (If the order index is
/// Correct, or in some special cases with the Increasing order, we could yield sooner. The
/// current algorithm does not take advantage of this.)
///
/// The consumer maintains a producer heap, and uses it to decide which producer should yield the next output
/// result. After yielding an element from a particular producer, the consumer will take another element
/// from the same producer. However, if the producer buffer exceeded a particular threshold, the consumer
/// will take the entire buffer, and give the producer an empty buffer to fill.
///
/// Finally, if the producer notices that its buffer has exceeded an even greater threshold, it will
/// go to sleep and wait until the consumer takes the entire buffer.
/// </summary>
internal class OrderPreservingPipeliningMergeHelper<TOutput, TKey> : IMergeHelper<TOutput>
{
private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks.
private readonly PartitionedStream<TOutput, TKey> _partitions; // Source partitions.
private readonly TaskScheduler _taskScheduler; // The task manager to execute the query.
/// <summary>
/// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer.
/// If false, the producer will make each result available to the consumer immediately after it is
/// produced.
/// </summary>
private readonly bool _autoBuffered;
/// <summary>
/// Buffers for the results. Each buffer has elements added by one producer, and removed
/// by the consumer.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _buffers;
/// <summary>
/// Whether each producer is done producing. Set to true by individual producers, read by consumer.
/// </summary>
private readonly bool[] _producerDone;
/// <summary>
/// Whether a particular producer is waiting on the consumer. Read by the consumer, set to true
/// by producers, set to false by the consumer.
/// </summary>
private readonly bool[] _producerWaiting;
/// <summary>
/// Whether the consumer is waiting on a particular producer. Read by producers, set to true
/// by consumer, set to false by producer.
/// </summary>
private readonly bool[] _consumerWaiting;
/// <summary>
/// Each object is a lock protecting the corresponding elements in _buffers, _producerDone,
/// _producerWaiting and _consumerWaiting.
/// </summary>
private readonly object[] _bufferLocks;
/// <summary>
/// A comparer used by the producer heap.
/// </summary>
private IComparer<Producer<TKey>> _producerComparer;
/// <summary>
/// The initial capacity of the buffer queue. The value was chosen experimentally.
/// </summary>
internal const int INITIAL_BUFFER_SIZE = 128;
/// <summary>
/// If the consumer notices that the queue reached this limit, it will take the entire buffer from
/// the producer, instead of just popping off one result. The value was chosen experimentally.
/// </summary>
internal const int STEAL_BUFFER_SIZE = 1024;
/// <summary>
/// If the producer notices that the queue reached this limit, it will go to sleep until woken up
/// by the consumer. Chosen experimentally.
/// </summary>
internal const int MAX_BUFFER_SIZE = 8192;
//-----------------------------------------------------------------------------------
// Instantiates a new merge helper.
//
// Arguments:
// partitions - the source partitions from which to consume data.
// ignoreOutput - whether we're enumerating "for effect" or for output.
//
internal OrderPreservingPipeliningMergeHelper(
PartitionedStream<TOutput, TKey> partitions,
TaskScheduler taskScheduler,
CancellationState cancellationState,
bool autoBuffered,
int queryId,
IComparer<TKey> keyComparer)
{
Debug.Assert(partitions != null);
TraceHelpers.TraceInfo("KeyOrderPreservingMergeHelper::.ctor(..): creating an order preserving merge helper");
_taskGroupState = new QueryTaskGroupState(cancellationState, queryId);
_partitions = partitions;
_taskScheduler = taskScheduler;
_autoBuffered = autoBuffered;
int partitionCount = _partitions.PartitionCount;
_buffers = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerDone = new bool[partitionCount];
_consumerWaiting = new bool[partitionCount];
_producerWaiting = new bool[partitionCount];
_bufferLocks = new object[partitionCount];
if (keyComparer == Util.GetDefaultComparer<int>())
{
Debug.Assert(typeof(TKey) == typeof(int));
_producerComparer = (IComparer<Producer<TKey>>)(object)new ProducerComparerInt();
}
else
{
_producerComparer = new ProducerComparer(keyComparer);
}
}
//-----------------------------------------------------------------------------------
// Schedules execution of the merge itself.
//
void IMergeHelper<TOutput>.Execute()
{
OrderPreservingPipeliningSpoolingTask<TOutput, TKey>.Spool(
_taskGroupState, _partitions, _consumerWaiting, _producerWaiting, _producerDone,
_buffers, _bufferLocks, _taskScheduler, _autoBuffered);
}
//-----------------------------------------------------------------------------------
// Gets the enumerator from which to enumerate output results.
//
IEnumerator<TOutput> IMergeHelper<TOutput>.GetEnumerator()
{
return new OrderedPipeliningMergeEnumerator(this, _producerComparer);
}
//-----------------------------------------------------------------------------------
// Returns the results as an array.
//
public TOutput[] GetResultsAsArray()
{
Debug.Fail("An ordered pipelining merge is not intended to be used this way.");
throw new InvalidOperationException();
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
private class ProducerComparer : IComparer<Producer<TKey>>
{
private IComparer<TKey> _keyComparer;
internal ProducerComparer(IComparer<TKey> keyComparer)
{
_keyComparer = keyComparer;
}
public int Compare(Producer<TKey> x, Producer<TKey> y)
{
return _keyComparer.Compare(y.MaxKey, x.MaxKey);
}
}
/// <summary>
/// Enumerator over the results of an order-preserving pipelining merge.
/// </summary>
private class OrderedPipeliningMergeEnumerator : MergeEnumerator<TOutput>
{
/// <summary>
/// Merge helper associated with this enumerator
/// </summary>
private OrderPreservingPipeliningMergeHelper<TOutput, TKey> _mergeHelper;
/// <summary>
/// Heap used to efficiently locate the producer whose result should be consumed next.
/// For each producer, stores the order index for the next element to be yielded.
///
/// Read and written by the consumer only.
/// </summary>
private readonly FixedMaxHeap<Producer<TKey>> _producerHeap;
/// <summary>
/// Stores the next element to be yielded from each producer. We use a separate array
/// rather than storing this information in the producer heap to keep the Producer struct
/// small.
///
/// Read and written by the consumer only.
/// </summary>
private readonly TOutput[] _producerNextElement;
/// <summary>
/// A private buffer for the consumer. When the size of a producer buffer exceeds a threshold
/// (STEAL_BUFFER_SIZE), the consumer will take ownership of the entire buffer, and give the
/// producer a new empty buffer to place results into.
///
/// Read and written by the consumer only.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _privateBuffer;
/// <summary>
/// Tracks whether MoveNext() has already been called previously.
/// </summary>
private bool _initialized = false;
/// <summary>
/// Constructor
/// </summary>
internal OrderedPipeliningMergeEnumerator(OrderPreservingPipeliningMergeHelper<TOutput, TKey> mergeHelper, IComparer<Producer<TKey>> producerComparer)
: base(mergeHelper._taskGroupState)
{
int partitionCount = mergeHelper._partitions.PartitionCount;
_mergeHelper = mergeHelper;
_producerHeap = new FixedMaxHeap<Producer<TKey>>(partitionCount, producerComparer);
_privateBuffer = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerNextElement = new TOutput[partitionCount];
}
/// <summary>
/// Returns the current result
/// </summary>
public override TOutput Current
{
get
{
int producerToYield = _producerHeap.MaxValue.ProducerIndex;
return _producerNextElement[producerToYield];
}
}
/// <summary>
/// Moves the enumerator to the next result, or returns false if there are no more results to yield.
/// </summary>
public override bool MoveNext()
{
if (!_initialized)
{
//
// Initialization: wait until each producer has produced at least one element. Since the order indices
// are increasing, we cannot start yielding until we have at least one element from each producer.
//
_initialized = true;
for (int producer = 0; producer < _mergeHelper._partitions.PartitionCount; producer++)
{
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
// Get the first element from this producer
if (TryWaitForElement(producer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.Insert(new Producer<TKey>(element.First, producer));
_producerNextElement[producer] = element.Second;
}
else
{
// If this producer didn't produce any results because it encountered an exception,
// cancellation would have been initiated by now. If cancellation has started, we will
// propagate the exception now.
ThrowIfInTearDown();
}
}
}
else
{
// If the producer heap is empty, we are done. In fact, we know that a previous MoveNext() call
// already returned false.
if (_producerHeap.Count == 0)
{
return false;
}
//
// Get the next element from the producer that yielded a value last. Update the producer heap.
// The next producer to yield will be in the front of the producer heap.
//
// The last producer whose result the merge yielded
int lastProducer = _producerHeap.MaxValue.ProducerIndex;
// Get the next element from the same producer
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
if (TryGetPrivateElement(lastProducer, ref element)
|| TryWaitForElement(lastProducer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.ReplaceMax(new Producer<TKey>(element.First, lastProducer));
_producerNextElement[lastProducer] = element.Second;
}
else
{
// If this producer is done because it encountered an exception, cancellation
// would have been initiated by now. If cancellation has started, we will propagate
// the exception now.
ThrowIfInTearDown();
// This producer is done. Remove it from the producer heap.
_producerHeap.RemoveMax();
}
}
return _producerHeap.Count > 0;
}
/// <summary>
/// If the cancellation of the query has been initiated (because one or more producers
/// encountered exceptions, or because external cancellation token has been set), the method
/// will tear down the query and rethrow the exception.
/// </summary>
private void ThrowIfInTearDown()
{
if (_mergeHelper._taskGroupState.CancellationState.MergedCancellationToken.IsCancellationRequested)
{
try
{
// Wake up all producers. Since the cancellation token has already been
// set, the producers will eventually stop after waking up.
object[] locks = _mergeHelper._bufferLocks;
for (int i = 0; i < locks.Length; i++)
{
lock (locks[i])
{
Monitor.Pulse(locks[i]);
}
}
// Now, we wait for all producers to wake up, notice the cancellation and stop executing.
// QueryEnd will wait on all tasks to complete and then propagate all exceptions.
_taskGroupState.QueryEnd(false);
Debug.Fail("QueryEnd() should have thrown an exception.");
}
finally
{
// Clear the producer heap so that future calls to MoveNext simply return false.
_producerHeap.Clear();
}
}
}
/// <summary>
/// Wait until a producer's buffer is non-empty, or until that producer is done.
/// </summary>
/// <returns>false if there is no element to yield because the producer is done, true otherwise</returns>
private bool TryWaitForElement(int producer, ref Pair<TKey, TOutput> element)
{
Queue<Pair<TKey, TOutput>> buffer = _mergeHelper._buffers[producer];
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
// If the buffer is empty, we need to wait on the producer
if (buffer.Count == 0)
{
// If the producer is already done, return false
if (_mergeHelper._producerDone[producer])
{
element = default(Pair<TKey, TOutput>);
return false;
}
_mergeHelper._consumerWaiting[producer] = true;
Monitor.Wait(bufferLock);
// If the buffer is still empty, the producer is done
if (buffer.Count == 0)
{
Debug.Assert(_mergeHelper._producerDone[producer]);
element = default(Pair<TKey, TOutput>);
return false;
}
}
Debug.Assert(buffer.Count > 0, "Producer's buffer should not be empty here.");
// If the producer is waiting, wake it up
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
_mergeHelper._producerWaiting[producer] = false;
}
if (buffer.Count < STEAL_BUFFER_SIZE)
{
element = buffer.Dequeue();
return true;
}
else
{
// Privatize the entire buffer
_privateBuffer[producer] = _mergeHelper._buffers[producer];
// Give an empty buffer to the producer
_mergeHelper._buffers[producer] = new Queue<Pair<TKey, TOutput>>(INITIAL_BUFFER_SIZE);
// No return statement.
// This is the only branch that contines below of the lock region.
}
}
// Get an element out of the private buffer.
bool gotElement = TryGetPrivateElement(producer, ref element);
Debug.Assert(gotElement);
return true;
}
/// <summary>
/// Looks for an element from a particular producer in the consumer's private buffer.
/// </summary>
private bool TryGetPrivateElement(int producer, ref Pair<TKey, TOutput> element)
{
var privateChunk = _privateBuffer[producer];
if (privateChunk != null)
{
if (privateChunk.Count > 0)
{
element = privateChunk.Dequeue();
return true;
}
Debug.Assert(_privateBuffer[producer].Count == 0);
_privateBuffer[producer] = null;
}
return false;
}
public override void Dispose()
{
// Wake up any waiting producers
int partitionCount = _mergeHelper._buffers.Length;
for (int producer = 0; producer < partitionCount; producer++)
{
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
}
}
}
base.Dispose();
}
}
}
/// <summary>
/// A structure to represent a producer in the producer heap.
/// </summary>
internal struct Producer<TKey>
{
internal readonly TKey MaxKey; // Order index of the next element from this producer
internal readonly int ProducerIndex; // Index of the producer, [0..DOP)
internal Producer(TKey maxKey, int producerIndex)
{
MaxKey = maxKey;
ProducerIndex = producerIndex;
}
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
internal class ProducerComparerInt : IComparer<Producer<int>>
{
public int Compare(Producer<int> x, Producer<int> y)
{
Debug.Assert(x.MaxKey >= 0 && y.MaxKey >= 0); // Guarantees no overflow on next line
return y.MaxKey - x.MaxKey;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor;
using V1=AssetBundleGraph;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph
{
[CustomNode("Group Assets/Group By File Path", 40)]
public class Grouping : Node, Model.NodeDataImporter {
enum GroupingPatternType : int {
WildCard,
RegularExpression
};
[SerializeField] private SerializableMultiTargetString m_groupingKeyword;
[SerializeField] private SerializableMultiTargetInt m_patternType;
[SerializeField] private bool m_allowSlash;
[SerializeField] private SerializableMultiTargetString m_groupNameFormat;
public override string ActiveStyle {
get {
return "node 2 on";
}
}
public override string InactiveStyle {
get {
return "node 2";
}
}
public override string Category {
get {
return "Group";
}
}
public override void Initialize(Model.NodeData data) {
m_groupingKeyword = new SerializableMultiTargetString(Model.Settings.GROUPING_KEYWORD_DEFAULT);
m_patternType = new SerializableMultiTargetInt((int)GroupingPatternType.WildCard);
m_allowSlash = false;
m_groupNameFormat = new SerializableMultiTargetString();
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public void Import(V1.NodeData v1, Model.NodeData v2) {
m_groupingKeyword = new SerializableMultiTargetString(v1.GroupingKeywords);
m_patternType = new SerializableMultiTargetInt((int)GroupingPatternType.WildCard);
m_allowSlash = true;
m_groupNameFormat = new SerializableMultiTargetString();
}
public override Node Clone(Model.NodeData newData) {
var newNode = new Grouping();
newNode.m_groupingKeyword = new SerializableMultiTargetString(m_groupingKeyword);
newNode.m_patternType = new SerializableMultiTargetInt(m_patternType);
newNode.m_allowSlash = m_allowSlash;
newNode.m_groupNameFormat = new SerializableMultiTargetString(m_groupNameFormat);
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
return newNode;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
if (m_groupingKeyword == null) {
return;
}
EditorGUILayout.HelpBox("Group By File Path: Create group of assets from asset's file path.", MessageType.Info);
editor.UpdateNodeName(node);
GUILayout.Space(10f);
var newSlash = EditorGUILayout.ToggleLeft("Allow directory separator ('/') in group name", m_allowSlash);
if(newSlash != m_allowSlash) {
using(new RecordUndoScope("Change Allow Slash Setting", node, true)){
m_allowSlash = newSlash;
onValueChanged();
}
}
if(m_allowSlash) {
EditorGUILayout.HelpBox("Allowing directory separator for group name may create incompatible group name with other nodes. Please use this option carefully.", MessageType.Info);
}
GUILayout.Space(4f);
//Show target configuration tab
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_groupingKeyword.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => {
using(new RecordUndoScope("Remove Target Grouping Keyword Settings", node, true)){
if(enabled) {
m_groupingKeyword[editor.CurrentEditingGroup] = m_groupingKeyword.DefaultValue;
m_patternType[editor.CurrentEditingGroup] = m_patternType.DefaultValue;
m_groupNameFormat[editor.CurrentEditingGroup] = m_groupNameFormat.DefaultValue;
} else {
m_groupingKeyword.Remove(editor.CurrentEditingGroup);
m_patternType.Remove(editor.CurrentEditingGroup);
m_groupNameFormat.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
}
});
using (disabledScope) {
var newType = (GroupingPatternType)EditorGUILayout.EnumPopup("Pattern Type",(GroupingPatternType)m_patternType[editor.CurrentEditingGroup]);
if (newType != (GroupingPatternType)m_patternType[editor.CurrentEditingGroup]) {
using(new RecordUndoScope("Change Grouping Pattern Type", node, true)){
m_patternType[editor.CurrentEditingGroup] = (int)newType;
onValueChanged();
}
}
var newGroupingKeyword = EditorGUILayout.TextField("Grouping Keyword",m_groupingKeyword[editor.CurrentEditingGroup]);
string helpText = null;
switch((GroupingPatternType)m_patternType[editor.CurrentEditingGroup]) {
case GroupingPatternType.WildCard:
helpText = "Grouping Keyword requires \"*\" in itself. It assumes there is a pattern such as \"ID_0\" in incoming paths when configured as \"ID_*\" ";
break;
case GroupingPatternType.RegularExpression:
helpText = "Grouping Keyword requires pattern definition with \"()\" in Regular Expression manner.";
break;
}
EditorGUILayout.HelpBox(helpText, MessageType.Info);
if (newGroupingKeyword != m_groupingKeyword[editor.CurrentEditingGroup]) {
using(new RecordUndoScope("Change Grouping Keywords", node, true)){
m_groupingKeyword[editor.CurrentEditingGroup] = newGroupingKeyword;
onValueChanged();
}
}
var newGroupNameFormat = EditorGUILayout.TextField("Group Name Format",m_groupNameFormat[editor.CurrentEditingGroup]);
EditorGUILayout.HelpBox(
"You can customize group name. You can use variable {OldGroup} for old group name and {NewGroup} for current matching name.",
MessageType.Info);
if (newGroupNameFormat != m_groupNameFormat[editor.CurrentEditingGroup]) {
using(new RecordUndoScope("Change Group Name", node, true)){
m_groupNameFormat[editor.CurrentEditingGroup] = newGroupNameFormat;
onValueChanged();
}
}
}
}
}
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
GroupingOutput(target, node, incoming, connectionsToOutput, Output);
}
private void GroupingOutput (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
ValidateGroupingKeyword(
m_groupingKeyword[target],
(GroupingPatternType)m_patternType[target],
() => {
throw new NodeException("Grouping Keyword can not be empty.", "Set valid grouping keyword.",node);
},
() => {
throw new NodeException(String.Format("Grouping Keyword must contain {0} for numbering: currently {1}", Model.Settings.KEYWORD_WILDCARD, m_groupingKeyword[target]),
string.Format("Add {0} to the grouping keyword.", Model.Settings.KEYWORD_WILDCARD), node);
}
);
if(connectionsToOutput == null || Output == null) {
return;
}
var outputDict = new Dictionary<string, List<AssetReference>>();
if(incoming != null) {
Regex regex = null;
switch((GroupingPatternType)m_patternType[target]) {
case GroupingPatternType.WildCard:
{
var groupingKeyword = m_groupingKeyword[target];
var split = groupingKeyword.Split(Model.Settings.KEYWORD_WILDCARD);
var groupingKeywordPrefix = split[0];
var groupingKeywordPostfix = split[1];
regex = new Regex(groupingKeywordPrefix + "(.*?)" + groupingKeywordPostfix);
}
break;
case GroupingPatternType.RegularExpression:
{
regex = new Regex(m_groupingKeyword[target]);
}
break;
}
foreach(var ag in incoming) {
foreach (var g in ag.assetGroups.Keys) {
var assets = ag.assetGroups [g];
foreach(var a in assets) {
var targetPath = a.path;
var match = regex.Match(targetPath);
if (match.Success) {
var newGroupingKey = match.Groups[1].Value;
if (!string.IsNullOrEmpty (m_groupNameFormat [target])) {
newGroupingKey = m_groupNameFormat [target]
.Replace ("{NewGroup}", newGroupingKey)
.Replace ("{OldGroup}", g);
}
if(!m_allowSlash && newGroupingKey.Contains("/")) {
throw new NodeException(String.Format("Grouping Keyword with directory separator('/') found: \"{0}\" from asset: {1}",
newGroupingKey, targetPath),
"Remove directory separator from grouping keyword, or enable 'Allow directory separator ('/') in group name' option.", node);
}
if (!outputDict.ContainsKey(newGroupingKey)) {
outputDict[newGroupingKey] = new List<AssetReference>();
}
outputDict[newGroupingKey].Add(a);
}
}
}
}
}
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, outputDict);
}
private void ValidateGroupingKeyword (string currentGroupingKeyword,
GroupingPatternType currentType,
Action NullOrEmpty,
Action ShouldContainWildCardKey
) {
if (string.IsNullOrEmpty(currentGroupingKeyword)) NullOrEmpty();
if (currentType == GroupingPatternType.WildCard &&
!currentGroupingKeyword.Contains(Model.Settings.KEYWORD_WILDCARD.ToString()))
{
ShouldContainWildCardKey();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using BASeCamp.BASeBlock.Blocks;
using BASeCamp.BASeBlock.Events;
namespace BASeCamp.BASeBlock.Projectiles
{
/// <summary>
/// "Bullet" object, which hits blocks. However, it doesn't actually impact the block (call the block's PerformBlockHit()) until
/// a static "health" value stored for each block exceeds a given value. At which point it does, and resets that counter.
/// </summary>
public class Bullet : GameObject, IMovingObject, iLocatable
{
private class BulletBlockDamageData
{
private Block _BlockObject = null;
private int _Damage = 0;
private int _HP = 10; //takes ten hits before we call the blocks hit routine normally.
public Block BlockObject
{
get { return _BlockObject; }
private set { _BlockObject = value; }
}
public int Damage
{
get { return _Damage; }
set { _Damage = value; }
}
public int HP
{
get { return _HP; }
set { _HP = value; }
}
public BulletBlockDamageData(Block pBlockObject, int pHP)
{
_BlockObject = pBlockObject;
_HP = pHP;
}
}
private static readonly Brush DefaultBulletBrush = new SolidBrush(Color.Yellow);
private static BCBlockGameState LastState;
private static Dictionary<Block, BulletBlockDamageData> DamageData = new Dictionary<Block, BulletBlockDamageData>();
protected Object _Owner = null; //set to whatever or whoever shot this.
protected PointF _Location;
protected PointF _Velocity;
protected Brush _BulletBrush = DefaultBulletBrush;
private bool _DamagePaddle = false;
public PointF Velocity { get { return _Velocity; } set { _Velocity = value; } }
public PointF Location { get { return _Location; } set { _Location = value; } }
public bool DamagePaddle { get { return _DamagePaddle; } set { _DamagePaddle = value; } }
public Brush BulletBrush { get { return _BulletBrush; } set { _BulletBrush = value; } }
public Object Owner { get { return _Owner; } set { _Owner = value; } }
/// <summary>
/// used to perform a single frame of this gameobjects animation.
/// </summary>
/// <param name="gamestate">Game State object</param>
/// <param name="AddObjects">out parameter, populate with any new GameObjects that will be added to the game.</param>
/// <param name="removeobjects">otu parameter, populate with gameobjects that should be deleted.</param>
/// <returns>true to indicate that this gameobject should be removed. False otherwise.</returns>
///
public Bullet(PointF pPosition, PointF pVelocity)
: this(pPosition, pVelocity, false)
{
}
public Bullet(PointF pPosition, PointF pVelocity, bool pDamagePaddle)
{
Location = pPosition;
Velocity = pVelocity;
_DamagePaddle = pDamagePaddle;
}
private static readonly int Default_HP = 10;
private BulletBlockDamageData getDamageData(Block forblock)
{
//returns or creates the bulletBlockDamage data for the given block.
if (DamageData.ContainsKey(forblock))
return DamageData[forblock];
else
{
BulletBlockDamageData returnthis = new BulletBlockDamageData(forblock, Default_HP);
DamageData.Add(forblock, returnthis);
return returnthis;
}
}
private void AttachToBlock(Block attachto)
{
AttachedBlock = attachto;
AttachedBlock.OnBlockDestroy += AttachedBlock_OnBlockDestroy;
}
void AttachedBlock_OnBlockDestroy(Object Sender,BlockHitEventArgs<bool> e)
{
AttachedBlock = null;
isdestroyed = true;
e.Result = true;
}
private int _DamageAmount = 2; //amount of damage this bullet will do if it hits the paddle.
private int frameinc = 0;
private bool isdestroyed = false;
private Block AttachedBlock = null; //The bullet's "stick" to the block they hit, but don't do damage.
protected virtual bool Impact(BCBlockGameState gamestate,Block smackblock)
{
BulletBlockDamageData bbd = getDamageData(smackblock);
bbd.Damage++;
if (bbd.Damage >= bbd.HP)
{
//destroy(or rather, perform a "standard" block hit, which may or may not destroy it.
BCBlockGameState.Block_Hit(gamestate, smackblock);
bbd.Damage = 0; //reset to zero.
}
else
{
//don't destroy. We still make a sound though.
BCBlockGameState.EmitBlockSound(gamestate, smackblock);
//attach...
if (smackblock.MustDestroy())
AttachToBlock(smackblock);
else
{
return true;
}
}
return false;
}
//The point being that you can't see how much damage you've dne to them so just seeing how many spots are stuck to the side can help.
public override bool PerformFrame(BCBlockGameState gamestate)
{
frameinc++;
if (frameinc == 21) frameinc = 0;
if (AttachedBlock != null)
{
//TODO: add code to move the bullet if the block moves.
if (frameinc >= 20)
{
if (!gamestate.Blocks.Contains(AttachedBlock))
return true;
}
return false;
}
if (_DamagePaddle)
{
if (gamestate.PlayerPaddle != null)
{
if (gamestate.PlayerPaddle.Getrect().Contains(new Point((int)Location.X, (int)Location.Y)))
{
//damage.
gamestate.PlayerPaddle.HP -= _DamageAmount;
return true;
}
}
}
if (isdestroyed) return true;
if (gamestate != LastState)
{
LastState = gamestate;
DamageData = new Dictionary<Block, BulletBlockDamageData>();
}
BCBlockGameState.IncrementLocation(gamestate, ref _Location, Velocity);
//use hittest to see if there are blocks...
List<Block> hittest = BCBlockGameState.Block_HitTest(gamestate.Blocks.ToList(), Location);
if (hittest.Count > 0)
{
gamestate.Forcerefresh = true;
foreach (Block smackblock in hittest)
{
if (smackblock != Owner)
{
try
{
if (Impact(gamestate, smackblock)) return true;
}
catch (Exception exx)
{
Debug.Print(exx.ToString());
}
} //smackblock!=owner
}
//return true; //destroy the bullet.
}
var alleyeguys = (from m in gamestate.GameObjects where m is EyeGuy select m);
var allcharacters = (from m in gamestate.GameObjects where m is PlatformObject select m);
if (alleyeguys.Count() > 0)
{
foreach (EyeGuy iterateguy in alleyeguys)
{
if (iterateguy.GetRectangleF().Contains(Location))
{
if (iterateguy != Owner)
{
iterateguy.HitPoints -= 5;
}
}
}
}
if (allcharacters.Count() > 0)
{
foreach (PlatformObject iteratechar in allcharacters)
{
if (iteratechar.GetRectangleF().Contains(Location))
iteratechar.Die(gamestate);
}
}
if (!gamestate.GameArea.Contains(new Point((int)Location.X, (int)Location.Y)))
{
return true;
}
else
{
return false;
}
//move the bullet...
}
public override void Draw(Graphics g)
{
//throw new NotImplementedException();
g.FillRectangle(BulletBrush, Location.X - 1, Location.Y - 1, 2, 2);
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//*************************************************************************************
// ArcGIS Network Analyst extension - Closest Facility Demonstration
//
// This simple code shows how to :
// 1) Open a workspace and open a Network DataSet
// 2) Create a NAContext and its NASolver
// 3) Load Incidents/Facilites from Feature Classes and create Network Locations
// 4) Set the Solver parameters
// 5) Solve a Closest Facility problem
// 6) Read the CFRoutes output to display the total facilities
// and the list of the routes found
//************************************************************************************
using System;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalyst;
namespace ClosestFacilitySolver
{
public partial class frmClosestFacilitySolver : Form
{
private INAContext m_NAContext;
private readonly string OUTPUTCLASSNAME = "CFRoutes";
#region Main Form Constructor and Setup
public frmClosestFacilitySolver()
{
InitializeComponent();
Initialize();
}
/// <summary>
/// Initialize the solver by calling the ArcGIS Network Analyst extension functions.
/// </summary>
private void Initialize()
{
IFeatureWorkspace featureWorkspace = null;
INetworkDataset networkDataset = null;
try
{
// Open Geodatabase and network dataset
IWorkspace workspace = OpenWorkspace(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ArcGIS\data\SanFrancisco\SanFrancisco.gdb"));
networkDataset = OpenNetworkDataset(workspace, "Transportation", "Streets_ND");
featureWorkspace = workspace as IFeatureWorkspace;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Unable to open dataset. Error Message: " + ex.Message);
this.Close();
return;
}
// Create NAContext and NASolver
CreateSolverContext(networkDataset);
// Get available cost attributes from the network dataset
INetworkAttribute networkAttribute;
for (int i = 0; i < networkDataset.AttributeCount - 1; i++)
{
networkAttribute = networkDataset.get_Attribute(i);
if (networkAttribute.UsageType == esriNetworkAttributeUsageType.esriNAUTCost)
{
cboCostAttribute.Items.Add(networkAttribute.Name);
}
}
cboCostAttribute.SelectedIndex = 0;
txtTargetFacility.Text = "1";
txtCutOff.Text = "";
// Load incidents from a feature class
IFeatureClass inputFClass = featureWorkspace.OpenFeatureClass("Stores");
LoadNANetworkLocations("Incidents", inputFClass, 500);
// Load facilities from a feature class
inputFClass = featureWorkspace.OpenFeatureClass("FireStations");
LoadNANetworkLocations("Facilities", inputFClass, 500);
//Create Layer for Network Dataset and add to ArcMap
INetworkLayer networkLayer = new NetworkLayerClass();
networkLayer.NetworkDataset = networkDataset;
var layer = networkLayer as ILayer;
layer.Name = "Network Dataset";
axMapControl.AddLayer(layer, 0);
//Create a Network Analysis Layer and add to ArcMap
INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
layer = naLayer as ILayer;
layer.Name = m_NAContext.Solver.DisplayName;
axMapControl.AddLayer(layer, 0);
}
#endregion
#region Button Clicks
/// <summary>
/// Call the Closest Facility cost matrix solver and display the results
/// </summary>
/// <param name="sender">Sender of the event</param>
/// <param name="e">Event</param>
private void cmdSolve_Click(object sender, System.EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
lstOutput.Items.Clear();
IGPMessages gpMessages = new GPMessagesClass();
try
{
lstOutput.Items.Add("Solving...");
SetSolverSettings();
if (!m_NAContext.Solver.Solve(m_NAContext, gpMessages, null))
lstOutput.Items.Add("Partial Solve Generated.");
DisplayOutput();
}
catch (Exception ee)
{
lstOutput.Items.Add("Failure: " + ee.Message);
}
lstOutput.Items.Add(GetGPMessagesAsString(gpMessages));
cmdSolve.Text = "Find Closest Facilities";
RefreshMapDisplay();
this.Cursor = Cursors.Default;
}
#endregion
#region Set up Context and Solver
/// <summary>
/// Geodatabase function: open work space
/// </summary>
/// <param name="strGDBName">Input file name</param>
/// <returns>Workspace</returns>
public IWorkspace OpenWorkspace(string strGDBName)
{
// As Workspace Factories are Singleton objects, they must be instantiated with the Activator
var workspaceFactory = System.Activator.CreateInstance(System.Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory")) as ESRI.ArcGIS.Geodatabase.IWorkspaceFactory;
if (!System.IO.Directory.Exists(strGDBName))
{
MessageBox.Show("The workspace: " + strGDBName + " does not exist", "Workspace Error");
return null;
}
IWorkspace workspace = null;
try
{
workspace = workspaceFactory.OpenFromFile(strGDBName, 0);
}
catch (Exception ex)
{
MessageBox.Show("Opening workspace failed: " + ex.Message, "Workspace Error");
}
return workspace;
}
/// <summary>
/// Geodatabase function: open network dataset
/// </summary>
/// <param name="workspace">Input workspace</param>
/// <param name="strNDSName">Input network dataset name</param>
/// <returns>NetworkDataset</returns>
public INetworkDataset OpenNetworkDataset(IWorkspace workspace, string featureDatasetName, string strNDSName)
{
// Obtain the dataset container from the workspace
var featureWorkspace = workspace as IFeatureWorkspace;
ESRI.ArcGIS.Geodatabase.IFeatureDataset featureDataset = featureWorkspace.OpenFeatureDataset(featureDatasetName);
var featureDatasetExtensionContainer = featureDataset as ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtensionContainer;
ESRI.ArcGIS.Geodatabase.IFeatureDatasetExtension featureDatasetExtension = featureDatasetExtensionContainer.FindExtension(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset);
var datasetContainer3 = featureDatasetExtension as ESRI.ArcGIS.Geodatabase.IDatasetContainer3;
// Use the container to open the network dataset.
ESRI.ArcGIS.Geodatabase.IDataset dataset = datasetContainer3.get_DatasetByName(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTNetworkDataset, strNDSName);
return dataset as ESRI.ArcGIS.Geodatabase.INetworkDataset;
}
/// <summary>
/// Geodatabase function: get network dataset
/// </summary>
/// <param name="networkDataset">Input network dataset</param>
/// <returns>DE network dataset</returns>
public IDENetworkDataset GetDENetworkDataset(INetworkDataset networkDataset)
{
// Cast from the network dataset to the DatasetComponent
IDatasetComponent dsComponent = networkDataset as IDatasetComponent;
// Get the data element
return dsComponent.DataElement as IDENetworkDataset;
}
/// <summary>
/// Create NASolver and NAContext
/// </summary>
/// <param name="networkDataset">Input network dataset</param>
/// <returns>NAContext</returns>
public void CreateSolverContext(INetworkDataset networkDataset)
{
if (networkDataset == null) return;
//Get the Data Element
IDENetworkDataset deNDS = GetDENetworkDataset(networkDataset);
INASolver naSolver = new NAClosestFacilitySolver();
m_NAContext = naSolver.CreateContext(deNDS, naSolver.Name);
((INAContextEdit)m_NAContext).Bind(networkDataset, new GPMessagesClass());
}
/// <summary>
/// Set solver settings
/// </summary>
/// <param name="strNAClassName">NAClass name</param>
/// <param name="inputFC">Input feature class</param>
/// <param name="maxSnapTolerance">Max snap tolerance</param>
public void LoadNANetworkLocations(string strNAClassName, IFeatureClass inputFC, double maxSnapTolerance)
{
INamedSet classes = m_NAContext.NAClasses;
INAClass naClass = classes.get_ItemByName(strNAClassName) as INAClass;
// delete existing Locations except if that a barriers
naClass.DeleteAllRows();
// Create a NAClassLoader and set the snap tolerance (meters unit)
INAClassLoader classLoader = new NAClassLoader();
classLoader.Locator = m_NAContext.Locator;
if (maxSnapTolerance > 0) ((INALocator3)classLoader.Locator).MaxSnapTolerance = maxSnapTolerance;
classLoader.NAClass = naClass;
//Create field map to automatically map fields from input class to NAClass
INAClassFieldMap fieldMap = new NAClassFieldMapClass();
fieldMap.CreateMapping(naClass.ClassDefinition, inputFC.Fields);
classLoader.FieldMap = fieldMap;
// Avoid loading network locations onto non-traversable portions of elements
INALocator3 locator = m_NAContext.Locator as INALocator3;
locator.ExcludeRestrictedElements = true;
locator.CacheRestrictedElements(m_NAContext);
//Load Network Locations
int rowsIn = 0;
int rowsLocated = 0;
IFeatureCursor featureCursor = inputFC.Search(null, true);
classLoader.Load((ICursor)featureCursor, null, ref rowsIn, ref rowsLocated);
//Message all of the network analysis agents that the analysis context has changed
((INAContextEdit)m_NAContext).ContextChanged();
}
#endregion
#region Post-Solve
/// <summary>
/// Display analysis results in the list box
/// </summary>
public void DisplayOutput()
{
ITable table = m_NAContext.NAClasses.get_ItemByName(OUTPUTCLASSNAME) as ITable;
if (table == null)
{
lstOutput.Items.Add("Impossible to get the " + OUTPUTCLASSNAME + " table");
}
lstOutput.Items.Add("Number facilities found " + table.RowCount(null).ToString());
lstOutput.Items.Add("");
if (table.RowCount(null) > 0)
{
lstOutput.Items.Add("IncidentID, FacilityID,FacilityRank,Total_" + cboCostAttribute.Text);
double total_impedance;
long incidentID;
long facilityID;
long facilityRank;
ICursor cursor;
IRow row;
cursor = table.Search(null, false);
row = cursor.NextRow();
while (row != null)
{
incidentID = long.Parse(row.get_Value(table.FindField("IncidentID")).ToString());
facilityID = long.Parse(row.get_Value(table.FindField("FacilityID")).ToString());
facilityRank = long.Parse(row.get_Value(table.FindField("FacilityRank")).ToString());
total_impedance = double.Parse(row.get_Value(table.FindField("Total_" + cboCostAttribute.Text)).ToString());
lstOutput.Items.Add(incidentID.ToString() + ",\t" + facilityID.ToString() +
",\t" + facilityRank.ToString() + ",\t" + total_impedance.ToString("F2"));
row = cursor.NextRow();
}
}
lstOutput.Refresh();
}
/// <summary>
/// Gather the error/warning/informative messages from GPMessages
/// <summary>
/// <param name="gpMessages">GPMessages container</param>
/// <returns>string of all GPMessages</returns>
public string GetGPMessagesAsString(IGPMessages gpMessages)
{
// Gather Error/Warning/Informative Messages
var messages = new StringBuilder();
if (gpMessages != null)
{
for (int i = 0; i < gpMessages.Count; i++)
{
IGPMessage gpMessage = gpMessages.GetMessage(i);
string message = gpMessage.Description;
switch (gpMessages.GetMessage(i).Type)
{
case esriGPMessageType.esriGPMessageTypeError:
messages.AppendLine("Error " + gpMessage.ErrorCode + ": " + message);
break;
case esriGPMessageType.esriGPMessageTypeWarning:
messages.AppendLine("Warning: " + message);
break;
default:
messages.AppendLine("Information: " + message);
break;
}
}
}
return messages.ToString();
}
/// <summary>
/// Refresh the map display
/// <summary>
public void RefreshMapDisplay()
{
// Zoom to the extent of the service areas
IGeoDataset geoDataset = m_NAContext.NAClasses.get_ItemByName(OUTPUTCLASSNAME) as IGeoDataset;
IEnvelope envelope = geoDataset.Extent;
if (!envelope.IsEmpty)
{
envelope.Expand(1.1, 1.1, true);
axMapControl.Extent = envelope;
m_NAContext.Solver.UpdateLayer(axMapControl.get_Layer(0) as INALayer);
}
axMapControl.Refresh();
}
#endregion
#region Solver Settings
/// <summary>
/// Set solver settings
/// </summary>
public void SetSolverSettings()
{
//Set Route specific Settings
INASolver naSolver = m_NAContext.Solver;
INAClosestFacilitySolver cfSolver = naSolver as INAClosestFacilitySolver;
if (txtCutOff.Text.Length > 0 && IsNumeric(txtCutOff.Text.Trim()))
cfSolver.DefaultCutoff = txtCutOff.Text;
else
cfSolver.DefaultCutoff = null;
if (txtTargetFacility.Text.Length > 0 && IsNumeric(txtTargetFacility.Text))
cfSolver.DefaultTargetFacilityCount = int.Parse(txtTargetFacility.Text);
else
cfSolver.DefaultTargetFacilityCount = 1;
cfSolver.OutputLines = esriNAOutputLineType.esriNAOutputLineTrueShapeWithMeasure;
cfSolver.TravelDirection = esriNATravelDirection.esriNATravelDirectionToFacility;
// Set generic solver settings
// Set the impedance attribute
INASolverSettings naSolverSettings;
naSolverSettings = naSolver as INASolverSettings;
naSolverSettings.ImpedanceAttributeName = cboCostAttribute.Text;
// Set the OneWay Restriction if necessary
IStringArray restrictions;
restrictions = naSolverSettings.RestrictionAttributeNames;
restrictions.RemoveAll();
if (chkUseRestriction.Checked)
restrictions.Add("oneway");
naSolverSettings.RestrictionAttributeNames = restrictions;
//Restrict UTurns
naSolverSettings.RestrictUTurns = esriNetworkForwardStarBacktrack.esriNFSBNoBacktrack;
naSolverSettings.IgnoreInvalidLocations = true;
// Set the Hierarchy attribute
naSolverSettings.UseHierarchy = chkUseHierarchy.Checked;
if (naSolverSettings.UseHierarchy)
naSolverSettings.HierarchyAttributeName = "HierarchyMultiNet";
// Do not forget to update the context after you set your impedance
naSolver.UpdateContext(m_NAContext, GetDENetworkDataset(m_NAContext.NetworkDataset), new GPMessagesClass());
}
/// <summary>
/// Check whether a string represents a double value.
/// </summary>
/// <param name="str">String to test</param>
/// <returns>bool</returns>
private bool IsNumeric(string str)
{
try
{
double.Parse(str.Trim());
}
catch (Exception)
{
return false;
}
return true;
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using JetBrains.Annotations;
namespace Nzb
{
/// <summary>
/// Represents a NZB document.
/// </summary>
/// <remarks>
/// See <see href="http://wiki.sabnzbd.org/nzb-specs" /> for the specification.
/// </remarks>
[PublicAPI]
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public sealed class NzbDocument
{
/// <summary>
/// The default encoding for a NZB document.
/// </summary>
[NotNull]
public static readonly Encoding DefaultEncoding = Encoding.GetEncoding("iso-8859-1");
private static readonly IReadOnlyList<NzbSegment> EmptySegments = new NzbSegment[0];
private static readonly IReadOnlyList<string> EmptyGroups = new string[0];
private static readonly IReadOnlyDictionary<string, string> EmptyMetadata = new Dictionary<string, string>(capacity: 0);
private NzbDocument(IReadOnlyDictionary<string, string> metadata, IReadOnlyList<NzbFile> files, long bytes)
{
Metadata = Check.NotNull(metadata, nameof(metadata));
Files = Check.NotNull(files, nameof(files));
Bytes = bytes;
}
/// <summary>
/// Gets the metadata associated with the contents of the document.
/// </summary>
/// <value>The content metadata.</value>
[NotNull]
public IReadOnlyDictionary<string, string> Metadata { get; }
/// <summary>
/// Gets the information about all the files linked in the document.
/// </summary>
/// <value>The files linked in the document.</value>
[NotNull, ItemNotNull]
public IReadOnlyList<NzbFile> Files { get; }
/// <summary>
/// Gets the total number of bytes for all files linked in the document.
/// </summary>
/// <value>The total number of bytes for all files linked in the document.</value>
public long Bytes { get; }
private string DebuggerDisplay => ToString();
/// <summary>
/// Loads the document from the specified stream, using <see cref="DefaultEncoding"/>.
/// </summary>
/// <param name="stream">The stream.</param>
[Pure, NotNull]
public static Task<NzbDocument> Load([NotNull] Stream stream) => Load(stream, DefaultEncoding);
/// <summary>
/// Loads the document from the specified stream, using the specified encoding.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="encoding">The encoding to use.</param>
/// <exception cref="InvalidNzbFormatException">The <paramref name="stream"/> represents an invalid NZB document.</exception>
[Pure, NotNull]
public static async Task<NzbDocument> Load([NotNull] Stream stream, [NotNull] Encoding encoding)
{
Check.NotNull(stream, nameof(stream));
Check.NotNull(encoding, nameof(encoding));
using (var reader = new StreamReader(stream, encoding))
{
return Parse(await reader.ReadToEndAsync());
}
}
/// <summary>
/// Parses the specified text.
/// </summary>
/// <param name="text">The text to parse.</param>
/// <exception cref="InvalidNzbFormatException">The <paramref name="text"/> represents an invalid NZB document.</exception>
[Pure, NotNull]
public static NzbDocument Parse([NotNull] string text)
{
Check.NotEmpty(text, nameof(text));
var document = XDocument.Parse(text);
var nzbElement = document.Element(Constants.NzbElement);
if (nzbElement == null)
{
throw new InvalidNzbFormatException("Could not find required 'nzb' element.");
}
var metadata = ParseMetadata(nzbElement);
var files = ParseFiles(nzbElement, out var bytes);
return new NzbDocument(metadata, files, bytes);
}
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="string" /> that represents this instance.</returns>
public override string ToString() => $"Files: {Files.Count}, Size: {Bytes} bytes";
private static IReadOnlyDictionary<string, string> ParseMetadata(XContainer element)
{
var headElement = element.Element(Constants.HeadElement);
if (headElement == null)
{
return EmptyMetadata;
}
var metaElements = headElement.Elements(Constants.MetaElement).ToArray();
var metadata = new Dictionary<string, string>(capacity: metaElements.Length);
foreach (var metaElement in metaElements)
{
var typeAttribute = metaElement.Attribute(Constants.TypeAttribute);
if (typeAttribute != null)
{
metadata.Add(typeAttribute.Value, metaElement.Value);
}
}
return metadata;
}
private static IReadOnlyList<NzbFile> ParseFiles(XContainer element, out long bytes)
{
var fileElements = element.Elements(Constants.FileElement).ToArray();
var files = new List<NzbFile>(capacity: fileElements.Length);
bytes = 0;
foreach (var fileElement in fileElements)
{
var file = ParseFile(fileElement);
bytes += file.Bytes;
files.Add(file);
}
return files;
}
private static NzbFile ParseFile(XElement element)
{
var poster = element.AttributeValueOrEmpty(Constants.PosterAttribute);
var unixTimestamp = element
.AttributeValueOrEmpty(Constants.DateAttribute)
.TryParseOrDefault((string s, out long l) => long.TryParse(s, out l));
var date = unixTimestamp.ToUnixEpoch();
var subject = element.AttributeValueOrEmpty(Constants.SubjectAttribute);
var groups = ParseGroups(element);
var segments = ParseSegments(element, out long bytes);
return new NzbFile(poster, date, subject, groups, segments, bytes);
}
private static IReadOnlyList<string> ParseGroups(XContainer element)
{
var groupsElement = element.Element(Constants.GroupsElement);
if (groupsElement == null)
{
return EmptyGroups;
}
var groupElements = groupsElement.Elements(Constants.GroupElement).ToArray();
var groups = new List<string>(capacity: groupElements.Length);
foreach (var groupElement in groupElements)
{
groups.Add(groupElement.Value);
}
return groups;
}
private static IReadOnlyList<NzbSegment> ParseSegments(XContainer element, out long bytes)
{
bytes = 0;
var segmentsElement = element.Element(Constants.SegmentsElement);
if (segmentsElement == null)
{
return EmptySegments;
}
var segmentElements = segmentsElement.Elements(Constants.SegmentElement).ToArray();
var segments = new List<NzbSegment>(capacity: segmentElements.Length);
foreach (var segmentElement in segmentElements)
{
var segment = ParseSegment(segmentElement);
bytes += segment.Bytes;
segments.Add(segment);
}
return segments;
}
private static NzbSegment ParseSegment(XElement element)
{
var bytes = element
.AttributeValueOrEmpty(Constants.BytesAttribute)
.TryParseOrDefault((string s, out long l) => long.TryParse(s, out l));
var number = element
.AttributeValueOrEmpty(Constants.NumberAttribute)
.TryParseOrDefault((string s, out int i) => int.TryParse(s, out i));
var messageId = element.Value;
return new NzbSegment(bytes, number, messageId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Lucene.Net.Codecs.Lucene3x
{
using Lucene.Net.Support;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using Bits = Lucene.Net.Util.Bits;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
using StringHelper = Lucene.Net.Util.StringHelper;
/// <summary>
/// Reads Lucene 3.x norms format and exposes it via DocValues API
/// @lucene.experimental </summary>
/// @deprecated Only for reading existing 3.x indexes
[Obsolete("Only for reading existing 3.x indexes")]
public class Lucene3xNormsProducer : DocValuesProducer
{
/// <summary>
/// norms header placeholder </summary>
internal static readonly sbyte[] NORMS_HEADER = { (sbyte)'N', (sbyte)'R', (sbyte)'M', -1 };
/// <summary>
/// Extension of norms file </summary>
internal const string NORMS_EXTENSION = "nrm";
/// <summary>
/// Extension of separate norms file </summary>
internal const string SEPARATE_NORMS_EXTENSION = "s";
private readonly IDictionary<string, NormsDocValues> Norms = new Dictionary<string, NormsDocValues>();
// any .nrm or .sNN files we have open at any time.
// TODO: just a list, and double-close() separate norms files?
internal readonly ISet<IndexInput> OpenFiles = new IdentityHashSet<IndexInput>();
// points to a singleNormFile
internal IndexInput SingleNormStream;
internal readonly int Maxdoc;
private readonly AtomicLong ramBytesUsed;
// note: just like segmentreader in 3.x, we open up all the files here (including separate norms) up front.
// but we just don't do any seeks or reading yet.
public Lucene3xNormsProducer(Directory dir, SegmentInfo info, FieldInfos fields, IOContext context)
{
Directory separateNormsDir = info.Dir; // separate norms are never inside CFS
Maxdoc = info.DocCount;
string segmentName = info.Name;
bool success = false;
try
{
long nextNormSeek = NORMS_HEADER.Length; //skip header (header unused for now)
foreach (FieldInfo fi in fields)
{
if (fi.HasNorms())
{
string fileName = GetNormFilename(info, fi.Number);
Directory d = HasSeparateNorms(info, fi.Number) ? separateNormsDir : dir;
// singleNormFile means multiple norms share this file
bool singleNormFile = IndexFileNames.MatchesExtension(fileName, NORMS_EXTENSION);
IndexInput normInput = null;
long normSeek;
if (singleNormFile)
{
normSeek = nextNormSeek;
if (SingleNormStream == null)
{
SingleNormStream = d.OpenInput(fileName, context);
OpenFiles.Add(SingleNormStream);
}
// All norms in the .nrm file can share a single IndexInput since
// they are only used in a synchronized context.
// If this were to change in the future, a clone could be done here.
normInput = SingleNormStream;
}
else
{
normInput = d.OpenInput(fileName, context);
OpenFiles.Add(normInput);
// if the segment was created in 3.2 or after, we wrote the header for sure,
// and don't need to do the sketchy file size check. otherwise, we check
// if the size is exactly equal to maxDoc to detect a headerless file.
// NOTE: remove this check in Lucene 5.0!
string version = info.Version;
bool isUnversioned = (version == null || StringHelper.VersionComparator.Compare(version, "3.2") < 0) && normInput.Length() == Maxdoc;
if (isUnversioned)
{
normSeek = 0;
}
else
{
normSeek = NORMS_HEADER.Length;
}
}
NormsDocValues norm = new NormsDocValues(this, normInput, normSeek);
Norms[fi.Name] = norm;
nextNormSeek += Maxdoc; // increment also if some norms are separate
}
}
// TODO: change to a real check? see LUCENE-3619
Debug.Assert(SingleNormStream == null || nextNormSeek == SingleNormStream.Length(), SingleNormStream != null ? "len: " + SingleNormStream.Length() + " expected: " + nextNormSeek : "null");
success = true;
}
finally
{
if (!success)
{
IOUtils.CloseWhileHandlingException(OpenFiles);
}
}
ramBytesUsed = new AtomicLong();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Close(OpenFiles.ToArray());
}
finally
{
Norms.Clear();
OpenFiles.Clear();
}
}
}
private static string GetNormFilename(SegmentInfo info, int number)
{
if (HasSeparateNorms(info, number))
{
long gen = Convert.ToInt64(info.GetAttribute(Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + number));
return IndexFileNames.FileNameFromGeneration(info.Name, SEPARATE_NORMS_EXTENSION + number, gen);
}
else
{
// single file for all norms
return IndexFileNames.SegmentFileName(info.Name, "", NORMS_EXTENSION);
}
}
private static bool HasSeparateNorms(SegmentInfo info, int number)
{
string v = info.GetAttribute(Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + number);
if (v == null)
{
return false;
}
else
{
Debug.Assert(Convert.ToInt64(v) != SegmentInfo.NO);
return true;
}
}
// holds a file+offset pointing to a norms, and lazy-loads it
// to a singleton NumericDocValues instance
private sealed class NormsDocValues
{
private readonly Lucene3xNormsProducer OuterInstance;
private readonly IndexInput File;
private readonly long Offset;
private NumericDocValues Instance_Renamed;
public NormsDocValues(Lucene3xNormsProducer outerInstance, IndexInput normInput, long normSeek)
{
this.OuterInstance = outerInstance;
this.File = normInput;
this.Offset = normSeek;
}
internal NumericDocValues Instance
{
get
{
lock (this)
{
if (Instance_Renamed == null)
{
var bytes = new byte[OuterInstance.Maxdoc];
// some norms share fds
lock (File)
{
File.Seek(Offset);
File.ReadBytes(bytes, 0, bytes.Length, false);
}
// we are done with this file
if (File != OuterInstance.SingleNormStream)
{
OuterInstance.OpenFiles.Remove(File);
File.Dispose();
}
OuterInstance.ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(bytes));
Instance_Renamed = new NumericDocValuesAnonymousInnerClassHelper(this, bytes);
}
return Instance_Renamed;
}
}
}
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
private readonly byte[] Bytes;
public NumericDocValuesAnonymousInnerClassHelper(NormsDocValues outerInstance, byte[] bytes)
{
this.Bytes = bytes;
}
public override long Get(int docID)
{
return Bytes[docID];
}
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
var dv = Norms[field.Name];
Debug.Assert(dv != null);
return dv.Instance;
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
throw new InvalidOperationException();
}
public override SortedDocValues GetSorted(FieldInfo field)
{
throw new InvalidOperationException();
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
throw new InvalidOperationException();
}
public override Bits GetDocsWithField(FieldInfo field)
{
throw new InvalidOperationException();
}
public override long RamBytesUsed()
{
return ramBytesUsed.Get();
}
public override void CheckIntegrity()
{
}
}
}
| |
//
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.Specialized;
using Manos;
using Manos.IO;
using Manos.Http;
using Manos.Collections;
namespace Manos.Http.Testing
{
public class MockHttpRequest : IHttpRequest
{
private DataDictionary data;
private DataDictionary uri_data;
private DataDictionary post_data;
private DataDictionary query_data;
private DataDictionary cookies;
private HttpHeaders headers;
private Dictionary<string,UploadedFile> uploaded_files;
private Encoding encoding;
public MockHttpRequest()
{
Reset();
}
public MockHttpRequest (HttpMethod method, string path)
{
Method = method;
Path = path;
Reset();
}
public void Reset()
{
data = new DataDictionary ();
uri_data = new DataDictionary ();
query_data = new DataDictionary ();
post_data = new DataDictionary ();
Properties = new Dictionary<string,object> ();
data.Children.Add (UriData);
data.Children.Add (QueryData);
data.Children.Add (PostData);
}
public void Dispose ()
{
}
public HttpMethod Method {
get;
set;
}
public string Path {
get;
set;
}
public bool Aborted {
get;
private set;
}
public DataDictionary Data {
get {
return data;
}
}
public DataDictionary PostData {
get {
return post_data;
}
}
public DataDictionary UriData {
get {
return uri_data;
}
set {
uri_data = value;
}
}
public DataDictionary QueryData {
get {
return query_data;
}
set {
query_data = value;
}
}
public DataDictionary Cookies {
get {
if (cookies == null)
cookies = new DataDictionary ();
return cookies;
}
set { cookies = value; }
}
public HttpHeaders Headers {
get {
if (headers == null)
headers = new HttpHeaders ();
return headers;
}
set {
headers = value;
}
}
public Encoding ContentEncoding {
get {
if (encoding == null)
encoding = Encoding.Default;
return encoding;
}
}
public Dictionary<string,UploadedFile> Files {
get {
if (uploaded_files == null)
uploaded_files = new Dictionary<string,UploadedFile> ();
return uploaded_files;
}
}
public int MajorVersion {
get;
set;
}
public int MinorVersion {
get;
set;
}
public ITcpSocket Socket {
get;
set;
}
public string PostBody {
get;
set;
}
public Dictionary<string,object> Properties {
get;
set;
}
public void SetProperty (string name, object o)
{
if (name == null)
throw new ArgumentNullException ("name");
if (o == null) {
Properties.Remove (name);
return;
}
Properties [name] = o;
}
public object GetProperty (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
object res = null;
if (!Properties.TryGetValue (name, out res))
return null;
return res;
}
public T GetProperty<T> (string name)
{
object res = GetProperty (name);
if (res == null)
return default (T);
return (T) res;
}
public void Read (Action onClose)
{
}
public void SetWwwFormData (DataDictionary data)
{
PostData.Children.Add (data);
}
public void WriteMetadata (StringBuilder builder)
{
builder.Append (Encoding.ASCII.GetString (HttpMethodBytes.GetBytes (Method)));
builder.Append (" ");
builder.Append (Path);
builder.Append (" HTTP/");
builder.Append (MajorVersion.ToString (CultureInfo.InvariantCulture));
builder.Append (".");
builder.Append (MinorVersion.ToString (CultureInfo.InvariantCulture));
builder.Append ("\r\n");
Headers.Write (builder, null, Encoding.ASCII);
}
}
}
| |
// _________________________________________________________________________________________
// Name: BaseWPHHelpers
// Purpose: Common helpers for tree walking etc
// Author: Andrew Whiddett
// (c) Copyright 2006 REZN8 Productions Inc
// _________________________________________________________________________________________
#region Using
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
#endregion
namespace BaseWPFHelpers
{
public class Helpers
{
/// <summary>
/// Helper method to create a snapshot of a visual item as a bitmap image. Typically used for things like drag and drop
/// or any time we want to do something where we don't want the hit of a video running in an animating object
/// </summary>
/// <param name="element">Element to take a snapshot of</param>
/// <returns>Bitmap image of the element</returns>
public static RenderTargetBitmap CreateImageBrushFromVisual(FrameworkElement element)
{
RenderTargetBitmap bitmapImage =
new RenderTargetBitmap((int)element.ActualWidth,
(int)element.ActualHeight,
96, 96,
PixelFormats.Pbgra32);
bitmapImage.Render(element);
return bitmapImage;
}
/// <summary>
/// Base Interface that describes the visual match pattern
/// Part of the Visual tree walkers
/// </summary>
public interface IFinderMatchVisualHelper
{
/// <summary>
/// Does this item match the input visual item
/// </summary>
/// <param name="item">Item to check </param>
/// <returns>True if matched, else false</returns>
bool DoesMatch(DependencyObject item);
/// <summary>
/// Property that defines if we should stop walking the tree after the first match is found
/// </summary>
bool StopAfterFirst
{
get;
set;
}
}
/// <summary>
/// Visual tree walker class that matches based on Type
/// </summary>
public class FinderMatchType : IFinderMatchVisualHelper
{
private Type _ty = null;
private bool _stopafterfirst = false;
public FinderMatchType(Type ty)
{
_ty = ty;
}
public FinderMatchType(Type ty, bool StopAfterFirst)
{
_ty = ty;
_stopafterfirst = StopAfterFirst;
}
public bool DoesMatch(DependencyObject item)
{
return _ty.IsInstanceOfType(item);
}
public bool StopAfterFirst
{
get
{
return _stopafterfirst;
}
set
{
_stopafterfirst = value;
}
}
}
/// <summary>
/// Visual tree walker function that matches on name of an element
/// </summary>
public class FinderMatchName : IFinderMatchVisualHelper
{
private String _name = "";
public FinderMatchName(String name)
{
_name = name;
}
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is FrameworkElement)
{
if ((item as FrameworkElement).Name == _name) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one of the same name..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Visual tree helper that matches if the item is focused
/// </summary>
public class FinderMatchFocused : IFinderMatchVisualHelper
{
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is FrameworkElement)
{
if ((item as FrameworkElement).IsFocused) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one item in focus..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Visual tree helper that matches is the item is an itemshost. Typically used in ItemControls
/// </summary>
public class FinderMatchItemHost : IFinderMatchVisualHelper
{
public bool DoesMatch(DependencyObject item)
{
bool bMatch = false;
if (item is Panel)
{
if ((item as Panel).IsItemsHost) bMatch = true;
}
return bMatch;
}
/// <summary>
/// StopAfterFirst Property.. always true, you can't have more than one item host in an item control..
/// </summary>
public bool StopAfterFirst
{
get
{
return true;
}
set
{
}
}
}
/// <summary>
/// Typically used method that walks down the visual tree from a given point to locate a given match only
/// once. Typically used with Name/ItemHost etc type matching.
///
/// Only returns one element
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>Null if no match, else returns the first element that matches</returns>
public static FrameworkElement SingleFindDownInTree(Visual parent, IFinderMatchVisualHelper helper)
{
helper.StopAfterFirst = true;
List<FrameworkElement> lst = FindDownInTree(parent, helper);
FrameworkElement feRet = null;
if (lst.Count > 0) feRet = lst[0];
return feRet;
}
/// <summary>
/// All way visual tree helper that searches UP and DOWN in a tree for the matching pattern.
///
/// This is used to walk for name matches or type matches typically.
///
/// Returns only the first matching element
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>Null if no match, else returns the first element that matches</returns>
public static FrameworkElement SingleFindInTree(Visual parent, IFinderMatchVisualHelper helper)
{
helper.StopAfterFirst = true;
List<FrameworkElement> lst = FindInTree(parent, helper);
FrameworkElement feRet = null;
if (lst.Count > 0) feRet = lst[0];
return feRet;
}
/// <summary>
/// Walker that looks down in the visual tree for any matching elements, typically used with Type
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>List of matching FrameworkElements</returns>
public static List<FrameworkElement> FindDownInTree(Visual parent, IFinderMatchVisualHelper helper)
{
List<FrameworkElement> lst = new List<FrameworkElement>();
FindDownInTree(lst, parent, null, helper);
return lst;
}
/// <summary>
/// Walker that looks both UP and down in the visual tree for any matching elements, typically used with Type
/// </summary>
/// <param name="parent">Start point in the tree to search</param>
/// <param name="helper">Match Helper to use</param>
/// <returns>List of matching FrameworkElements</returns>
public static List<FrameworkElement> FindInTree(Visual parent, IFinderMatchVisualHelper helper)
{
List<FrameworkElement> lst = new List<FrameworkElement>();
FindUpInTree(lst, parent, null, helper);
return lst;
}
/// <summary>
/// Really a helper for FindDownInTree, typically not called directly.
/// </summary>
/// <param name="lst"></param>
/// <param name="parent"></param>
/// <param name="ignore"></param>
/// <param name="helper"></param>
public static void FindDownInTree(List<FrameworkElement> lst, DependencyObject parent, DependencyObject ignore, IFinderMatchVisualHelper helper)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
if (lst.Count > 0 && helper.StopAfterFirst) break;
DependencyObject visual = VisualTreeHelper.GetChild(parent, i);
if (visual is FrameworkElement)
{
(visual as FrameworkElement).ApplyTemplate();
}
if (helper.DoesMatch(visual))
{
lst.Add(visual as FrameworkElement);
}
if (lst.Count > 0 && helper.StopAfterFirst) break;
if (visual != ignore)
{
FindDownInTree(lst, visual, ignore, helper);
}
}
}
/// <summary>
/// Really a helper to look Up in a tree, typically not called directly.
/// </summary>
/// <param name="lst"></param>
/// <param name="parent"></param>
/// <param name="ignore"></param>
/// <param name="helper"></param>
public static void FindUpInTree(List<FrameworkElement> lst, Visual parent, Visual ignore, IFinderMatchVisualHelper helper)
{
// First thing to do is find Down in the existing node...
//FindDownInTree(lst, parent, ignore, helper);
if (helper.DoesMatch(parent))
{
lst.Add(parent as FrameworkElement);
}
// Ok, now check to see we are not at a stop.. i.e. got it.
if (lst.Count > 0 && helper.StopAfterFirst)
{
// Hum, don't think we need to do anything here: yet.
}
else
{
// Ok, now try to get a new parent...
FrameworkElement feCast = parent as FrameworkElement;
if (feCast != null)
{
FrameworkElement feNewParent = feCast.Parent as FrameworkElement;
if (feNewParent == null || feNewParent == feCast)
{
// Try to get the templated parent
feNewParent = feCast.TemplatedParent as FrameworkElement;
}
// Now check to see that we have a valid parent
if (feNewParent != null && feNewParent != feCast)
{
// Pass up
FindUpInTree(lst, feNewParent, feCast, helper);
}
}
}
}
/// <summary>
/// Simple form call that returns all elements of a given type down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static List<FrameworkElement> FindElementsOfType(Visual parent, Type ty)
{
return FindDownInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Simple form call that returns the first element of a given type down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static FrameworkElement FindElementOfType(Visual parent, Type ty)
{
return SingleFindDownInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Simple form call that returns the first element of a given type up in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ty"></param>
/// <returns></returns>
public static FrameworkElement FindElementOfTypeUp(Visual parent, Type ty)
{
return SingleFindInTree(parent, new FinderMatchType(ty));
}
/// <summary>
/// Helper to pause any media elements down in the visual tree
/// </summary>
/// <param name="parent"></param>
public static void TurnOffMediaElements(Visual parent)
{
List<FrameworkElement> lst = FindElementsOfType(parent,typeof(MediaElement));
foreach (FrameworkElement me in lst)
{
MediaElement meCast = me as MediaElement;
if (meCast != null)
{
if (meCast.CanPause)
{
try
{
meCast.Pause();
}
catch (Exception e)
{
}
}
}
}
}
/// <summary>
/// Helper to resume playing any media elements down in the visual tree
/// </summary>
/// <param name="parent"></param>
public static void TurnOnMediaElements(Visual parent)
{
List<FrameworkElement> lst = FindElementsOfType(parent, typeof(MediaElement));
foreach (FrameworkElement me in lst)
{
MediaElement meCast = me as MediaElement;
if (meCast != null)
{
try
{
meCast.Play();
}
catch (Exception e)
{
}
}
}
}
/// <summary>
/// Helper to find the currently focused element
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static FrameworkElement FindFocusedElement(Visual parent)
{
return SingleFindInTree(parent, new FinderMatchFocused());
}
/// <summary>
/// Helper to find a items host (e.g. in a listbox etc) down in the tree
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static FrameworkElement FindItemsHost(Visual parent)
{
return SingleFindDownInTree(parent, new FinderMatchItemHost());
}
/// <summary>
/// Helper to find the given named element down in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ElementName"></param>
/// <returns></returns>
public static FrameworkElement FindVisualElement(Visual parent, String ElementName)
{
return SingleFindDownInTree(parent, new FinderMatchName(ElementName));
}
/// <summary>
/// Helper to find the given named element up in the visual tree
/// </summary>
/// <param name="parent"></param>
/// <param name="ElementName"></param>
/// <returns></returns>
public static FrameworkElement FindVisualElementUp(Visual parent, String ElementName)
{
return SingleFindInTree(parent, new FinderMatchName(ElementName));
}
}
}
| |
using System.Linq;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.Collections;
using NUnit.Framework;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
[TestFixture]
public class ManyToManyMutablePropertyModelGenerationTests : BaseModelFixture
{
[Test]
public void ShouldSetName()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => { })
.ModelShouldMatch(x => x.Name.ShouldEqual("BagOfChildren"));
}
[Test]
public void AccessShouldSetModelAccessPropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Access.Field())
.ModelShouldMatch(x => x.Access.ShouldEqual("field"));
}
[Test]
public void BatchSizeShouldSetModelBatchSizePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.BatchSize(10))
.ModelShouldMatch(x => x.BatchSize.ShouldEqual(10));
}
[Test]
public void CacheShouldSetModelCachePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Cache.ReadOnly())
.ModelShouldMatch(x =>
{
x.Cache.ShouldNotBeNull();
x.Cache.Usage.ShouldEqual("read-only");
});
}
[Test]
public void CascadeShouldSetModelCascadePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Cascade.All())
.ModelShouldMatch(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void CollectionTypeShouldSetModelCollectionTypePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.CollectionType("type"))
.ModelShouldMatch(x => x.CollectionType.ShouldEqual(new TypeReference("type")));
}
[Test]
public void ForeignKeyCascadeOnDeleteShouldSetModelKeyOnDeletePropertyToCascade()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ForeignKeyCascadeOnDelete())
.ModelShouldMatch(x => x.Key.OnDelete.ShouldEqual("cascade"));
}
[Test]
public void InverseShouldSetModelInversePropertyToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Inverse())
.ModelShouldMatch(x => x.Inverse.ShouldBeTrue());
}
[Test]
public void NotInverseShouldSetModelInversePropertyToFalse()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Not.Inverse())
.ModelShouldMatch(x => x.Inverse.ShouldBeFalse());
}
[Test]
public void WithParentKeyColumnShouldAddColumnToModelKeyColumnsCollection()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ParentKeyColumn("col"))
.ModelShouldMatch(x => x.Key.Columns.Count().ShouldEqual(1));
}
[Test]
public void WithForeignKeyConstraintNamesShouldAddForeignKeyToBothColumns()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ForeignKeyConstraintNames("p_fk", "c_fk"))
.ModelShouldMatch(x =>
{
x.Key.ForeignKey.ShouldEqual("p_fk");
((ManyToManyMapping)x.Relationship).ForeignKey.ShouldEqual("c_fk");
});
}
[Test]
public void WithChildKeyColumnShouldAddColumnToModelRelationshipColumnsCollection()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ChildKeyColumn("col"))
.ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).Columns.Count().ShouldEqual(1));
}
[Test]
public void LazyLoadShouldSetModelLazyPropertyToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.True));
}
[Test]
public void NotLazyLoadShouldSetModelLazyPropertyToFalse()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Not.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.False));
}
[Test]
public void ExtraLazyLoadShouldSetModelLazyPropertyToExtra()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ExtraLazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.Extra));
}
[Test]
public void NotExtraLazyLoadShouldSetModelLazyPropertyToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Not.ExtraLazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(Lazy.True));
}
[Test]
public void NotFoundShouldSetModelRelationshipNotFoundPropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.NotFound.Ignore())
.ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).NotFound.ShouldEqual("ignore"));
}
[Test]
public void WhereShouldSetModelWherePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Where("x = 1"))
.ModelShouldMatch(x => x.Where.ShouldEqual("x = 1"));
}
[Test]
public void WithTableNameShouldSetModelTableNamePropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Table("t"))
.ModelShouldMatch(x => x.TableName.ShouldEqual("t"));
}
[Test]
public void SchemaIsShouldSetModelSchemaPropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Schema("dto"))
.ModelShouldMatch(x => x.Schema.ShouldEqual("dto"));
}
[Test]
public void FetchShouldSetModelFetchPropertyToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Fetch.Select())
.ModelShouldMatch(x => x.Fetch.ShouldEqual("select"));
}
[Test]
public void PersisterShouldSetModelPersisterPropertyToAssemblyQualifiedName()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Persister<CustomPersister>())
.ModelShouldMatch(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister)));
}
[Test]
public void CheckShouldSetModelCheckToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Check("x > 100"))
.ModelShouldMatch(x => x.Check.ShouldEqual("x > 100"));
}
[Test]
public void OptimisticLockShouldSetModelOptimisticLockToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.OptimisticLock())
.ModelShouldMatch(x => x.OptimisticLock.ShouldEqual(true));
}
[Test]
public void GenericShouldSetModelGenericToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Generic())
.ModelShouldMatch(x => x.Generic.ShouldBeTrue());
}
[Test]
public void NotGenericShouldSetModelGenericToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Not.Generic())
.ModelShouldMatch(x => x.Generic.ShouldBeFalse());
}
[Test]
public void ReadOnlyShouldSetModelMutableToFalse()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Mutable.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetModelMutableToTrue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Mutable.ShouldBeTrue());
}
[Test]
public void SubselectShouldSetModelSubselectToValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.Subselect("whee"))
.ModelShouldMatch(x => x.Subselect.ShouldEqual("whee"));
}
[Test]
public void OrderByShouldSetAttributeOnBag()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.OrderBy("col1"))
.ModelShouldMatch(x => x.OrderBy.ShouldEqual("col1"));
}
[Test]
public void ChildOrderByShouldSetAttributeOnRelationshipModel()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ChildOrderBy("col1"))
.ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).OrderBy.ShouldEqual("col1"));
}
[Test]
public void ChildWhereShouldSetAttributeOnRelationshipModel()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ChildWhere("some condition"))
.ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).Where.ShouldEqual("some condition"));
}
[Test]
public void GenericChildWhereShouldSetAttributeOnRelationshipModel()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.ChildWhere(x => x.Name == "Name"))
.ModelShouldMatch(x => ((ManyToManyMapping)x.Relationship).Where.ShouldEqual("Name = 'Name'"));
}
[Test]
public void EntityNameShouldSetModelValue()
{
ManyToMany(x => x.BagOfChildren)
.Mapping(m => m.EntityName("name"))
.ModelShouldMatch(x => x.Relationship.EntityName.ShouldEqual("name"));
}
}
}
| |
using UnityEngine;
public class Interpolation
{
// Basic linear interpolation for two floating point values
static public float Linear(float v0, float v1, float factor)
{
return v0 * (1.0f - factor) + v1 * factor;
}
// Basic linear interpolation for a pair of 2D vector
static public Vector2 Linear(Vector2 v0, Vector2 v1, float factor)
{
return v0 * (1.0f - factor) + v1 * factor;
}
// Basic linear interpolation for a pair of 3D vectors
static public Vector3 Linear(Vector3 v0, Vector3 v1, float factor)
{
return v0 * (1.0f - factor) + v1 * factor;
}
// Quaternion version of linear interpolation actually uses SLERP
static public Quaternion Linear(Quaternion q0, Quaternion q1, float factor)
{
return Quaternion.Slerp(q0, q1, factor);
}
// Color version of linear interpolation
static public Color Linear(Color c0, Color c1, float factor)
{
return c0 * (1.0f - factor) + c1 * factor;
}
// Cosine interpolation for two floating point values
static public float Cosine(float v1, float v2, float factor)
{
factor = (1.0f - Mathf.Cos(factor * Mathf.PI)) * 0.5f;
return (v1 * (1.0f - factor) + v2 * factor);
}
// Cosine interpolation for two vectors
static public Vector3 Cosine(Vector3 v1, Vector3 v2, float factor)
{
factor = (1.0f - Mathf.Cos(factor * Mathf.PI)) * 0.5f;
return (v1 * (1.0f - factor) + v2 * factor);
}
// Cosine interpolation for two quaternions
static public Quaternion Cosine(Quaternion q1, Quaternion q2, float factor)
{
factor = (1.0f - Mathf.Cos(factor * Mathf.PI)) * 0.5f;
return Quaternion.Slerp(q1, q2, factor);
}
// Hermite 2-value interpolation (ease in, ease out)
static public float Hermite(float start, float end, float factor)
{
factor = factor * factor * (3.0f - 2.0f * factor);
return Mathf.Lerp(start, end, factor);
}
// Hermite 2-vector interpolation (ease in, ease out)
static public Vector3 Hermite(Vector3 v0, Vector3 v1, float factor)
{
factor = factor * factor * (3.0f - 2.0f * factor);
return v0 * (1.0f - factor) + v1 * factor;
}
// Hermite 2-color interpolation (ease in, ease out)
static public Color Hermite(Color v0, Color v1, float factor)
{
factor = factor * factor * (3.0f - 2.0f * factor);
return v0 * (1.0f - factor) + v1 * factor;
}
// Hermite 2-quaternion interpolation (ease in, ease out)
static public Quaternion Hermite(Quaternion q1, Quaternion q2, float factor)
{
factor = factor * factor * (3.0f - 2.0f * factor);
return Quaternion.Slerp(q1, q2, factor);
}
// Hermite spline tangent for a float-based spline
static public float GetHermiteTangent(float distance0, float distance1, float duration0, float duration1)
{
return (distance0 / duration0 + distance1 / duration1) * 0.5f;
}
// Calculates a hermite spline tangent at the given point using 3 vectors and two duration factors
static public Vector3 GetHermiteTangent(Vector3 distance0, Vector3 distance1, float duration0, float duration1)
{
return distance0 * (0.5f / duration0) + distance1 * (0.5f / duration1);
}
// Hermite spline interpolation with the provided tangents
static public float Hermite(float pos0, float pos1, float tan0, float tan1, float factor, float duration)
{
float factor2 = factor * factor;
float factor3 = factor2 * factor;
return pos0 * (2.0f * factor3 - 3.0f * factor2 + 1.0f) +
pos1 * (3.0f * factor2 - 2.0f * factor3) +
(tan0 * (factor3 - 2.0f * factor2 + factor) +
tan1 * (factor3 - factor2)) * duration;
}
// Hermite spline interpolation with the provided tangents
static public Vector3 Hermite(Vector3 pos0, Vector3 pos1, Vector3 tan0, Vector3 tan1, float factor, float duration)
{
float factor2 = factor * factor;
float factor3 = factor2 * factor;
return pos0 * (2.0f * factor3 - 3.0f * factor2 + 1.0f) +
pos1 * (3.0f * factor2 - 2.0f * factor3) +
(tan0 * (factor3 - 2.0f * factor2 + factor) +
tan1 * (factor3 - factor2)) * duration;
}
// Optimized function for cases where val0 = 0, and val1 = 1
static public float Hermite(float tan0, float tan1, float factor, float duration)
{
float factor2 = factor * factor;
float factor3 = factor2 * factor;
return (3.0f * factor2 - 2.0f * factor3) +
(tan0 * (factor3 - 2.0f * factor2 + factor) +
tan1 * (factor3 - factor2)) * duration;
}
// Spherical linear interpolation that does not choose the shortest path (for SQUAD)
private static Quaternion SlerpNoInvert (Quaternion from, Quaternion to, float factor)
{
float dot = Quaternion.Dot(from, to);
if (Mathf.Abs(dot) > 0.999999f)
{
return Quaternion.Lerp(from, to, factor);
}
float theta = Mathf.Acos( Mathf.Clamp(dot, -1.0f, 1.0f) );
float sinInv = 1.0f / Mathf.Sin(theta);
float first = Mathf.Sin((1.0f - factor) * theta) * sinInv;
float second = Mathf.Sin(factor * theta) * sinInv;
return new Quaternion( first * from.x + second * to.x,
first * from.y + second * to.y,
first * from.z + second * to.z,
first * from.w + second * to.w );
}
// Quaternion Logarithm
private static Quaternion Log(Quaternion q)
{
float a = Mathf.Acos( Mathf.Clamp(q.w, -1.0f, 1.0f) ), s = Mathf.Sin(a);
if (Mathf.Abs(s) < 0.000001f)
{
return new Quaternion( 0.0f, 0.0f, 0.0f, 0.0f );
}
a /= s;
return new Quaternion(q.x * a, q.y * a, q.z * a, 0.0f);
}
// Quaternion Exponent
private static Quaternion Exp(Quaternion q)
{
float a = Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z),
s = Mathf.Sin(a),
c = Mathf.Cos(a);
if (Mathf.Abs(a) < 0.000001f)
{
return new Quaternion(0.0f, 0.0f, 0.0f, c);
}
s /= a;
return new Quaternion(q.x * s, q.y * s, q.z * s, c);
}
// Finds the control quaternion for the specified quaternion to be used in SQUAD
static public Quaternion GetSquadControlRotation(Quaternion past, Quaternion current, Quaternion future)
{
Quaternion inv = new Quaternion( -current.x, -current.y, -current.z, current.w );
Quaternion q0 = Log(inv * past);
Quaternion q1 = Log(inv * future);
Quaternion sum = new Quaternion(
-0.25f * (q0.x + q1.x),
-0.25f * (q0.y + q1.y),
-0.25f * (q0.z + q1.z),
-0.25f * (q0.w + q1.w));
return current * Exp(sum);
}
// Spherical Cubic interpolation -- ctrlFrom and ctrlTo are control quaternions
static public Quaternion Squad(Quaternion from, Quaternion to, Quaternion ctrlFrom, Quaternion ctrlTo, float factor)
{
return SlerpNoInvert( SlerpNoInvert(from, to, factor),
SlerpNoInvert(ctrlFrom, ctrlTo, factor),
factor * 2.0f * (1.0f - factor) );
}
}
| |
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="Dialog.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright>
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace MSBuild.ExtensionPack.UI
{
using System.Globalization;
using Microsoft.Build.Framework;
using MSBuild.ExtensionPack.UI.Extended;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Confirm</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, ConfirmText, ErrorText, ErrorTitle, Button1Text, Button2Text, MaskText <b>Output: </b>ButtonClickedText, UserText)</para>
/// <para><i>Show</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, Button1Text, Button2Text, Button3Text, MessageColour, MessageBold <b>Output: </b>ButtonClickedText)</para>
/// <para><i>Prompt</i> (<b>Required: </b>Text <b>Optional: </b>Title, Height, Width, Button1Text, Button2Text, Button3Text, MessageColour, MessageBold, MaskText <b>Output: </b>ButtonClickedText, UserText)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Confirm a Password -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Confirm" Title="Confirmation Required" Button2Text="Cancel" Text="Enter Password" ConfirmText="Confirm Password" MaskText="true">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// <!-- A simple message -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Show" Text="Hello MSBuild">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <!-- A longer message with a few more attributes set -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Show" Title="A Longer Message" MessageBold="True" Button2Text="Cancel" MessageColour="Green" Height="300" Width="600" Text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras vitae velit. Pellentesque malesuada diam eget sem. Praesent vestibulum. Donec egestas, quam at viverra volutpat, eros nulla gravida nisi, sed bibendum metus mauris ut diam. Aliquam interdum lacus nec quam. Etiam porta, elit sed pretium vestibulum, nisi dui condimentum enim, ut rhoncus ipsum leo nec est. Nullam congue velit id ligula. Sed imperdiet bibendum pede. In hac habitasse platea dictumst. Praesent eleifend, elit quis convallis aliquam, mi arcu feugiat sem, at blandit mauris nisi eget mauris.">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <!-- A simple prompt for input -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Prompt" Title="Information Required" Button2Text="Cancel" Text="Please enter your Name below">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// <!-- A prompt for password input -->
/// <MSBuild.ExtensionPack.UI.Dialog TaskAction="Prompt" Title="Sensitive Information Required" Button2Text="Cancel" Text="Please enter your Password below" MessageColour="Red" MaskText="true">
/// <Output TaskParameter="ButtonClickedText" PropertyName="Clicked"/>
/// <Output TaskParameter="UserText" PropertyName="Typed"/>
/// </MSBuild.ExtensionPack.UI.Dialog>
/// <Message Text="User Clicked: $(Clicked)"/>
/// <Message Text="User Typed: $(Typed)"/>
/// </Target >
/// </Project>
/// ]]></code>
/// </example>
public class Dialog : BaseTask
{
private const string ShowTaskAction = "Show";
private const string PromptTaskAction = "Prompt";
private const string ConfirmTaskAction = "Confirm";
/// <summary>
/// Sets the height of the form. Default is 180
/// </summary>
public int Height { get; set; } = 180;
/// <summary>
/// Sets the width of the form. Default is 400
/// </summary>
public int Width { get; set; } = 400;
/// <summary>
/// Sets the text for Button1. Default is 'Ok'
/// </summary>
public string Button1Text { get; set; } = "OK";
/// <summary>
/// Sets the text for Button2. If no text is set the button will not be displayed
/// </summary>
public string Button2Text { get; set; }
/// <summary>
/// Set the text for Button3. If no text is set the button will not be displayed
/// </summary>
public string Button3Text { get; set; }
/// <summary>
/// Sets the text for the message that is displayed
/// </summary>
[Required]
public string Text { get; set; }
/// <summary>
/// Sets the title for the error messagebox if Confirm fails. Default is 'Error'
/// </summary>
public string ErrorTitle { get; set; } = "Error";
/// <summary>
/// Sets the text for the error messagebox if Confirm fails. Default is 'The supplied values do not match'
/// </summary>
public string ErrorText { get; set; } = "The supplied values do not match";
/// <summary>
/// Sets the confirmation text for the message that is displayed. Default is 'Confirm'
/// </summary>
public string ConfirmText { get; set; } = "Confirm";
/// <summary>
/// Sets the Title of the Dialog. Default is 'Message' for Show and Prompt, 'Confirm' for Confirm TaskAction
/// </summary>
public string Title { get; set; } = "Message";
/// <summary>
/// Sets the message text colour. Default is ControlText (usually black).
/// </summary>
public string MessageColour { get; set; }
/// <summary>
/// Sets whether the message text is bold. Default is false.
/// </summary>
public bool MessageBold { get; set; }
/// <summary>
/// Set to true to use the default password character to mask the user input
/// </summary>
public bool MaskText { get; set; }
/// <summary>
/// Gets the text of the button that the user clicked
/// </summary>
[Output]
public string ButtonClickedText { get; set; }
/// <summary>
/// Gets the text that the user typed into the Prompt
/// </summary>
[Output]
public string UserText { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
switch (this.TaskAction)
{
case ShowTaskAction:
this.Show();
break;
case PromptTaskAction:
this.Prompt();
break;
case ConfirmTaskAction:
this.Confirm();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Show()
{
using (MessageForm form = new MessageForm(this.Text, this.MessageColour, this.MessageBold, this.Button1Text, this.Button2Text, this.Button3Text))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
}
}
private void Prompt()
{
using (PromptForm form = new PromptForm(this.Text, this.MessageColour, this.MessageBold, this.Button1Text, this.Button2Text, this.Button3Text, this.MaskText))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
this.UserText = form.UserText;
}
}
private void Confirm()
{
using (ConfirmForm form = new ConfirmForm(this.Text, this.ConfirmText, this.ErrorTitle, this.ErrorText, this.Button1Text, this.Button2Text, this.MaskText))
{
form.Width = this.Width;
form.Height = this.Height;
form.Text = this.Title;
form.ShowDialog();
this.ButtonClickedText = form.ButtonClickedText;
this.UserText = form.UserText;
}
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BTDB.Buffer;
using Microsoft.Extensions.Primitives;
namespace BTDB.StreamLayer
{
public ref struct SpanReader
{
public SpanReader(in ReadOnlySpan<byte> data)
{
Buf = data;
Original = data;
Controller = null;
}
public SpanReader(in ByteBuffer data)
{
Buf = data.AsSyncReadOnlySpan();
Original = Buf;
Controller = null;
}
public SpanReader(ISpanReader controller)
{
Controller = controller;
Buf = new ReadOnlySpan<byte>();
Original = new ReadOnlySpan<byte>();
controller.Init(ref this);
}
public ReadOnlySpan<byte> Buf;
public ReadOnlySpan<byte> Original;
public readonly ISpanReader? Controller;
/// <summary>
/// Remembers actual position into controller. Useful for continuing reading across async calls.
/// This method could be called only once and only as last called method on SpanReader instance.
/// </summary>
public void Sync()
{
if (Controller == null) ThrowCanBeUsedOnlyWithController();
Controller!.Sync(ref this);
}
static void ThrowCanBeUsedOnlyWithController()
{
throw new InvalidOperationException("Need controller");
}
public long GetCurrentPosition()
{
return Controller?.GetCurrentPosition(this) ?? (long)Unsafe.ByteOffset(
ref MemoryMarshal.GetReference(Original),
ref MemoryMarshal.GetReference(Buf));
}
public void SetCurrentPosition(long position)
{
if (Controller != null)
{
Controller.SetCurrentPosition(ref this, position);
}
else
{
Buf = Original.Slice((int)position);
}
}
public bool Eof
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Buf.IsEmpty && (Controller?.FillBufAndCheckForEof(ref this) ?? true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void NeedOneByteInBuffer()
{
if (Eof)
{
PackUnpack.ThrowEndOfStreamException();
}
}
ref byte PessimisticBlockReadAsByteRef(ref byte buf, uint len)
{
if (Controller == null)
{
if ((uint)Buf.Length >= len)
{
ref var res = ref MemoryMarshal.GetReference(Buf);
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
return ref res;
}
PackUnpack.ThrowEndOfStreamException();
}
else
{
if (Controller.FillBufAndCheckForEof(ref this))
PackUnpack.ThrowEndOfStreamException();
if ((uint)Buf.Length >= len)
{
ref var res = ref MemoryMarshal.GetReference(Buf);
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
return ref res;
}
ref var cur = ref buf;
do
{
Unsafe.CopyBlockUnaligned(ref cur, ref MemoryMarshal.GetReference(Buf), (uint)Buf.Length);
cur = ref Unsafe.AddByteOffset(ref cur, (IntPtr)Buf.Length);
len -= (uint)Buf.Length;
Buf = new ReadOnlySpan<byte>();
if (Controller.FillBufAndCheckForEof(ref this))
PackUnpack.ThrowEndOfStreamException();
} while (len > (uint)Buf.Length);
Unsafe.CopyBlockUnaligned(ref cur, ref MemoryMarshal.GetReference(Buf), len);
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
}
return ref buf;
}
public bool ReadBool()
{
NeedOneByteInBuffer();
return PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) != 0;
}
public void SkipBool()
{
SkipUInt8();
}
public byte ReadUInt8()
{
NeedOneByteInBuffer();
return PackUnpack.UnsafeGetAndAdvance(ref Buf, 1);
}
public void SkipUInt8()
{
NeedOneByteInBuffer();
PackUnpack.UnsafeAdvance(ref Buf, 1);
}
public sbyte ReadInt8()
{
NeedOneByteInBuffer();
return (sbyte)PackUnpack.UnsafeGetAndAdvance(ref Buf, 1);
}
public void SkipInt8()
{
SkipUInt8();
}
public sbyte ReadInt8Ordered()
{
NeedOneByteInBuffer();
return (sbyte)(PackUnpack.UnsafeGetAndAdvance(ref Buf, 1) - 128);
}
public void SkipInt8Ordered()
{
SkipUInt8();
}
public short ReadVInt16()
{
var res = ReadVInt64();
if (res > short.MaxValue || res < short.MinValue)
throw new InvalidDataException(
$"Reading VInt16 overflowed with {res}");
return (short)res;
}
public void SkipVInt16()
{
var res = ReadVInt64();
if (res > short.MaxValue || res < short.MinValue)
throw new InvalidDataException(
$"Skipping VInt16 overflowed with {res}");
}
public ushort ReadVUInt16()
{
var res = ReadVUInt64();
if (res > ushort.MaxValue) throw new InvalidDataException($"Reading VUInt16 overflowed with {res}");
return (ushort)res;
}
public void SkipVUInt16()
{
var res = ReadVUInt64();
if (res > ushort.MaxValue) throw new InvalidDataException($"Skipping VUInt16 overflowed with {res}");
}
public int ReadVInt32()
{
var res = ReadVInt64();
if (res > int.MaxValue || res < int.MinValue)
throw new InvalidDataException(
$"Reading VInt32 overflowed with {res}");
return (int)res;
}
public void SkipVInt32()
{
var res = ReadVInt64();
if (res > int.MaxValue || res < int.MinValue)
throw new InvalidDataException(
$"Skipping VInt32 overflowed with {res}");
}
public uint ReadVUInt32()
{
var res = ReadVUInt64();
if (res > uint.MaxValue) throw new InvalidDataException($"Reading VUInt32 overflowed with {res}");
return (uint)res;
}
public void SkipVUInt32()
{
var res = ReadVUInt64();
if (res > uint.MaxValue) throw new InvalidDataException($"Skipping VUInt32 overflowed with {res}");
}
[SkipLocalsInit]
public long ReadVInt64()
{
NeedOneByteInBuffer();
ref var byteRef = ref MemoryMarshal.GetReference(Buf);
var len = PackUnpack.LengthVIntByFirstByte(byteRef);
if (len <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
return PackUnpack.UnsafeUnpackVInt(ref byteRef, len);
}
else
{
Span<byte> buf = stackalloc byte[(int)len];
return PackUnpack.UnsafeUnpackVInt(
ref PessimisticBlockReadAsByteRef(ref MemoryMarshal.GetReference(buf), len), len);
}
}
public void SkipVInt64()
{
NeedOneByteInBuffer();
var len = PackUnpack.LengthVIntByFirstByte(MemoryMarshal.GetReference(Buf));
if (len <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
}
else
{
SkipBlock(len);
}
}
[SkipLocalsInit]
public ulong ReadVUInt64()
{
NeedOneByteInBuffer();
ref var byteRef = ref MemoryMarshal.GetReference(Buf);
var len = PackUnpack.LengthVUIntByFirstByte(byteRef);
if (len <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
return PackUnpack.UnsafeUnpackVUInt(ref byteRef, len);
}
else
{
Span<byte> buf = stackalloc byte[(int)len];
return PackUnpack.UnsafeUnpackVUInt(
ref PessimisticBlockReadAsByteRef(ref MemoryMarshal.GetReference(buf), len), len);
}
}
public void SkipVUInt64()
{
NeedOneByteInBuffer();
ref var byteRef = ref MemoryMarshal.GetReference(Buf);
var len = PackUnpack.LengthVUIntByFirstByte(byteRef);
if (len <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, (int)len);
}
else
{
SkipBlock(len);
}
}
[SkipLocalsInit]
public long ReadInt64()
{
if (8 <= (uint)Buf.Length)
{
return (long)PackUnpack.AsBigEndian(
Unsafe.As<byte, ulong>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 8)));
}
else
{
Span<byte> buf = stackalloc byte[8];
return (long)PackUnpack.AsBigEndian(
Unsafe.As<byte, ulong>(ref PessimisticBlockReadAsByteRef(ref MemoryMarshal.GetReference(buf), 8)));
}
}
public void SkipInt64()
{
if (8 <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, 8);
}
else
{
SkipBlock(8);
}
}
[SkipLocalsInit]
public int ReadInt32()
{
if (4 <= (uint)Buf.Length)
{
return (int)PackUnpack.AsBigEndian(
Unsafe.As<byte, uint>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 4)));
}
else
{
Span<byte> buf = stackalloc byte[4];
return (int)PackUnpack.AsBigEndian(
Unsafe.As<byte, uint>(ref PessimisticBlockReadAsByteRef(ref MemoryMarshal.GetReference(buf), 4)));
}
}
[SkipLocalsInit]
public int ReadInt32LE()
{
if (4 <= (uint)Buf.Length)
{
return (int)PackUnpack.AsLittleEndian(
Unsafe.As<byte, uint>(ref PackUnpack.UnsafeGetAndAdvance(ref Buf, 4)));
}
else
{
Span<byte> buf = stackalloc byte[4];
return (int)PackUnpack.AsLittleEndian(
Unsafe.As<byte, uint>(ref PessimisticBlockReadAsByteRef(ref MemoryMarshal.GetReference(buf), 4)));
}
}
public void SkipInt32()
{
if (4 <= (uint)Buf.Length)
{
PackUnpack.UnsafeAdvance(ref Buf, 4);
}
else
{
SkipBlock(4);
}
}
public DateTime ReadDateTime()
{
return DateTime.FromBinary(ReadInt64());
}
public void SkipDateTime()
{
SkipInt64();
}
public DateTimeOffset ReadDateTimeOffset()
{
var ticks = ReadVInt64();
var offset = ReadTimeSpan();
return new DateTimeOffset(ticks, offset);
}
public void SkipDateTimeOffset()
{
SkipVInt64();
SkipTimeSpan();
}
public TimeSpan ReadTimeSpan()
{
return new TimeSpan(ReadVInt64());
}
public void SkipTimeSpan()
{
SkipVInt64();
}
public unsafe string? ReadString()
{
var len = ReadVUInt64();
if (len == 0) return null;
len--;
if (len > int.MaxValue) throw new InvalidDataException($"Reading String length overflowed with {len}");
var l = (int)len;
if (l == 0) return "";
var result = new string('\0', l);
fixed (char* res = result)
{
var i = 0;
while (i < l)
{
NeedOneByteInBuffer();
var cc = MemoryMarshal.GetReference(Buf);
if (cc < 0x80)
{
res[i++] = (char)cc;
PackUnpack.UnsafeAdvance(ref Buf, 1);
continue;
}
var c = ReadVUInt64();
if (c > 0xffff)
{
if (c > 0x10ffff)
throw new InvalidDataException($"Reading String unicode value overflowed with {c}");
c -= 0x10000;
res[i++] = (char)((c >> 10) + 0xD800);
res[i++] = (char)((c & 0x3FF) + 0xDC00);
}
else
{
res[i++] = (char)c;
}
}
}
return result;
}
[SkipLocalsInit]
public string? ReadStringOrdered()
{
var len = 0;
Span<char> charStackBuf = stackalloc char[256];
var charBuf = charStackBuf;
while (true)
{
var c = ReadVUInt32();
if (c == 0) break;
c--;
if (c > 0xffff)
{
if (c > 0x10ffff)
{
if (len == 0 && c == 0x110000) return null;
throw new InvalidDataException($"Reading String unicode value overflowed with {c}");
}
c -= 0x10000;
if (charBuf.Length < len + 2)
{
var newCharBuf = (Span<char>)new char[charBuf.Length * 2];
charBuf.CopyTo(newCharBuf);
charBuf = newCharBuf;
}
Unsafe.Add(ref MemoryMarshal.GetReference(charBuf), len++) = (char)((c >> 10) + 0xD800);
Unsafe.Add(ref MemoryMarshal.GetReference(charBuf), len++) = (char)((c & 0x3FF) + 0xDC00);
}
else
{
if (charBuf.Length < len + 1)
{
var newCharBuf = (Span<char>)new char[charBuf.Length * 2];
charBuf.CopyTo(newCharBuf);
charBuf = newCharBuf;
}
Unsafe.Add(ref MemoryMarshal.GetReference(charBuf), len++) = (char)c;
}
}
return len == 0 ? "" : new string(charBuf.Slice(0, len));
}
public void SkipString()
{
var len = ReadVUInt64();
if (len == 0) return;
len--;
if (len > int.MaxValue) throw new InvalidDataException($"Skipping String length overflowed with {len}");
var l = (int)len;
if (l == 0) return;
var i = 0;
while (i < l)
{
var c = ReadVUInt64();
if (c > 0xffff)
{
if (c > 0x10ffff)
throw new InvalidDataException(
$"Skipping String unicode value overflowed with {c}");
i += 2;
}
else
{
i++;
}
}
}
public void SkipStringOrdered()
{
var c = ReadVUInt32();
if (c == 0) return;
c--;
if (c > 0x10ffff)
{
if (c == 0x110000) return;
throw new InvalidDataException($"Skipping String unicode value overflowed with {c}");
}
while (true)
{
c = ReadVUInt32();
if (c == 0) break;
c--;
if (c > 0x10ffff) throw new InvalidDataException($"Skipping String unicode value overflowed with {c}");
}
}
public void ReadBlock(ref byte buffer, uint length)
{
if (length > Buf.Length)
{
if (Controller != null)
{
if (Buf.Length > 0)
{
Unsafe.CopyBlockUnaligned(ref buffer, ref MemoryMarshal.GetReference(Buf), (uint)Buf.Length);
buffer = ref Unsafe.AddByteOffset(ref buffer, (IntPtr)Buf.Length);
length -= (uint)Buf.Length;
Buf = new ReadOnlySpan<byte>();
}
if (!Controller.ReadBlock(ref this, ref buffer, length)) return;
}
Buf = new ReadOnlySpan<byte>();
PackUnpack.ThrowEndOfStreamException();
}
Unsafe.CopyBlockUnaligned(ref buffer, ref PackUnpack.UnsafeGetAndAdvance(ref Buf, (int)length), length);
}
public void ReadBlock(in Span<byte> buffer)
{
ReadBlock(ref MemoryMarshal.GetReference(buffer), (uint)buffer.Length);
}
public void ReadBlock(byte[] data, int offset, int length)
{
ReadBlock(data.AsSpan(offset, length));
}
public void SkipBlock(uint length)
{
if (length > Buf.Length)
{
if (Controller != null)
{
length -= (uint)Buf.Length;
Buf = new ReadOnlySpan<byte>();
if (!Controller.SkipBlock(ref this, length))
return;
}
Buf = new ReadOnlySpan<byte>();
PackUnpack.ThrowEndOfStreamException();
}
PackUnpack.UnsafeAdvance(ref Buf, (int)length);
}
public void SkipBlock(int length)
{
SkipBlock((uint)length);
}
public void ReadBlock(ByteBuffer buffer)
{
ReadBlock(buffer.AsSyncSpan());
}
[SkipLocalsInit]
public Guid ReadGuid()
{
Span<byte> buffer = stackalloc byte[16];
ReadBlock(ref MemoryMarshal.GetReference(buffer), 16);
return new Guid(buffer);
}
public void SkipGuid()
{
SkipBlock(16);
}
public float ReadSingle()
{
return BitConverter.Int32BitsToSingle(ReadInt32());
}
public void SkipSingle()
{
SkipInt32();
}
public double ReadDouble()
{
return BitConverter.Int64BitsToDouble(ReadInt64());
}
public void SkipDouble()
{
SkipInt64();
}
public decimal ReadDecimal()
{
var header = ReadUInt8();
ulong first = 0;
uint second = 0;
switch (header >> 5 & 3)
{
case 0:
break;
case 1:
first = ReadVUInt64();
break;
case 2:
second = ReadVUInt32();
first = (ulong)ReadInt64();
break;
case 3:
second = (uint)ReadInt32();
first = (ulong)ReadInt64();
break;
}
var res = new decimal((int)first, (int)(first >> 32), (int)second, (header & 128) != 0,
(byte)(header & 31));
return res;
}
public void SkipDecimal()
{
var header = ReadUInt8();
switch (header >> 5 & 3)
{
case 0:
break;
case 1:
SkipVUInt64();
break;
case 2:
SkipVUInt32();
SkipInt64();
break;
case 3:
SkipBlock(12);
break;
}
}
public byte[]? ReadByteArray()
{
var length = ReadVUInt32();
if (length == 0) return null;
var bytes = new byte[length - 1];
ReadBlock(bytes);
return bytes;
}
public void SkipByteArray()
{
var length = ReadVUInt32();
if (length == 0) return;
SkipBlock(length - 1);
}
public ReadOnlySpan<byte> ReadByteArrayAsSpan()
{
var length = ReadVUInt32();
if (length-- == 0) return new ReadOnlySpan<byte>();
var res = Buf.Slice(0, (int)length);
PackUnpack.UnsafeAdvance(ref Buf, (int)length);
return res;
}
public byte[] ReadByteArrayRawTillEof()
{
var res = Buf.ToArray();
PackUnpack.UnsafeAdvance(ref Buf, Buf.Length);
return res;
}
public byte[] ReadByteArrayRaw(int len)
{
var res = new byte[len];
ReadBlock(res);
return res;
}
[SkipLocalsInit]
public bool CheckMagic(byte[] magic)
{
if (Buf.Length >= magic.Length)
{
if (!Buf.Slice(0, magic.Length).SequenceEqual(magic)) return false;
PackUnpack.UnsafeAdvance(ref Buf, magic.Length);
return true;
}
Span<byte> buf = stackalloc byte[magic.Length];
try
{
ReadBlock(ref MemoryMarshal.GetReference(buf), (uint)buf.Length);
return buf.SequenceEqual(magic);
}
catch (EndOfStreamException)
{
return false;
}
}
[SkipLocalsInit]
public IPAddress? ReadIPAddress()
{
switch (ReadUInt8())
{
case 0:
return new IPAddress((uint)ReadInt32LE());
case 1:
{
Span<byte> ip6Bytes = stackalloc byte[16];
ReadBlock(ref MemoryMarshal.GetReference(ip6Bytes), 16);
return new IPAddress(ip6Bytes);
}
case 2:
{
Span<byte> ip6Bytes = stackalloc byte[16];
ReadBlock(ref MemoryMarshal.GetReference(ip6Bytes), 16);
var scopeId = (long)ReadVUInt64();
return new IPAddress(ip6Bytes, scopeId);
}
case 3:
return null;
default: throw new InvalidDataException("Unknown type of IPAddress");
}
}
public void SkipIPAddress()
{
switch (ReadUInt8())
{
case 0:
SkipInt32();
return;
case 1:
SkipBlock(16);
return;
case 2:
SkipBlock(16);
SkipVUInt64();
return;
case 3:
return;
default: throw new InvalidDataException("Unknown type of IPAddress");
}
}
public Version? ReadVersion()
{
var major = ReadVUInt32();
if (major == 0) return null;
var minor = ReadVUInt32();
if (minor == 0) return new Version((int)major - 1, 0);
var build = ReadVUInt32();
if (build == 0) return new Version((int)major - 1, (int)minor - 1);
var revision = ReadVUInt32();
if (revision == 0) return new Version((int)major - 1, (int)minor - 1, (int)build - 1);
return new Version((int)major - 1, (int)minor - 1, (int)build - 1, (int)revision - 1);
}
public void SkipVersion()
{
var major = ReadVUInt32();
if (major == 0) return;
var minor = ReadVUInt32();
if (minor == 0) return;
var build = ReadVUInt32();
if (build == 0) return;
SkipVUInt32();
}
public StringValues ReadStringValues()
{
var count = ReadVUInt32();
var a = new string[count];
for (var i = 0u; i < count; i++)
{
a[i] = ReadString()!;
}
return new StringValues(a);
}
public void SkipStringValues()
{
var count = ReadVUInt32();
for (var i = 0u; i < count; i++)
{
SkipString();
}
}
}
}
| |
using System.Drawing;
namespace HearThis.UI
{
partial class Shell
{
/// <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(Shell));
this.l10NSharpExtender1 = new L10NSharp.UI.L10NSharpExtender(this.components);
this.toolStripButtonSave = new System.Windows.Forms.ToolStripButton();
this.toolStripButtonChooseProject = new System.Windows.Forms.ToolStripButton();
this._uiLanguageMenu = new System.Windows.Forms.ToolStripDropDownButton();
this._btnMode = new System.Windows.Forms.ToolStripDropDownButton();
this._toolStrip = new System.Windows.Forms.ToolStrip();
this._moreMenu = new System.Windows.Forms.ToolStripDropDownButton();
this._settingsItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this._syncWithAndroidItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this._exportSoundFilesItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this._mergeHearthisPackItem = new System.Windows.Forms.ToolStripMenuItem();
this._saveHearthisPackItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.supportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this._aboutHearThisItem = new System.Windows.Forms.ToolStripMenuItem();
this._actorCharacterButton = new System.Windows.Forms.Button();
this._actorLabel = new System.Windows.Forms.Label();
this._characterLabel = new System.Windows.Forms.Label();
this._recordingToolControl1 = new HearThis.UI.RecordingToolControl();
this._settingsProtectionHelper = new SIL.Windows.Forms.SettingProtection.SettingsProtectionHelper(this.components);
this._multiVoicePanel = new System.Windows.Forms.Panel();
this._multiVoiceMarginPanel = new System.Windows.Forms.Panel();
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).BeginInit();
this._toolStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this._recordingToolControl1)).BeginInit();
this._multiVoicePanel.SuspendLayout();
this.SuspendLayout();
//
// l10NSharpExtender1
//
this.l10NSharpExtender1.LocalizationManagerId = "HearThis";
this.l10NSharpExtender1.PrefixForNewItems = "Shell";
//
// toolStripButtonSave
//
this.toolStripButtonSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButtonSave.Image = global::HearThis.Properties.Resources.TopToolbar_Save;
this.toolStripButtonSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.l10NSharpExtender1.SetLocalizableToolTip(this.toolStripButtonSave, null);
this.l10NSharpExtender1.SetLocalizationComment(this.toolStripButtonSave, null);
this.l10NSharpExtender1.SetLocalizingId(this.toolStripButtonSave, "RecordingControl.Save");
this.toolStripButtonSave.Margin = new System.Windows.Forms.Padding(0, 1, 10, 2);
this.toolStripButtonSave.Name = "toolStripButtonSave";
this.toolStripButtonSave.Size = new System.Drawing.Size(23, 20);
this.toolStripButtonSave.Text = "Save";
this.toolStripButtonSave.Click += new System.EventHandler(this.OnSaveClick);
//
// toolStripButtonChooseProject
//
this.toolStripButtonChooseProject.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripButtonChooseProject.Image = global::HearThis.Properties.Resources.TopToolbar_Open;
this.toolStripButtonChooseProject.ImageTransparentColor = System.Drawing.Color.Magenta;
this.l10NSharpExtender1.SetLocalizableToolTip(this.toolStripButtonChooseProject, null);
this.l10NSharpExtender1.SetLocalizationComment(this.toolStripButtonChooseProject, null);
this.l10NSharpExtender1.SetLocalizingId(this.toolStripButtonChooseProject, "RecordingControl.ChooseProject");
this.toolStripButtonChooseProject.Margin = new System.Windows.Forms.Padding(0, 1, 10, 2);
this.toolStripButtonChooseProject.Name = "toolStripButtonChooseProject";
this.toolStripButtonChooseProject.Size = new System.Drawing.Size(23, 20);
this.toolStripButtonChooseProject.Text = "Choose Project";
this.toolStripButtonChooseProject.Click += new System.EventHandler(this.OnChooseProject);
//
// _uiLanguageMenu
//
this._uiLanguageMenu.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this._uiLanguageMenu.ForeColor = System.Drawing.Color.DarkGray;
this.l10NSharpExtender1.SetLocalizableToolTip(this._uiLanguageMenu, null);
this.l10NSharpExtender1.SetLocalizationComment(this._uiLanguageMenu, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._uiLanguageMenu, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._uiLanguageMenu, "RecordingControl._uiLanguageMenu");
this._uiLanguageMenu.Name = "_uiLanguageMenu";
this._uiLanguageMenu.Size = new System.Drawing.Size(58, 20);
this._uiLanguageMenu.Text = "English";
this._uiLanguageMenu.ToolTipText = "User-interface Language";
this._uiLanguageMenu.DropDownOpening += new System.EventHandler(this.MenuDropDownOpening);
//
// _btnMode
//
this._btnMode.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this._btnMode.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this._btnMode.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this._btnMode.ForeColor = System.Drawing.SystemColors.ControlDark;
this._btnMode.ImageTransparentColor = System.Drawing.Color.Magenta;
this.l10NSharpExtender1.SetLocalizableToolTip(this._btnMode, null);
this.l10NSharpExtender1.SetLocalizationComment(this._btnMode, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._btnMode, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._btnMode, "Shell.Shell._btnMode");
this._btnMode.Name = "_btnMode";
this._btnMode.Size = new System.Drawing.Size(97, 20);
this._btnMode.Text = "Administrative";
this._btnMode.ToolTipText = "Mode";
this._btnMode.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.ModeDropDownItemClicked);
//
// _toolStrip
//
this._toolStrip.AutoSize = false;
this._toolStrip.BackColor = System.Drawing.Color.Transparent;
this._toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this._toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonSave,
this.toolStripButtonChooseProject,
this._moreMenu,
this._uiLanguageMenu,
this._btnMode});
this.l10NSharpExtender1.SetLocalizableToolTip(this._toolStrip, null);
this.l10NSharpExtender1.SetLocalizationComment(this._toolStrip, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._toolStrip, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._toolStrip, "RecordingControl.ToolStrip");
this._toolStrip.Location = new System.Drawing.Point(0, 0);
this._toolStrip.Name = "_toolStrip";
this._toolStrip.Padding = new System.Windows.Forms.Padding(15, 10, 20, 0);
this._toolStrip.Size = new System.Drawing.Size(719, 33);
this._toolStrip.TabIndex = 35;
this._toolStrip.Text = "toolStrip1";
//
// _moreMenu
//
this._moreMenu.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this._moreMenu.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this._moreMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this._settingsItem,
this.toolStripMenuItem1,
this._syncWithAndroidItem,
this.toolStripMenuItem2,
this._exportSoundFilesItem,
this.toolStripMenuItem3,
this._mergeHearthisPackItem,
this._saveHearthisPackItem,
this.toolStripMenuItem4,
this.supportToolStripMenuItem,
this.toolStripSeparator1,
this._aboutHearThisItem});
this._moreMenu.ForeColor = System.Drawing.Color.DarkGray;
this._moreMenu.ImageTransparentColor = System.Drawing.Color.Magenta;
this.l10NSharpExtender1.SetLocalizableToolTip(this._moreMenu, null);
this.l10NSharpExtender1.SetLocalizationComment(this._moreMenu, null);
this.l10NSharpExtender1.SetLocalizingId(this._moreMenu, "Shell.MoreMenu");
this._moreMenu.Name = "_moreMenu";
this._moreMenu.Size = new System.Drawing.Size(48, 20);
this._moreMenu.Text = "More";
this._moreMenu.DropDownOpening += new System.EventHandler(this.MenuDropDownOpening);
//
// _settingsItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._settingsItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._settingsItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._settingsItem, "RecordingControl.toolStripButtonSettings");
this._settingsItem.Name = "_settingsItem";
this._settingsItem.Size = new System.Drawing.Size(194, 22);
this._settingsItem.Text = "Settings...";
this._settingsItem.Click += new System.EventHandler(this.OnSettingsButtonClicked);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(191, 6);
//
// _syncWithAndroidItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._syncWithAndroidItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._syncWithAndroidItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._syncWithAndroidItem, "Shell.SyncWithAndroidMenuItem");
this._syncWithAndroidItem.Name = "_syncWithAndroidItem";
this._syncWithAndroidItem.Size = new System.Drawing.Size(194, 22);
this._syncWithAndroidItem.Text = "Sync with Android...";
this._syncWithAndroidItem.Click += new System.EventHandler(this._syncWithAndroidItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(191, 6);
//
// _exportSoundFilesItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._exportSoundFilesItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._exportSoundFilesItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._exportSoundFilesItem, "RecordingControl.PublishSoundFiles");
this._exportSoundFilesItem.Name = "_exportSoundFilesItem";
this._exportSoundFilesItem.Size = new System.Drawing.Size(194, 22);
this._exportSoundFilesItem.Text = "Export Sound Files...";
this._exportSoundFilesItem.Click += new System.EventHandler(this.OnPublishClick);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(191, 6);
//
// _mergeHearthisPackItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._mergeHearthisPackItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._mergeHearthisPackItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._mergeHearthisPackItem, "Shell.MergeHearthisPackMenuItem");
this._mergeHearthisPackItem.Name = "_mergeHearthisPackItem";
this._mergeHearthisPackItem.Size = new System.Drawing.Size(194, 22);
this._mergeHearthisPackItem.Text = "Merge HearThis Pack...";
this._mergeHearthisPackItem.Click += new System.EventHandler(this._mergeHearThisPackItem_Click);
//
// _saveHearthisPackItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._saveHearthisPackItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._saveHearthisPackItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._saveHearthisPackItem, "Shell.SaveHearthisPackMenuItem");
this._saveHearthisPackItem.Name = "_saveHearthisPackItem";
this._saveHearthisPackItem.Size = new System.Drawing.Size(194, 22);
this._saveHearthisPackItem.Text = "Save HearThis Pack...";
this._saveHearthisPackItem.Click += new System.EventHandler(this._saveHearThisPackItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(191, 6);
//
// supportToolStripMenuItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this.supportToolStripMenuItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this.supportToolStripMenuItem, null);
this.l10NSharpExtender1.SetLocalizingId(this.supportToolStripMenuItem, "Shell.Shell.SupportMenuItem");
this.supportToolStripMenuItem.Name = "supportToolStripMenuItem";
this.supportToolStripMenuItem.Size = new System.Drawing.Size(194, 22);
this.supportToolStripMenuItem.Text = "Support...";
this.supportToolStripMenuItem.Click += new System.EventHandler(this.supportToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.BackColor = System.Drawing.Color.DarkRed;
this.toolStripSeparator1.ForeColor = System.Drawing.Color.DarkOrange;
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(191, 6);
//
// _aboutHearThisItem
//
this.l10NSharpExtender1.SetLocalizableToolTip(this._aboutHearThisItem, null);
this.l10NSharpExtender1.SetLocalizationComment(this._aboutHearThisItem, null);
this.l10NSharpExtender1.SetLocalizingId(this._aboutHearThisItem, "RecordingControl.About");
this._aboutHearThisItem.Name = "_aboutHearThisItem";
this._aboutHearThisItem.Size = new System.Drawing.Size(194, 22);
this._aboutHearThisItem.Text = "About HearThis...";
this._aboutHearThisItem.Click += new System.EventHandler(this.OnAboutClick);
//
// _actorCharacterButton
//
this._actorCharacterButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this._actorCharacterButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this._actorCharacterButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this._actorCharacterButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._actorCharacterButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this._actorCharacterButton.Image = global::HearThis.Properties.Resources.speakIntoMike75x50;
this.l10NSharpExtender1.SetLocalizableToolTip(this._actorCharacterButton, null);
this.l10NSharpExtender1.SetLocalizationComment(this._actorCharacterButton, null);
this.l10NSharpExtender1.SetLocalizingId(this._actorCharacterButton, "Shell.button1");
this._actorCharacterButton.Location = new System.Drawing.Point(18, 10);
this._actorCharacterButton.Name = "_actorCharacterButton";
this._actorCharacterButton.Size = new System.Drawing.Size(78, 51);
this._actorCharacterButton.TabIndex = 37;
this._actorCharacterButton.UseVisualStyleBackColor = false;
this._actorCharacterButton.Click += new System.EventHandler(this._actorCharacterButton_Click);
//
// _actorLabel
//
this._actorLabel.AutoSize = true;
this._actorLabel.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._actorLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(202)))), ((int)(((byte)(1)))));
this.l10NSharpExtender1.SetLocalizableToolTip(this._actorLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this._actorLabel, null);
this.l10NSharpExtender1.SetLocalizationPriority(this._actorLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._actorLabel, "Shell._actorLabel");
this._actorLabel.Location = new System.Drawing.Point(130, 1);
this._actorLabel.Name = "_actorLabel";
this._actorLabel.Size = new System.Drawing.Size(58, 30);
this._actorLabel.TabIndex = 38;
this._actorLabel.Text = "?????";
this._actorLabel.Click += new System.EventHandler(this._actorLabel_Click);
//
// _characterLabel
//
this._characterLabel.AutoSize = true;
this._characterLabel.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._characterLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(202)))), ((int)(((byte)(1)))));
this.l10NSharpExtender1.SetLocalizableToolTip(this._characterLabel, null);
this.l10NSharpExtender1.SetLocalizationComment(this._characterLabel, "Designer text is just a place-holder and will not appear in the actual UI.");
this.l10NSharpExtender1.SetLocalizationPriority(this._characterLabel, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this._characterLabel, "Shell.label1");
this._characterLabel.Location = new System.Drawing.Point(130, 30);
this._characterLabel.Name = "_characterLabel";
this._characterLabel.Size = new System.Drawing.Size(102, 30);
this._characterLabel.TabIndex = 39;
this._characterLabel.Text = "Character";
this._characterLabel.Click += new System.EventHandler(this._characterLabel_Click);
//
// _recordingToolControl1
//
this._recordingToolControl1.BackColor = this._recordingToolControl1.BackColor;
this._recordingToolControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this._recordingToolControl1.HidingSkippedBlocks = false;
this.l10NSharpExtender1.SetLocalizableToolTip(this._recordingToolControl1, null);
this.l10NSharpExtender1.SetLocalizationComment(this._recordingToolControl1, null);
this.l10NSharpExtender1.SetLocalizingId(this._recordingToolControl1, "Shell.RecordingToolControl");
this._recordingToolControl1.Location = new System.Drawing.Point(0, 0);
this._recordingToolControl1.Margin = new System.Windows.Forms.Padding(10);
this._recordingToolControl1.Name = "_recordingToolControl1";
this._recordingToolControl1.ShowingSkipButton = false;
this._recordingToolControl1.Size = new System.Drawing.Size(719, 556);
this._recordingToolControl1.TabIndex = 1;
//
// _multiVoicePanel
//
this._multiVoicePanel.Controls.Add(this._characterLabel);
this._multiVoicePanel.Controls.Add(this._actorLabel);
this._multiVoicePanel.Controls.Add(this._actorCharacterButton);
this._multiVoicePanel.Dock = System.Windows.Forms.DockStyle.Top;
this._multiVoicePanel.Location = new System.Drawing.Point(0, 43);
this._multiVoicePanel.Name = "_multiVoicePanel";
this._multiVoicePanel.Padding = new System.Windows.Forms.Padding(0, 10, 0, 0);
this._multiVoicePanel.Size = new System.Drawing.Size(719, 63);
this._multiVoicePanel.TabIndex = 37;
this._multiVoicePanel.Visible = false;
//
// _multiVoiceMarginPanel
//
this._multiVoiceMarginPanel.Dock = System.Windows.Forms.DockStyle.Top;
this._multiVoiceMarginPanel.Location = new System.Drawing.Point(0, 33);
this._multiVoiceMarginPanel.Name = "_multiVoiceMarginPanel";
this._multiVoiceMarginPanel.Size = new System.Drawing.Size(719, 10);
this._multiVoiceMarginPanel.TabIndex = 40;
this._multiVoiceMarginPanel.Visible = false;
//
// Shell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65)))));
this.ClientSize = new System.Drawing.Size(719, 556);
this.Controls.Add(this._multiVoicePanel);
this.Controls.Add(this._multiVoiceMarginPanel);
this.Controls.Add(this._toolStrip);
this.Controls.Add(this._recordingToolControl1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.l10NSharpExtender1.SetLocalizableToolTip(this, null);
this.l10NSharpExtender1.SetLocalizationComment(this, "Product name");
this.l10NSharpExtender1.SetLocalizationPriority(this, L10NSharp.LocalizationPriority.NotLocalizable);
this.l10NSharpExtender1.SetLocalizingId(this, "Shell.HearThis");
this.MinimumSize = new System.Drawing.Size(719, 595);
this.Name = "Shell";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.Text = "HearThis";
this.ResizeEnd += new System.EventHandler(this.Shell_ResizeEnd);
((System.ComponentModel.ISupportInitialize)(this.l10NSharpExtender1)).EndInit();
this._toolStrip.ResumeLayout(false);
this._toolStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this._recordingToolControl1)).EndInit();
this._multiVoicePanel.ResumeLayout(false);
this._multiVoicePanel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private RecordingToolControl _recordingToolControl1;
private L10NSharp.UI.L10NSharpExtender l10NSharpExtender1;
private SIL.Windows.Forms.SettingProtection.SettingsProtectionHelper _settingsProtectionHelper;
private System.Windows.Forms.ToolStripButton toolStripButtonSave;
private System.Windows.Forms.ToolStripButton toolStripButtonChooseProject;
private System.Windows.Forms.ToolStripDropDownButton _uiLanguageMenu;
private System.Windows.Forms.ToolStripDropDownButton _btnMode;
private System.Windows.Forms.ToolStrip _toolStrip;
private System.Windows.Forms.Panel _multiVoicePanel;
private System.Windows.Forms.Label _actorLabel;
private System.Windows.Forms.Button _actorCharacterButton;
private System.Windows.Forms.Label _characterLabel;
private System.Windows.Forms.ToolStripDropDownButton _moreMenu;
private System.Windows.Forms.ToolStripMenuItem _settingsItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem _syncWithAndroidItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem _exportSoundFilesItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem _mergeHearthisPackItem;
private System.Windows.Forms.ToolStripMenuItem _saveHearthisPackItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem _aboutHearThisItem;
private System.Windows.Forms.ToolStripMenuItem supportToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.Panel _multiVoiceMarginPanel;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Outlining;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextViewExtensions
{
/// <summary>
/// Collects the content types in the view's buffer graph.
/// </summary>
public static ISet<IContentType> GetContentTypes(this ITextView textView)
{
return new HashSet<IContentType>(
textView.BufferGraph.GetTextBuffers(_ => true).Select(b => b.ContentType));
}
public static bool IsReadOnlyOnSurfaceBuffer(this ITextView textView, SnapshotSpan span)
{
var spansInView = textView.BufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeInclusive, textView.TextBuffer);
return spansInView.Any(spanInView => textView.TextBuffer.IsReadOnly(spanInView.Span));
}
public static SnapshotPoint? GetCaretPoint(this ITextView textView, ITextBuffer subjectBuffer)
{
var caret = textView.Caret.Position;
return textView.BufferGraph.MapUpOrDownToBuffer(caret.BufferPosition, subjectBuffer);
}
public static SnapshotPoint? GetCaretPoint(this ITextView textView, Predicate<ITextSnapshot> match)
{
var caret = textView.Caret.Position;
var span = textView.BufferGraph.MapUpOrDownToFirstMatch(new SnapshotSpan(caret.BufferPosition, 0), match);
if (span.HasValue)
{
return span.Value.Start;
}
else
{
return null;
}
}
public static VirtualSnapshotPoint? GetVirtualCaretPoint(this ITextView textView, ITextBuffer subjectBuffer)
{
if (subjectBuffer == textView.TextBuffer)
{
return textView.Caret.Position.VirtualBufferPosition;
}
var mappedPoint = textView.BufferGraph.MapDownToBuffer(
textView.Caret.Position.VirtualBufferPosition.Position,
PointTrackingMode.Negative,
subjectBuffer,
PositionAffinity.Predecessor);
return mappedPoint.HasValue
? new VirtualSnapshotPoint(mappedPoint.Value)
: default(VirtualSnapshotPoint);
}
public static ITextBuffer GetBufferContainingCaret(this ITextView textView, string contentType = ContentTypeNames.RoslynContentType)
{
var point = GetCaretPoint(textView, s => s.ContentType.IsOfType(contentType));
return point.HasValue ? point.Value.Snapshot.TextBuffer : null;
}
public static SnapshotPoint? GetPositionInView(this ITextView textView, SnapshotPoint point)
{
return textView.BufferGraph.MapUpToSnapshot(point, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);
}
public static NormalizedSnapshotSpanCollection GetSpanInView(this ITextView textView, SnapshotSpan span)
{
return textView.BufferGraph.MapUpToSnapshot(span, SpanTrackingMode.EdgeInclusive, textView.TextSnapshot);
}
public static void SetSelection(
this ITextView textView, VirtualSnapshotPoint anchorPoint, VirtualSnapshotPoint activePoint)
{
var isReversed = activePoint < anchorPoint;
var start = isReversed ? activePoint : anchorPoint;
var end = isReversed ? anchorPoint : activePoint;
SetSelection(textView, new SnapshotSpan(start.Position, end.Position), isReversed);
}
public static void SetSelection(
this ITextView textView, SnapshotSpan span, bool isReversed = false)
{
var spanInView = textView.GetSpanInView(span).Single();
textView.Selection.Select(spanInView, isReversed);
textView.Caret.MoveTo(isReversed ? spanInView.Start : spanInView.End);
}
public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, SnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None)
{
return textView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(point), outliningManagerService, ensureSpanVisibleOptions);
}
public static bool TryMoveCaretToAndEnsureVisible(this ITextView textView, VirtualSnapshotPoint point, IOutliningManagerService outliningManagerService = null, EnsureSpanVisibleOptions ensureSpanVisibleOptions = EnsureSpanVisibleOptions.None)
{
if (textView.IsClosed)
{
return false;
}
var pointInView = textView.GetPositionInView(point.Position);
if (!pointInView.HasValue)
{
return false;
}
// If we were given an outlining service, we need to expand any outlines first, or else
// the Caret.MoveTo won't land in the correct location if our target is inside a
// collapsed outline.
if (outliningManagerService != null)
{
var outliningManager = outliningManagerService.GetOutliningManager(textView);
if (outliningManager != null)
{
outliningManager.ExpandAll(new SnapshotSpan(pointInView.Value, length: 0), match: _ => true);
}
}
var newPosition = textView.Caret.MoveTo(new VirtualSnapshotPoint(pointInView.Value, point.VirtualSpaces));
// We use the caret's position in the view's current snapshot here in case something
// changed text in response to a caret move (e.g. line commit)
var spanInView = new SnapshotSpan(newPosition.BufferPosition, 0);
textView.ViewScroller.EnsureSpanVisible(spanInView, ensureSpanVisibleOptions);
return true;
}
/// <summary>
/// Gets or creates a view property that would go away when view gets closed
/// </summary>
public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>(
this TTextView textView,
Func<TTextView, TProperty> valueCreator) where TTextView : ITextView
{
return textView.GetOrCreateAutoClosingProperty(typeof(TProperty), valueCreator);
}
/// <summary>
/// Gets or creates a view property that would go away when view gets closed
/// </summary>
public static TProperty GetOrCreateAutoClosingProperty<TProperty, TTextView>(
this TTextView textView,
object key,
Func<TTextView, TProperty> valueCreator) where TTextView : ITextView
{
TProperty value;
GetOrCreateAutoClosingProperty(textView, key, valueCreator, out value);
return value;
}
/// <summary>
/// Gets or creates a view property that would go away when view gets closed
/// </summary>
public static bool GetOrCreateAutoClosingProperty<TProperty, TTextView>(
this TTextView textView,
object key,
Func<TTextView, TProperty> valueCreator,
out TProperty value) where TTextView : ITextView
{
return AutoClosingViewProperty<TProperty, TTextView>.GetOrCreateValue(textView, key, valueCreator, out value);
}
/// <summary>
/// Gets or creates a per subject buffer property.
/// </summary>
public static TProperty GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>(
this TTextView textView,
ITextBuffer subjectBuffer,
object key,
Func<TTextView, ITextBuffer, TProperty> valueCreator) where TTextView : class, ITextView
{
TProperty value;
GetOrCreatePerSubjectBufferProperty(textView, subjectBuffer, key, valueCreator, out value);
return value;
}
/// <summary>
/// Gets or creates a per subject buffer property, returning true if it needed to create it.
/// </summary>
public static bool GetOrCreatePerSubjectBufferProperty<TProperty, TTextView>(
this TTextView textView,
ITextBuffer subjectBuffer,
object key,
Func<TTextView, ITextBuffer, TProperty> valueCreator,
out TProperty value) where TTextView : class, ITextView
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(subjectBuffer);
Contract.ThrowIfNull(valueCreator);
return PerSubjectBufferProperty<TProperty, TTextView>.GetOrCreateValue(textView, subjectBuffer, key, valueCreator, out value);
}
public static bool TryGetPerSubjectBufferProperty<TProperty, TTextView>(
this TTextView textView,
ITextBuffer subjectBuffer,
object key,
out TProperty value) where TTextView : class, ITextView
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(subjectBuffer);
return PerSubjectBufferProperty<TProperty, TTextView>.TryGetValue(textView, subjectBuffer, key, out value);
}
public static void AddPerSubjectBufferProperty<TProperty, TTextView>(
this TTextView textView,
ITextBuffer subjectBuffer,
object key,
TProperty value) where TTextView : class, ITextView
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(subjectBuffer);
PerSubjectBufferProperty<TProperty, TTextView>.AddValue(textView, subjectBuffer, key, value);
}
public static void RemovePerSubjectBufferProperty<TProperty, TTextView>(
this TTextView textView,
ITextBuffer subjectBuffer,
object key) where TTextView : class, ITextView
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(subjectBuffer);
PerSubjectBufferProperty<TProperty, TTextView>.RemoveValue(textView, subjectBuffer, key);
}
public static bool TypeCharWasHandledStrangely(
this ITextView textView,
ITextBuffer subjectBuffer,
char ch)
{
var finalCaretPositionOpt = textView.GetCaretPoint(subjectBuffer);
if (finalCaretPositionOpt == null)
{
// Caret moved outside of our buffer. Don't want to handle this typed character.
return true;
}
var previousPosition = finalCaretPositionOpt.Value.Position - 1;
var inRange = previousPosition >= 0 && previousPosition < subjectBuffer.CurrentSnapshot.Length;
if (!inRange)
{
// The character before the caret isn't even in the buffer we care about. Don't
// handle this.
return true;
}
if (subjectBuffer.CurrentSnapshot[previousPosition] != ch)
{
// The character that was typed is not in the buffer at the typed location. Don't
// handle this character.
return true;
}
return false;
}
public static int? GetDesiredIndentation(this ITextView textView, ISmartIndentationService smartIndentService, ITextSnapshotLine line)
{
var pointInView = textView.BufferGraph.MapUpToSnapshot(
line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);
if (!pointInView.HasValue)
{
return null;
}
var lineInView = textView.TextSnapshot.GetLineFromPosition(pointInView.Value.Position);
return smartIndentService.GetDesiredIndentation(textView, lineInView);
}
public static bool TryGetSurfaceBufferSpan(
this ITextView textView,
VirtualSnapshotSpan virtualSnapshotSpan,
out VirtualSnapshotSpan surfaceBufferSpan)
{
// If we are already on the surface buffer, then there's no reason to attempt mappings
// as we'll lose virtualness
if (virtualSnapshotSpan.Snapshot.TextBuffer == textView.TextBuffer)
{
surfaceBufferSpan = virtualSnapshotSpan;
return true;
}
// We have to map. We'll lose virtualness in this process because
// mapping virtual points through projections is poorly defined.
var targetSpan = textView.BufferGraph.MapUpToSnapshot(
virtualSnapshotSpan.SnapshotSpan,
SpanTrackingMode.EdgeExclusive,
textView.TextSnapshot).FirstOrNullable();
if (targetSpan.HasValue)
{
surfaceBufferSpan = new VirtualSnapshotSpan(targetSpan.Value);
return true;
}
surfaceBufferSpan = default(VirtualSnapshotSpan);
return false;
}
}
}
| |
// File: Param.cs
// Project: ROS_C-Sharp
//
// ROS.NET
// Eric McCann <emccann@cs.uml.edu>
// UMass Lowell Robotics Laboratory
//
// Reimplementation of the ROS (ros.org) ros_cpp client in C#.
//
// Created: 04/28/2015
// Updated: 02/10/2016
#region USINGZ
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using XmlRpc_Wrapper;
#endregion
namespace Ros_CSharp
{
public delegate void ParamDelegate(string key, XmlRpcValue value);
public delegate void ParamStringDelegate(string key, string value);
public delegate void ParamDoubleDelegate(string key, double value);
public delegate void ParamIntDelegate(string key, int value);
public delegate void ParamBoolDelegate(string key, bool value);
#if !TRACE
[DebuggerStepThrough]
#endif
public static class Param
{
public static Dictionary<string, XmlRpcValue> parms = new Dictionary<string, XmlRpcValue>();
public static object parms_mutex = new object();
public static List<string> subscribed_params = new List<string>();
private static Dictionary<string, List<ParamStringDelegate>> StringCallbacks = new Dictionary<string, List<ParamStringDelegate>>();
private static Dictionary<string, List<ParamIntDelegate>> IntCallbacks = new Dictionary<string, List<ParamIntDelegate>>();
private static Dictionary<string, List<ParamDoubleDelegate>> DoubleCallbacks = new Dictionary<string, List<ParamDoubleDelegate>>();
private static Dictionary<string, List<ParamBoolDelegate>> BoolCallbacks = new Dictionary<string, List<ParamBoolDelegate>>();
private static Dictionary<string, List<ParamDelegate>> Callbacks = new Dictionary<string, List<ParamDelegate>>();
public static void Subscribe(string key, ParamBoolDelegate del)
{
if (!BoolCallbacks.ContainsKey(key))
BoolCallbacks.Add(key, new List<ParamBoolDelegate>());
BoolCallbacks[key].Add(del);
update(key, getParam(key, true));
}
public static void Subscribe(string key, ParamIntDelegate del)
{
if (!IntCallbacks.ContainsKey(key))
IntCallbacks.Add(key, new List<ParamIntDelegate>());
IntCallbacks[key].Add(del);
update(key, getParam(key, true));
}
public static void Subscribe(string key, ParamDoubleDelegate del)
{
if (!DoubleCallbacks.ContainsKey(key))
DoubleCallbacks.Add(key, new List<ParamDoubleDelegate>());
DoubleCallbacks[key].Add(del);
update(key, getParam(key, true));
}
public static void Subscribe(string key, ParamStringDelegate del)
{
if (!StringCallbacks.ContainsKey(key))
StringCallbacks.Add(key, new List<ParamStringDelegate>());
StringCallbacks[key].Add(del);
update(key, getParam(key, true));
}
public static void Subscribe(string key, ParamDelegate del)
{
if (!Callbacks.ContainsKey(key))
Callbacks.Add(key, new List<ParamDelegate>());
Callbacks[key].Add(del);
update(key, getParam(key, true));
}
/// <summary>
/// Sets the paramater on the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <param name="val">Value of the paramter</param>
public static void set(string key, XmlRpcValue val)
{
string mapped_key = names.resolve(key);
XmlRpcValue parm = new XmlRpcValue(), response = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
parm.Set(2, val);
lock (parms_mutex)
{
if (master.execute("setParam", parm, response, payload, true))
{
if (subscribed_params.Contains(mapped_key))
parms.Add(mapped_key, val);
}
}
}
/// <summary>
/// Sets the paramater on the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <param name="val">Value of the paramter</param>
public static void set(string key, string val)
{
string mapped_key = names.resolve(key);
XmlRpcValue parm = new XmlRpcValue(), response = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
parm.Set(2, val);
lock (parms_mutex)
{
if (master.execute("setParam", parm, response, payload, true))
{
if (subscribed_params.Contains(mapped_key))
parms.Add(mapped_key, parm);
}
}
}
/// <summary>
/// Sets the paramater on the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <param name="val">Value of the paramter</param>
public static void set(string key, double val)
{
string mapped_key = names.resolve(key);
XmlRpcValue parm = new XmlRpcValue(), response = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
parm.Set(2, val);
lock (parms_mutex)
{
if (master.execute("setParam", parm, response, payload, true))
{
if (subscribed_params.Contains(mapped_key))
parms.Add(mapped_key, parm);
}
}
}
/// <summary>
/// Sets the paramater on the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <param name="val">Value of the paramter</param>
public static void set(string key, int val)
{
string mapped_key = names.resolve(key);
XmlRpcValue parm = new XmlRpcValue(), response = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
parm.Set(2, val);
lock (parms_mutex)
{
if (master.execute("setParam", parm, response, payload, true))
{
if (subscribed_params.Contains(mapped_key))
parms.Add(mapped_key, parm);
}
}
}
/// <summary>
/// Sets the paramater on the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <param name="val">Value of the paramter</param>
public static void set(string key, bool val)
{
string mapped_key = names.resolve(key);
XmlRpcValue parm = new XmlRpcValue(), response = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
parm.Set(2, val);
lock (parms_mutex)
{
if (master.execute("setParam", parm, response, payload, true))
{
if (subscribed_params.Contains(mapped_key))
parms.Add(mapped_key, parm);
}
}
}
/// <summary>
/// Gets the parameter from the parameter server
/// </summary>
/// <param name="key">Name of the parameter</param>
/// <returns></returns>
internal static XmlRpcValue getParam(String key, bool use_cache = false)
{
string mapped_key = names.resolve(key);
XmlRpcValue payload = new XmlRpcValue();
if (!getImpl(mapped_key, ref payload, use_cache))
payload = null;
return payload;
}
private static bool safeGet<T>(string key, ref T dest, object def = null)
{
try
{
XmlRpcValue v = getParam(key);
if (v == null || !v.Valid)
{
if (def == null)
return false;
dest = (T) def;
return true;
}
dest = v.Get<T>();
return true;
}
catch
{
return false;
}
}
public static bool get(string key, ref XmlRpcValue dest)
{
return safeGet(key, ref dest);
}
public static bool get(string key, ref bool dest)
{
return safeGet(key, ref dest);
}
public static bool get(string key, ref bool dest, bool def)
{
return safeGet(key, ref dest, def);
}
public static bool get(string key, ref int dest)
{
return safeGet(key, ref dest);
}
public static bool get(string key, ref int dest, int def)
{
return safeGet(key, ref dest, def);
}
public static bool get(string key, ref double dest)
{
return safeGet(key, ref dest);
}
public static bool get(string key, ref double dest, double def)
{
return safeGet(key, ref dest, def);
}
public static bool get(string key, ref string dest, string def = null)
{
return safeGet(key, ref dest, dest);
}
public static List<string> list()
{
List<string> ret = new List<string>();
XmlRpcValue parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
if (!master.execute("getParamNames", parm, result, payload, false))
return ret;
if (result.Size != 3 || result[0].GetInt() != 1 || result[2].Type != XmlRpcValue.ValueType.TypeArray)
{
EDB.WriteLine("Expected a return code, a description, and a list!");
return ret;
}
for (int i = 0; i < payload.Size; i++)
{
ret.Add(payload[i].GetString());
}
return ret;
}
/// <summary>
/// Checks if the paramter exists.
/// </summary>
/// <param name="key">Name of the paramerer</param>
/// <returns></returns>
public static bool has(string key)
{
XmlRpcValue parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, names.resolve(key));
if (!master.execute("hasParam", parm, result, payload, false))
return false;
if (result.Size != 3 || result[0].GetInt() != 1 || result[2].Type != XmlRpcValue.ValueType.TypeBoolean)
return false;
return result[2].asBool;
}
/// <summary>
/// Deletes a parameter from the parameter server.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool del(string key)
{
string mapped_key = names.resolve(key);
lock (parms_mutex)
{
if (subscribed_params.Contains(key))
{
subscribed_params.Remove(key);
if (parms.ContainsKey(key))
parms.Remove(key);
}
}
XmlRpcValue parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, mapped_key);
if (!master.execute("deleteParam", parm, result, payload, false))
return false;
return true;
}
public static void init(IDictionary remapping_args)
{
foreach (object o in remapping_args.Keys)
{
string name = (string) o;
string param = (string) remapping_args[o];
if (name.Length < 2) continue;
if (name[0] == '_' && name[1] != '_')
{
string local_name = "~" + name.Substring(1);
int i = 0;
bool success = int.TryParse(param, out i);
if (success)
{
set(names.resolve(local_name), i);
continue;
}
double d = 0;
success = double.TryParse(param, out d);
if (success)
{
set(names.resolve(local_name), d);
continue;
}
bool b = false;
success = bool.TryParse(param.ToLower(), out b);
if (success)
{
set(names.resolve(local_name), b);
continue;
}
set(names.resolve(local_name), param);
}
}
XmlRpcManager.Instance.bind("paramUpdate", paramUpdateCallback);
}
/// <summary>
/// Manually update the value of a parameter
/// </summary>
/// <param name="key">Name of parameter</param>
/// <param name="v">Value to update param to</param>
public static void update(string key, XmlRpcValue v)
{
if (v == null)
return;
string clean_key = names.clean(key);
lock (parms_mutex)
{
if (!parms.ContainsKey(clean_key))
parms.Add(clean_key, v);
else
parms[clean_key] = v;
if (BoolCallbacks.ContainsKey(clean_key))
{
foreach (ParamBoolDelegate b in BoolCallbacks[clean_key])
b.Invoke(clean_key, new XmlRpcValue(v).GetBool());
}
if (IntCallbacks.ContainsKey(clean_key))
{
foreach (ParamIntDelegate b in IntCallbacks[clean_key])
b.Invoke(clean_key, new XmlRpcValue(v).GetInt());
}
if (DoubleCallbacks.ContainsKey(clean_key))
{
foreach (ParamDoubleDelegate b in DoubleCallbacks[clean_key])
b.Invoke(clean_key, new XmlRpcValue(v).GetDouble());
}
if (StringCallbacks.ContainsKey(clean_key))
{
foreach (ParamStringDelegate b in StringCallbacks[clean_key])
b.Invoke(clean_key, new XmlRpcValue(v).GetString());
}
if (Callbacks.ContainsKey(clean_key))
{
foreach (ParamDelegate b in Callbacks[clean_key])
b.Invoke(clean_key, new XmlRpcValue(v));
}
}
}
/// <summary>
/// Fired when a parameter gets updated
/// </summary>
/// <param name="parm">Name of parameter</param>
/// <param name="result">New value of parameter</param>
public static void paramUpdateCallback(XmlRpcValue val, XmlRpcValue result)
{
val.Set(0, 1);
val.Set(1, "");
val.Set(2, 0);
//update(XmlRpcValue.LookUp(parm)[1].Get<string>(), XmlRpcValue.LookUp(parm)[2]);
/// TODO: check carefully this stuff. It looks strange
update(val[1].Get<string>(), val[2]);
}
public static bool getImpl(string key, ref XmlRpcValue v, bool use_cache)
{
string mapped_key = names.resolve(key);
if (use_cache)
{
lock (parms_mutex)
{
if (subscribed_params.Contains(mapped_key))
{
if (parms.ContainsKey(mapped_key))
{
if (parms[mapped_key].Valid)
{
v = parms[mapped_key];
return true;
}
return false;
}
}
else
{
subscribed_params.Add(mapped_key);
XmlRpcValue parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
parm.Set(0, this_node.Name);
parm.Set(1, XmlRpcManager.Instance.uri);
parm.Set(2, mapped_key);
if (!master.execute("subscribeParam", parm, result, payload, false))
{
subscribed_params.Remove(mapped_key);
use_cache = false;
}
}
}
}
XmlRpcValue parm2 = new XmlRpcValue(), result2 = new XmlRpcValue();
parm2.Set(0, this_node.Name);
parm2.Set(1, mapped_key);
v.SetArray(0);
bool ret = master.execute("getParam", parm2, result2, v, false);
if (use_cache)
{
lock (parms_mutex)
{
parms.Add(mapped_key, v);
}
}
return ret;
}
}
}
| |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.CustomMarshalers;
using System.Security;
using System.Collections;
namespace WmcSoft.TextObjectModel
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
ComVisible(true),
SuppressUnmanagedCodeSecurity,
Guid("8CC497C0-A1DF-11CE-8098-00AA0047BE5D"),
DefaultMember("Name")]
public interface ITextDocument
{
[DispId(0)]
string Name {
[return: MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
get;
}
[DispId(1)]
ITextSelection Selection {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)]
get;
}
[DispId(2)]
int StoryCount {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)]
get;
}
[DispId(3)]
ITextStoryRanges StoryRanges {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)]
get;
}
[DispId(4)]
int Saved {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)]
set;
}
[DispId(5)]
float DefaultTabStop {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(6)]
void New();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)]
void Open([In, MarshalAs(UnmanagedType.Struct)] ref object pVar, [In] int Flags, [In] int CodePage);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(8)]
void Save([In, MarshalAs(UnmanagedType.Struct)] ref object pVar, [In] int Flags, [In] int CodePage);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(9)]
int Freeze();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10)]
int Unfreeze();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
void BeginEditCollection();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
void EndEditCollection();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(13)]
int Undo([In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(14)]
int Redo([In] int Count);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(15)]
ITextRange Range([In] int cp1, [In] int cp2);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10)]
ITextRange RangeFromPoint([In] int x, [In] int y);
}
[ComImport, Guid("8CC497C3-A1DF-11CE-8098-00AA0047BE5D"), DefaultMember("Duplicate"), TypeLibType(0xc0)]
public interface ITextFont
{
[DispId(0)]
ITextFont Duplicate {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
get;
[param: In, MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x301)]
int CanChange();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(770)]
int IsEqual([In, MarshalAs(UnmanagedType.Interface)] ITextFont pFont);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x303)]
void Reset([In] int Value);
[DispId(0x304)]
int Style {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x304)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x304)]
set;
}
[DispId(0x305)]
int AllCaps {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x305)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x305)]
set;
}
[DispId(0x306)]
int Animation {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x306)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x306)]
set;
}
[DispId(0x307)]
int BackColor {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x307)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x307)]
set;
}
[DispId(0x308)]
int Bold {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x308)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x308)]
set;
}
[DispId(0x309)]
int Emboss {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x309)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x309)]
set;
}
[DispId(0x310)]
int ForeColor {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x310)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x310)]
set;
}
[DispId(0x311)]
int Hidden {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x311)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x311)]
set;
}
[DispId(0x312)]
int Engrave {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x312)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x312)]
set;
}
[DispId(0x313)]
int Italic {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x313)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x313)]
set;
}
[DispId(0x314)]
float Kerning {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x314)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x314)]
set;
}
[DispId(0x315)]
int LanguageID {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x315)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x315)]
set;
}
[DispId(790)]
string Name {
[return: MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(790)]
get;
[param: In, MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(790)]
set;
}
[DispId(0x317)]
int Outline {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x317)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x317)]
set;
}
[DispId(0x318)]
float Position {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x318)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x318)]
set;
}
[DispId(0x319)]
int Protected {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x319)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x319)]
set;
}
[DispId(800)]
int Shadow {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(800)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(800)]
set;
}
[DispId(0x321)]
float Size {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x321)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x321)]
set;
}
[DispId(0x322)]
int SmallCaps {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x322)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x322)]
set;
}
[DispId(0x323)]
float Spacing {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x323)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x323)]
set;
}
[DispId(0x324)]
int StrikeThrough {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x324)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x324)]
set;
}
[DispId(0x325)]
int Subscript {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x325)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x325)]
set;
}
[DispId(0x326)]
int Superscript {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x326)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x326)]
set;
}
[DispId(0x327)]
int Underline {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x327)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x327)]
set;
}
[DispId(0x328)]
int Weight {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x328)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x328)]
set;
}
}
[ComImport, Guid("8CC497C4-A1DF-11CE-8098-00AA0047BE5D"), TypeLibType(0xc0), DefaultMember("Duplicate")]
public interface ITextPara
{
[DispId(0)]
ITextPara Duplicate {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
get;
[param: In, MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x401)]
int CanChange();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x402)]
int IsEqual([In, MarshalAs(UnmanagedType.Interface)] ITextPara pPara);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x403)]
void Reset([In] int Value);
[DispId(0x404)]
int Style {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x404)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x404)]
set;
}
[DispId(0x405)]
int Alignment {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x405)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x405)]
set;
}
[DispId(0x406)]
int Hyphenation {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x406)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x406)]
set;
}
[DispId(0x407)]
float FirstLineIndent {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x407)]
get;
}
[DispId(0x408)]
int KeepTogether {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x408)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x408)]
set;
}
[DispId(0x409)]
int KeepWithNext {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x409)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x409)]
set;
}
[DispId(0x410)]
float LeftIndent {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x410)]
get;
}
[DispId(0x411)]
float LineSpacing {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x411)]
get;
}
[DispId(0x412)]
int LineSpacingRule {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x412)]
get;
}
[DispId(0x413)]
int ListAlignment {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x413)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x413)]
set;
}
[DispId(0x414)]
int ListLevelIndex {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x414)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x414)]
set;
}
[DispId(0x415)]
int ListStart {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x415)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x415)]
set;
}
[DispId(0x416)]
float ListTab {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x416)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x416)]
set;
}
[DispId(0x417)]
int ListType {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x417)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x417)]
set;
}
[DispId(0x418)]
int NoLineNumber {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x418)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x418)]
set;
}
[DispId(0x419)]
int PageBreakBefore {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x419)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x419)]
set;
}
[DispId(0x420)]
float RightIndent {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x420)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x420)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x421)]
void SetIndents([In] float StartIndent, [In] float LeftIndent, [In] float RightIndent);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x422)]
void SetLineSpacing([In] int LineSpacingRule, [In] float LineSpacing);
[DispId(0x423)]
float SpaceAfter {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x423)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x423)]
set;
}
[DispId(0x424)]
float SpaceBefore {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x424)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x424)]
set;
}
[DispId(0x425)]
int WidowControl {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x425)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x425)]
set;
}
[DispId(0x426)]
int TabCount {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x426)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x427)]
void AddTab([In] float tbPos, [In] int tbAlign, [In] int tbLeader);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x428)]
void ClearAllTabs();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x429)]
void DeleteTab([In] float tbPos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x430)]
void GetTab([In] int iTab, [Out] out float ptbPos, [Out] out int ptbAlign, [Out] out int ptbLeader);
}
[ComImport, TypeLibType(0xc0), Guid("8CC497C2-A1DF-11CE-8098-00AA0047BE5D"), DefaultMember("Text")]
public interface ITextRange
{
[DispId(0)]
string Text {
[return: MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
get;
[param: In, MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
set;
}
[DispId(0x201)]
int Char {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x201)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x201)]
set;
}
[DispId(0x202)]
ITextRange Duplicate {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x202)]
get;
}
[DispId(0x203)]
ITextRange FormattedText {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x203)]
get;
[param: In, MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x203)]
set;
}
[DispId(0x204)]
int Start {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x204)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x204)]
set;
}
[DispId(0x205)]
int End {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x205)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x205)]
set;
}
[DispId(0x206)]
ITextFont Font {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x206)]
get;
[param: In, MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x206)]
set;
}
[DispId(0x207)]
ITextPara Para {
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x207)]
get;
[param: In, MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x207)]
set;
}
[DispId(520)]
int StoryLength {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(520)]
get;
}
[DispId(0x209)]
int StoryType {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x209)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x210)]
void Collapse([In] int bStart);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x211)]
int Expand([In] int Unit);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(530)]
int GetIndex([In] int Unit);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x213)]
void SetIndex([In] int Unit, [In] int Index, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x214)]
void SetRange([In] int cpActive, [In] int cpOther);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x215)]
int InRange([In, MarshalAs(UnmanagedType.Interface)] ITextRange pRange);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x216)]
int InStory([In, MarshalAs(UnmanagedType.Interface)] ITextRange pRange);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x217)]
int IsEqual([In, MarshalAs(UnmanagedType.Interface)] ITextRange pRange);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x218)]
void Select();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x219)]
int StartOf([In] int Unit, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x220)]
int EndOf([In] int Unit, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x221)]
int Move([In] int Unit, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x222)]
int MoveStart([In] int Unit, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x223)]
int MoveEnd([In] int Unit, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x224)]
int MoveWhile([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x225)]
int MoveStartWhile([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(550)]
int MoveEndWhile([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x227)]
int MoveUntil([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x228)]
int MoveStartUntil([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x229)]
int MoveEndUntil([In, MarshalAs(UnmanagedType.Struct)] ref object Cset, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(560)]
int FindText([In, MarshalAs(UnmanagedType.BStr)] string bstr, [In] int cch, [In] int Flags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x231)]
int FindTextStart([In, MarshalAs(UnmanagedType.BStr)] string bstr, [In] int cch, [In] int Flags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x232)]
int FindTextEnd([In, MarshalAs(UnmanagedType.BStr)] string bstr, [In] int cch, [In] int Flags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x233)]
int Delete([In] int Unit, [In] int Count);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x234)]
void Cut([Out, MarshalAs(UnmanagedType.Struct)] out object pVar);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x235)]
void Copy([Out, MarshalAs(UnmanagedType.Struct)] out object pVar);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x236)]
void Paste([In, MarshalAs(UnmanagedType.Struct)] ref object pVar, [In] int Format);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x237)]
int CanPaste([In, MarshalAs(UnmanagedType.Struct)] ref object pVar, [In] int Format);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x238)]
int CanEdit();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x239)]
void ChangeCase([In] int Type);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x240)]
void GetPoint([In] int Type, [Out] out int px, [Out] out int py);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x241)]
void SetPoint([In] int x, [In] int y, [In] int Type, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x242)]
void ScrollIntoView([In] int Value);
[return: MarshalAs(UnmanagedType.IUnknown)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x243)]
object GetEmbeddedObject();
}
[ComImport, Guid("8CC497C1-A1DF-11CE-8098-00AA0047BE5D"), TypeLibType(0xc0), DefaultMember("Text")]
public interface ITextSelection : ITextRange
{
[DispId(0x101)]
int Flags {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x101)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x101)]
set;
}
[DispId(0x102)]
int Type {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x102)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x103)]
int MoveLeft([In] int Unit, [In] int Count, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(260)]
int MoveRight([In] int Unit, [In] int Count, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x105)]
int MoveUp([In] int Unit, [In] int Count, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x106)]
int MoveDown([In] int Unit, [In] int Count, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x107)]
int HomeKey([In] int Unit, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x108)]
int EndKey([In] int Unit, [In] int Extend);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x109)]
void TypeText([In, MarshalAs(UnmanagedType.BStr)] string bstr);
}
[ComImport, Guid("8CC497C5-A1DF-11CE-8098-00AA0047BE5D"), DefaultMember("Item"), TypeLibType(0xc0)]
public interface ITextStoryRanges : IEnumerable
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "", MarshalTypeRef = typeof(EnumeratorToEnumVariantMarshaler), MarshalCookie = "")]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc(1), DispId(-4)]
new IEnumerator GetEnumerator();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0)]
ITextRange Item([In] int Index);
[DispId(2)]
int Count {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)]
get;
}
}
public enum Constants
{
// Fields
AlignBar = 4,
AlignCenter = 1,
AlignDecimal = 3,
AlignJustify = 3,
AlignLeft = 0,
AlignRight = 2,
AnimationMax = 8,
AutoColor = -9999997,
Backward = -1073741823,
BlinkingBackground = 2,
Cell = 12,
Character = 1,
CharFormat = 13,
CollapseEnd = 0,
CollapseStart = 1,
Column = 9,
CommentsStory = 4,
CreateAlways = 0x20,
CreateNew = 0x10,
Dashes = 2,
Default = -9999996,
Dots = 1,
Dotted = 4,
Double = 3,
End = 0,
EndnotesStory = 3,
EvenPagesFooterStory = 8,
EvenPagesHeaderStory = 6,
Extend = 1,
False = 0,
FirstPageFooterStory = 11,
FirstPageHeaderStory = 10,
FootnotesStory = 2,
Forward = 0x3fffffff,
HTML = 3,
LasVegasLights = 1,
Line = 5,
Lines = 3,
LineSpace1pt5 = 1,
LineSpaceAtLeast = 3,
LineSpaceDouble = 2,
LineSpaceExactly = 4,
LineSpaceMultiple = 5,
LineSpaceSingle = 0,
ListBullet = 1,
ListNone = 0,
ListNumberAsArabic = 2,
ListNumberAsLCLetter = 3,
ListNumberAsLCRoman = 5,
ListNumberAsSequence = 7,
ListNumberAsUCLetter = 4,
ListNumberAsUCRoman = 6,
ListParentheses = 0x10000,
ListPeriod = 0x20000,
ListPlain = 0x30000,
LowerCase = 0,
MainTextStory = 1,
MarchingBlackAnts = 4,
MarchingRedAnts = 5,
MatchCase = 4,
MatchPattern = 8,
MatchWord = 2,
Move = 0,
NoAnimation = 0,
None = 0,
NoSelection = 0,
Object = 0x10,
OpenAlways = 0x40,
OpenExisting = 0x30,
ParaFormat = 14,
Paragraph = 4,
PasteFile = 0x1000,
PrimaryFooterStory = 9,
PrimaryHeaderStory = 7,
ReadOnly = 0x100,
Row = 10,
RTF = 1,
Screen = 7,
Section = 8,
SelActive = 8,
SelAtEOL = 2,
SelectionBlock = 6,
SelectionColumn = 4,
SelectionFrame = 3,
SelectionInlineShape = 7,
SelectionIP = 1,
SelectionNormal = 2,
SelectionRow = 5,
SelectionShape = 8,
SelOvertype = 4,
SelReplace = 0x10,
SelStartActive = 1,
Sentence = 3,
SentenceCase = 4,
ShareDenyRead = 0x200,
ShareDenyWrite = 0x400,
Shimmer = 6,
Single = 1,
Spaces = 0,
SparkleText = 3,
Start = 0x20,
Story = 6,
TabBack = -3,
TabHere = -1,
Table = 15,
TabNext = -2,
Text = 2,
TextFrameStory = 5,
TitleCase = 2,
Toggle = -9999998,
ToggleCase = 5,
True = -1,
TruncateExisting = 80,
Undefined = -9999999,
UnknownStory = 0,
UpperCase = 1,
Window = 11,
WipeDown = 7,
WipeRight = 8,
Word = 2,
WordDocument = 4,
Words = 2
}
#if C
[InterfaceType(ComInterfaceType.InterfaceIsDual), SuppressUnmanagedCodeSecurity, Guid("8CC497C0-A1DF-11ce-8098-00AA0047BE5D"), ComVisible(true)]
public interface ITextDocument
{
string GetName();
object GetSelection();
int GetStoryCount();
object GetStoryRanges();
int GetSaved();
void SetSaved(int value);
object GetDefaultTabStop();
void SetDefaultTabStop(object value);
void New();
void Open(object pVar, int flags, int codePage);
void Save(object pVar, int flags, int codePage);
int Freeze();
int Unfreeze();
void BeginEditCollection();
void EndEditCollection();
int Undo(int count);
int Redo(int count);
[return: MarshalAs(UnmanagedType.Interface)]
ITextRange Range(int cp1, int cp2);
[return: MarshalAs(UnmanagedType.Interface)]
ITextRange RangeFromPoint(int x, int y);
}
[InterfaceType(ComInterfaceType.InterfaceIsDual), ComVisible(true), SuppressUnmanagedCodeSecurity, Guid("8CC497C2-A1DF-11ce-8098-00AA0047BE5D")]
public interface ITextRange
{
string GetText();
void SetText(string text);
object GetChar();
void SetChar(object ch);
[return: MarshalAs(UnmanagedType.Interface)]
ITextRange GetDuplicate();
[return: MarshalAs(UnmanagedType.Interface)]
ITextRange GetFormattedText();
void SetFormattedText([In, MarshalAs(UnmanagedType.Interface)] ITextRange range);
int GetStart();
void SetStart(int cpFirst);
int GetEnd();
void SetEnd(int cpLim);
object GetFont();
void SetFont(object font);
object GetPara();
void SetPara(object para);
int GetStoryLength();
int GetStoryType();
void Collapse(int start);
int Expand(int unit);
int GetIndex(int unit);
void SetIndex(int unit, int index, int extend);
void SetRange(int cpActive, int cpOther);
int InRange([In, MarshalAs(UnmanagedType.Interface)] ITextRange range);
int InStory([In, MarshalAs(UnmanagedType.Interface)] ITextRange range);
int IsEqual([In, MarshalAs(UnmanagedType.Interface)] ITextRange range);
void Select();
int StartOf(int unit, int extend);
int EndOf(int unit, int extend);
int Move(int unit, int count);
int MoveStart(int unit, int count);
int MoveEnd(int unit, int count);
int MoveWhile(object cset, int count);
int MoveStartWhile(object cset, int count);
int MoveEndWhile(object cset, int count);
int MoveUntil(object cset, int count);
int MoveStartUntil(object cset, int count);
int MoveEndUntil(object cset, int count);
int FindText(string text, int cch, int flags);
int FindTextStart(string text, int cch, int flags);
int FindTextEnd(string text, int cch, int flags);
int Delete(int unit, int count);
void Cut(out object pVar);
void Copy(out object pVar);
void Paste(object pVar, int format);
int CanPaste(object pVar, int format);
int CanEdit();
void ChangeCase(int type);
void GetPoint(int type, out int x, out int y);
void SetPoint(int x, int y, int type, int extend);
void ScrollIntoView(int value);
object GetEmbeddedObject();
}
#endif
}
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Configuration.Provider;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Web.Configuration;
using SubSonic.Utilities;
namespace SubSonic
{
/// <summary>
/// Summary for the DataService class
/// </summary>
public static class DataService
{
/// <summary>
///
/// </summary>
public static SubSonicSection ConfigSectionSettings;
#region Provider-specific bits
private static readonly object _lock = new object();
private static DataProviderCollection _providers;
private static DataProvider defaultProvider;
private static bool enableTrace;
private static SubSonicSection section;
/// <summary>
/// Gets or sets a value indicating whether [enable trace].
/// </summary>
/// <value><c>true</c> if [enable trace]; otherwise, <c>false</c>.</value>
public static bool EnableTrace
{
get { return enableTrace; }
set { enableTrace = value; }
}
/// <summary>
/// Gets the provider count.
/// </summary>
/// <value>The provider count.</value>
public static int ProviderCount
{
get
{
if(_providers != null)
return _providers.Count;
return 0;
}
}
/// <summary>
/// Gets or sets the config section.
/// </summary>
/// <value>The config section.</value>
public static SubSonicSection ConfigSection
{
get { return section; }
set { section = value; }
}
/// <summary>
/// Gets or sets the provider.
/// </summary>
/// <value>The provider.</value>
public static DataProvider Provider
{
get
{
if(defaultProvider == null)
LoadProviders();
return defaultProvider;
}
set { defaultProvider = value; }
}
/// <summary>
/// Gets or sets the providers.
/// </summary>
/// <value>The providers.</value>
public static DataProviderCollection Providers
{
get
{
if(_providers == null)
LoadProviders();
return _providers;
}
set { _providers = value; }
}
/// <summary>
/// Gets the namespace.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string GetNamespace(string providerName)
{
return Providers[providerName].GeneratedNamespace;
}
/// <summary>
/// Gets the provider names.
/// </summary>
/// <returns></returns>
public static string[] GetProviderNames()
{
if(Providers != null)
{
int providerCount = Providers.Count;
string[] providerNames = new string[providerCount];
int i = 0;
foreach(DataProvider provider in Providers)
{
providerNames[i] = provider.Name;
i++;
}
return providerNames;
}
return new string[] {};
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static DataProvider GetInstance(string providerName)
{
//ensure load
LoadProviders();
//ensure it's instanced
if(String.IsNullOrEmpty(providerName) || String.IsNullOrEmpty(providerName.Trim()))
return defaultProvider;
DataProvider provider = _providers[providerName];
if(provider != null)
return provider;
throw new ArgumentException("No provider is defined with the name " + providerName, "providerName");
}
/// <summary>
/// Gets the instance.
/// </summary>
/// <returns></returns>
private static DataProvider GetInstance()
{
return GetInstance(null);
}
/// <summary>
/// Loads the providers.
/// </summary>
public static void LoadProviders()
{
// Avoid claiming lock if providers are already loaded
if(defaultProvider == null)
{
lock(_lock)
{
// Do this again to make sure DefaultProvider is still null
if(defaultProvider == null)
{
//we allow for passing in a configuration section
//check to see if one's been passed in
if(section == null)
{
section = ConfigSectionSettings ?? (SubSonicSection)ConfigurationManager.GetSection(ConfigurationSectionName.SUB_SONIC_SERVICE);
//if it's still null, throw an exception
if(section == null)
throw new ConfigurationErrorsException("Can't find the SubSonicService section of the application config file");
}
//set the builder's template directory
CodeService.TemplateDirectory = section.TemplateDirectory;
enableTrace = Convert.ToBoolean(section.EnableTrace);
// Load registered providers and point DefaultProvider
// to the default provider
_providers = new DataProviderCollection();
ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(DataProvider));
defaultProvider = _providers[section.DefaultProvider];
if(defaultProvider == null && _providers.Count > 0)
{
IEnumerator enumer = _providers.GetEnumerator();
enumer.MoveNext();
defaultProvider = (DataProvider)enumer.Current;
if(defaultProvider == null)
throw new ProviderException("No providers could be located in the SubSonicService section of the application config file.");
}
}
}
}
}
/// <summary>
/// Resets the databases.
/// </summary>
public static void ResetDatabases()
{
/*
//add in the providers, and their databases
Databases = new DBCollection();
if(_providers != null)
{
foreach(DataProvider prov in _providers)
{
DB db = new DB(prov.Name);
db.ConnectionString = prov.ConnectionString;
db.ProviderName = prov.Name;
db.Provider = prov;
Databases.Add(db);
}
}
* */
}
/// <summary>
/// Adds the provider.
/// </summary>
/// <param name="provider">The provider.</param>
public static void AddProvider(DataProvider provider)
{
if(_providers == null)
_providers = new DataProviderCollection();
_providers.Add(provider);
}
#endregion
#region SQL Generation Support
/// <summary>
/// Gets the generator.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static ISqlGenerator GetGenerator(string providerName)
{
DataProvider provider = GetInstance(providerName);
return GetGenerator(provider);
}
/// <summary>
/// Gets a SQL Generator specific to provider specified by providerName.
/// </summary>
/// <param name="provider">A provider instance.</param>
/// <returns>An ISQLGenerator instance.</returns>
public static ISqlGenerator GetGenerator(DataProvider provider)
{
return GetGenerator(provider, null);
}
/// <summary>
/// Gets a SQL Generator specific to provider specified by providerName.
/// </summary>
/// <param name="provider">A provider instance.</param>
/// <param name="sqlQuery">A SqlQuery instance.</param>
/// <returns>An ISQLGenerator instance.</returns>
public static ISqlGenerator GetGenerator(DataProvider provider, SqlQuery sqlQuery)
{
ISqlGenerator generator;
switch(provider.NamedProviderType)
{
case DataProviderTypeName.SQL_SERVER:
if(Utility.IsSql2005(provider))
generator = new Sql2005Generator(sqlQuery);
else if(Utility.IsSql2008(provider))
generator = new Sql2008Generator(sqlQuery);
else
generator = new Sql2000Generator(sqlQuery);
break;
case DataProviderTypeName.MY_SQL:
generator = new MySqlGenerator(sqlQuery);
break;
case DataProviderTypeName.ORACLE:
generator = new OracleGenerator(sqlQuery);
break;
case DataProviderTypeName.SQLITE:
generator = new SqlLiteGenerator(sqlQuery);
break;
case DataProviderTypeName.SQL_CE:
generator = new SqlCEGenerator(sqlQuery);
break;
case DataProviderTypeName.MSACCESS:
generator = new MSJetGenerator(sqlQuery);
break;
default:
generator = new ANSISqlGenerator(sqlQuery);
break;
}
return generator;
}
#endregion
#region Scripting
/// <summary>
/// Scripts the table data.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public static string ScriptTableData(string tableName)
{
return GetInstance().ScriptData(tableName);
}
/// <summary>
/// Scripts the table data.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string ScriptTableData(string tableName, string providerName)
{
return GetInstance(providerName).ScriptData(tableName);
}
/// <summary>
/// Scripts the data.
/// </summary>
/// <returns></returns>
public static string ScriptData()
{
return ScriptData(String.Empty);
}
/// <summary>
/// Scripts the data.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string ScriptData(string providerName)
{
string[] tables = GetTableNames(providerName);
StringBuilder sb = new StringBuilder();
foreach(string table in tables)
{
sb.Append(GetInstance(providerName).ScriptData(table, providerName));
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Scripts the data.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string ScriptData(string tableName, string providerName)
{
return GetInstance(providerName).ScriptData(tableName, providerName);
}
#endregion
#region Database Interaction
/// <summary>
/// Gets the SP schema collection.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static List<StoredProcedure> GetSPSchemaCollection(string providerName)
{
List<StoredProcedure> _sps = new List<StoredProcedure>();
string[] sps = GetSPList(providerName, true);
DataProvider provider = Providers[providerName];
{
Utility.WriteTrace(String.Format("Generating Stored Procedure collection for {0}", providerName));
int generatedSprocs = 0;
foreach(string s in sps)
{
string spName = s;
string spSchemaName = "";
int i = s.IndexOf('.');
if (i >= 0) {
spName = s.Substring(i + 1);
spSchemaName = s.Substring(0, i);
}
if (CodeService.ShouldGenerate(spName, provider.IncludeProcedures, provider.ExcludeProcedures, provider))
{
//declare the sp
StoredProcedure sp = new StoredProcedure(spName, provider, spSchemaName);
//get the params
using (IDataReader rdr = GetSPParams(spName, providerName))
{
while(rdr.Read())
{
StoredProcedure.Parameter par = new StoredProcedure.Parameter();
provider.SetParameter(rdr, par);
par.QueryParameter = provider.FormatParameterNameForSQL(par.Name);
par.DisplayName = Utility.GetParameterName(par.Name, provider);
sp.Parameters.Add(par);
}
rdr.Close();
}
_sps.Add(sp);
generatedSprocs++;
}
}
Utility.WriteTrace(String.Format("Finished! {0} of {1} procedures generated.", generatedSprocs, sps.GetLength(0)));
}
return _sps;
}
/// <summary>
/// Gets the SQL.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public static string GetSql(Query qry)
{
return GetInstance(qry.ProviderName).GetSql(qry);
}
/// <summary>
/// Builds the command.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public static QueryCommand BuildCommand(Query qry)
{
QueryCommand cmd = GetInstance(qry.ProviderName).BuildCommand(qry);
cmd.ProviderName = qry.ProviderName;
cmd.Provider = qry.Provider;
cmd.CommandTimeout = qry.CommandTimeout;
return cmd;
}
/// <summary>
/// Executes a transaction of the passed-in commands.
/// </summary>
/// <param name="commands">The commands.</param>
public static void ExecuteTransaction(QueryCommandCollection commands)
{
if(commands == null || commands.Count == 0)
return;
commands[0].Provider.ExecuteTransaction(commands);
//GetInstance().ExecuteTransaction(commands);
}
/// <summary>
/// Executes a transaction of the passed-in commands.
/// </summary>
/// <param name="commands">The commands.</param>
/// <param name="providerName">Name of the provider.</param>
public static void ExecuteTransaction(QueryCommandCollection commands, string providerName)
{
GetInstance(providerName).ExecuteTransaction(commands);
}
/// <summary>
/// Gets the record count.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public static int GetRecordCount(Query qry)
{
return GetInstance(qry.ProviderName).GetRecordCount(qry);
}
/// <summary>
/// Returns an IDataReader using the passed-in command
/// </summary>
/// <param name="cmd"></param>
/// <returns>IDataReader</returns>
public static IDataReader GetReader(QueryCommand cmd)
{
return GetInstance(cmd.ProviderName).GetReader(cmd);
}
/// <summary>
/// Returns a single row optimized IDataReader using the passed-in command
/// </summary>
/// <param name="cmd"></param>
/// <returns>IDataReader</returns>
public static IDataReader GetSingleRecordReader(QueryCommand cmd)
{
return GetInstance(cmd.ProviderName).GetSingleRecordReader(cmd);
}
/// <summary>
/// Returns a DataSet based on the passed-in command
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
public static DataSet GetDataSet(QueryCommand cmd)
{
return GetInstance(cmd.ProviderName).GetDataSet(cmd);
}
/// <summary>
/// Returns a DataSet based on the passed-in command
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
public static T GetDataSet<T>(QueryCommand cmd) where T : DataSet, new()
{
return GetInstance(cmd.ProviderName).GetDataSet<T>(cmd);
}
/// <summary>
/// Returns a scalar object based on the passed-in command
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
public static object ExecuteScalar(QueryCommand cmd)
{
return GetInstance(cmd.ProviderName).ExecuteScalar(cmd);
}
/// <summary>
/// Executes a pass-through query on the DB
/// </summary>
/// <param name="cmd"></param>
public static int ExecuteQuery(QueryCommand cmd)
{
return GetInstance(cmd.ProviderName).ExecuteQuery(cmd);
}
#endregion
#region Schema
/// <summary>
/// Clears the schema cache.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
public static void ClearSchemaCache(string providerName)
{
DataProvider provider = GetInstance(providerName);
provider.schemaCollection.Clear();
provider.ReloadSchema();
}
//public static TableSchema.Table GetSchema(string tableName, string providerName)
//{
// string[] views = GetViewNames(providerName);
// foreach (string view in views)
// {
// if (Utilities.Utility.IsMatch(view, tableName))
// {
// return GetSchema(tableName, providerName, TableType.View);
// }
// }
// return GetSchema(tableName, providerName, TableType.Table);
//}
/// <summary>
/// Reverse-compat overload; this defaults to Tables. if you need to specify a view, use the
/// other method call.
/// </summary>
/// <param name="tableName"></param>
/// <param name="providerName"></param>
/// <returns></returns>
public static TableSchema.Table GetSchema(string tableName, string providerName)
{
return GetSchema(tableName, providerName, TableType.Table);
}
/// <summary>
/// Tables the exists.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public static bool TableExists(string providerName, string tableName)
{
string[] tables = GetTableNames(providerName);
bool result = false;
foreach(string tbl in tables)
{
if(Utility.IsMatch(tbl, tableName))
{
result = true;
break;
}
}
return result;
}
/// <summary>
/// Gets the schema.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <param name="tableType">Type of the table.</param>
/// <returns></returns>
public static TableSchema.Table GetSchema(string tableName, string providerName, TableType tableType)
{
TableSchema.Table result;
//the schema could be held in memory
//if it is, use that; else go to the DB
DataProvider provider = GetInstance(providerName);
if(provider.schemaCollection.ContainsKey(tableName))
result = provider.schemaCollection[tableName];
else
{
//look it up
//when done, add it to the collection
result = provider.GetTableSchema(tableName, tableType);
if(result != null)
provider.AddSchema(tableName, result);
}
return result;
}
/// <summary>
/// Gets the table schema.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static TableSchema.Table GetTableSchema(string tableName, string providerName)
{
return GetSchema(tableName, providerName, TableType.Table) ?? GetSchema(tableName, providerName, TableType.View);
}
/// <summary>
/// Gets the table schema.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <param name="tableType">Type of the table.</param>
/// <returns></returns>
public static TableSchema.Table GetTableSchema(string tableName, string providerName, TableType tableType)
{
return GetSchema(tableName, providerName, tableType);
}
/// <summary>
/// Gets the table names.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetTableNames(string providerName)
{
return GetInstance(providerName).GetTableNameList();
}
/// <summary>
/// Gets the ordered table names.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetOrderedTableNames(string providerName)
{
List<string> addedTables = new List<string>();
TableSchema.Table[] tbls = GetTables(providerName);
for(int i = 0; i < tbls.Length; i++)
{
int fkCount = tbls[i].ForeignKeys.Count;
if(fkCount == 0)
addedTables.Add(tbls[i].TableName);
else
{
List<string> fkTables = new List<string>();
foreach(TableSchema.TableColumn col in tbls[i].Columns)
{
if(col.IsForeignKey)
fkTables.Add(col.ForeignKeyTableName);
}
bool allDependenciesAdded = true;
foreach(string fkTableName in fkTables)
{
if(!addedTables.Contains(fkTableName) && !Utility.IsMatch(fkTableName, tbls[i].TableName))
{
allDependenciesAdded = false;
break;
}
}
if(allDependenciesAdded && !addedTables.Contains(tbls[i].TableName))
addedTables.Add(tbls[i].TableName);
}
}
for(int i = 0; i < tbls.Length; i++)
{
if(tbls[i].PrimaryKeys.Length < 2 && !addedTables.Contains(tbls[i].TableName))
addedTables.Add(tbls[i].TableName);
}
for(int i = 0; i < tbls.Length; i++)
{
if(tbls[i].PrimaryKeys.Length > 1 && !addedTables.Contains(tbls[i].TableName))
addedTables.Add(tbls[i].TableName);
}
return addedTables.ToArray();
}
/// <summary>
/// Gets the tables.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static TableSchema.Table[] GetTables(string providerName)
{
string[] tableNames = GetTableNames(providerName);
TableSchema.Table[] tables = new TableSchema.Table[tableNames.Length];
for(int i = 0; i < tables.Length; i++)
tables[i] = GetSchema(tableNames[i], providerName, TableType.Table);
return tables;
}
/// <summary>
/// Gets the foreign key tables.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetForeignKeyTables(string tableName, string providerName)
{
return GetInstance().GetForeignKeyTables(tableName);
}
//public static string[] GetManyToMany(string providerName, string tableName)
//{
// return GetInstance(providerName).GetManyToManyTables(tableName);
//}
/// <summary>
/// Gets the view names.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetViewNames(string providerName)
{
return GetInstance(providerName).GetViewNameList();
}
/// <summary>
/// Gets the views.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static TableSchema.Table[] GetViews(string providerName)
{
string[] viewNames = GetViewNames(providerName);
TableSchema.Table[] views = new TableSchema.Table[viewNames.Length];
for(int i = 0; i < views.Length; i++)
views[i] = GetSchema(viewNames[i], providerName, TableType.View);
return views;
}
/// <summary>
/// Gets the SP list.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetSPList(string providerName)
{
return GetInstance(providerName).GetSPList();
}
/// <summary>
/// Gets the SP name and schema list.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string[] GetSPList(string providerName, bool includeSchema)
{
return GetInstance(providerName).GetSPList(includeSchema);
}
/// <summary>
/// Gets the primary key table names.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static ArrayList GetPrimaryKeyTableNames(string tableName, string providerName)
{
return GetInstance(providerName).GetPrimaryKeyTableNames(tableName);
}
/// <summary>
/// Gets the primary key tables.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static TableSchema.Table[] GetPrimaryKeyTables(string tableName, string providerName)
{
return GetInstance(providerName).GetPrimaryKeyTables(tableName);
}
/// <summary>
/// Gets the name of the foreign key table.
/// </summary>
/// <param name="fkColumn">The fk column.</param>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string GetForeignKeyTableName(string fkColumn, string tableName, string providerName)
{
return GetInstance(providerName).GetForeignKeyTableName(fkColumn, tableName);
}
/// <summary>
/// Gets the foreign key table.
/// </summary>
/// <param name="fkColumn">The fk column.</param>
/// <param name="table">The table.</param>
/// <returns></returns>
public static TableSchema.Table GetForeignKeyTable(TableSchema.TableColumn fkColumn, TableSchema.Table table)
{
return GetInstance(table.Provider.Name).GetForeignKeyTable(fkColumn, table);
}
/// <summary>
/// Gets the SP params.
/// </summary>
/// <param name="spName">Name of the sp.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static IDataReader GetSPParams(string spName, string providerName)
{
return GetInstance(providerName).GetSPParams(spName);
}
/// <summary>
/// Gets the type of the db.
/// </summary>
/// <param name="dataType">Type of the data.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static DbType GetDbType(string dataType, string providerName)
{
return GetInstance(providerName).GetDbType(dataType);
}
/// <summary>
/// Gets the type of the client.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public static string GetClientType(string providerName)
{
return GetInstance(providerName).GetType().Name;
}
#endregion
#region DBCommand Helpers
/// <summary>
/// Gets the I db command.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
internal static IDbCommand GetIDbCommand(QueryCommand qry)
{
return GetInstance(qry.ProviderName).GetCommand(qry);
}
/// <summary>
/// Gets the db command.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
internal static DbCommand GetDbCommand(QueryCommand qry)
{
return GetInstance(qry.ProviderName).GetDbCommand(qry);
}
#endregion
}
}
| |
namespace AgileObjects.AgileMapper.Members
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#if NET35
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
using Caching;
using Dictionaries;
using Extensions.Internal;
using NetStandardPolyfills;
using ReadableExpressions.Extensions;
internal class QualifiedMember : IQualifiedMember
{
public static readonly QualifiedMember All = new QualifiedMember(default(Member), null);
public static readonly QualifiedMember None = new QualifiedMember(default(Member), null);
private readonly MapperContext _mapperContext;
private readonly QualifiedMember _parent;
private readonly Func<QualifiedMember, string> _pathFactory;
private readonly ICache<Member, QualifiedMember> _childMemberCache;
private ICache<Type, QualifiedMember> _runtimeTypedMemberCache;
protected QualifiedMember(Member[] memberChain, QualifiedMember adaptedMember)
: this(memberChain, adaptedMember.JoinedNames, adaptedMember._mapperContext)
{
if (IsSimple || adaptedMember.IsSimple)
{
return;
}
Context = adaptedMember.Context;
foreach (var childMember in adaptedMember._childMemberCache.Values)
{
_childMemberCache.GetOrAdd(childMember.LeafMember, m => childMember);
}
}
private QualifiedMember(Member[] memberChain, IList<string> joinedNames, MapperContext mapperContext)
: this(memberChain.Last(), mapperContext)
{
MemberChain = memberChain;
JoinedNames = joinedNames;
_pathFactory = m => m.MemberChain.GetFullName();
IsRecursion = DetermineRecursion();
}
private QualifiedMember(Member member, QualifiedMember parent, MapperContext mapperContext)
: this(member, mapperContext)
{
if (parent == null)
{
MemberChain = new[] { member };
JoinedNames = NamingSettings.RootMatchingNames;
_pathFactory = m => m.LeafMember.JoiningName;
return;
}
_parent = parent;
MemberChain = parent.MemberChain.Append(member);
var memberMatchingNames = mapperContext.Naming.GetMatchingNamesFor(member, parent.Context);
JoinedNames = parent.JoinedNames.ExtendWith(memberMatchingNames, mapperContext);
_pathFactory = m => m._parent.GetPath() + m.LeafMember.JoiningName;
IsRecursion = DetermineRecursion();
}
private QualifiedMember(Member leafMember, MapperContext mapperContext)
{
if (leafMember == null)
{
return;
}
IsRoot = leafMember.IsRoot;
LeafMember = leafMember;
_mapperContext = mapperContext;
if (!IsSimple)
{
_childMemberCache = mapperContext.Cache
.CreateNewWithHashCodes<Member, QualifiedMember>();
}
RegistrationName = this.IsConstructorParameter() ? "ctor:" + Name : Name;
IsReadOnly = IsReadable && !leafMember.IsWriteable;
}
#region Setup
private bool DetermineRecursion()
{
if (IsSimple || (Type == typeof(object)))
{
return false;
}
if (Depth < 3)
{
// Need at least 3 members for recursion:
// Foo -> Foo.ChildFoo -> Foo.ChildFoo.ChildFoo
return false;
}
for (var i = Depth - 2; i >= 0; --i)
{
if ((LeafMember.Type == MemberChain[i].Type) &&
((Depth - i > 2) || LeafMember.Equals(MemberChain[i])))
{
// Recursion if the types match and either:
// 1. It's via an intermediate object, e.g. Order.OrderItem.Order, or
// 2. It's the same member, e.g. root.Parent.Parent
return true;
}
}
return false;
}
#endregion
#region Factory Methods
public static QualifiedMember CreateRoot(Member rootMember, MapperContext mapperContext)
=> new QualifiedMember(rootMember, null, mapperContext);
public static QualifiedMember Create(Member[] memberChain, MapperContext mapperContext)
{
var qualifiedMember = new QualifiedMember(memberChain, Enumerable<string>.EmptyArray, mapperContext);
QualifiedMemberContext.Set(qualifiedMember, mapperContext);
return qualifiedMember;
}
#endregion
public IQualifiedMemberContext Context { get; private set; }
public virtual bool IsRoot { get; }
public Member[] MemberChain { get; }
public int Depth => MemberChain.Length;
public Member LeafMember { get; }
public Type Type => LeafMember?.Type;
public Type RootType => MemberChain[0].Type;
public string GetFriendlyTypeName() => Type.GetFriendlyName();
public Type ElementType => LeafMember?.ElementType;
public virtual Type GetElementType(Type sourceElementType) => ElementType;
public string Name => LeafMember.Name;
public virtual string RegistrationName { get; }
public IList<string> JoinedNames { get; private set; }
public string GetPath() => _pathFactory.Invoke(this);
public bool IsComplex => LeafMember.IsComplex;
public bool IsEnumerable => LeafMember.IsEnumerable;
public bool IsDictionary => LeafMember.IsDictionary;
public bool IsSimple => LeafMember.IsSimple;
public bool IsReadable => LeafMember.IsReadable;
public bool IsReadOnly { get; set; }
public bool IsRecursion { get; }
public bool IsCustom { get; set; }
public virtual bool GuardObjectValuePopulations => false;
public virtual bool HasCompatibleType(Type type) => Type?.IsAssignableTo(type) == true;
IQualifiedMember IQualifiedMember.GetElementMember() => this.GetElementMember();
IQualifiedMember IQualifiedMember.Append(Member childMember) => Append(childMember);
[DebuggerStepThrough]
public QualifiedMember Append(Member childMember)
=> _childMemberCache.GetOrAdd(childMember, CreateChildMember);
protected virtual QualifiedMember CreateChildMember(Member childMember)
=> CreateFinalMember(new QualifiedMember(childMember, this, _mapperContext));
public QualifiedMember GetChildMember(string registrationName)
=> _childMemberCache.Values.First(childMember => childMember.RegistrationName == registrationName);
public IQualifiedMember RelativeTo(IQualifiedMember otherMember)
{
var otherQualifiedMember = (QualifiedMember)otherMember;
if ((otherQualifiedMember.LeafMember == MemberChain[0]) &&
otherQualifiedMember.MemberChain[0].IsRoot &&
((otherQualifiedMember.Depth + 1) == Depth))
{
return this;
}
var relativeMemberChain = MemberChain.RelativeTo(otherQualifiedMember.MemberChain);
return new QualifiedMember(relativeMemberChain, this);
}
IQualifiedMember IQualifiedMember.WithType(Type runtimeType)
{
if (runtimeType == Type)
{
return this;
}
var typedMember = WithType(runtimeType);
if (runtimeType.IsDictionary())
{
return new DictionarySourceMember(typedMember, typedMember);
}
return typedMember;
}
public QualifiedMember WithType(Type runtimeType)
{
if (runtimeType == Type)
{
return this;
}
var runtimeTypedMember = RuntimeTypedMemberCache
.GetOrAdd(runtimeType, CreateRuntimeTypedMember);
return runtimeTypedMember;
}
private ICache<Type, QualifiedMember> RuntimeTypedMemberCache
=> _runtimeTypedMemberCache ??=
_mapperContext.Cache.CreateNewWithHashCodes<Type, QualifiedMember>();
protected virtual QualifiedMember CreateRuntimeTypedMember(Type runtimeType)
{
var newMemberChain = new Member[Depth];
var finalMemberIndex = Depth - 1;
for (var i = 0; i < finalMemberIndex; ++i)
{
newMemberChain[i] = MemberChain[i];
}
newMemberChain[finalMemberIndex] = LeafMember.WithType(runtimeType);
return CreateFinalMember(new QualifiedMember(newMemberChain, this));
}
private QualifiedMember CreateFinalMember(QualifiedMember member)
{
member.SetContext(Context);
return member.IsTargetMember
? _mapperContext.QualifiedMemberFactory.GetFinalTargetMember(member)
: member;
}
private bool IsTargetMember => MemberChain[0].Name == Member.RootTargetMemberName;
public bool CouldMatch(QualifiedMember otherMember) => JoinedNames.CouldMatch(otherMember.JoinedNames);
public virtual bool Matches(IQualifiedMember otherMember)
{
if (otherMember == this)
{
return true;
}
if (otherMember is QualifiedMember otherQualifiedMember)
{
return JoinedNames.Match(otherQualifiedMember.JoinedNames);
}
return otherMember.Matches(this);
}
public virtual Expression GetAccess(Expression instance, IMemberMapperData mapperData)
=> LeafMember.GetAccess(instance);
public Expression GetQualifiedAccess(Expression parentInstance)
=> MemberChain.GetQualifiedAccess(parentInstance);
IQualifiedMember IQualifiedMember.SetContext(IQualifiedMemberContext context)
=> SetContext(context);
public QualifiedMember SetContext(IQualifiedMemberContext context)
{
Context = context;
if (IsRoot || (JoinedNames?.Any() != false))
{
return this;
}
var matchingNameSets = MemberChain.ProjectToArray(
context,
(ctx, m) => ctx.MapperContext.Naming.GetMatchingNamesFor(m, ctx));
JoinedNames = _mapperContext.Naming.GetJoinedNamesFor(matchingNameSets);
return this;
}
public virtual bool CheckExistingElementValue => false;
#region ExcludeFromCodeCoverage
#if DEBUG
[ExcludeFromCodeCoverage]
#endif
#endregion
public virtual BlockExpression GetAccessChecked(IMemberMapperData mapperData) => null;
public virtual Expression GetHasDefaultValueCheck(IMemberMapperData mapperData)
=> this.GetAccess(mapperData).GetIsDefaultComparison();
public virtual Expression GetPopulation(Expression value, IMemberMapperData mapperData)
=> LeafMember.GetPopulation(mapperData.TargetInstance, value);
public virtual void MapCreating(Type sourceType)
{
}
#region ExcludeFromCodeCoverage
#if DEBUG
[ExcludeFromCodeCoverage]
#endif
#endregion
public override string ToString() => GetPath() + ": " + Type.GetFriendlyName();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Fody;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
public static class CecilExtensions
{
public static bool ContainsSkipWeaving(this IEnumerable<CustomAttribute> attributes)
{
return attributes.Any(x => x.AttributeType.FullName == "Janitor.SkipWeaving");
}
public static void RemoveSkipWeaving(this Collection<CustomAttribute> attributes)
{
var attribute = attributes.SingleOrDefault(x => x.AttributeType.FullName == "Janitor.SkipWeaving");
if (attribute != null)
{
attributes.Remove(attribute);
}
}
public static bool MethodExists(this TypeDefinition typeDefinition, string method)
{
return typeDefinition.Methods.Any(x => x.Name == method);
}
public static bool FieldExists(this TypeDefinition typeDefinition, string field)
{
return typeDefinition.Fields.Any(x => x.Name == field);
}
public static bool IsClass(this TypeDefinition x)
{
return x.BaseType != null &&
!x.IsEnum &&
!x.IsInterface;
}
public static bool IsIDisposable(this TypeReference typeRef)
{
if (typeRef.IsArray)
{
return false;
}
if (typeRef.IsGenericParameter)
{
var genericParameter = (GenericParameter)typeRef;
return genericParameter.Constraints.Any(c => c.ConstraintType.IsIDisposable());
}
var type = typeRef.Resolve();
if (type.Interfaces.Any(i => i.InterfaceType.FullName.Equals("System.IDisposable")))
{
return true;
}
if (type.FullName.Equals("System.IDisposable"))
{
return true;
}
return type.BaseType != null &&
type.BaseType.IsIDisposable();
}
public static void InsertAtStart(this Collection<Instruction> collection, params Instruction[] instructions)
{
var indexOf = 0;
foreach (var instruction in instructions)
{
collection.Insert(indexOf, instruction);
indexOf++;
}
}
public static void Add(this Collection<Instruction> collection, params Instruction[] instructions)
{
foreach (var instruction in instructions)
{
collection.Add(instruction);
}
}
public static void Add(this Collection<Instruction> collection, IEnumerable<Instruction> instructions)
{
foreach (var instruction in instructions)
{
collection.Add(instruction);
}
}
public static MethodDefinition Find(this TypeDefinition typeReference, string name, params string[] paramTypes)
{
foreach (var method in typeReference.Methods)
{
if (method.IsMatch(name, paramTypes))
{
return method;
}
}
throw new WeavingException($"Could not find '{name}' on '{typeReference.Name}'");
}
public static string GetName(this FieldDefinition field)
{
return $"{field.DeclaringType.FullName}.{field.Name}";
}
public static bool IsMatch(this MethodReference methodReference, string name, params string[] paramTypes)
{
if (methodReference.Parameters.Count != paramTypes.Length)
{
return false;
}
if (methodReference.Name != name)
{
return false;
}
var parameters = methodReference.Parameters;
for (var index = 0; index < parameters.Count; index++)
{
var parameterDefinition = parameters[index];
var paramType = paramTypes[index];
if (parameterDefinition.ParameterType.Name != paramType)
{
return false;
}
}
return true;
}
public static bool IsGeneratedCode(this ICustomAttributeProvider value)
{
if (value == null)
{
return false;
}
if (value.CustomAttributes
.Select(x => x.AttributeType)
.Any(a => a.Name == "CompilerGeneratedAttribute" ||
a.Name == "GeneratedCodeAttribute"))
{
return true;
}
return IsGeneratedCode((value as TypeDefinition)?.DeclaringType);
}
public static bool IsEmptyOrNotImplemented(this MethodDefinition method)
{
var instructions = method.Body.Instructions
.Where(i => i.OpCode != OpCodes.Nop &&
i.OpCode != OpCodes.Ret).ToList();
if (instructions.Count == 0)
{
return true;
}
if (instructions.Count != 2 ||
instructions[0].OpCode != OpCodes.Newobj ||
instructions[1].OpCode != OpCodes.Throw)
{
return false;
}
var ctor = (MethodReference)instructions[0].Operand;
if (ctor.DeclaringType.FullName == "System.NotImplementedException")
{
return true;
}
return false;
}
public static FieldReference GetGeneric(this FieldDefinition definition)
{
if (!definition.DeclaringType.HasGenericParameters)
{
return definition;
}
var declaringType = new GenericInstanceType(definition.DeclaringType);
foreach (var parameter in definition.DeclaringType.GenericParameters)
{
declaringType.GenericArguments.Add(parameter);
}
return new FieldReference(definition.Name, definition.FieldType, declaringType);
}
public static MethodReference GetGeneric(this MethodReference reference)
{
if (!reference.DeclaringType.HasGenericParameters)
{
return reference;
}
var declaringType = new GenericInstanceType(reference.DeclaringType);
foreach (var parameter in reference.DeclaringType.GenericParameters)
{
declaringType.GenericArguments.Add(parameter);
}
var methodReference = new MethodReference(reference.Name, reference.MethodReturnType.ReturnType, declaringType)
{
HasThis = reference.HasThis
};
foreach (var parameterDefinition in reference.Parameters)
{
methodReference.Parameters.Add(parameterDefinition);
}
return methodReference;
}
public static void HideLineFromDebugger(SequencePoint seqPoint)
{
if (seqPoint?.Document == null)
{
return;
}
// This tells the debugger to ignore and step through
// all the following instructions to the next instruction
// with a valid SequencePoint. That way IL can be hidden from
// the Debugger. See
// http://blogs.msdn.com/b/abhinaba/archive/2005/10/10/479016.aspx
seqPoint.StartLine = 0xfeefee;
seqPoint.EndLine = 0xfeefee;
}
public static OpCode GetCallingConvention(this MethodReference method)
{
if (method.Resolve().IsVirtual)
{
return OpCodes.Callvirt;
}
return OpCodes.Call;
}
public static MethodReference MakeGeneric(this MethodReference method, params TypeReference[] args)
{
if (args.Length == 0)
{
return method;
}
if (method.GenericParameters.Count != args.Length)
{
throw new ArgumentException("Invalid number of generic type arguments supplied");
}
var genericTypeRef = new GenericInstanceMethod(method);
foreach (var arg in args)
{
genericTypeRef.GenericArguments.Add(arg);
}
return genericTypeRef;
}
public static TypeReference GetDisposable(this TypeReference reference)
{
if (reference.IsGenericParameter)
{
var genericParameter = (GenericParameter)reference;
return genericParameter.Constraints.First(c => c.ConstraintType.IsIDisposable()).ConstraintType;
}
return reference;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public class InteractiveWindowHistoryTests : IDisposable
{
#region Helpers
private readonly InteractiveWindowTestHost _testHost;
private readonly IInteractiveWindow _window;
private readonly IInteractiveWindowOperations _operations;
public InteractiveWindowHistoryTests()
{
_testHost = new InteractiveWindowTestHost();
_window = _testHost.Window;
_operations = _window.Operations;
}
void IDisposable.Dispose()
{
_testHost.Dispose();
}
/// <summary>
/// Sets the active code to the specified text w/o executing it.
/// </summary>
private void SetActiveCode(string text)
{
using (var edit = _window.CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null))
{
edit.Replace(new Span(0, _window.CurrentLanguageBuffer.CurrentSnapshot.Length), text);
edit.Apply();
}
}
private async Task InsertAndExecuteInputs(params string[] inputs)
{
foreach (var input in inputs)
{
await InsertAndExecuteInput(input).ConfigureAwait(true);
}
}
private async Task InsertAndExecuteInput(string input)
{
_window.InsertCode(input);
AssertCurrentSubmission(input);
await ExecuteInput().ConfigureAwait(true);
}
private async Task ExecuteInput()
{
await ((InteractiveWindow)_window).ExecuteInputAsync().ConfigureAwait(true);
}
private void AssertCurrentSubmission(string expected)
{
Assert.Equal(expected, _window.CurrentLanguageBuffer.CurrentSnapshot.GetText());
}
#endregion Helpers
[WpfFact]
public async Task CheckHistoryPrevious()
{
const string inputString = "1 ";
await InsertAndExecuteInput(inputString).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString);
}
[WpfFact]
public async Task CheckHistoryPreviousWithAnEmptySubmission() {
//submit, submit, submit, up, up, up
const string inputString1 = "1 ";
const string inputString2 = " ";
const string inputString3 = "3 ";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
await InsertAndExecuteInput(inputString3).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
//second input was empty, so it wasn't added to history
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//has reached the top, no change
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[WpfFact]
public async Task CheckHistoryPreviousNotCircular()
{
//submit, submit, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//this up should not be circular
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[WpfFact]
public async Task CheckHistoryPreviousAfterSubmittingEntryFromHistory()
{
//submit, submit, submit, up, up, submit, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
await InsertAndExecuteInput(inputString3).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
await ExecuteInput().ConfigureAwait(true);
//history navigation should start from the last history pointer
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//has reached the top, no change
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[WpfFact]
public async Task CheckHistoryPreviousAfterSubmittingNewEntryWhileNavigatingHistory()
{
//submit, submit, up, up, submit new, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
SetActiveCode(inputString3);
AssertCurrentSubmission(inputString3);
await ExecuteInput().ConfigureAwait(true);
//History pointer should be reset. Previous should now bring up last entry
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//has reached the top, no change
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[WpfFact]
public async Task CheckHistoryNextNotCircular()
{
//submit, submit, down, up, down, down
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string empty = "";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
//Next should do nothing as history pointer is uninitialized and there is
//no next entry. Buffer should be empty
_operations.HistoryNext();
AssertCurrentSubmission(empty);
//Go back once entry
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
//Go fwd one entry - should do nothing as history pointer is at last entry
//buffer should have same value as before
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//Next should again do nothing as it is the last item, buffer should have the same value
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//This is to make sure the window doesn't crash
await ExecuteInput().ConfigureAwait(true);
AssertCurrentSubmission(empty);
}
[WpfFact]
public async Task CheckHistoryNextAfterSubmittingEntryFromHistory()
{
//submit, submit, submit, up, up, submit, down, down, down
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
await InsertAndExecuteInput(inputString3).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
//submit inputString2 again. Should be added at the end of history
await ExecuteInput().ConfigureAwait(true);
//history navigation should start from the last history pointer
_operations.HistoryNext();
AssertCurrentSubmission(inputString3);
//This next should take us to the InputString2 which was resubmitted
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//has reached the top, no change
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
}
[WpfFact]
public async Task CheckHistoryNextAfterSubmittingNewEntryWhileNavigatingHistory()
{
//submit, submit, up, up, submit new, down, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
const string empty = "";
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
SetActiveCode(inputString3);
AssertCurrentSubmission(inputString3);
await ExecuteInput().ConfigureAwait(true);
//History pointer should be reset. next should do nothing
_operations.HistoryNext();
AssertCurrentSubmission(empty);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
}
[WpfFact]
public async Task CheckUncommittedInputAfterNavigatingHistory()
{
//submit, submit, up, up, submit new, down, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string uncommittedInput = nameof(uncommittedInput);
await InsertAndExecuteInput(inputString1).ConfigureAwait(true);
await InsertAndExecuteInput(inputString2).ConfigureAwait(true);
//Add uncommitted input
SetActiveCode(uncommittedInput);
//Navigate history. This should save uncommitted input
_operations.HistoryPrevious();
//Navigate to next item at the end of history.
//This should bring back uncommitted input
_operations.HistoryNext();
AssertCurrentSubmission(uncommittedInput);
}
[WpfFact]
public async Task CheckHistoryPreviousAfterReset()
{
const string resetCommand1 = "#reset";
const string resetCommand2 = "#reset ";
await InsertAndExecuteInput(resetCommand1).ConfigureAwait(true);
await InsertAndExecuteInput(resetCommand2).ConfigureAwait(true);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand2);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1);
}
[WpfFact]
public async Task TestHistoryPrevious()
{
await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true);
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
}
[WpfFact]
public async Task TestHistoryNext()
{
await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true);
SetActiveCode("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryNext(); AssertCurrentSubmission("2");
_operations.HistoryNext(); AssertCurrentSubmission("3");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
}
[WpfFact]
public async Task TestHistoryPreviousWithPattern_NoMatch()
{
await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true);
_operations.HistoryPrevious("4"); AssertCurrentSubmission("");
_operations.HistoryPrevious("4"); AssertCurrentSubmission("");
}
[WpfFact]
public async Task TestHistoryPreviousWithPattern_PatternMaintained()
{
await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true);
_operations.HistoryPrevious("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry.
_operations.HistoryPrevious("12"); AssertCurrentSubmission("123");
_operations.HistoryPrevious("12"); AssertCurrentSubmission("123");
}
[WpfFact]
public async Task TestHistoryPreviousWithPattern_PatternDropped()
{
await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true);
_operations.HistoryPrevious("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry.
_operations.HistoryPrevious(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration.
_operations.HistoryPrevious(null); AssertCurrentSubmission("1");
}
[WpfFact]
public async Task TestHistoryPreviousWithPattern_PatternChanged()
{
await InsertAndExecuteInputs("10", "20", "15", "25").ConfigureAwait(true);
_operations.HistoryPrevious("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20");
}
[WpfFact]
public async Task TestHistoryNextWithPattern_NoMatch()
{
await InsertAndExecuteInputs("start", "1", "12", "123").ConfigureAwait(true);
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("4"); AssertCurrentSubmission("end");
_operations.HistoryNext("4"); AssertCurrentSubmission("end");
}
[WpfFact]
public async Task TestHistoryNextWithPattern_PatternMaintained()
{
await InsertAndExecuteInputs("start", "1", "12", "123").ConfigureAwait(true);
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry.
_operations.HistoryNext("12"); AssertCurrentSubmission("123");
_operations.HistoryNext("12"); AssertCurrentSubmission("end");
}
[WpfFact]
public async Task TestHistoryNextWithPattern_PatternDropped()
{
await InsertAndExecuteInputs("start", "3", "2", "1").ConfigureAwait(true);
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry.
_operations.HistoryNext(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration.
_operations.HistoryNext(null); AssertCurrentSubmission("end");
}
[WpfFact]
public async Task TestHistoryNextWithPattern_PatternChanged()
{
await InsertAndExecuteInputs("start", "25", "15", "20", "10").ConfigureAwait(true);
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("15");
_operations.HistoryPrevious(); AssertCurrentSubmission("25");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry.
_operations.HistoryNext("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry.
_operations.HistoryNext("2"); AssertCurrentSubmission("end");
}
[WpfFact]
public async Task TestHistorySearchPrevious()
{
await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true);
// Default search string is empty.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("1"); // Pattern is captured before this step.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("12");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
}
[WpfFact]
public async Task TestHistorySearchPreviousWithPattern()
{
await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true);
SetActiveCode("12");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); // Pattern is captured before this step.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
}
[WpfFact]
public async Task TestHistorySearchNextWithPattern()
{
await InsertAndExecuteInputs("12", "123", "12", "1").ConfigureAwait(true);
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistorySearchNext(); AssertCurrentSubmission("123"); // Pattern is captured before this step.
_operations.HistorySearchNext(); AssertCurrentSubmission("12");
_operations.HistorySearchNext(); AssertCurrentSubmission("end");
}
[WpfFact]
public async Task TestHistoryPreviousAndSearchPrevious()
{
await InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1").ConfigureAwait(true);
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryPrevious(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious.
}
[WpfFact]
public async Task TestHistoryPreviousAndSearchPrevious_ExplicitPattern()
{
await InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1").ConfigureAwait(true);
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious("2"); AssertCurrentSubmission("200");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious.
}
[WpfFact]
public async Task TestHistoryNextAndSearchNext()
{
await InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200").ConfigureAwait(true);
SetActiveCode("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistoryPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("30");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryNext(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext.
_operations.HistoryNext(); AssertCurrentSubmission("4");
}
[WpfFact]
public async Task TestHistoryNextAndSearchNext_ExplicitPattern()
{
await InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200").ConfigureAwait(true);
SetActiveCode("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistoryPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("30");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryNext("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext.
_operations.HistoryNext("2"); AssertCurrentSubmission("4");
}
}
}
| |
// 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.
/*============================================================
**
** Class: Privilege
**
** Purpose: Managed wrapper for NT privileges.
**
** Date: July 1, 2004
**
===========================================================*/
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Threading;
using CultureInfo = System.Globalization.CultureInfo;
using FCall = System.Security.Principal.Win32;
using Luid = Interop.Advapi32.LUID;
namespace System.Security.AccessControl
{
#if false
internal delegate void PrivilegedHelper();
#endif
internal sealed class Privilege
{
[ThreadStatic]
private static TlsContents tlsSlotData;
private static Dictionary<Luid, string> privileges = new Dictionary<Luid, string>();
private static Dictionary<string, Luid> luids = new Dictionary<string, Luid>();
private static ReaderWriterLockSlim privilegeLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private bool needToRevert = false;
private bool initialState = false;
private bool stateWasChanged = false;
private Luid luid;
private readonly Thread currentThread = Thread.CurrentThread;
private TlsContents tlsContents = null;
public const string CreateToken = "SeCreateTokenPrivilege";
public const string AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege";
public const string LockMemory = "SeLockMemoryPrivilege";
public const string IncreaseQuota = "SeIncreaseQuotaPrivilege";
public const string UnsolicitedInput = "SeUnsolicitedInputPrivilege";
public const string MachineAccount = "SeMachineAccountPrivilege";
public const string TrustedComputingBase = "SeTcbPrivilege";
public const string Security = "SeSecurityPrivilege";
public const string TakeOwnership = "SeTakeOwnershipPrivilege";
public const string LoadDriver = "SeLoadDriverPrivilege";
public const string SystemProfile = "SeSystemProfilePrivilege";
public const string SystemTime = "SeSystemtimePrivilege";
public const string ProfileSingleProcess = "SeProfileSingleProcessPrivilege";
public const string IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege";
public const string CreatePageFile = "SeCreatePagefilePrivilege";
public const string CreatePermanent = "SeCreatePermanentPrivilege";
public const string Backup = "SeBackupPrivilege";
public const string Restore = "SeRestorePrivilege";
public const string Shutdown = "SeShutdownPrivilege";
public const string Debug = "SeDebugPrivilege";
public const string Audit = "SeAuditPrivilege";
public const string SystemEnvironment = "SeSystemEnvironmentPrivilege";
public const string ChangeNotify = "SeChangeNotifyPrivilege";
public const string RemoteShutdown = "SeRemoteShutdownPrivilege";
public const string Undock = "SeUndockPrivilege";
public const string SyncAgent = "SeSyncAgentPrivilege";
public const string EnableDelegation = "SeEnableDelegationPrivilege";
public const string ManageVolume = "SeManageVolumePrivilege";
public const string Impersonate = "SeImpersonatePrivilege";
public const string CreateGlobal = "SeCreateGlobalPrivilege";
public const string TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege";
public const string ReserveProcessor = "SeReserveProcessorPrivilege";
//
// This routine is a wrapper around a hashtable containing mappings
// of privilege names to LUIDs
//
private static Luid LuidFromPrivilege(string privilege)
{
Luid luid;
luid.LowPart = 0;
luid.HighPart = 0;
//
// Look up the privilege LUID inside the cache
//
try
{
privilegeLock.EnterReadLock();
if (luids.ContainsKey(privilege))
{
luid = luids[privilege];
privilegeLock.ExitReadLock();
}
else
{
privilegeLock.ExitReadLock();
if (false == Interop.Advapi32.LookupPrivilegeValue(null, privilege, out luid))
{
int error = Marshal.GetLastWin32Error();
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error == Interop.Errors.ERROR_NO_SUCH_PRIVILEGE)
{
throw new ArgumentException(
SR.Format(SR.Argument_InvalidPrivilegeName,
privilege));
}
else
{
System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
privilegeLock.EnterWriteLock();
}
}
finally
{
if (privilegeLock.IsReadLockHeld)
{
privilegeLock.ExitReadLock();
}
if (privilegeLock.IsWriteLockHeld)
{
if (!luids.ContainsKey(privilege))
{
luids[privilege] = luid;
privileges[luid] = privilege;
}
privilegeLock.ExitWriteLock();
}
}
return luid;
}
private sealed class TlsContents : IDisposable
{
private bool disposed = false;
private int referenceCount = 1;
private SafeTokenHandle threadHandle = new SafeTokenHandle(IntPtr.Zero);
private bool isImpersonating = false;
private static volatile SafeTokenHandle processHandle = new SafeTokenHandle(IntPtr.Zero);
private static readonly object syncRoot = new object();
#region Constructor and Finalizer
public TlsContents()
{
int error = 0;
int cachingError = 0;
bool success = true;
if (processHandle.IsInvalid)
{
lock (syncRoot)
{
if (processHandle.IsInvalid)
{
SafeTokenHandle localProcessHandle;
if (false == Interop.Advapi32.OpenProcessToken(
Interop.Kernel32.GetCurrentProcess(),
TokenAccessLevels.Duplicate,
out localProcessHandle))
{
cachingError = Marshal.GetLastWin32Error();
success = false;
}
processHandle = localProcessHandle;
}
}
}
try
{
// Make the sequence non-interruptible
}
finally
{
try
{
//
// Open the thread token; if there is no thread token, get one from
// the process token by impersonating self.
//
SafeTokenHandle threadHandleBefore = this.threadHandle;
error = FCall.OpenThreadToken(
TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
WinSecurityContext.Process,
out this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
if (success == true)
{
this.threadHandle = threadHandleBefore;
if (error != Interop.Errors.ERROR_NO_TOKEN)
{
success = false;
}
System.Diagnostics.Debug.Assert(this.isImpersonating == false, "Incorrect isImpersonating state");
if (success == true)
{
error = 0;
if (false == Interop.Advapi32.DuplicateTokenEx(
processHandle,
TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero,
Interop.Advapi32.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
System.Security.Principal.TokenType.TokenImpersonation,
ref this.threadHandle))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
if (success == true)
{
error = FCall.SetThreadToken(this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
success = false;
}
}
if (success == true)
{
this.isImpersonating = true;
}
}
else
{
error = cachingError;
}
}
else
{
success = true;
}
}
finally
{
if (!success)
{
Dispose();
}
}
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED ||
error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
~TlsContents()
{
if (!this.disposed)
{
Dispose(false);
}
}
#endregion
#region IDisposable implementation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (this.disposed) return;
if (disposing)
{
if (this.threadHandle != null)
{
this.threadHandle.Dispose();
this.threadHandle = null;
}
}
if (this.isImpersonating)
{
Interop.Advapi32.RevertToSelf();
}
this.disposed = true;
}
#endregion
#region Reference Counting
public void IncrementReferenceCount()
{
this.referenceCount++;
}
public int DecrementReferenceCount()
{
int result = --this.referenceCount;
if (result == 0)
{
Dispose();
}
return result;
}
public int ReferenceCountValue
{
get { return this.referenceCount; }
}
#endregion
#region Properties
public SafeTokenHandle ThreadHandle
{
[System.Security.SecurityCritical] // auto-generated
get
{ return this.threadHandle; }
}
public bool IsImpersonating
{
get { return this.isImpersonating; }
}
#endregion
}
#region Constructors
public Privilege(string privilegeName)
{
if (privilegeName == null)
{
throw new ArgumentNullException(nameof(privilegeName));
}
Contract.EndContractBlock();
this.luid = LuidFromPrivilege(privilegeName);
}
#endregion
//
// Finalizer simply ensures that the privilege was not leaked
//
~Privilege()
{
System.Diagnostics.Debug.Assert(!this.needToRevert, "Must revert privileges that you alter!");
if (this.needToRevert)
{
Revert();
}
}
#region Public interface
public void Enable()
{
this.ToggleState(true);
}
public bool NeedToRevert
{
get { return this.needToRevert; }
}
#endregion
// [SecurityPermission( SecurityAction.Demand, TogglePrivileges=true )]
private void ToggleState(bool enable)
{
int error = 0;
//
// All privilege operations must take place on the same thread
//
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
//
// This privilege was already altered and needs to be reverted before it can be altered again
//
if (this.needToRevert)
{
throw new InvalidOperationException(SR.InvalidOperation_MustRevertPrivilege);
}
//
// Need to make this block of code non-interruptible so that it would preserve
// consistency of thread oken state even in the face of catastrophic exceptions
//
try
{
//
// The payload is entirely in the finally block
// This is how we ensure that the code will not be
// interrupted by catastrophic exceptions
//
}
finally
{
try
{
//
// Retrieve TLS state
//
this.tlsContents = tlsSlotData;
if (this.tlsContents == null)
{
this.tlsContents = new TlsContents();
tlsSlotData = this.tlsContents;
}
else
{
this.tlsContents.IncrementReferenceCount();
}
Interop.Advapi32.LUID_AND_ATTRIBUTES luidAndAttrs = new Interop.Advapi32.LUID_AND_ATTRIBUTES();
luidAndAttrs.Luid = this.luid;
luidAndAttrs.Attributes = enable ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED;
Interop.Advapi32.TOKEN_PRIVILEGE newState = new Interop.Advapi32.TOKEN_PRIVILEGE();
newState.PrivilegeCount = 1;
newState.Privileges[0] = luidAndAttrs;
Interop.Advapi32.TOKEN_PRIVILEGE previousState = new Interop.Advapi32.TOKEN_PRIVILEGE();
uint previousSize = 0;
//
// Place the new privilege on the thread token and remember the previous state.
//
if (false == Interop.Advapi32.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
ref newState,
(uint)Marshal.SizeOf(previousState),
ref previousState,
ref previousSize))
{
error = Marshal.GetLastWin32Error();
}
else if (Interop.Errors.ERROR_NOT_ALL_ASSIGNED == Marshal.GetLastWin32Error())
{
error = Interop.Errors.ERROR_NOT_ALL_ASSIGNED;
}
else
{
//
// This is the initial state that revert will have to go back to
//
this.initialState = ((previousState.Privileges[0].Attributes & Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED) != 0);
//
// Remember whether state has changed at all
//
this.stateWasChanged = (this.initialState != enable);
//
// If we had to impersonate, or if the privilege state changed we'll need to revert
//
this.needToRevert = this.tlsContents.IsImpersonating || this.stateWasChanged;
}
}
finally
{
if (!this.needToRevert)
{
this.Reset();
}
}
}
if (error == Interop.Errors.ERROR_NOT_ALL_ASSIGNED)
{
throw new PrivilegeNotHeldException(privileges[this.luid]);
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED ||
error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
// [SecurityPermission( SecurityAction.Demand, TogglePrivileges=true )]
public void Revert()
{
int error = 0;
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
if (!this.NeedToRevert)
{
return;
}
//
// This code must be eagerly prepared and non-interruptible.
//
try
{
//
// The payload is entirely in the finally block
// This is how we ensure that the code will not be
// interrupted by catastrophic exceptions
//
}
finally
{
bool success = true;
try
{
//
// Only call AdjustTokenPrivileges if we're not going to be reverting to self,
// on this Revert, since doing the latter obliterates the thread token anyway
//
if (this.stateWasChanged &&
(this.tlsContents.ReferenceCountValue > 1 ||
!this.tlsContents.IsImpersonating))
{
Interop.Advapi32.LUID_AND_ATTRIBUTES luidAndAttrs = new Interop.Advapi32.LUID_AND_ATTRIBUTES();
luidAndAttrs.Luid = this.luid;
luidAndAttrs.Attributes = (this.initialState ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED);
Interop.Advapi32.TOKEN_PRIVILEGE newState = new Interop.Advapi32.TOKEN_PRIVILEGE();
newState.PrivilegeCount = 1;
newState.Privileges[0] = luidAndAttrs;
Interop.Advapi32.TOKEN_PRIVILEGE previousState = new Interop.Advapi32.TOKEN_PRIVILEGE();
uint previousSize = 0;
if (false == Interop.Advapi32.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
ref newState,
(uint)Marshal.SizeOf(previousState),
ref previousState,
ref previousSize))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
}
finally
{
if (success)
{
this.Reset();
}
}
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}
#if false
public static void RunWithPrivilege( string privilege, bool enabled, PrivilegedHelper helper )
{
if ( helper == null )
{
throw new ArgumentNullException( "helper" );
}
Contract.EndContractBlock();
Privilege p = new Privilege( privilege );
try
{
if (enabled)
{
p.Enable();
}
else
{
p.Disable();
}
helper();
}
finally
{
p.Revert();
}
}
#endif
private void Reset()
{
this.stateWasChanged = false;
this.initialState = false;
this.needToRevert = false;
if (this.tlsContents != null)
{
if (0 == this.tlsContents.DecrementReferenceCount())
{
this.tlsContents = null;
tlsSlotData = null;
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace Southwind{
/// <summary>
/// Strongly-typed collection for the AlphabeticalListOfProduct class.
/// </summary>
[Serializable]
public partial class AlphabeticalListOfProductCollection : ReadOnlyList<AlphabeticalListOfProduct, AlphabeticalListOfProductCollection>
{
public AlphabeticalListOfProductCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the alphabetical list of products view.
/// </summary>
[Serializable]
public partial class AlphabeticalListOfProduct : ReadOnlyRecord<AlphabeticalListOfProduct>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("alphabetical list of products", TableType.View, DataService.GetInstance("Southwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 10;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = false;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema);
colvarSupplierID.ColumnName = "SupplierID";
colvarSupplierID.DataType = DbType.Int32;
colvarSupplierID.MaxLength = 10;
colvarSupplierID.AutoIncrement = false;
colvarSupplierID.IsNullable = true;
colvarSupplierID.IsPrimaryKey = false;
colvarSupplierID.IsForeignKey = false;
colvarSupplierID.IsReadOnly = false;
schema.Columns.Add(colvarSupplierID);
TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema);
colvarCategoryID.ColumnName = "CategoryID";
colvarCategoryID.DataType = DbType.Int32;
colvarCategoryID.MaxLength = 10;
colvarCategoryID.AutoIncrement = false;
colvarCategoryID.IsNullable = true;
colvarCategoryID.IsPrimaryKey = false;
colvarCategoryID.IsForeignKey = false;
colvarCategoryID.IsReadOnly = false;
schema.Columns.Add(colvarCategoryID);
TableSchema.TableColumn colvarQuantityPerUnit = new TableSchema.TableColumn(schema);
colvarQuantityPerUnit.ColumnName = "QuantityPerUnit";
colvarQuantityPerUnit.DataType = DbType.String;
colvarQuantityPerUnit.MaxLength = 20;
colvarQuantityPerUnit.AutoIncrement = false;
colvarQuantityPerUnit.IsNullable = true;
colvarQuantityPerUnit.IsPrimaryKey = false;
colvarQuantityPerUnit.IsForeignKey = false;
colvarQuantityPerUnit.IsReadOnly = false;
schema.Columns.Add(colvarQuantityPerUnit);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Decimal;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = true;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarUnitsInStock = new TableSchema.TableColumn(schema);
colvarUnitsInStock.ColumnName = "UnitsInStock";
colvarUnitsInStock.DataType = DbType.Int16;
colvarUnitsInStock.MaxLength = 5;
colvarUnitsInStock.AutoIncrement = false;
colvarUnitsInStock.IsNullable = true;
colvarUnitsInStock.IsPrimaryKey = false;
colvarUnitsInStock.IsForeignKey = false;
colvarUnitsInStock.IsReadOnly = false;
schema.Columns.Add(colvarUnitsInStock);
TableSchema.TableColumn colvarUnitsOnOrder = new TableSchema.TableColumn(schema);
colvarUnitsOnOrder.ColumnName = "UnitsOnOrder";
colvarUnitsOnOrder.DataType = DbType.Int16;
colvarUnitsOnOrder.MaxLength = 5;
colvarUnitsOnOrder.AutoIncrement = false;
colvarUnitsOnOrder.IsNullable = true;
colvarUnitsOnOrder.IsPrimaryKey = false;
colvarUnitsOnOrder.IsForeignKey = false;
colvarUnitsOnOrder.IsReadOnly = false;
schema.Columns.Add(colvarUnitsOnOrder);
TableSchema.TableColumn colvarReorderLevel = new TableSchema.TableColumn(schema);
colvarReorderLevel.ColumnName = "ReorderLevel";
colvarReorderLevel.DataType = DbType.Int16;
colvarReorderLevel.MaxLength = 5;
colvarReorderLevel.AutoIncrement = false;
colvarReorderLevel.IsNullable = true;
colvarReorderLevel.IsPrimaryKey = false;
colvarReorderLevel.IsForeignKey = false;
colvarReorderLevel.IsReadOnly = false;
schema.Columns.Add(colvarReorderLevel);
TableSchema.TableColumn colvarDiscontinued = new TableSchema.TableColumn(schema);
colvarDiscontinued.ColumnName = "Discontinued";
colvarDiscontinued.DataType = DbType.Boolean;
colvarDiscontinued.MaxLength = 4;
colvarDiscontinued.AutoIncrement = false;
colvarDiscontinued.IsNullable = false;
colvarDiscontinued.IsPrimaryKey = false;
colvarDiscontinued.IsForeignKey = false;
colvarDiscontinued.IsReadOnly = false;
schema.Columns.Add(colvarDiscontinued);
TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema);
colvarCategoryName.ColumnName = "CategoryName";
colvarCategoryName.DataType = DbType.String;
colvarCategoryName.MaxLength = 15;
colvarCategoryName.AutoIncrement = false;
colvarCategoryName.IsNullable = false;
colvarCategoryName.IsPrimaryKey = false;
colvarCategoryName.IsForeignKey = false;
colvarCategoryName.IsReadOnly = false;
schema.Columns.Add(colvarCategoryName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Southwind"].AddSchema("alphabetical list of products",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public AlphabeticalListOfProduct()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public AlphabeticalListOfProduct(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public AlphabeticalListOfProduct(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public AlphabeticalListOfProduct(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get
{
return GetColumnValue<int>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("SupplierID")]
[Bindable(true)]
public int? SupplierID
{
get
{
return GetColumnValue<int?>("SupplierID");
}
set
{
SetColumnValue("SupplierID", value);
}
}
[XmlAttribute("CategoryID")]
[Bindable(true)]
public int? CategoryID
{
get
{
return GetColumnValue<int?>("CategoryID");
}
set
{
SetColumnValue("CategoryID", value);
}
}
[XmlAttribute("QuantityPerUnit")]
[Bindable(true)]
public string QuantityPerUnit
{
get
{
return GetColumnValue<string>("QuantityPerUnit");
}
set
{
SetColumnValue("QuantityPerUnit", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal? UnitPrice
{
get
{
return GetColumnValue<decimal?>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("UnitsInStock")]
[Bindable(true)]
public short? UnitsInStock
{
get
{
return GetColumnValue<short?>("UnitsInStock");
}
set
{
SetColumnValue("UnitsInStock", value);
}
}
[XmlAttribute("UnitsOnOrder")]
[Bindable(true)]
public short? UnitsOnOrder
{
get
{
return GetColumnValue<short?>("UnitsOnOrder");
}
set
{
SetColumnValue("UnitsOnOrder", value);
}
}
[XmlAttribute("ReorderLevel")]
[Bindable(true)]
public short? ReorderLevel
{
get
{
return GetColumnValue<short?>("ReorderLevel");
}
set
{
SetColumnValue("ReorderLevel", value);
}
}
[XmlAttribute("Discontinued")]
[Bindable(true)]
public bool Discontinued
{
get
{
return GetColumnValue<bool>("Discontinued");
}
set
{
SetColumnValue("Discontinued", value);
}
}
[XmlAttribute("CategoryName")]
[Bindable(true)]
public string CategoryName
{
get
{
return GetColumnValue<string>("CategoryName");
}
set
{
SetColumnValue("CategoryName", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string SupplierID = @"SupplierID";
public static string CategoryID = @"CategoryID";
public static string QuantityPerUnit = @"QuantityPerUnit";
public static string UnitPrice = @"UnitPrice";
public static string UnitsInStock = @"UnitsInStock";
public static string UnitsOnOrder = @"UnitsOnOrder";
public static string ReorderLevel = @"ReorderLevel";
public static string Discontinued = @"Discontinued";
public static string CategoryName = @"CategoryName";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudioTools.Project
{
// This class is No longer used by project system, retained for backwards for languages
// which have already shipped this public type.
#if SHAREDPROJECT_OLESERVICEPROVIDER
public class OleServiceProvider : IOleServiceProvider, IDisposable {
#region Public Types
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public delegate object ServiceCreatorCallback(Type serviceType);
#endregion
#region Private Types
private class ServiceData : IDisposable {
private Type serviceType;
private object instance;
private ServiceCreatorCallback creator;
private bool shouldDispose;
public ServiceData(Type serviceType, object instance, ServiceCreatorCallback callback, bool shouldDispose) {
Utilities.ArgumentNotNull("serviceType", serviceType);
if ((null == instance) && (null == callback)) {
throw new ArgumentNullException("instance");
}
this.serviceType = serviceType;
this.instance = instance;
this.creator = callback;
this.shouldDispose = shouldDispose;
}
public object ServiceInstance {
get {
if (null == instance) {
Debug.Assert(serviceType != null);
instance = creator(serviceType);
}
return instance;
}
}
public Guid Guid {
get { return serviceType.GUID; }
}
public void Dispose() {
if ((shouldDispose) && (null != instance)) {
IDisposable disp = instance as IDisposable;
if (null != disp) {
disp.Dispose();
}
instance = null;
}
creator = null;
GC.SuppressFinalize(this);
}
}
#endregion
#region fields
private Dictionary<Guid, ServiceData> services = new Dictionary<Guid, ServiceData>();
private bool isDisposed;
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
#endregion
#region ctors
public OleServiceProvider() {
}
#endregion
#region IOleServiceProvider Members
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) {
ppvObject = (IntPtr)0;
int hr = VSConstants.S_OK;
ServiceData serviceInstance = null;
if (services != null && services.ContainsKey(guidService)) {
serviceInstance = services[guidService];
}
if (serviceInstance == null) {
return VSConstants.E_NOINTERFACE;
}
// Now check to see if the user asked for an IID other than
// IUnknown. If so, we must do another QI.
//
if (riid.Equals(NativeMethods.IID_IUnknown)) {
object inst = serviceInstance.ServiceInstance;
if (inst == null) {
return VSConstants.E_NOINTERFACE;
}
ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance);
} else {
IntPtr pUnk = IntPtr.Zero;
try {
pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance);
hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject);
} finally {
if (pUnk != IntPtr.Zero) {
Marshal.Release(pUnk);
}
}
}
return hr;
}
#endregion
#region Dispose
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Adds the given service to the service container.
/// </summary>
/// <param name="serviceType">The type of the service to add.</param>
/// <param name="serviceInstance">An instance of the service.</param>
/// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The services created here will be disposed in the Dispose method of this type.")]
public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance) {
// Create the description of this service. Note that we don't do any validation
// of the parameter here because the constructor of ServiceData will do it for us.
ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance);
// Now add the service desctription to the dictionary.
AddService(service);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The services created here will be disposed in the Dispose method of this type.")]
public void AddService(Type serviceType, ServiceCreatorCallback callback, bool shouldDisposeServiceInstance) {
// Create the description of this service. Note that we don't do any validation
// of the parameter here because the constructor of ServiceData will do it for us.
ServiceData service = new ServiceData(serviceType, null, callback, shouldDisposeServiceInstance);
// Now add the service desctription to the dictionary.
AddService(service);
}
private void AddService(ServiceData data) {
// Make sure that the collection of services is created.
if (null == services) {
services = new Dictionary<Guid, ServiceData>();
}
// Disallow the addition of duplicate services.
if (services.ContainsKey(data.Guid)) {
throw new InvalidOperationException();
}
services.Add(data.Guid, data);
}
/// <devdoc>
/// Removes the given service type from the service container.
/// </devdoc>
public void RemoveService(Type serviceType) {
Utilities.ArgumentNotNull("serviceType", serviceType);
if (services.ContainsKey(serviceType.GUID)) {
services.Remove(serviceType.GUID);
}
}
#region helper methods
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing) {
// Everybody can go here.
if (!this.isDisposed) {
// Synchronize calls to the Dispose simulteniously.
lock (Mutex) {
if (disposing) {
// Remove all our services
if (services != null) {
foreach (ServiceData data in services.Values) {
data.Dispose();
}
services.Clear();
services = null;
}
}
this.isDisposed = true;
}
}
}
#endregion
}
#endif
}
| |
using Microsoft.AppCenter.Analytics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.AccessCache;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WinIRC.Ui;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WinIRC
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class BehaviourSettingsView : BaseSettingsPage
{
List<String> UserListClickSettings = new List<string> { "Mention user in channel", "PM the user", "Show the context menu" };
public BehaviourSettingsView()
{
this.InitializeComponent();
Title = "Behaviour";
LoadSettings();
}
private async void LoadSettings()
{
UserListClick.ItemsSource = UserListClickSettings;
if (Config.Contains(Config.UserListClick))
{
this.UserListClick.SelectedIndex = Config.GetInt(Config.UserListClick);
}
else
{
Config.SetInt(Config.UserListClick, 0);
this.UserListClick.SelectedIndex = 0;
}
if (Config.Contains(Config.SwitchOnJoin))
{
this.AutoChannelSwitch.IsOn = Config.GetBoolean(Config.SwitchOnJoin);
}
else
{
Config.SetBoolean(Config.SwitchOnJoin, true);
this.AutoChannelSwitch.IsOn = true;
}
if (Config.Contains(Config.UseTabs))
{
this.TabsSwitch.IsOn = Config.GetBoolean(Config.UseTabs);
}
else
{
Config.SetBoolean(Config.UseTabs, true);
this.TabsSwitch.IsOn = true;
}
if (Config.Contains(Config.EnableLogs))
{
this.LogChannels.IsOn = Config.GetBoolean(Config.EnableLogs);
}
else
{
Config.SetBoolean(Config.EnableLogs, false);
this.LogChannels.IsOn = false;
}
if (Config.Contains(Config.UploadFile))
{
FileUploadURL.Text = Config.GetString(Config.UploadFile);
}
else
{
Config.SetString(Config.UploadFile, "https://0x0.st");
FileUploadURL.Text = "https://0x0.st";
}
if (Config.Contains(Config.PasteImage))
{
ImageUploadURL.Text = Config.GetString(Config.PasteImage);
}
if (Config.Contains(Config.PasteText))
{
TextUploadURL.Text = Config.GetString(Config.PasteText);
}
this.AnalyticsSwitch.IsOn = await Analytics.IsEnabledAsync();
this.SettingsLoaded = true;
}
private void UserListClick_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetInt(Config.UserListClick, UserListClick.SelectedIndex);
}
private void AutoChannelSwitch_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.SwitchOnJoin, AutoChannelSwitch.IsOn);
}
private void TabsSwitch_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.UseTabs, TabsSwitch.IsOn);
base.UpdateUi();
}
private void LogFolder_Click(object sender, RoutedEventArgs e)
{
ChooseFolder();
}
private async void ChooseFolder()
{
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
// Application now has read/write access to all contents in the picked folder
// (including other sub-folder contents)
StorageApplicationPermissions.FutureAccessList.AddOrReplace(Config.LogsFolder, folder);
}
else
{
LogChannels.IsOn = false;
}
}
private void LogChannels_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetBoolean(Config.EnableLogs, LogChannels.IsOn);
if (LogChannels.IsOn)
{
ChooseFolder();
}
}
private void AnalyticsSwitch_Toggled(object sender, RoutedEventArgs e)
{
if (!SettingsLoaded)
return;
Analytics.SetEnabledAsync(AnalyticsSwitch.IsOn);
}
private void ImageUploadURL_TextChanged(object sender, TextChangedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetString(Config.PasteImage, ImageUploadURL.Text);
}
private void TextUploadURL_TextChanged(object sender, TextChangedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetString(Config.PasteText, TextUploadURL.Text);
}
private void FileUploadURL_TextChanged(object sender, TextChangedEventArgs e)
{
if (!SettingsLoaded)
return;
Config.SetString(Config.UploadFile, FileUploadURL.Text);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ChainTests
{
internal static bool CanModifyStores { get; } = TestEnvironmentConfiguration.CanModifyStores;
private static bool TrustsMicrosoftDotComRoot
{
get
{
// Verifies that the microsoft.com certs build with only the certificates in the root store
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
return chain.Build(microsoftDotCom);
}
}
}
[Fact]
public static void BuildChain()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
// Halfway between microsoftDotCom's NotBefore and NotAfter
// This isn't a boundary condition test.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Chain built validly");
// The chain should have 3 members
Assert.Equal(3, chain.ChainElements.Count);
// These are the three specific members.
Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void VerifyChainFromHandle()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Source chain built validly");
Assert.Equal(3, chain.ChainElements.Count);
using (var chainHolder2 = new ChainHolder(chain.ChainContext))
{
X509Chain chain2 = chainHolder2.Chain;
Assert.NotSame(chain, chain2);
Assert.Equal(chain.ChainContext, chain2.ChainContext);
Assert.Equal(3, chain2.ChainElements.Count);
Assert.NotSame(chain.ChainElements[0], chain2.ChainElements[0]);
Assert.NotSame(chain.ChainElements[1], chain2.ChainElements[1]);
Assert.NotSame(chain.ChainElements[2], chain2.ChainElements[2]);
Assert.Equal(microsoftDotCom, chain2.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain2.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain2.ChainElements[2].Certificate);
// ChainPolicy is not carried over from the Chain(IntPtr) constructor
Assert.NotEqual(chain.ChainPolicy.VerificationFlags, chain2.ChainPolicy.VerificationFlags);
Assert.NotEqual(chain.ChainPolicy.VerificationTime, chain2.ChainPolicy.VerificationTime);
Assert.NotEqual(chain.ChainPolicy.RevocationMode, chain2.ChainPolicy.RevocationMode);
Assert.Equal(X509VerificationFlags.NoFlag, chain2.ChainPolicy.VerificationFlags);
// Re-set the ChainPolicy properties
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain2.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain2.Build(microsoftDotCom);
Assert.True(valid, "Cloned chain built validly");
}
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalFact(nameof(CanModifyStores))]
public static void VerifyChainFromHandle_Unix()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero));
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void TestDispose()
{
X509Chain chain;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
chain = chainHolder.Chain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(microsoftDotCom);
Assert.NotEqual(IntPtr.Zero, chain.ChainContext);
}
// No exception thrown for accessing ChainContext on disposed chain
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
[Fact]
// Crashing on macOS 10.13 Beta
[ActiveIssue(21436, TestPlatforms.OSX)]
public static void TestResetMethod()
{
using (var sampleCert = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(sampleCert);
bool valid = chain.Build(sampleCert);
Assert.False(valid);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain.Build(sampleCert);
Assert.True(valid, "Chain built validly");
Assert.Equal(1, chain.ChainElements.Count);
chain.Reset();
Assert.Equal(0, chain.ChainElements.Count);
// ChainPolicy did not reset (for desktop compat)
Assert.Equal(X509VerificationFlags.AllowUnknownCertificateAuthority, chain.ChainPolicy.VerificationFlags);
valid = chain.Build(sampleCert);
Assert.Equal(1, chain.ChainElements.Count);
// This succeeds because ChainPolicy did not reset
Assert.True(valid, "Chain built validly after reset");
}
}
/// <summary>
/// Tests that when a certificate chain has a root certification which is not trusted by the trust provider,
/// Build returns false and a ChainStatus returns UntrustedRoot
/// </summary>
[Fact]
[OuterLoop]
public static void BuildChainExtraStoreUntrustedRoot()
{
using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword))
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet))
using (var chainHolder = new ChainHolder())
{
X509Certificate2Collection collection = ic.Collection;
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.AddRange(collection);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);
bool valid = chain.Build(testCert);
Assert.False(valid);
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
}
}
public static IEnumerable<object[]> VerifyExpressionData()
{
// The test will be using the chain for TestData.MicrosoftDotComSslCertBytes
// The leaf cert (microsoft.com) is valid from 2014-10-15 00:00:00Z to 2016-10-15 23:59:59Z
DateTime[] validTimes =
{
// The NotBefore value
new DateTime(2014, 10, 15, 0, 0, 0, DateTimeKind.Utc),
// One second before the NotAfter value
new DateTime(2016, 10, 15, 23, 59, 58, DateTimeKind.Utc),
};
// The NotAfter value as a boundary condition differs on Windows and OpenSSL.
// Windows considers it valid (<= NotAfter).
// OpenSSL considers it invalid (< NotAfter), with a comment along the lines of
// "it'll be invalid in a millisecond, why bother with the <="
// So that boundary condition is not being tested.
DateTime[] invalidTimes =
{
// One second before the NotBefore time
new DateTime(2014, 10, 14, 23, 59, 59, DateTimeKind.Utc),
// One second after the NotAfter time
new DateTime(2016, 10, 16, 0, 0, 0, DateTimeKind.Utc),
};
List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3);
// Build (date, result, kind) tuples. The kind is used to help describe the test case.
// The DateTime format that xunit uses does show a difference in the DateTime itself, but
// having the Kind be a separate parameter just helps.
foreach (DateTime utcTime in validTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, true, utcTime.Kind });
testCases.Add(new object[] { local, true, local.Kind });
testCases.Add(new object[] { unspecified, true, unspecified.Kind });
}
foreach (DateTime utcTime in invalidTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, false, utcTime.Kind });
testCases.Add(new object[] { local, false, local.Kind });
testCases.Add(new object[] { unspecified, false, unspecified.Kind });
}
return testCases;
}
[Theory]
[MemberData(nameof(VerifyExpressionData))]
public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind)
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// Ignore anything except NotTimeValid
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = verificationTime;
bool builtSuccessfully = chain.Build(microsoftDotCom);
Assert.Equal(shouldBeValid, builtSuccessfully);
// If we failed to build the chain, ensure that NotTimeValid is one of the reasons.
if (!shouldBeValid)
{
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
}
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_Match()
{
using (var msCer = new X509Certificate2(TestData.MsCertificate))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2);
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(msCer);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Gibberish. (Code Signing + ".1")
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_Match()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(cert);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[ConditionalFact(nameof(TrustsMicrosoftDotComRoot), nameof(CanModifyStores))]
[OuterLoop(/* Modifies user certificate store */)]
public static void BuildChain_MicrosoftDotCom_WithRootCertInUserAndSystemRootCertStores()
{
// Verifies that when the same root cert is placed in both a user and machine root certificate store,
// any certs chain building to that root cert will build correctly
//
// We use a copy of the microsoft.com SSL certs and root certs to validate that the chain can build
// successfully
bool shouldInstallCertToUserStore = true;
bool installedCertToUserStore = false;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// Check that microsoft.com's root certificate IS installed in the machine root store as a sanity step
using (var machineRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
machineRootStore.Open(OpenFlags.ReadOnly);
bool foundCert = false;
foreach (var machineCert in machineRootStore.Certificates)
{
if (machineCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
machineCert.Dispose();
}
Assert.True(foundCert, string.Format("Did not find expected certificate with thumbprint '{0}' in the machine root store", microsoftDotComRoot.Thumbprint));
}
// Concievably at this point there could still be something wrong and we still don't chain build correctly - if that's
// the case, then there's likely something wrong with the machine. Validating that happy path is out of scope
// of this particular test.
// Check that microsoft.com's root certificate is NOT installed on in the user cert store as a sanity step
// We won't try to install the microsoft.com root cert into the user root store if it's already there
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
{
userRootStore.Open(OpenFlags.ReadOnly);
foreach (var userCert in userRootStore.Certificates)
{
bool foundCert = false;
if (userCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
userCert.Dispose();
if (foundCert)
{
shouldInstallCertToUserStore = false;
}
}
}
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
using (var chainHolder = new ChainHolder())
{
try
{
if (shouldInstallCertToUserStore)
{
try
{
userRootStore.Open(OpenFlags.ReadWrite);
}
catch (CryptographicException)
{
return;
}
userRootStore.Add(microsoftDotComRoot); // throws CryptographicException
installedCertToUserStore = true;
}
X509Chain chainValidator = chainHolder.Chain;
chainValidator.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chainValidator.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool chainBuildResult = chainValidator.Build(microsoftDotCom);
StringBuilder builder = new StringBuilder();
foreach (var status in chainValidator.ChainStatus)
{
builder.AppendFormat("{0} {1}{2}", status.Status, status.StatusInformation, Environment.NewLine);
}
Assert.True(chainBuildResult,
string.Format("Certificate chain build failed. ChainStatus is:{0}{1}", Environment.NewLine, builder.ToString()));
}
finally
{
if (installedCertToUserStore)
{
userRootStore.Remove(microsoftDotComRoot);
}
}
}
}
}
[Fact]
[OuterLoop( /* May require using the network, to download CRLs and intermediates */)]
public static void VerifyWithRevocation()
{
using (var cert = new X509Certificate2(Path.Combine("TestData", "MS.cer")))
using (var onlineChainHolder = new ChainHolder())
using (var offlineChainHolder = new ChainHolder())
{
X509Chain onlineChain = onlineChainHolder.Chain;
X509Chain offlineChain = offlineChainHolder.Chain;
onlineChain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
onlineChain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
onlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
onlineChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
// Attempt the online test a couple of times, in case there was just a CRL
// download failure.
const int RetryLimit = 3;
bool valid = false;
for (int i = 0; i < RetryLimit; i++)
{
valid = onlineChain.Build(cert);
if (valid)
{
break;
}
for (int j = 0; j < onlineChain.ChainElements.Count; j++)
{
X509ChainElement chainElement = onlineChain.ChainElements[j];
// Since `NoError` gets mapped as the empty array, just look for non-empty arrays
if (chainElement.ChainElementStatus.Length > 0)
{
X509ChainStatusFlags allFlags = chainElement.ChainElementStatus.Aggregate(
X509ChainStatusFlags.NoError,
(cur, status) => cur | status.Status);
Console.WriteLine(
$"{nameof(VerifyWithRevocation)}: online attempt {i} - errors at depth {j}: {allFlags}");
}
chainElement.Certificate.Dispose();
}
Thread.Sleep(1000); // For network flakiness
}
if (TestEnvironmentConfiguration.RunManualTests)
{
Assert.True(valid, $"Online Chain Built Validly within {RetryLimit} tries");
}
else if (!valid)
{
Console.WriteLine($"SKIP [{nameof(VerifyWithRevocation)}]: Chain failed to build within {RetryLimit} tries.");
}
// Since the network was enabled, we should get the whole chain.
Assert.Equal(3, onlineChain.ChainElements.Count);
Assert.Equal(0, onlineChain.ChainElements[0].ChainElementStatus.Length);
Assert.Equal(0, onlineChain.ChainElements[1].ChainElementStatus.Length);
// The root CA is not expected to be installed on everyone's machines,
// so allow for it to report UntrustedRoot, but nothing else..
X509ChainStatus[] rootElementStatus = onlineChain.ChainElements[2].ChainElementStatus;
if (rootElementStatus.Length != 0)
{
Assert.Equal(1, rootElementStatus.Length);
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, rootElementStatus[0].Status);
}
// Now that everything is cached, try again in Offline mode.
offlineChain.ChainPolicy.VerificationFlags = onlineChain.ChainPolicy.VerificationFlags;
offlineChain.ChainPolicy.VerificationTime = onlineChain.ChainPolicy.VerificationTime;
offlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
offlineChain.ChainPolicy.RevocationFlag = onlineChain.ChainPolicy.RevocationFlag;
valid = offlineChain.Build(cert);
Assert.True(valid, "Offline Chain Built Validly");
// Everything should look just like the online chain:
Assert.Equal(onlineChain.ChainElements.Count, offlineChain.ChainElements.Count);
for (int i = 0; i < offlineChain.ChainElements.Count; i++)
{
X509ChainElement onlineElement = onlineChain.ChainElements[i];
X509ChainElement offlineElement = offlineChain.ChainElements[i];
Assert.Equal(onlineElement.ChainElementStatus, offlineElement.ChainElementStatus);
Assert.Equal(onlineElement.Certificate, offlineElement.Certificate);
}
}
}
[Fact]
public static void Create()
{
using (var chain = X509Chain.Create())
Assert.NotNull(chain);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnLogPrestacion class.
/// </summary>
[Serializable]
public partial class PnLogPrestacionCollection : ActiveList<PnLogPrestacion, PnLogPrestacionCollection>
{
public PnLogPrestacionCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnLogPrestacionCollection</returns>
public PnLogPrestacionCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnLogPrestacion o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_log_prestacion table.
/// </summary>
[Serializable]
public partial class PnLogPrestacion : ActiveRecord<PnLogPrestacion>, IActiveRecord
{
#region .ctors and Default Settings
public PnLogPrestacion()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnLogPrestacion(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnLogPrestacion(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnLogPrestacion(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_log_prestacion", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLogPrestacion = new TableSchema.TableColumn(schema);
colvarIdLogPrestacion.ColumnName = "id_log_prestacion";
colvarIdLogPrestacion.DataType = DbType.Int32;
colvarIdLogPrestacion.MaxLength = 0;
colvarIdLogPrestacion.AutoIncrement = true;
colvarIdLogPrestacion.IsNullable = false;
colvarIdLogPrestacion.IsPrimaryKey = true;
colvarIdLogPrestacion.IsForeignKey = false;
colvarIdLogPrestacion.IsReadOnly = false;
colvarIdLogPrestacion.DefaultSetting = @"";
colvarIdLogPrestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLogPrestacion);
TableSchema.TableColumn colvarIdPrestacion = new TableSchema.TableColumn(schema);
colvarIdPrestacion.ColumnName = "id_prestacion";
colvarIdPrestacion.DataType = DbType.Int32;
colvarIdPrestacion.MaxLength = 0;
colvarIdPrestacion.AutoIncrement = false;
colvarIdPrestacion.IsNullable = false;
colvarIdPrestacion.IsPrimaryKey = false;
colvarIdPrestacion.IsForeignKey = false;
colvarIdPrestacion.IsReadOnly = false;
colvarIdPrestacion.DefaultSetting = @"";
colvarIdPrestacion.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPrestacion);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = true;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema);
colvarTipo.ColumnName = "tipo";
colvarTipo.DataType = DbType.AnsiString;
colvarTipo.MaxLength = -1;
colvarTipo.AutoIncrement = false;
colvarTipo.IsNullable = true;
colvarTipo.IsPrimaryKey = false;
colvarTipo.IsForeignKey = false;
colvarTipo.IsReadOnly = false;
colvarTipo.DefaultSetting = @"";
colvarTipo.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipo);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = -1;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema);
colvarUsuario.ColumnName = "usuario";
colvarUsuario.DataType = DbType.AnsiString;
colvarUsuario.MaxLength = -1;
colvarUsuario.AutoIncrement = false;
colvarUsuario.IsNullable = true;
colvarUsuario.IsPrimaryKey = false;
colvarUsuario.IsForeignKey = false;
colvarUsuario.IsReadOnly = false;
colvarUsuario.DefaultSetting = @"";
colvarUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarUsuario);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_log_prestacion",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLogPrestacion")]
[Bindable(true)]
public int IdLogPrestacion
{
get { return GetColumnValue<int>(Columns.IdLogPrestacion); }
set { SetColumnValue(Columns.IdLogPrestacion, value); }
}
[XmlAttribute("IdPrestacion")]
[Bindable(true)]
public int IdPrestacion
{
get { return GetColumnValue<int>(Columns.IdPrestacion); }
set { SetColumnValue(Columns.IdPrestacion, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime? Fecha
{
get { return GetColumnValue<DateTime?>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("Tipo")]
[Bindable(true)]
public string Tipo
{
get { return GetColumnValue<string>(Columns.Tipo); }
set { SetColumnValue(Columns.Tipo, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
[XmlAttribute("Usuario")]
[Bindable(true)]
public string Usuario
{
get { return GetColumnValue<string>(Columns.Usuario); }
set { SetColumnValue(Columns.Usuario, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdPrestacion,DateTime? varFecha,string varTipo,string varDescripcion,string varUsuario)
{
PnLogPrestacion item = new PnLogPrestacion();
item.IdPrestacion = varIdPrestacion;
item.Fecha = varFecha;
item.Tipo = varTipo;
item.Descripcion = varDescripcion;
item.Usuario = varUsuario;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLogPrestacion,int varIdPrestacion,DateTime? varFecha,string varTipo,string varDescripcion,string varUsuario)
{
PnLogPrestacion item = new PnLogPrestacion();
item.IdLogPrestacion = varIdLogPrestacion;
item.IdPrestacion = varIdPrestacion;
item.Fecha = varFecha;
item.Tipo = varTipo;
item.Descripcion = varDescripcion;
item.Usuario = varUsuario;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLogPrestacionColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPrestacionColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn TipoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn UsuarioColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLogPrestacion = @"id_log_prestacion";
public static string IdPrestacion = @"id_prestacion";
public static string Fecha = @"fecha";
public static string Tipo = @"tipo";
public static string Descripcion = @"descripcion";
public static string Usuario = @"usuario";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// ReSharper disable once CheckNamespace
namespace Fluent
{
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Fluent.Extensions;
using Fluent.Helpers;
using Fluent.Internal;
using Fluent.Internal.KnownBoxes;
/// <summary>
/// Represents gallery item
/// </summary>
public class GalleryItem : ListBoxItem, IKeyTipedControl, ICommandSource
{
#region Properties
#region KeyTip
/// <inheritdoc />
public string KeyTip
{
get { return (string)this.GetValue(KeyTipProperty); }
set { this.SetValue(KeyTipProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for Keys.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(GalleryItem));
#endregion
/// <summary>
/// Gets a value that indicates whether a Button is currently activated.
/// This is a dependency property.
/// </summary>
public bool IsPressed
{
get { return (bool)this.GetValue(IsPressedProperty); }
private set { this.SetValue(IsPressedPropertyKey, value); }
}
private static readonly DependencyPropertyKey IsPressedPropertyKey =
DependencyProperty.RegisterReadOnly(nameof(IsPressed), typeof(bool),
typeof(GalleryItem), new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>Identifies the <see cref="IsPressed"/> dependency property.</summary>
public static readonly DependencyProperty IsPressedProperty = IsPressedPropertyKey.DependencyProperty;
/// <summary>
/// Gets or sets GalleryItem group
/// </summary>
public string Group
{
get { return (string)this.GetValue(GroupProperty); }
set { this.SetValue(GroupProperty, value); }
}
/// <summary>Identifies the <see cref="Group"/> dependency property.</summary>
public static readonly DependencyProperty GroupProperty =
DependencyProperty.Register(nameof(Group), typeof(string),
typeof(GalleryItem), new PropertyMetadata());
/// <summary>
/// Gets or sets whether ribbon control click must close backstage or popup.
/// </summary>
public bool IsDefinitive
{
get { return (bool)this.GetValue(IsDefinitiveProperty); }
set { this.SetValue(IsDefinitiveProperty, value); }
}
/// <summary>Identifies the <see cref="IsDefinitive"/> dependency property.</summary>
public static readonly DependencyProperty IsDefinitiveProperty =
DependencyProperty.Register(nameof(IsDefinitive), typeof(bool), typeof(GalleryItem), new PropertyMetadata(BooleanBoxes.TrueBox));
#region Command
private bool currentCanExecute = true;
/// <inheritdoc />
[Category("Action")]
[Localizability(LocalizationCategory.NeverLocalize)]
[Bindable(true)]
public ICommand Command
{
get
{
return (ICommand)this.GetValue(CommandProperty);
}
set
{
this.SetValue(CommandProperty, value);
}
}
/// <inheritdoc />
[Bindable(true)]
[Localizability(LocalizationCategory.NeverLocalize)]
[Category("Action")]
public object CommandParameter
{
get
{
return this.GetValue(CommandParameterProperty);
}
set
{
this.SetValue(CommandParameterProperty, value);
}
}
/// <inheritdoc />
[Bindable(true)]
[Category("Action")]
public IInputElement CommandTarget
{
get
{
return (IInputElement)this.GetValue(CommandTargetProperty);
}
set
{
this.SetValue(CommandTargetProperty, value);
}
}
/// <summary>Identifies the <see cref="CommandParameter"/> dependency property.</summary>
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(GalleryItem), new PropertyMetadata());
/// <summary>Identifies the <see cref="Command"/> dependency property.</summary>
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(GalleryItem), new PropertyMetadata(OnCommandChanged));
/// <summary>Identifies the <see cref="CommandTarget"/> dependency property.</summary>
public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register(nameof(CommandTarget), typeof(IInputElement), typeof(GalleryItem), new PropertyMetadata());
/// <summary>
/// Gets or sets the command to invoke when mouse enters or leaves this button. The commandparameter will be the <see cref="GalleryItem"/> instance.
/// This is a dependency property.
/// </summary>
[Bindable(true)]
[Category("Action")]
public ICommand PreviewCommand
{
get { return (ICommand)this.GetValue(PreviewCommandProperty); }
set { this.SetValue(PreviewCommandProperty, value); }
}
/// <summary>Identifies the <see cref="PreviewCommand"/> dependency property.</summary>
public static readonly DependencyProperty PreviewCommandProperty =
DependencyProperty.Register(nameof(PreviewCommand), typeof(ICommand), typeof(GalleryItem), new PropertyMetadata());
/// <summary>
/// Gets or sets the command to invoke when mouse enters or leaves this button. The commandparameter will be the <see cref="GalleryItem"/> instance.
/// This is a dependency property.
/// </summary>
[Bindable(true)]
[Category("Action")]
public ICommand CancelPreviewCommand
{
get { return (ICommand)this.GetValue(CancelPreviewCommandProperty); }
set { this.SetValue(CancelPreviewCommandProperty, value); }
}
/// <summary>Identifies the <see cref="CancelPreviewCommand"/> dependency property.</summary>
public static readonly DependencyProperty CancelPreviewCommandProperty =
DependencyProperty.Register(nameof(CancelPreviewCommand), typeof(ICommand), typeof(GalleryItem), new PropertyMetadata());
/// <summary>
/// Handles Command changed
/// </summary>
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as GalleryItem;
if (control is null)
{
return;
}
if (e.OldValue is ICommand oldCommand)
{
oldCommand.CanExecuteChanged -= control.OnCommandCanExecuteChanged;
}
if (e.NewValue is ICommand newCommand)
{
newCommand.CanExecuteChanged += control.OnCommandCanExecuteChanged;
}
control.UpdateCanExecute();
}
/// <summary>
/// Handles Command CanExecute changed
/// </summary>
private void OnCommandCanExecuteChanged(object sender, EventArgs e)
{
this.UpdateCanExecute();
}
private void UpdateCanExecute()
{
var canExecute = this.Command != null
&& this.CanExecuteCommand();
if (this.currentCanExecute != canExecute)
{
this.currentCanExecute = canExecute;
this.CoerceValue(IsEnabledProperty);
}
}
#endregion
#region IsEnabled
/// <inheritdoc />
protected override bool IsEnabledCore => base.IsEnabledCore && (this.currentCanExecute || this.Command is null);
#endregion
#endregion
#region Events
#region Click
/// <summary>
/// Occurs when a RibbonControl is clicked.
/// </summary>
[Category("Behavior")]
public event RoutedEventHandler Click
{
add
{
this.AddHandler(ClickEvent, value);
}
remove
{
this.RemoveHandler(ClickEvent, value);
}
}
/// <summary>
/// Identifies the RibbonControl.Click routed event.
/// </summary>
public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent(nameof(Click), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(GalleryItem));
/// <summary>
/// Raises click event
/// </summary>
public void RaiseClick()
{
this.RaiseEvent(new RoutedEventArgs(ClickEvent, this));
}
#endregion
#endregion
#region Constructors
/// <summary>
/// Static constructor
/// </summary>
static GalleryItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(GalleryItem), new FrameworkPropertyMetadata(typeof(GalleryItem)));
IsSelectedProperty.AddOwner(typeof(GalleryItem), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.None, OnIsSelectedChanged));
}
private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
((GalleryItem)d).BringIntoView();
if (ItemsControlHelper.ItemsControlFromItemContainer(d) is Selector parentSelector)
{
var item = parentSelector.ItemContainerGenerator.ItemFromContainerOrContainerContent(d);
if (ReferenceEquals(parentSelector.SelectedItem, item) == false)
{
parentSelector.SelectedItem = item;
}
}
}
}
/// <summary>
/// Default constructor
/// </summary>
public GalleryItem()
{
this.Click += this.OnClick;
}
#endregion
#region Overrides
/// <inheritdoc />
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
this.IsPressed = true;
Mouse.Capture(this);
e.Handled = true;
}
/// <inheritdoc />
protected override void OnLostMouseCapture(MouseEventArgs e)
{
base.OnLostMouseCapture(e);
this.IsPressed = false;
}
/// <inheritdoc />
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
this.IsPressed = false;
if (ReferenceEquals(Mouse.Captured, this))
{
Mouse.Capture(null);
}
var position = Mouse.PrimaryDevice.GetPosition(this);
if (position.X >= 0.0 && position.X <= this.ActualWidth && position.Y >= 0.0 && position.Y <= this.ActualHeight && e.ClickCount == 1)
{
this.RaiseClick();
e.Handled = true;
}
e.Handled = true;
}
/// <inheritdoc />
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
CommandHelper.Execute(this.PreviewCommand, this, null);
}
/// <inheritdoc />
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
CommandHelper.Execute(this.CancelPreviewCommand, this, null);
}
#endregion
#region Protected methods
/// <summary>
/// Handles click event
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">The event data</param>
protected virtual void OnClick(object sender, RoutedEventArgs e)
{
// Close popup on click
if (this.IsDefinitive)
{
PopupService.RaiseDismissPopupEvent(sender, DismissPopupMode.Always);
}
this.ExecuteCommand();
this.IsSelected = true;
e.Handled = true;
}
#endregion
/// <inheritdoc />
public KeyTipPressedResult OnKeyTipPressed()
{
this.RaiseClick();
return KeyTipPressedResult.Empty;
}
/// <inheritdoc />
public void OnKeyTipBack()
{
}
}
}
| |
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
namespace Amqp
{
using System;
using System.Threading;
using Amqp.Framing;
using Amqp.Sasl;
using Amqp.Types;
/// <summary>
/// The callback that is invoked when an open frame is received from peer.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="open">The received open frame.</param>
public delegate void OnOpened(Connection connection, Open open);
/// <summary>
/// The Connection class represents an AMQP connection.
/// </summary>
public class Connection : AmqpObject
{
enum State
{
Start,
HeaderSent,
OpenPipe,
OpenClosePipe,
HeaderReceived,
HeaderExchanged,
OpenSent,
OpenReceived,
Opened,
CloseReceived,
ClosePipe,
CloseSent,
End
}
/// <summary>
/// A flag to disable server certificate validation when TLS is used.
/// </summary>
public static bool DisableServerCertValidation;
internal const uint DefaultMaxFrameSize = 256 * 1024;
internal const ushort DefaultMaxSessions = 256;
const uint MaxIdleTimeout = 30 * 60 * 1000;
static readonly TimerCallback onHeartBeatTimer = OnHeartBeatTimer;
readonly Address address;
readonly OnOpened onOpened;
Session[] localSessions;
Session[] remoteSessions;
ushort channelMax;
State state;
ITransport transport;
uint maxFrameSize;
Pump reader;
Timer heartBeatTimer;
Connection(ushort channelMax, uint maxFrameSize)
{
this.channelMax = channelMax;
this.maxFrameSize = maxFrameSize;
this.localSessions = new Session[1];
this.remoteSessions = new Session[1];
}
/// <summary>
/// Initializes a connection from the address.
/// </summary>
/// <param name="address">The address.</param>
public Connection(Address address)
: this(address, null, null, null)
{
}
/// <summary>
/// Initializes a connection with SASL profile, open and open callback.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="saslProfile">The SASL profile to do authentication (optional). If it is null and address has user info, SASL PLAIN profile is used.</param>
/// <param name="open">The open frame to send (optional). If not null, all mandatory fields must be set. Ensure that other fields are set to desired values.</param>
/// <param name="onOpened">The callback to handle remote open frame (optional).</param>
public Connection(Address address, SaslProfile saslProfile, Open open, OnOpened onOpened)
: this(DefaultMaxSessions, DefaultMaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
if (open != null)
{
this.maxFrameSize = open.MaxFrameSize;
this.channelMax = open.ChannelMax;
}
else
{
open = new Open()
{
ContainerId = Guid.NewGuid().ToString(),
HostName = this.address.Host,
MaxFrameSize = this.maxFrameSize,
ChannelMax = this.channelMax
};
}
this.Connect(saslProfile, open);
}
#if DOTNET || NETFX_CORE
internal Connection(AmqpSettings amqpSettings, Address address, IAsyncTransport transport, Open open, OnOpened onOpened)
: this((ushort)(amqpSettings.MaxSessionsPerConnection - 1), (uint)amqpSettings.MaxFrameSize)
{
this.address = address;
this.onOpened = onOpened;
this.maxFrameSize = (uint)amqpSettings.MaxFrameSize;
this.transport = transport;
transport.SetConnection(this);
// after getting the transport, move state to open pipe before starting the pump
if (open == null)
{
open = new Open()
{
ContainerId = amqpSettings.ContainerId,
HostName = amqpSettings.HostName ?? this.address.Host,
ChannelMax = this.channelMax,
MaxFrameSize = this.maxFrameSize
};
}
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
}
/// <summary>
/// Gets a factory with default settings.
/// </summary>
public static ConnectionFactory Factory
{
get { return new ConnectionFactory(); }
}
#endif
object ThisLock
{
get { return this; }
}
internal ushort AddSession(Session session)
{
this.ThrowIfClosed("AddSession");
lock (this.ThisLock)
{
int count = this.localSessions.Length;
for (int i = 0; i < count; ++i)
{
if (this.localSessions[i] == null)
{
this.localSessions[i] = session;
return (ushort)i;
}
}
if (count - 1 < this.channelMax)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.localSessions, expanded, count);
this.localSessions = expanded;
this.localSessions[count] = session;
return (ushort)count;
}
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax));
}
}
internal void SendCommand(ushort channel, DescribedList command)
{
this.ThrowIfClosed("Send");
ByteBuffer buffer = Frame.Encode(FrameType.Amqp, channel, command);
this.transport.Send(buffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1}", channel, command);
}
internal void SendCommand(ushort channel, Transfer transfer, ByteBuffer payload)
{
this.ThrowIfClosed("Send");
int payloadSize;
ByteBuffer buffer = Frame.Encode(FrameType.Amqp, channel, transfer, payload, (int)this.maxFrameSize, out payloadSize);
this.transport.Send(buffer);
Trace.WriteLine(TraceLevel.Frame, "SEND (ch={0}) {1} payload {2}", channel, transfer, payloadSize);
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
protected override bool OnClose(Error error)
{
lock (this.ThisLock)
{
State newState = State.Start;
if (this.state == State.OpenPipe )
{
newState = State.OpenClosePipe;
}
else if (state == State.OpenSent)
{
newState = State.ClosePipe;
}
else if (this.state == State.Opened)
{
newState = State.CloseSent;
}
else if (this.state == State.CloseReceived)
{
newState = State.End;
}
else if (this.state == State.End)
{
return true;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "Close", this.state));
}
this.SendClose(error);
this.state = newState;
return this.state == State.End;
}
}
static void OnHeartBeatTimer(object state)
{
var thisPtr = (Connection)state;
byte[] frame = new byte[] { 0, 0, 0, 8, 2, 0, 0, 0 };
thisPtr.transport.Send(new ByteBuffer(frame, 0, frame.Length, frame.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND (ch=0) empty");
}
void Connect(SaslProfile saslProfile, Open open)
{
ITransport transport;
TcpTransport tcpTransport = new TcpTransport();
tcpTransport.Connect(this, this.address, DisableServerCertValidation);
transport = tcpTransport;
if (saslProfile != null)
{
transport = saslProfile.Open(this.address.Host, transport);
}
else if (this.address.User != null)
{
transport = new SaslPlainProfile(this.address.User, this.address.Password).Open(this.address.Host, transport);
}
this.transport = transport;
// after getting the transport, move state to open pipe before starting the pump
this.SendHeader();
this.SendOpen(open);
this.state = State.OpenPipe;
this.reader = new Pump(this);
this.reader.Start();
}
void ThrowIfClosed(string operation)
{
if (this.state >= State.ClosePipe)
{
throw new AmqpException(this.Error ??
new Error()
{
Condition = ErrorCode.IllegalState,
Description = Fx.Format(SRAmqp.AmqpIllegalOperationState, operation, this.state)
});
}
}
void SendHeader()
{
byte[] header = new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', 0, 1, 0, 0 };
this.transport.Send(new ByteBuffer(header, 0, header.Length, header.Length));
Trace.WriteLine(TraceLevel.Frame, "SEND AMQP 0 1.0.0");
}
void SendOpen(Open open)
{
this.SendCommand(0, open);
}
void SendClose(Error error)
{
this.SendCommand(0, new Close() { Error = error });
}
void OnOpen(Open open)
{
lock (this.ThisLock)
{
if (this.state == State.OpenSent)
{
this.state = State.Opened;
}
else if (this.state == State.ClosePipe)
{
this.state = State.CloseSent;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnOpen", this.state));
}
}
if (open.ChannelMax < this.channelMax)
{
this.channelMax = open.ChannelMax;
}
if (open.MaxFrameSize < this.maxFrameSize)
{
this.maxFrameSize = open.MaxFrameSize;
}
uint idleTimeout = open.IdleTimeOut;
if (idleTimeout > 0 && idleTimeout < uint.MaxValue)
{
idleTimeout -= 3000;
if (idleTimeout > MaxIdleTimeout)
{
idleTimeout = MaxIdleTimeout;
}
this.heartBeatTimer = new Timer(onHeartBeatTimer, this, (int)idleTimeout, (int)idleTimeout);
}
if (this.onOpened != null)
{
this.onOpened(this, open);
}
}
void OnClose(Close close)
{
lock (this.ThisLock)
{
if (this.state == State.Opened)
{
this.SendClose(null);
}
else if (this.state == State.CloseSent)
{
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnClose", this.state));
}
this.state = State.End;
this.OnEnded(close.Error);
}
}
internal virtual void OnBegin(ushort remoteChannel, Begin begin)
{
lock (this.ThisLock)
{
if (remoteChannel > this.channelMax)
{
throw new AmqpException(ErrorCode.NotAllowed,
Fx.Format(SRAmqp.AmqpHandleExceeded, this.channelMax + 1));
}
Session session = this.GetSession(this.localSessions, begin.RemoteChannel);
session.OnBegin(remoteChannel, begin);
int count = this.remoteSessions.Length;
if (count - 1 < remoteChannel)
{
int size = Math.Min(count * 2, this.channelMax + 1);
Session[] expanded = new Session[size];
Array.Copy(this.remoteSessions, expanded, count);
this.remoteSessions = expanded;
}
var remoteSession = this.remoteSessions[remoteChannel];
if (remoteSession != null)
{
throw new AmqpException(ErrorCode.HandleInUse,
Fx.Format(SRAmqp.AmqpHandleInUse, remoteChannel, remoteSession.GetType().Name));
}
this.remoteSessions[remoteChannel] = session;
}
}
void OnEnd(ushort remoteChannel, End end)
{
Session session = this.GetSession(this.remoteSessions, remoteChannel);
if (session.OnEnd(end))
{
lock (this.ThisLock)
{
this.localSessions[session.Channel] = null;
this.remoteSessions[remoteChannel] = null;
}
}
}
void OnSessionCommand(ushort remoteChannel, DescribedList command, ByteBuffer buffer)
{
this.GetSession(this.remoteSessions, remoteChannel).OnCommand(command, buffer);
}
Session GetSession(Session[] sessions, ushort channel)
{
lock (this.ThisLock)
{
Session session = null;
if (channel < sessions.Length)
{
session = sessions[channel];
}
if (session == null)
{
throw new AmqpException(ErrorCode.NotFound,
Fx.Format(SRAmqp.AmqpChannelNotFound, channel));
}
return session;
}
}
internal bool OnHeader(ProtocolHeader header)
{
Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", header);
lock (this.ThisLock)
{
if (this.state == State.OpenPipe)
{
this.state = State.OpenSent;
}
else if (this.state == State.OpenClosePipe)
{
this.state = State.ClosePipe;
}
else
{
throw new AmqpException(ErrorCode.IllegalState,
Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnHeader", this.state));
}
if (header.Major != 1 || header.Minor != 0 || header.Revision != 0)
{
throw new AmqpException(ErrorCode.NotImplemented, header.ToString());
}
}
return true;
}
internal bool OnFrame(ByteBuffer buffer)
{
bool shouldContinue = true;
try
{
ushort channel;
DescribedList command;
Frame.GetFrame(buffer, out channel, out command);
if (buffer.Length > 0)
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1} payload {2}", channel, command, buffer.Length);
}
else
{
Trace.WriteLine(TraceLevel.Frame, "RECV (ch={0}) {1}", channel, command);
}
if (command != null)
{
if (command.Descriptor.Code == Codec.Open.Code)
{
this.OnOpen((Open)command);
}
else if (command.Descriptor.Code == Codec.Close.Code)
{
this.OnClose((Close)command);
shouldContinue = false;
}
else if (command.Descriptor.Code == Codec.Begin.Code)
{
this.OnBegin(channel, (Begin)command);
}
else if (command.Descriptor.Code == Codec.End.Code)
{
this.OnEnd(channel, (End)command);
}
else
{
this.OnSessionCommand(channel, command, buffer);
}
}
}
catch (Exception exception)
{
this.OnException(exception);
shouldContinue = false;
}
return shouldContinue;
}
void OnException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", exception.ToString());
AmqpException amqpException = exception as AmqpException;
Error error = amqpException != null ?
amqpException.Error :
new Error() { Condition = ErrorCode.InternalError, Description = exception.Message };
if (this.state < State.ClosePipe)
{
try
{
this.Close(0, error);
}
catch
{
this.state = State.End;
}
}
else
{
this.state = State.End;
}
if (this.state == State.End)
{
this.OnEnded(error);
}
}
internal void OnIoException(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, "I/O: {0}", exception.ToString());
if (this.state != State.End)
{
Error error = new Error() { Condition = ErrorCode.ConnectionForced };
for (int i = 0; i < this.localSessions.Length; i++)
{
if (this.localSessions[i] != null)
{
this.localSessions[i].Abort(error);
}
}
this.state = State.End;
this.OnEnded(error);
}
}
void OnEnded(Error error)
{
if (this.heartBeatTimer != null)
{
this.heartBeatTimer.Dispose();
}
if (this.transport != null)
{
this.transport.Close();
}
for (int i = 0; i < this.localSessions.Length; i++)
{
var session = this.localSessions[i];
if (session != null)
{
session.Abort(error);
}
}
this.NotifyClosed(error);
}
sealed class Pump
{
readonly Connection connection;
public Pump(Connection connection)
{
this.connection = connection;
}
public void Start()
{
Fx.StartThread(this.PumpThread);
}
void PumpThread()
{
try
{
ProtocolHeader header = Reader.ReadHeader(this.connection.transport);
this.connection.OnHeader(header);
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
return;
}
byte[] sizeBuffer = new byte[FixedWidth.UInt];
while (sizeBuffer != null && this.connection.state != State.End)
{
try
{
ByteBuffer buffer = Reader.ReadFrameBuffer(this.connection.transport, sizeBuffer, this.connection.maxFrameSize);
if (buffer != null)
{
this.connection.OnFrame(buffer);
}
else
{
sizeBuffer = null;
}
}
catch (Exception exception)
{
this.connection.OnIoException(exception);
}
}
}
}
}
}
| |
/**
* _____ _____ _____ _____ __ _____ _____ _____ _____
* | __| | | | | | | | | __| | |
* |__ | | | | | | | | | |__| | | | |- -| --|
* |_____|_____|_|_|_|_____| |_____|_____|_____|_____|_____|
*
* UNICORNS AT WARP SPEED SINCE 2010
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace SumoLogic.Logging.Log4Net.Tests
{
using System;
using System.IO;
using System.Threading;
using log4net;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using SumoLogic.Logging.Common.Sender;
using SumoLogic.Logging.Common.Tests;
using Xunit;
/// <summary>
/// <see cref="BufferedSumoLogicAppenderTest"/> class related tests.
/// </summary>
public class BufferedSumoLogicAppenderTest : IDisposable
{
/// <summary>
/// The HTTP messages handler mock.
/// </summary>
private MockHttpMessageHandler messagesHandler;
/// <summary>
/// The log4net log.
/// </summary>
private ILog log4netLog;
/// <summary>
/// The log4net logger.
/// </summary>
private Logger log4netLogger;
/// <summary>
/// The buffered SumoLogic appender.
/// </summary>
private BufferedSumoLogicAppender bufferedSumoLogicAppender;
/// <summary>
/// Test logging of a single message.
/// </summary>
[Fact]
public void TestSingleMessage()
{
SetUpLogger(1, 10000, 10);
log4netLog.Info("This is a message");
Assert.Equal(0, messagesHandler.ReceivedRequests.Count);
TestHelper.Eventually(() =>
{
Assert.Equal(1, messagesHandler.ReceivedRequests.Count);
Assert.Equal("This is a message" + Environment.NewLine + Environment.NewLine, messagesHandler.LastReceivedRequest.Content.ReadAsStringAsync().Result);
});
}
/// <summary>
/// Test logging of a single message.
/// </summary>
[Fact]
public void TestFlushMessage()
{
SetUpLogger(1, 10000, 10000);
log4netLog.Info("This is a message");
Assert.Equal(0, messagesHandler.ReceivedRequests.Count);
bool success = (log4netLogger.Repository as log4net.Appender.IFlushable)?.Flush(5000) ?? false;
Assert.True(success);
Assert.Equal(1, messagesHandler.ReceivedRequests.Count);
Assert.Equal("This is a message" + Environment.NewLine + Environment.NewLine, messagesHandler.LastReceivedRequest.Content.ReadAsStringAsync().Result);
}
/// <summary>
/// Test logging of multiple messages.
/// </summary>
[Fact]
public void TestMultipleMessages()
{
SetUpLogger(1, 10000, 10);
int numMessages = 20;
for (int i = 0; i < numMessages; i++)
{
log4netLog.Info("info " + i);
Thread.Sleep(TimeSpan.FromMilliseconds(100));
}
TestHelper.Eventually(() =>
{
Assert.Equal(numMessages, messagesHandler.ReceivedRequests.Count);
});
}
/// <summary>
/// Test batching of multiple messages based on messages per request setting.
/// </summary>
[Fact]
public void TestBatchingBySize()
{
// Huge time window, ensure all messages get batched into one
SetUpLogger(100, 10000, 10);
int numMessages = 100;
for (int i = 0; i < numMessages; i++)
{
log4netLog.Info("info " + i);
}
Assert.Equal(0, messagesHandler.ReceivedRequests.Count);
TestHelper.Eventually(() =>
{
Assert.Equal(1, messagesHandler.ReceivedRequests.Count);
});
}
/// <summary>
/// Test batching of multiple messages based on max flush interval setting.
/// </summary>
[Fact]
public void TestBatchingByWindow()
{
// Small time window, ensure all messages get batched by time
SetUpLogger(10000, 500, 10);
for (int i = 1; i <= 5; ++i)
{
log4netLog.Info("message" + i);
}
Assert.Equal(0, messagesHandler.ReceivedRequests.Count);
TestHelper.Eventually(() =>
{
Assert.Equal(1, messagesHandler.ReceivedRequests.Count);
});
for (int i = 6; i <= 10; ++i)
{
log4netLog.Info("message" + i);
}
Assert.Equal(1, messagesHandler.ReceivedRequests.Count);
TestHelper.Eventually(() =>
{
Assert.Equal(2, messagesHandler.ReceivedRequests.Count);
});
}
/// <summary>
/// Test that setting <see cref="BufferedSumoLogicAppender.UseConsoleLog"/> to true
/// will cause the appender to log to the console.
/// </summary>
[Fact]
public void TestConsoleLogging()
{
lock (ConsoleMutex.mutex)
{
var writer = new StringWriter();
try
{
Console.SetOut(writer);
SetUpLogger(10000, 500, 10);
log4netLog.Info("hello");
writer.Flush();
var consoleText = writer.GetStringBuilder().ToString();
Assert.True(!string.IsNullOrWhiteSpace(consoleText));
}
finally
{
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
writer.Close();
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used and optionally disposes of the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to releases only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
log4netLogger.RemoveAllAppenders();
messagesHandler.Dispose();
}
}
[Fact]
public void TestRequiresLayout()
{
SetUpLogger(1, 10000, 10);
var oldLayout = bufferedSumoLogicAppender.Layout;
var oldErrorHandler = bufferedSumoLogicAppender.ErrorHandler;
try
{
bufferedSumoLogicAppender.ErrorHandler = new TestErrorHandler();
bufferedSumoLogicAppender.Layout = null; // set to bogus null/missing value
log4netLog.Info("oops"); // push through a message
// nothing should be thrown, but an error should be generated
var errHandler = (TestErrorHandler)bufferedSumoLogicAppender.ErrorHandler;
Assert.Single(errHandler.Errors);
Assert.Contains("No layout set", errHandler.Errors[0]);
}
finally
{
bufferedSumoLogicAppender.Layout = oldLayout;
bufferedSumoLogicAppender.ErrorHandler = oldErrorHandler;
}
}
/// <summary>
/// Setups the logger with the <see cref="BufferedSumoLogicAppender"/> based on the given settings.
/// </summary>
/// <param name="messagesPerRequest">The maximum messages per request.</param>
/// <param name="maxFlushInterval">The maximum flush interval, in milliseconds.</param>
/// <param name="flushingAccuracy">The flushing accuracy, in milliseconds.</param>
/// <param name="retryInterval">The retry interval, in milliseconds.</param>
private void SetUpLogger(long messagesPerRequest, long maxFlushInterval, long flushingAccuracy, long retryInterval = 10000)
{
messagesHandler = new MockHttpMessageHandler();
bufferedSumoLogicAppender = new BufferedSumoLogicAppender(null, messagesHandler);
bufferedSumoLogicAppender.Url = "http://www.fakeadress.com";
bufferedSumoLogicAppender.SourceName = "BufferedSumoLogicAppenderSourceName";
bufferedSumoLogicAppender.SourceCategory = "BufferedSumoLogicAppenderSourceCategory";
bufferedSumoLogicAppender.SourceHost = "BufferedSumoLogicAppenderSourceHost";
bufferedSumoLogicAppender.MessagesPerRequest = messagesPerRequest;
bufferedSumoLogicAppender.MaxFlushInterval = maxFlushInterval;
bufferedSumoLogicAppender.FlushingAccuracy = flushingAccuracy;
bufferedSumoLogicAppender.RetryInterval = retryInterval;
bufferedSumoLogicAppender.Layout = new PatternLayout("%m%n");
bufferedSumoLogicAppender.UseConsoleLog = true;
bufferedSumoLogicAppender.ActivateOptions();
log4netLog = LogManager.GetLogger(typeof(BufferedSumoLogicAppenderTest));
log4netLogger = (Logger)log4netLog.Logger;
log4netLogger.Additivity = false;
log4netLogger.Level = Level.All;
log4netLogger.RemoveAllAppenders();
log4netLogger.AddAppender(bufferedSumoLogicAppender);
log4netLogger.Repository.Configured = true;
}
}
}
| |
#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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.IO;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
internal enum ReadType
{
Read,
ReadAsInt32,
ReadAsBytes,
ReadAsString,
ReadAsDecimal,
ReadAsDateTime,
#if !NET20
ReadAsDateTimeOffset
#endif
}
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
/// </summary>
public class JsonTextReader : JsonReader, IJsonLineInfo
{
private const char UnicodeReplacementChar = '\uFFFD';
private const int MaximumJavascriptIntegerCharacterLength = 380;
private readonly TextReader _reader;
private char[] _chars;
private int _charsUsed;
private int _charPos;
private int _lineStartPos;
private int _lineNumber;
private bool _isEndOfFile;
private StringBuffer _buffer;
private StringReference _stringReference;
internal PropertyNameTable NameTable;
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
public JsonTextReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_lineNumber = 1;
_chars = new char[1025];
}
#if DEBUG
internal void SetCharBuffer(char[] chars)
{
_chars = chars;
}
#endif
private StringBuffer GetBuffer()
{
if (_buffer == null)
{
_buffer = new StringBuffer(1025);
}
else
{
_buffer.Position = 0;
}
return _buffer;
}
private void OnNewLine(int pos)
{
_lineNumber++;
_lineStartPos = pos - 1;
}
private void ParseString(char quote)
{
_charPos++;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quote);
SetPostValueState(true);
if (_readType == ReadType.ReadAsBytes)
{
Guid g;
byte[] data;
if (_stringReference.Length == 0)
{
data = new byte[0];
}
else if (_stringReference.Length == 36 && ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g))
{
data = g.ToByteArray();
}
else
{
data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
}
SetToken(JsonToken.Bytes, data, false);
}
else if (_readType == ReadType.ReadAsString)
{
string text = _stringReference.ToString();
SetToken(JsonToken.String, text, false);
_quoteChar = quote;
}
else
{
string text = _stringReference.ToString();
if (_dateParseHandling != DateParseHandling.None)
{
DateParseHandling dateParseHandling;
if (_readType == ReadType.ReadAsDateTime)
dateParseHandling = DateParseHandling.DateTime;
#if !NET20
else if (_readType == ReadType.ReadAsDateTimeOffset)
dateParseHandling = DateParseHandling.DateTimeOffset;
#endif
else
dateParseHandling = _dateParseHandling;
object dt;
if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, DateFormatString, Culture, out dt))
{
SetToken(JsonToken.Date, dt, false);
return;
}
}
SetToken(JsonToken.String, text, false);
_quoteChar = quote;
}
}
private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count)
{
const int charByteCount = 2;
Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount);
}
private void ShiftBufferIfNeeded()
{
// once in the last 10% of the buffer shift the remaining content to the start to avoid
// unnessesarly increasing the buffer size when reading numbers/strings
int length = _chars.Length;
if (length - _charPos <= length * 0.1)
{
int count = _charsUsed - _charPos;
if (count > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, count);
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = count;
_chars[_charsUsed] = '\0';
}
}
private int ReadData(bool append)
{
return ReadData(append, 0);
}
private int ReadData(bool append, int charsRequired)
{
if (_isEndOfFile)
return 0;
// char buffer is full
if (_charsUsed + charsRequired >= _chars.Length - 1)
{
if (append)
{
// copy to new array either double the size of the current or big enough to fit required content
int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1);
// increase the size of the buffer
char[] dst = new char[newArrayLength];
BlockCopyChars(_chars, 0, dst, 0, _chars.Length);
_chars = dst;
}
else
{
int remainingCharCount = _charsUsed - _charPos;
if (remainingCharCount + charsRequired + 1 >= _chars.Length)
{
// the remaining count plus the required is bigger than the current buffer size
char[] dst = new char[remainingCharCount + charsRequired + 1];
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount);
_chars = dst;
}
else
{
// copy any remaining data to the beginning of the buffer if needed and reset positions
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount);
}
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = remainingCharCount;
}
}
int attemptCharReadCount = _chars.Length - _charsUsed - 1;
int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount);
_charsUsed += charsRead;
if (charsRead == 0)
_isEndOfFile = true;
_chars[_charsUsed] = '\0';
return charsRead;
}
private bool EnsureChars(int relativePosition, bool append)
{
if (_charPos + relativePosition >= _charsUsed)
return ReadChars(relativePosition, append);
return true;
}
private bool ReadChars(int relativePosition, bool append)
{
if (_isEndOfFile)
return false;
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
int totalCharsRead = 0;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = ReadData(append, charsRequired - totalCharsRead);
// no more content
if (charsRead == 0)
break;
totalCharsRead += charsRead;
} while (totalCharsRead < charsRequired);
if (totalCharsRead < charsRequired)
return false;
return true;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
[DebuggerStepThrough]
public override bool Read()
{
_readType = ReadType.Read;
if (!ReadInternal())
{
SetToken(JsonToken.None);
return false;
}
return true;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Byte"/>[].
/// </summary>
/// <returns>
/// A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
/// </returns>
public override byte[] ReadAsBytes()
{
return ReadAsBytesInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override decimal? ReadAsDecimal()
{
return ReadAsDecimalInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override int? ReadAsInt32()
{
return ReadAsInt32Internal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
return ReadAsStringInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
return ReadAsDateTimeInternal();
}
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
return ReadAsDateTimeOffsetInternal();
}
#endif
internal override bool ReadInternal()
{
while (true)
{
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValue();
case State.Object:
case State.ObjectStart:
return ParseObject();
case State.PostValue:
// returns true if it hits
// end of object or array
if (ParsePostValue())
return true;
break;
case State.Finished:
if (EnsureChars(0, false))
{
EatWhitespace(false);
if (_isEndOfFile)
{
return false;
}
if (_chars[_charPos] == '/')
{
ParseComment();
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
return false;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
}
private void ReadStringIntoBuffer(char quote)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
StringBuffer buffer = null;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (ReadData(true) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!EnsureChars(0, true))
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
char writeChar;
switch (currentChar)
{
case 'b':
charPos++;
writeChar = '\b';
break;
case 't':
charPos++;
writeChar = '\t';
break;
case 'n':
charPos++;
writeChar = '\n';
break;
case 'f':
charPos++;
writeChar = '\f';
break;
case 'r':
charPos++;
writeChar = '\r';
break;
case '\\':
charPos++;
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
charPos++;
break;
case 'u':
charPos++;
_charPos = charPos;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
charPos++;
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
ProcessCarriageReturn(true);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
charPos--;
if (initialPosition == lastWritePosition)
{
_stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
}
else
{
if (buffer == null)
buffer = GetBuffer();
if (charPos > lastWritePosition)
buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
_stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
}
charPos++;
_charPos = charPos;
return;
}
break;
}
}
}
private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition)
{
if (writeToPosition > lastWritePosition)
{
buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition);
}
buffer.Append(writeChar);
}
private char ParseUnicode()
{
char writeChar;
if (EnsureChars(4, true))
{
string hexValues = new string(_chars, _charPos, 4);
char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
writeChar = hexChar;
_charPos += 4;
}
else
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character.");
}
return writeChar;
}
private void ReadNumberIntoBuffer()
{
int charPos = _charPos;
while (true)
{
switch (_chars[charPos])
{
case '\0':
_charPos = charPos;
if (_charsUsed == charPos)
{
if (ReadData(true) == 0)
return;
}
else
{
return;
}
break;
case '-':
case '+':
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
case 'd':
case 'D':
case 'e':
case 'E':
case 'f':
case 'F':
case 'x':
case 'X':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
charPos++;
break;
default:
_charPos = charPos;
char currentChar = _chars[_charPos];
if (char.IsWhiteSpace(currentChar)
|| currentChar == ','
|| currentChar == '}'
|| currentChar == ']'
|| currentChar == ')'
|| currentChar == '/')
{
return;
}
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing number: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
private void ClearRecentString()
{
if (_buffer != null)
_buffer.Position = 0;
_stringReference = new StringReference();
}
private bool ParsePostValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
{
_currentState = State.Finished;
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
ParseComment();
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
}
private bool ParseObject()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
ParseComment();
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return ParseProperty();
}
break;
}
}
}
private bool ParseProperty()
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quoteChar);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
ParseUnquotedProperty();
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (NameTable != null)
{
propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
// no match in name table
if (propertyName == null)
propertyName = _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
EatWhitespace(false);
if (_chars[_charPos] != ':')
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private bool ValidIdentifierChar(char value)
{
return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
}
private void ParseUnquotedProperty()
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
break;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
default:
char currentChar = _chars[_charPos];
if (ValidIdentifierChar(currentChar))
{
_charPos++;
break;
}
else if (char.IsWhiteSpace(currentChar) || currentChar == ':')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
private bool ParseValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
ParseString(currentChar);
return true;
case 't':
ParseTrue();
return true;
case 'f':
ParseFalse();
return true;
case 'n':
if (EnsureChars(1, true))
{
char next = _chars[_charPos + 1];
if (next == 'u')
ParseNull();
else if (next == 'e')
ParseConstructor();
else
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
else
{
throw JsonReaderException.Create(this, "Unexpected end.");
}
return true;
case 'N':
ParseNumberNaN();
return true;
case 'I':
ParseNumberPositiveInfinity();
return true;
case '-':
if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I')
ParseNumberNegativeInfinity();
else
ParseNumber();
return true;
case '/':
ParseComment();
return true;
case 'u':
ParseUndefined();
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber();
return true;
}
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
private void ProcessLineFeed()
{
_charPos++;
OnNewLine(_charPos);
}
private void ProcessCarriageReturn(bool append)
{
_charPos++;
if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed)
_charPos++;
OnNewLine(_charPos);
}
private bool EatWhitespace(bool oneOrMore)
{
bool finished = false;
bool ateWhitespace = false;
while (!finished)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
finished = true;
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
ateWhitespace = true;
_charPos++;
}
else
{
finished = true;
}
break;
}
}
return (!oneOrMore || ateWhitespace);
}
private void ParseConstructor()
{
if (MatchValueWithTrailingSeparator("new"))
{
EatWhitespace(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
ProcessCarriageReturn(true);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
EatWhitespace(false);
if (_chars[_charPos] != '(')
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private void ParseNumber()
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
ReadNumberIntoBuffer();
// set state to PostValue now so that if there is an error parsing the number then the reader can continue
SetPostValueState(true);
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
object numberValue;
JsonToken numberType;
bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1
&& _stringReference.Chars[_stringReference.StartIndex + 1] != '.'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'e'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
if (_readType == ReadType.ReadAsInt32)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt32(number, 16)
: Convert.ToInt32(number, 8);
numberValue = integer;
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
int value;
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
numberValue = value;
else if (parseResult == ParseResult.Overflow)
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Integer;
}
else if (_readType == ReadType.ReadAsDecimal)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (decimal)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
string number = _stringReference.ToString();
decimal value;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
numberValue = value;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Float;
}
else
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (long)firstChar - 48;
numberType = JsonToken.Integer;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
numberType = JsonToken.Integer;
}
else
{
long value;
ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
numberType = JsonToken.Integer;
}
else if (parseResult == ParseResult.Overflow)
{
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
else
{
string number = _stringReference.ToString();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
decimal d;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
}
else
{
double d;
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
}
numberType = JsonToken.Float;
}
}
}
ClearRecentString();
// index has already been updated
SetToken(numberType, numberValue, false);
}
private void ParseComment()
{
// should have already parsed / character before reaching this method
_charPos++;
if (!EnsureChars(1, false))
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
bool singlelineComment;
if (_chars[_charPos] == '*')
singlelineComment = false;
else if (_chars[_charPos] == '/')
singlelineComment = true;
else
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
int initialPosition = _charPos;
bool commentFinished = false;
while (!commentFinished)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
{
if (!singlelineComment)
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (EnsureChars(0, true))
{
if (_chars[_charPos] == '/')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
_charPos++;
commentFinished = true;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessCarriageReturn(true);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
SetToken(JsonToken.Comment, _stringReference.ToString());
ClearRecentString();
}
private bool MatchValue(string value)
{
if (!EnsureChars(value.Length - 1, true))
return false;
for (int i = 0; i < value.Length; i++)
{
if (_chars[_charPos + i] != value[i])
{
return false;
}
}
_charPos += value.Length;
return true;
}
private bool MatchValueWithTrailingSeparator(string value)
{
// will match value and then move to the next character, checking that it is a separator character
bool match = MatchValue(value);
if (!match)
return false;
if (!EnsureChars(0, false))
return true;
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private bool IsSeparator(char c)
{
switch (c)
{
case '}':
case ']':
case ',':
return true;
case '/':
// check next character to see if start of a comment
if (!EnsureChars(1, false))
return false;
var nextChart = _chars[_charPos + 1];
return (nextChart == '*' || nextChart == '/');
case ')':
if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
return true;
break;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
return true;
default:
if (char.IsWhiteSpace(c))
return true;
break;
}
return false;
}
private void ParseTrue()
{
// check characters equal 'true'
// and that it is followed by either a separator character
// or the text ends
if (MatchValueWithTrailingSeparator(JsonConvert.True))
{
SetToken(JsonToken.Boolean, true);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNull()
{
if (MatchValueWithTrailingSeparator(JsonConvert.Null))
{
SetToken(JsonToken.Null);
}
else
{
throw JsonReaderException.Create(this, "Error parsing null value.");
}
}
private void ParseUndefined()
{
if (MatchValueWithTrailingSeparator(JsonConvert.Undefined))
{
SetToken(JsonToken.Undefined);
}
else
{
throw JsonReaderException.Create(this, "Error parsing undefined value.");
}
}
private void ParseFalse()
{
if (MatchValueWithTrailingSeparator(JsonConvert.False))
{
SetToken(JsonToken.Boolean, false);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNumberNegativeInfinity()
{
if (MatchValueWithTrailingSeparator(JsonConvert.NegativeInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read -Infinity as a decimal.");
SetToken(JsonToken.Float, double.NegativeInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing negative infinity value.");
}
}
private void ParseNumberPositiveInfinity()
{
if (MatchValueWithTrailingSeparator(JsonConvert.PositiveInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read Infinity as a decimal.");
SetToken(JsonToken.Float, double.PositiveInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing positive infinity value.");
}
}
private void ParseNumberNaN()
{
if (MatchValueWithTrailingSeparator(JsonConvert.NaN))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read NaN as a decimal.");
SetToken(JsonToken.Float, double.NaN);
}
else
{
throw JsonReaderException.Create(this, "Error parsing NaN value.");
}
}
/// <summary>
/// Changes the state to closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
_reader.Close();
#else
_reader.Dispose();
#endif
if (_buffer != null)
_buffer.Clear();
}
/// <summary>
/// Gets a value indicating whether the class can return line information.
/// </summary>
/// <returns>
/// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>.
/// </returns>
public bool HasLineInfo()
{
return true;
}
/// <summary>
/// Gets the current line number.
/// </summary>
/// <value>
/// The current line number or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LineNumber
{
get
{
if (CurrentState == State.Start && LinePosition == 0)
return 0;
return _lineNumber;
}
}
/// <summary>
/// Gets the current line position.
/// </summary>
/// <value>
/// The current line position or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LinePosition
{
get { return _charPos - _lineStartPos; }
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
using System.Linq.Expressions;
#endif
using System.Diagnostics;
using System.Runtime.CompilerServices;
//using Microsoft.Scripting.Generation;
namespace System.Management.Automation.Interpreter
{
/// <summary>
/// Manages creation of interpreted delegates. These delegates will get
/// compiled if they are executed often enough.
/// </summary>
internal sealed class LightDelegateCreator
{
// null if we are forced to compile
private readonly Interpreter _interpreter;
private readonly Expression _lambda;
// Adaptive compilation support:
private Type _compiledDelegateType;
private Delegate _compiled;
private readonly object _compileLock = new object();
internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda)
{
Assert.NotNull(lambda);
_interpreter = interpreter;
_lambda = lambda;
}
//internal LightDelegateCreator(Interpreter interpreter, LightLambdaExpression lambda) {
// Assert.NotNull(lambda);
// _interpreter = interpreter;
// _lambda = lambda;
//}
internal Interpreter Interpreter
{
get { return _interpreter; }
}
private bool HasClosure
{
get { return _interpreter != null && _interpreter.ClosureSize > 0; }
}
internal bool HasCompiled
{
get { return _compiled != null; }
}
/// <summary>
/// true if the compiled delegate has the same type as the lambda;
/// false if the type was changed for interpretation.
/// </summary>
internal bool SameDelegateType
{
get { return _compiledDelegateType == DelegateType; }
}
public Delegate CreateDelegate()
{
return CreateDelegate(null);
}
internal Delegate CreateDelegate(StrongBox<object>[] closure)
{
if (_compiled != null)
{
// If the delegate type we want is not a Func/Action, we can't
// use the compiled code directly. So instead just fall through
// and create an interpreted LightLambda, which will pick up
// the compiled delegate on its first run.
//
// Ideally, we would just rebind the compiled delegate using
// Delegate.CreateDelegate. Unfortunately, it doesn't work on
// dynamic methods.
if (SameDelegateType)
{
return CreateCompiledDelegate(closure);
}
}
if (_interpreter == null)
{
// We can't interpret, so force a compile
Compile(null);
Delegate compiled = CreateCompiledDelegate(closure);
Debug.Assert(compiled.GetType() == DelegateType);
return compiled;
}
// Otherwise, we'll create an interpreted LightLambda
return new LightLambda(this, closure, _interpreter._compilationThreshold).MakeDelegate(DelegateType);
}
private Type DelegateType
{
get
{
LambdaExpression le = _lambda as LambdaExpression;
if (le != null)
{
return le.Type;
}
return null;
//return ((LightLambdaExpression)_lambda).Type;
}
}
/// <summary>
/// Used by LightLambda to get the compiled delegate.
/// </summary>
internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure)
{
Debug.Assert(HasClosure == (closure != null));
if (HasClosure)
{
// We need to apply the closure to get the actual delegate.
var applyClosure = (Func<StrongBox<object>[], Delegate>)_compiled;
return applyClosure(closure);
}
return _compiled;
}
/// <summary>
/// Create a compiled delegate for the LightLambda, and saves it so
/// future calls to Run will execute the compiled code instead of
/// interpreting.
/// </summary>
internal void Compile(object state)
{
if (_compiled != null)
{
return;
}
// Compilation is expensive, we only want to do it once.
lock (_compileLock)
{
if (_compiled != null)
{
return;
}
//PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted lambda compiled");
// Interpreter needs a standard delegate type.
// So change the lambda's delegate type to Func<...> or
// Action<...> so it can be called from the LightLambda.Run
// methods.
LambdaExpression lambda = (_lambda as LambdaExpression);// ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce();
if (_interpreter != null)
{
_compiledDelegateType = GetFuncOrAction(lambda);
lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters);
}
if (HasClosure)
{
_compiled = LightLambdaClosureVisitor.BindLambda(lambda, _interpreter.ClosureVariables);
}
else
{
_compiled = lambda.Compile();
}
}
}
private static Type GetFuncOrAction(LambdaExpression lambda)
{
Type delegateType;
bool isVoid = lambda.ReturnType == typeof(void);
//if (isVoid && lambda.Parameters.Count == 2 &&
// lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) {
// return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type));
//} else {
Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type);
if (isVoid)
{
if (Expression.TryGetActionType(types, out delegateType))
{
return delegateType;
}
}
else
{
types = types.AddLast(lambda.ReturnType);
if (Expression.TryGetFuncType(types, out delegateType))
{
return delegateType;
}
}
return lambda.Type;
//}
}
}
}
| |
//
// Puller.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
#if !NET_3_5
using StringEx = System.String;
#endif
namespace Couchbase.Lite.Replicator
{
internal sealed class Puller : Replication, IChangeTrackerClient
{
#region Constants
internal const int MAX_ATTS_SINCE = 50;
internal const int CHANGE_TRACKER_RESTART_DELAY_MS = 10000;
private const string TAG = "Puller";
#endregion
#region Variables
//TODO: Socket change tracker
//private bool caughtUp;
private bool _canBulkGet;
private Batcher<RevisionInternal> _downloadsToInsert;
private IList<RevisionInternal> _revsToPull;
private IList<RevisionInternal> _deletedRevsToPull;
private IList<RevisionInternal> _bulkRevsToPull;
private ChangeTracker _changeTracker;
private SequenceMap _pendingSequences;
private volatile int _httpConnectionCount;
private readonly object _locker = new object ();
private List<Task> _pendingBulkDownloads = new List<Task>();
#endregion
#region Constructors
internal Puller(Database db, Uri remote, bool continuous, TaskFactory workExecutor)
: this(db, remote, continuous, null, workExecutor) { }
internal Puller(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory, TaskFactory workExecutor)
: base(db, remote, continuous, clientFactory, workExecutor) { }
#endregion
#region Private Methods
private void PauseOrResume()
{
var pending = 0;
if(Batcher != null) {
pending += Batcher.Count();
}
if(_pendingSequences != null) {
pending += _pendingSequences.Count;
}
if(_changeTracker != null) {
_changeTracker.Paused = pending >= 200;
}
}
private void StartChangeTracker()
{
Log.D(TAG, "starting ChangeTracker with since = " + LastSequence);
var mode = Continuous
? ChangeTrackerMode.LongPoll
: ChangeTrackerMode.OneShot;
_changeTracker = new ChangeTracker(RemoteUrl, mode, LastSequence, true, this, WorkExecutor);
_changeTracker.Authenticator = Authenticator;
if(DocIds != null) {
if(ServerType != null && ServerType.StartsWith("CouchDB")) {
_changeTracker.SetDocIDs(DocIds.ToList());
} else {
Log.W(TAG, "DocIds parameter only supported on CouchDB");
}
}
if (Filter != null) {
_changeTracker.SetFilterName(Filter);
if (FilterParams != null) {
_changeTracker.SetFilterParams(FilterParams.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
}
}
_changeTracker.UsePost = CheckServerCompatVersion("0.93");
_changeTracker.Start();
}
private void ProcessChangeTrackerStopped(ChangeTracker tracker)
{
if (Continuous) {
if (_stateMachine.State == ReplicationState.Offline) {
// in this case, we don't want to do anything here, since
// we told the change tracker to go offline ..
Log.D(TAG, "Change tracker stopped because we are going offline");
} else if (_stateMachine.State == ReplicationState.Stopping || _stateMachine.State == ReplicationState.Stopped) {
Log.D(TAG, "Change tracker stopped because replicator is stopping or stopped.");
} else {
// otherwise, try to restart the change tracker, since it should
// always be running in continuous replications
const string msg = "Change tracker stopped during continuous replication";
Log.E(TAG, msg);
LastError = new Exception(msg);
FireTrigger(ReplicationTrigger.WaitingForChanges);
Log.D(TAG, "Scheduling change tracker restart in {0} ms", CHANGE_TRACKER_RESTART_DELAY_MS);
Task.Delay(CHANGE_TRACKER_RESTART_DELAY_MS).ContinueWith(t =>
{
// the replication may have been stopped by the time this scheduled fires
// so we need to check the state here.
if(_stateMachine.IsInState(ReplicationState.Running)) {
Log.D(TAG, "Still runing, restarting change tracker");
StartChangeTracker();
} else {
Log.D(TAG, "No longer running, not restarting change tracker");
}
});
}
} else {
if (LastError == null && tracker.Error != null) {
LastError = tracker.Error;
}
FireTrigger(ReplicationTrigger.StopGraceful);
}
}
private void FinishStopping()
{
StopRemoteRequests();
lock (_locker) {
_revsToPull = null;
_deletedRevsToPull = null;
_bulkRevsToPull = null;
}
if (_downloadsToInsert != null) {
_downloadsToInsert.FlushAll();
}
FireTrigger(ReplicationTrigger.StopImmediate);
}
private void ReplicationChanged(object sender, ReplicationChangeEventArgs args)
{
if (args.Source.CompletedChangesCount < args.Source.ChangesCount) {
return;
}
Changed -= ReplicationChanged;
FinishStopping();
}
private string JoinQuotedEscaped(IList<string> strings)
{
if (strings.Count == 0) {
return "[]";
}
IEnumerable<Byte> json = null;
try {
json = Manager.GetObjectMapper().WriteValueAsBytes(strings);
} catch (Exception e) {
Log.W(TAG, "Unable to serialize json", e);
}
return Uri.EscapeUriString(Runtime.GetStringForBytes(json));
}
private void QueueRemoteRevision(RevisionInternal rev)
{
if (rev.IsDeleted()) {
if (_deletedRevsToPull == null) {
_deletedRevsToPull = new List<RevisionInternal>(100);
}
_deletedRevsToPull.AddItem(rev);
} else {
if (_revsToPull == null) {
_revsToPull = new List<RevisionInternal>(100);
}
_revsToPull.AddItem(rev);
}
}
/// <summary>
/// Start up some HTTP GETs, within our limit on the maximum simultaneous number
/// The entire method is not synchronized, only the portion pulling work off the list
/// Important to not hold the synchronized block while we do network access
/// </summary>
private void PullRemoteRevisions()
{
//find the work to be done in a synchronized block
var workToStartNow = new List<RevisionInternal>();
var bulkWorkToStartNow = new List<RevisionInternal>();
lock (_locker)
{
while (LocalDatabase != null && _httpConnectionCount + bulkWorkToStartNow.Count + workToStartNow.Count < ManagerOptions.Default.MaxOpenHttpConnections)
{
int nBulk = 0;
if (_bulkRevsToPull != null) {
nBulk = Math.Min(_bulkRevsToPull.Count, ManagerOptions.Default.MaxRevsToGetInBulk);
}
if (nBulk == 1) {
// Rather than pulling a single revision in 'bulk', just pull it normally:
QueueRemoteRevision(_bulkRevsToPull[0]);
_bulkRevsToPull.Remove(0);
nBulk = 0;
}
if (nBulk > 0) {
// Prefer to pull bulk revisions:
var range = new Couchbase.Lite.Util.ArraySegment<RevisionInternal>(_bulkRevsToPull.ToArray(), 0, nBulk);
bulkWorkToStartNow.AddRange(range);
_bulkRevsToPull.RemoveAll(range);
} else {
// Prefer to pull an existing revision over a deleted one:
IList<RevisionInternal> queue = _revsToPull;
if (queue == null || queue.Count == 0) {
queue = _deletedRevsToPull;
if (queue == null || queue.Count == 0) {
break; // both queues are empty
}
}
workToStartNow.AddItem(queue[0]);
queue.Remove(0);
}
}
}
//actually run it outside the synchronized block
if (bulkWorkToStartNow.Count > 0) {
PullBulkRevisions(bulkWorkToStartNow);
}
foreach (var rev in workToStartNow) {
PullRemoteRevision(rev);
}
}
// Get a bunch of revisions in one bulk request. Will use _bulk_get if possible.
private void PullBulkRevisions(IList<RevisionInternal> bulkRevs)
{
var nRevs = bulkRevs == null ? 0 : bulkRevs.Count;
if (nRevs == 0) {
return;
}
Log.D(TAG, "{0} bulk-fetching {1} remote revisions...", this, nRevs);
Log.V(TAG, "{0} bulk-fetching remote revisions: {1}", this, bulkRevs);
if (!_canBulkGet) {
PullBulkWithAllDocs(bulkRevs);
return;
}
Log.V(TAG, "POST _bulk_get");
var remainingRevs = new List<RevisionInternal>(bulkRevs);
++_httpConnectionCount;
BulkDownloader dl;
try
{
dl = new BulkDownloader(WorkExecutor, ClientFactory, RemoteUrl, bulkRevs, LocalDatabase, RequestHeaders);
dl.DocumentDownloaded += (sender, args) =>
{
var props = args.DocumentProperties;
var rev = props.Get ("_id") != null
? new RevisionInternal (props)
: new RevisionInternal (props.GetCast<string> ("id"), props.GetCast<string> ("rev"), false);
var pos = remainingRevs.IndexOf(rev);
if (pos > -1) {
rev.SetSequence(remainingRevs[pos].GetSequence());
remainingRevs.RemoveAt(pos);
} else {
Log.W(TAG, "Received unexpected rev {0}; ignoring", rev);
return;
}
if (props.GetCast<string>("_id") != null) {
// Add to batcher ... eventually it will be fed to -insertRevisions:.
QueueDownloadedRevision(rev);
} else {
var status = StatusFromBulkDocsResponseItem(props);
LastError = new CouchbaseLiteException(status.Code);
RevisionFailed();
SafeIncrementCompletedChangesCount();
}
};
dl.Complete += (sender, args) =>
{
if (args != null && args.Error != null) {
RevisionFailed();
if(remainingRevs.Count == 0) {
LastError = args.Error;
}
} else if(remainingRevs.Count > 0) {
Log.W(TAG, "{0} revs not returned from _bulk_get: {1}",
remainingRevs.Count, remainingRevs);
for(int i = 0; i < remainingRevs.Count; i++) {
var rev = remainingRevs[i];
if(ShouldRetryDownload(rev.GetDocId())) {
_bulkRevsToPull.Add(remainingRevs[i]);
} else {
LastError = args.Error;
SafeIncrementCompletedChangesCount();
}
}
}
SafeAddToCompletedChangesCount(remainingRevs.Count);
--_httpConnectionCount;
PullRemoteRevisions();
};
} catch (Exception) {
return;
}
dl.Authenticator = Authenticator;
var t = WorkExecutor.StartNew(dl.Run, CancellationTokenSource.Token, TaskCreationOptions.LongRunning, WorkExecutor.Scheduler);
t.ConfigureAwait(false).GetAwaiter().OnCompleted(() => _pendingBulkDownloads.Remove(t));
_pendingBulkDownloads.Add(t);
}
private bool ShouldRetryDownload(string docId)
{
var localDoc = LocalDatabase.GetExistingLocalDocument(docId);
if (localDoc == null)
{
LocalDatabase.PutLocalDocument(docId, new Dictionary<string, object>
{
{"retryCount", 1}
});
return true;
}
var retryCount = (long)localDoc["retryCount"];
if (retryCount >= ManagerOptions.Default.MaxRetries)
{
PruneFailedDownload(docId);
return false;
}
localDoc["retryCount"] = (long)localDoc["retryCount"] + 1;
LocalDatabase.PutLocalDocument(docId, localDoc);
return true;
}
private void PruneFailedDownload(string docId)
{
LocalDatabase.DeleteLocalDocument(docId);
}
// This invokes the tranformation block if one is installed and queues the resulting Revision
private void QueueDownloadedRevision(RevisionInternal rev)
{
if (RevisionBodyTransformationFunction != null)
{
// Add 'file' properties to attachments pointing to their bodies:
foreach (var entry in rev.GetProperties().Get("_attachments").AsDictionary<string,object>())
{
var attachment = entry.Value as IDictionary<string, object>;
attachment.Remove("file");
if (attachment.Get("follows") != null && attachment.Get("data") == null)
{
var filePath = LocalDatabase.FileForAttachmentDict(attachment).AbsolutePath;
if (filePath != null)
{
attachment["file"] = filePath;
}
}
}
var xformed = TransformRevision(rev);
if (xformed == null)
{
Log.V(TAG, "Transformer rejected revision {0}", rev);
_pendingSequences.RemoveSequence(rev.GetSequence());
LastSequence = _pendingSequences.GetCheckpointedValue();
PauseOrResume();
return;
}
rev = xformed;
var attachments = (IDictionary<string, IDictionary<string, object>>)rev.GetProperties().Get("_attachments");
foreach (var entry in attachments.EntrySet())
{
var attachment = entry.Value;
attachment.Remove("file");
}
}
//TODO: rev.getBody().compact();
if (_downloadsToInsert != null) {
_downloadsToInsert.QueueObject(rev);
}
else {
Log.I(TAG, "downloadsToInsert is null");
}
}
// Get as many revisions as possible in one _all_docs request.
// This is compatible with CouchDB, but it only works for revs of generation 1 without attachments.
private void PullBulkWithAllDocs(IList<RevisionInternal> bulkRevs)
{
// http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API
++_httpConnectionCount;
var remainingRevs = new List<RevisionInternal>(bulkRevs);
var keys = bulkRevs.Select(rev => rev.GetDocId()).ToArray();
var body = new Dictionary<string, object>();
body.Put("keys", keys);
SendAsyncRequest(HttpMethod.Post, "/_all_docs?include_docs=true", body, (result, e) =>
{
var res = result.AsDictionary<string, object>();
if (e != null) {
LastError = e;
RevisionFailed();
SafeAddToCompletedChangesCount(bulkRevs.Count);
} else {
// Process the resulting rows' documents.
// We only add a document if it doesn't have attachments, and if its
// revID matches the one we asked for.
var rows = res.Get ("rows").AsList<IDictionary<string, object>>();
Log.V (TAG, "Checking {0} bulk-fetched remote revisions", rows.Count);
foreach (var row in rows) {
var doc = row.Get ("doc").AsDictionary<string, object>();
if (doc != null && doc.Get ("_attachments") == null)
{
var rev = new RevisionInternal (doc);
var pos = remainingRevs.IndexOf (rev);
if (pos > -1)
{
rev.SetSequence(remainingRevs[pos].GetSequence());
remainingRevs.Remove (pos);
QueueDownloadedRevision (rev);
}
}
}
}
// Any leftover revisions that didn't get matched will be fetched individually:
if (remainingRevs.Count > 0)
{
Log.V (TAG, "Bulk-fetch didn't work for {0} of {1} revs; getting individually", remainingRevs.Count, bulkRevs.Count);
foreach (var rev in remainingRevs)
{
QueueRemoteRevision (rev);
}
PullRemoteRevisions ();
}
--_httpConnectionCount;
// Start another task if there are still revisions waiting to be pulled:
PullRemoteRevisions();
});
}
/// <summary>Fetches the contents of a revision from the remote db, including its parent revision ID.
/// </summary>
/// <remarks>
/// Fetches the contents of a revision from the remote db, including its parent revision ID.
/// The contents are stored into rev.properties.
/// </remarks>
private void PullRemoteRevision(RevisionInternal rev)
{
Log.D(TAG, "PullRemoteRevision with rev: {0}", rev);
_httpConnectionCount++;
// Construct a query. We want the revision history, and the bodies of attachments that have
// been added since the latest revisions we have locally.
// See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document
var path = new StringBuilder("/" + Uri.EscapeUriString(rev.GetDocId()) + "?rev=" + Uri.EscapeUriString(rev.GetRevId()) + "&revs=true&attachments=true");
var tmp = LocalDatabase.Storage.GetPossibleAncestors(rev, MAX_ATTS_SINCE, true);
var knownRevs = tmp == null ? null : tmp.ToList();
if (knownRevs == null) {
//this means something is wrong, possibly the replicator has shut down
_httpConnectionCount--;
return;
}
if (knownRevs.Count > 0) {
path.Append("&atts_since=");
path.Append(JoinQuotedEscaped(knownRevs));
}
//create a final version of this variable for the log statement inside
//FIXME find a way to avoid this
var pathInside = path.ToString();
SendAsyncMultipartDownloaderRequest(HttpMethod.Get, pathInside, null, LocalDatabase, (result, e) =>
{
// OK, now we've got the response revision:
Log.D (TAG, "PullRemoteRevision got response for rev: " + rev);
if (e != null) {
Log.E (TAG, "Error pulling remote revision", e);
LastError = e;
RevisionFailed();
Log.D(TAG, "PullRemoteRevision updating completedChangesCount from " +
CompletedChangesCount + " -> " + (CompletedChangesCount + 1)
+ " due to error pulling remote revision");
SafeIncrementCompletedChangesCount();
} else {
var properties = result.AsDictionary<string, object>();
var gotRev = new PulledRevision(properties);
gotRev.SetSequence(rev.GetSequence());
Log.D(TAG, "PullRemoteRevision add rev: " + gotRev + " to batcher");
if (_downloadsToInsert != null) {
_downloadsToInsert.QueueObject(gotRev);
} else {
Log.E (TAG, "downloadsToInsert is null");
}
}
// Note that we've finished this task; then start another one if there
// are still revisions waiting to be pulled:
--_httpConnectionCount;
PullRemoteRevisions ();
});
}
/// <summary>This will be called when _revsToInsert fills up:</summary>
private void InsertDownloads(IList<RevisionInternal> downloads)
{
Log.V(TAG, "Inserting {0} revisions...", downloads.Count);
var time = DateTime.UtcNow;
downloads.Sort(new RevisionComparer());
if (LocalDatabase == null) {
return;
}
try {
var success = LocalDatabase.RunInTransaction(() =>
{
foreach (var rev in downloads) {
var fakeSequence = rev.GetSequence();
rev.SetSequence(0L);
var history = Database.ParseCouchDBRevisionHistory(rev.GetProperties());
if (history.Count == 0 && rev.GetGeneration() > 1) {
Log.W(TAG, "Missing revision history in response for: {0}", rev);
LastError = new CouchbaseLiteException(StatusCode.UpStreamError);
RevisionFailed();
continue;
}
Log.V(TAG, String.Format("Inserting {0} {1}", rev.GetDocId(), Manager.GetObjectMapper().WriteValueAsString(history)));
// Insert the revision:
try {
LocalDatabase.ForceInsert(rev, history, RemoteUrl);
} catch (CouchbaseLiteException e) {
if (e.Code == StatusCode.Forbidden) {
Log.I(TAG, "Remote rev failed validation: " + rev);
} else if(e.Code == StatusCode.DbBusy) {
// abort transaction; RunInTransaction will retry
return false;
} else {
Log.W(TAG, " failed to write {0}: status={1}", rev, e.Code);
RevisionFailed();
LastError = e;
continue;
}
} catch (Exception e) {
Log.E(TAG, "Exception inserting downloads.", e);
throw;
}
_pendingSequences.RemoveSequence(fakeSequence);
}
Log.D(TAG, " Finished inserting " + downloads.Count + " revisions");
return true;
});
Log.V(TAG, "Finished inserting {0} revisions. Success == {1}", downloads.Count, success);
} catch (Exception e) {
Log.E(TAG, "Exception inserting revisions", e);
}
// Checkpoint:
LastSequence = _pendingSequences.GetCheckpointedValue();
var delta = (DateTime.UtcNow - time).TotalMilliseconds;
Log.D(TAG, "Inserted {0} revs in {1} milliseconds", downloads.Count, delta);
var newCompletedChangesCount = CompletedChangesCount + downloads.Count;
Log.D(TAG, "InsertDownloads() updating CompletedChangesCount from {0} -> {1}", CompletedChangesCount, newCompletedChangesCount);
SafeAddToCompletedChangesCount(downloads.Count);
PauseOrResume();
}
#endregion
#region Overrides
public override bool CreateTarget { get { return false; } set { return; /* No-op intended. Only used in Pusher. */ } }
public override bool IsPull { get { return true; } }
public override IEnumerable<string> DocIds { get; set; }
public override IDictionary<string, string> Headers
{
get { return clientFactory.Headers; }
set { clientFactory.Headers = value; }
}
protected override void StopGraceful()
{
var changeTrackerCopy = _changeTracker;
if (changeTrackerCopy != null) {
Log.D(TAG, "stopping changetracker " + _changeTracker);
changeTrackerCopy.SetClient(null);
// stop it from calling my changeTrackerStopped()
changeTrackerCopy.Stop();
_changeTracker = null;
}
base.StopGraceful();
if (CompletedChangesCount == ChangesCount) {
FinishStopping();
} else {
Changed += ReplicationChanged;
}
}
protected override void PerformGoOffline()
{
base.PerformGoOffline();
if (_changeTracker != null) {
_changeTracker.Stop();
}
StopRemoteRequests();
}
protected override void PerformGoOnline()
{
base.PerformGoOnline();
BeginReplicating();
}
internal override void ProcessInbox(RevisionList inbox)
{
if (Status == ReplicationStatus.Offline) {
Log.D(TAG, "Offline, so skipping inbox process");
return;
}
Debug.Assert(inbox != null);
if (!_canBulkGet) {
_canBulkGet = CheckServerCompatVersion("0.81");
}
// Ask the local database which of the revs are not known to it:
var lastInboxSequence = ((PulledRevision)inbox[inbox.Count - 1]).GetRemoteSequenceID();
var numRevisionsRemoved = 0;
try {
// findMissingRevisions is the local equivalent of _revs_diff. it looks at the
// array of revisions in inbox and removes the ones that already exist. So whatever's left in inbox
// afterwards are the revisions that need to be downloaded.
numRevisionsRemoved = LocalDatabase.Storage.FindMissingRevisions(inbox);
} catch (Exception e) {
Log.W(TAG, "Failed to look up local revs", e);
inbox = null;
}
var inboxCount = 0;
if (inbox != null) {
inboxCount = inbox.Count;
}
if (numRevisionsRemoved > 0)
{
// Some of the revisions originally in the inbox aren't missing; treat those as processed:
SafeAddToCompletedChangesCount(numRevisionsRemoved);
}
if (inboxCount == 0) {
// Nothing to do. Just bump the lastSequence.
Log.V(TAG, string.Format("{0} no new remote revisions to fetch", this));
var seq = _pendingSequences.AddValue(lastInboxSequence);
_pendingSequences.RemoveSequence(seq);
LastSequence = _pendingSequences.GetCheckpointedValue();
PauseOrResume();
return;
}
Log.V(TAG, "Queuing {0} remote revisions...", inboxCount);
// Dump the revs into the queue of revs to pull from the remote db:
lock (_locker) {
int numBulked = 0;
for (int i = 0; i < inboxCount; i++) {
var rev = (PulledRevision)inbox[i];
//TODO: add support for rev isConflicted
if (_canBulkGet || (rev.GetGeneration() == 1 && !rev.IsDeleted() && !rev.IsConflicted)) {
//optimistically pull 1st-gen revs in bulk
if (_bulkRevsToPull == null) {
_bulkRevsToPull = new List<RevisionInternal>(100);
}
_bulkRevsToPull.AddItem(rev);
++numBulked;
} else {
QueueRemoteRevision(rev);
}
rev.SetSequence(_pendingSequences.AddValue(rev.GetRemoteSequenceID()));
}
Log.D(TAG, "Queued {0} remote revisions from seq={1} ({2} in bulk, {3} individually)", inboxCount,
((PulledRevision)inbox[0]).GetRemoteSequenceID(), numBulked, inboxCount - numBulked);
}
PullRemoteRevisions();
PauseOrResume();
}
internal override void BeginReplicating()
{
Log.D(TAG, string.Format("Using MaxOpenHttpConnections({0}), MaxRevsToGetInBulk({1})",
ManagerOptions.Default.MaxOpenHttpConnections, ManagerOptions.Default.MaxRevsToGetInBulk));
if (_downloadsToInsert == null) {
const int capacity = 200;
const int delay = 1000;
_downloadsToInsert = new Batcher<RevisionInternal>(WorkExecutor, capacity, delay, InsertDownloads);
}
if (_pendingSequences == null) {
_pendingSequences = new SequenceMap();
if (LastSequence != null) {
// Prime _pendingSequences so its checkpointedValue will reflect the last known seq:
var seq = _pendingSequences.AddValue(LastSequence);
_pendingSequences.RemoveSequence(seq);
Debug.Assert((_pendingSequences.GetCheckpointedValue().Equals(LastSequence)));
}
}
StartChangeTracker();
}
internal override void Stopping()
{
_downloadsToInsert = null;
base.Stopping();
}
#endregion
#region IChangeTrackerClient
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
var lastSequence = change.Get("seq").ToString();
var docID = (string)change.Get("id");
if (docID == null) {
return;
}
if (!LocalDatabase.IsValidDocumentId(docID)) {
if (!docID.StartsWith("_user/", StringComparison.InvariantCultureIgnoreCase)) {
Log.W(TAG, string.Format("{0}: Received invalid doc ID from _changes: {1} ({2})", this, docID, Manager.GetObjectMapper().WriteValueAsString(change)));
}
return;
}
var deleted = change.GetCast<bool>("deleted");
var changes = change.Get("changes").AsList<object>();
SafeAddToChangesCount(changes.Count);
foreach (var changeObj in changes) {
var changeDict = changeObj.AsDictionary<string, object>();
var revID = changeDict.GetCast<string>("rev");
if (revID == null) {
continue;
}
var rev = new PulledRevision(docID, revID, deleted, LocalDatabase);
rev.SetRemoteSequenceID(lastSequence);
if (changes.Count > 1) {
rev.IsConflicted = true;
}
Log.D(TAG, "Adding rev to inbox " + rev);
AddToInbox(rev);
}
PauseOrResume();
while (_revsToPull != null && _revsToPull.Count > 1000) {
try {
// Presumably we are letting 1 or more other threads do something while we wait.
Thread.Sleep(500);
}
catch (Exception e) {
Log.W(TAG, "Swalling exception while sleeping after receiving changetracker changes.", e);
// swallow
}
}
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
WorkExecutor.StartNew(() => ProcessChangeTrackerStopped(tracker));
}
public HttpClient GetHttpClient(bool longPoll)
{
var client = ClientFactory.GetHttpClient(longPoll);
var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator;
if (challengeResponseAuth != null) {
var authHandler = ClientFactory.Handler as DefaultAuthHandler;
if (authHandler != null) {
authHandler.Authenticator = challengeResponseAuth;
}
}
return client;
}
#endregion
#region Nested Classes
private sealed class RevisionComparer : IComparer<RevisionInternal>
{
public RevisionComparer() { }
public int Compare(RevisionInternal reva, RevisionInternal revb)
{
return Misc.TDSequenceCompare(reva != null ? reva.GetSequence() : -1L, revb != null ? revb.GetSequence() : -1L);
}
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Controller class for MAM_AnatomiaPatologica
/// </summary>
[System.ComponentModel.DataObject]
public partial class MamAnatomiaPatologicaController
{
// Preload our schema..
MamAnatomiaPatologica thisSchemaLoad = new MamAnatomiaPatologica();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public MamAnatomiaPatologicaCollection FetchAll()
{
MamAnatomiaPatologicaCollection coll = new MamAnatomiaPatologicaCollection();
Query qry = new Query(MamAnatomiaPatologica.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public MamAnatomiaPatologicaCollection FetchByID(object IdAnatomiaPatologica)
{
MamAnatomiaPatologicaCollection coll = new MamAnatomiaPatologicaCollection().Where("idAnatomiaPatologica", IdAnatomiaPatologica).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public MamAnatomiaPatologicaCollection FetchByQuery(Query qry)
{
MamAnatomiaPatologicaCollection coll = new MamAnatomiaPatologicaCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdAnatomiaPatologica)
{
return (MamAnatomiaPatologica.Delete(IdAnatomiaPatologica) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdAnatomiaPatologica)
{
return (MamAnatomiaPatologica.Destroy(IdAnatomiaPatologica) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int IdPaciente,int Edad,int GanglioAxilar,int NoduloMama,int Microcalcificaciones,int Piel,int Derrame,DateTime FechaTomaMuestra,DateTime FechaRecepcionMuestra,DateTime FechaInformeMuestra,string NumeroIngreso,int IdResponsableMuestra,int IdCentroSaludMuestra,int IdDiagnosticoCitologico,int IdDiagnosticoHistologico,DateTime FechaInforme,int IdResponsableInforme,int IdCentroSaludInforme,string Observaciones,bool Activo,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn,string Guia,string Metodo)
{
MamAnatomiaPatologica item = new MamAnatomiaPatologica();
item.IdPaciente = IdPaciente;
item.Edad = Edad;
item.GanglioAxilar = GanglioAxilar;
item.NoduloMama = NoduloMama;
item.Microcalcificaciones = Microcalcificaciones;
item.Piel = Piel;
item.Derrame = Derrame;
item.FechaTomaMuestra = FechaTomaMuestra;
item.FechaRecepcionMuestra = FechaRecepcionMuestra;
item.FechaInformeMuestra = FechaInformeMuestra;
item.NumeroIngreso = NumeroIngreso;
item.IdResponsableMuestra = IdResponsableMuestra;
item.IdCentroSaludMuestra = IdCentroSaludMuestra;
item.IdDiagnosticoCitologico = IdDiagnosticoCitologico;
item.IdDiagnosticoHistologico = IdDiagnosticoHistologico;
item.FechaInforme = FechaInforme;
item.IdResponsableInforme = IdResponsableInforme;
item.IdCentroSaludInforme = IdCentroSaludInforme;
item.Observaciones = Observaciones;
item.Activo = Activo;
item.CreatedBy = CreatedBy;
item.CreatedOn = CreatedOn;
item.ModifiedBy = ModifiedBy;
item.ModifiedOn = ModifiedOn;
item.Guia = Guia;
item.Metodo = Metodo;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdAnatomiaPatologica,int IdPaciente,int Edad,int GanglioAxilar,int NoduloMama,int Microcalcificaciones,int Piel,int Derrame,DateTime FechaTomaMuestra,DateTime FechaRecepcionMuestra,DateTime FechaInformeMuestra,string NumeroIngreso,int IdResponsableMuestra,int IdCentroSaludMuestra,int IdDiagnosticoCitologico,int IdDiagnosticoHistologico,DateTime FechaInforme,int IdResponsableInforme,int IdCentroSaludInforme,string Observaciones,bool Activo,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn,string Guia,string Metodo)
{
MamAnatomiaPatologica item = new MamAnatomiaPatologica();
item.MarkOld();
item.IsLoaded = true;
item.IdAnatomiaPatologica = IdAnatomiaPatologica;
item.IdPaciente = IdPaciente;
item.Edad = Edad;
item.GanglioAxilar = GanglioAxilar;
item.NoduloMama = NoduloMama;
item.Microcalcificaciones = Microcalcificaciones;
item.Piel = Piel;
item.Derrame = Derrame;
item.FechaTomaMuestra = FechaTomaMuestra;
item.FechaRecepcionMuestra = FechaRecepcionMuestra;
item.FechaInformeMuestra = FechaInformeMuestra;
item.NumeroIngreso = NumeroIngreso;
item.IdResponsableMuestra = IdResponsableMuestra;
item.IdCentroSaludMuestra = IdCentroSaludMuestra;
item.IdDiagnosticoCitologico = IdDiagnosticoCitologico;
item.IdDiagnosticoHistologico = IdDiagnosticoHistologico;
item.FechaInforme = FechaInforme;
item.IdResponsableInforme = IdResponsableInforme;
item.IdCentroSaludInforme = IdCentroSaludInforme;
item.Observaciones = Observaciones;
item.Activo = Activo;
item.CreatedBy = CreatedBy;
item.CreatedOn = CreatedOn;
item.ModifiedBy = ModifiedBy;
item.ModifiedOn = ModifiedOn;
item.Guia = Guia;
item.Metodo = Metodo;
item.Save(UserName);
}
}
}
| |
#region Licensing notice
// Copyright (C) 2012, Alexander Wieser-Kuciel <alexander.wieser@crystalbyte.de>
//
// 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 directives
using System;
using System.Collections.Generic;
using System.IO;
using Crystalbyte.Spectre.Razor.Templates;
#endregion
namespace Crystalbyte.Spectre.Razor.Hosting.Containers {
/// <summary>
/// Based Host implementation for hosting the RazorHost. This base
/// acts as a wrapper for implementing high level host services around
/// the RazorHost class. For example implementations can provide assembly
/// template caching so assemblies don't recompile for each access.
/// </summary>
/// <typeparam name="TBaseTemplateType"> The RazorTemplateBase class that templates will be based on </typeparam>
public abstract class RazorBaseHostContainer<TBaseTemplateType> : MarshalByRefObject
where TBaseTemplateType : RazorTemplateBase, new() {
protected RazorBaseHostContainer() {
UseAppDomain = true;
GeneratedNamespace = "__RazorHost";
ReferencedAssemblies = new List<string>();
ReferencedNamespaces = new List<string>();
Configuration = new RazorEngineConfiguration();
}
/// <summary>
/// Determines whether the Container hosts Razor
/// in a separate AppDomain. Seperate AppDomain
/// hosting allows unloading and releasing of
/// resources.
/// </summary>
public bool UseAppDomain { get; set; }
/// <summary>
/// Base folder location where the AppDomain
/// is hosted. By default uses the same folder
/// as the host application.
///
/// Determines where binary dependencies are
/// found for assembly references.
/// </summary>
public string BaseBinaryFolder { get; set; }
/// <summary>
/// List of referenced assemblies as string values.
/// Must be in GAC or in the current folder of the host app/
/// base BinaryFolder
/// </summary>
public List<string> ReferencedAssemblies { get; set; }
/// <summary>
/// List of additional namespaces to add to all templates.
///
/// By default:
/// System, System.Text, System.IO, System.Linq
/// </summary>
public List<string> ReferencedNamespaces { get; set; }
/// <summary>
/// Name of the generated namespace for template classes
/// </summary>
public string GeneratedNamespace { get; set; }
/// <summary>
/// Any error messages
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Cached instance of the Host. Required to keep the
/// reference to the host alive for multiple uses.
/// </summary>
public RazorEngine<TBaseTemplateType> Engine;
/// <summary>
/// Cached instance of the Host Factory - so we can unload
/// the host and its associated AppDomain.
/// </summary>
protected RazorEngineFactory<TBaseTemplateType> EngineFactory;
/// <summary>
/// Keep track of each compiled assembly
/// and when it was compiled.
///
/// Use a hash of the string to identify string
/// changes.
/// </summary>
protected Dictionary<int, CompiledAssemblyItem> LoadedAssemblies = new Dictionary<int, CompiledAssemblyItem>();
/// <summary>
/// Engine Configuration
/// </summary>
public RazorEngineConfiguration Configuration { get; set; }
/// <summary>
/// Call to start the Host running. Follow by a calls to RenderTemplate to
/// render individual templates. Call Stop when done.
/// </summary>
/// <returns> true or false - check ErrorMessage on false </returns>
public virtual bool Start() {
if (Engine == null) {
if (UseAppDomain)
Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHostInAppDomain();
else
Engine = RazorEngineFactory<TBaseTemplateType>.CreateRazorHost();
if (Engine == null)
return false;
Engine.HostContainer = this;
Engine.ReferencedNamespaces.AddRange(ReferencedNamespaces);
Engine.Configuration = Configuration;
if (Engine == null) {
ErrorMessage = EngineFactory.ErrorMessage;
return false;
}
}
return true;
}
/// <summary>
/// Stops the Host and releases the host AppDomain and cached
/// assemblies.
/// </summary>
/// <returns> true or false </returns>
public bool Stop() {
LoadedAssemblies.Clear();
RazorEngineFactory<RazorTemplateBase>.UnloadRazorHostInAppDomain();
Engine = null;
return true;
}
/// <summary>
/// Stock implementation of RenderTemplate that doesn't allow for
/// any sort of assembly caching. Instead it creates and re-renders
/// templates read from the reader each time.
///
/// Custom implementations of RenderTemplate should be created that
/// allow for caching by examing a filename or string hash to determine
/// whether a template needs to be re-generated and compiled before
/// rendering.
/// </summary>
/// <param name="reader"> TextReader that points at the template to compile </param>
/// <param name="context"> Optional context to pass to template </param>
/// <param name="writer"> TextReader passed in that receives output </param>
/// <returns> </returns>
public bool RenderTemplate(TextReader reader, object context, TextWriter writer) {
var assemblyId = Engine.ParseAndCompileTemplate(ReferencedAssemblies.ToArray(), reader);
if (assemblyId == null) {
ErrorMessage = Engine.ErrorMessage;
return false;
}
return RenderTemplateFromAssembly(assemblyId, context, writer);
}
/// <summary>
/// Renders a template based on a previously compiled assembly reference. This method allows for
/// caching assemblies by their assembly Id.
/// </summary>
/// <param name="assemblyId"> Id of a previously compiled assembly </param>
/// <param name="context"> Optional context object </param>
/// <param name="writer"> Output writer </param>
/// <param name="nameSpace"> Namespace for compiled template to execute </param>
/// <param name="className"> Class name for compiled template to execute </param>
/// <returns> </returns>
protected bool RenderTemplateFromAssembly(string assemblyId, object context, TextWriter writer) {
// String result will be empty as output will be rendered into the
// Response object's stream output. However a null result denotes
// an error
var result = Engine.RenderTemplateFromAssembly(assemblyId, context, writer);
if (result == null) {
ErrorMessage = Engine.ErrorMessage;
return false;
}
return true;
}
/// <summary>
/// Returns a unique ClassName for a template to execute
/// Optionally pass in an objectId on which the code is based
/// or null to get default behavior.
///
/// Default implementation just returns Guid as string
/// </summary>
/// <param name="objectId"> </param>
/// <returns> </returns>
protected virtual string GetSafeClassName(object objectId) {
return "_" + Guid.NewGuid().ToString().Replace("-", "_");
}
/// <summary>
/// Force this host to stay alive indefinitely
/// </summary>
/// <returns> </returns>
public override object InitializeLifetimeService() {
return null;
}
/// <summary>
/// Sets an error message consistently
/// </summary>
/// <param name="message"> </param>
protected void SetError(string message) {
if (message == null)
ErrorMessage = string.Empty;
ErrorMessage = message;
}
/// <summary>
/// Sets an error message consistently
/// </summary>
protected void SetError() {
SetError(null);
}
}
}
| |
/*
* OEML - REST API
*
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
*
* The version of the OpenAPI document: v1
* Contact: support@coinapi.io
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using RestSharp;
using CoinAPI.OMS.REST.V1.Client;
using CoinAPI.OMS.REST.V1.Model;
namespace CoinAPI.OMS.REST.V1.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IOrdersApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Cancel all orders request
/// </summary>
/// <remarks>
/// This request cancels all open orders on single specified exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <returns>MessageReject</returns>
MessageReject V1OrdersCancelAllPost (OrderCancelAllRequest orderCancelAllRequest);
/// <summary>
/// Cancel all orders request
/// </summary>
/// <remarks>
/// This request cancels all open orders on single specified exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <returns>ApiResponse of MessageReject</returns>
ApiResponse<MessageReject> V1OrdersCancelAllPostWithHttpInfo (OrderCancelAllRequest orderCancelAllRequest);
/// <summary>
/// Cancel order request
/// </summary>
/// <remarks>
/// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <returns>OrderExecutionReport</returns>
OrderExecutionReport V1OrdersCancelPost (OrderCancelSingleRequest orderCancelSingleRequest);
/// <summary>
/// Cancel order request
/// </summary>
/// <remarks>
/// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
ApiResponse<OrderExecutionReport> V1OrdersCancelPostWithHttpInfo (OrderCancelSingleRequest orderCancelSingleRequest);
/// <summary>
/// Get open orders
/// </summary>
/// <remarks>
/// Get last execution reports for open orders across all or single exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <returns>List<OrderExecutionReport></returns>
List<OrderExecutionReport> V1OrdersGet (string exchangeId = default(string));
/// <summary>
/// Get open orders
/// </summary>
/// <remarks>
/// Get last execution reports for open orders across all or single exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <returns>ApiResponse of List<OrderExecutionReport></returns>
ApiResponse<List<OrderExecutionReport>> V1OrdersGetWithHttpInfo (string exchangeId = default(string));
/// <summary>
/// Send new order
/// </summary>
/// <remarks>
/// This request creating new order for the specific exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <returns>OrderExecutionReport</returns>
OrderExecutionReport V1OrdersPost (OrderNewSingleRequest orderNewSingleRequest);
/// <summary>
/// Send new order
/// </summary>
/// <remarks>
/// This request creating new order for the specific exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
ApiResponse<OrderExecutionReport> V1OrdersPostWithHttpInfo (OrderNewSingleRequest orderNewSingleRequest);
/// <summary>
/// Get order execution report
/// </summary>
/// <remarks>
/// Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <returns>OrderExecutionReport</returns>
OrderExecutionReport V1OrdersStatusClientOrderIdGet (string clientOrderId);
/// <summary>
/// Get order execution report
/// </summary>
/// <remarks>
/// Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
ApiResponse<OrderExecutionReport> V1OrdersStatusClientOrderIdGetWithHttpInfo (string clientOrderId);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Cancel all orders request
/// </summary>
/// <remarks>
/// This request cancels all open orders on single specified exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of MessageReject</returns>
System.Threading.Tasks.Task<MessageReject> V1OrdersCancelAllPostAsync (OrderCancelAllRequest orderCancelAllRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancel all orders request
/// </summary>
/// <remarks>
/// This request cancels all open orders on single specified exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (MessageReject)</returns>
System.Threading.Tasks.Task<ApiResponse<MessageReject>> V1OrdersCancelAllPostWithHttpInfoAsync (OrderCancelAllRequest orderCancelAllRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancel order request
/// </summary>
/// <remarks>
/// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersCancelPostAsync (OrderCancelSingleRequest orderCancelSingleRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Cancel order request
/// </summary>
/// <remarks>
/// Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersCancelPostWithHttpInfoAsync (OrderCancelSingleRequest orderCancelSingleRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get open orders
/// </summary>
/// <remarks>
/// Get last execution reports for open orders across all or single exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of List<OrderExecutionReport></returns>
System.Threading.Tasks.Task<List<OrderExecutionReport>> V1OrdersGetAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get open orders
/// </summary>
/// <remarks>
/// Get last execution reports for open orders across all or single exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (List<OrderExecutionReport>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<OrderExecutionReport>>> V1OrdersGetWithHttpInfoAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Send new order
/// </summary>
/// <remarks>
/// This request creating new order for the specific exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersPostAsync (OrderNewSingleRequest orderNewSingleRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Send new order
/// </summary>
/// <remarks>
/// This request creating new order for the specific exchange.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersPostWithHttpInfoAsync (OrderNewSingleRequest orderNewSingleRequest, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get order execution report
/// </summary>
/// <remarks>
/// Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersStatusClientOrderIdGetAsync (string clientOrderId, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get order execution report
/// </summary>
/// <remarks>
/// Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </remarks>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersStatusClientOrderIdGetWithHttpInfoAsync (string clientOrderId, CancellationToken cancellationToken = default(CancellationToken));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class OrdersApi : IOrdersApi
{
private CoinAPI.OMS.REST.V1.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="OrdersApi"/> class.
/// </summary>
/// <returns></returns>
public OrdersApi(String basePath)
{
this.Configuration = new CoinAPI.OMS.REST.V1.Client.Configuration { BasePath = basePath };
ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="OrdersApi"/> class
/// </summary>
/// <returns></returns>
public OrdersApi()
{
this.Configuration = CoinAPI.OMS.REST.V1.Client.Configuration.Default;
ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="OrdersApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public OrdersApi(CoinAPI.OMS.REST.V1.Client.Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = CoinAPI.OMS.REST.V1.Client.Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public CoinAPI.OMS.REST.V1.Client.Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public CoinAPI.OMS.REST.V1.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public IDictionary<String, String> DefaultHeader()
{
return new ReadOnlyDictionary<string, string>(this.Configuration.DefaultHeader);
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Cancel all orders request This request cancels all open orders on single specified exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <returns>MessageReject</returns>
public MessageReject V1OrdersCancelAllPost (OrderCancelAllRequest orderCancelAllRequest)
{
ApiResponse<MessageReject> localVarResponse = V1OrdersCancelAllPostWithHttpInfo(orderCancelAllRequest);
return localVarResponse.Data;
}
/// <summary>
/// Cancel all orders request This request cancels all open orders on single specified exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <returns>ApiResponse of MessageReject</returns>
public ApiResponse<MessageReject> V1OrdersCancelAllPostWithHttpInfo (OrderCancelAllRequest orderCancelAllRequest)
{
// verify the required parameter 'orderCancelAllRequest' is set
if (orderCancelAllRequest == null)
throw new ApiException(400, "Missing required parameter 'orderCancelAllRequest' when calling OrdersApi->V1OrdersCancelAllPost");
var localVarPath = "/v1/orders/cancel/all";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderCancelAllRequest != null && orderCancelAllRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderCancelAllRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderCancelAllRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersCancelAllPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<MessageReject>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(MessageReject) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(MessageReject)));
}
/// <summary>
/// Cancel all orders request This request cancels all open orders on single specified exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of MessageReject</returns>
public async System.Threading.Tasks.Task<MessageReject> V1OrdersCancelAllPostAsync (OrderCancelAllRequest orderCancelAllRequest, CancellationToken cancellationToken = default(CancellationToken))
{
ApiResponse<MessageReject> localVarResponse = await V1OrdersCancelAllPostWithHttpInfoAsync(orderCancelAllRequest, cancellationToken);
return localVarResponse.Data;
}
/// <summary>
/// Cancel all orders request This request cancels all open orders on single specified exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelAllRequest">OrderCancelAllRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (MessageReject)</returns>
public async System.Threading.Tasks.Task<ApiResponse<MessageReject>> V1OrdersCancelAllPostWithHttpInfoAsync (OrderCancelAllRequest orderCancelAllRequest, CancellationToken cancellationToken = default(CancellationToken))
{
// verify the required parameter 'orderCancelAllRequest' is set
if (orderCancelAllRequest == null)
throw new ApiException(400, "Missing required parameter 'orderCancelAllRequest' when calling OrdersApi->V1OrdersCancelAllPost");
var localVarPath = "/v1/orders/cancel/all";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderCancelAllRequest != null && orderCancelAllRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderCancelAllRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderCancelAllRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType, cancellationToken);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersCancelAllPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<MessageReject>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(MessageReject) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(MessageReject)));
}
/// <summary>
/// Cancel order request Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <returns>OrderExecutionReport</returns>
public OrderExecutionReport V1OrdersCancelPost (OrderCancelSingleRequest orderCancelSingleRequest)
{
ApiResponse<OrderExecutionReport> localVarResponse = V1OrdersCancelPostWithHttpInfo(orderCancelSingleRequest);
return localVarResponse.Data;
}
/// <summary>
/// Cancel order request Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
public ApiResponse<OrderExecutionReport> V1OrdersCancelPostWithHttpInfo (OrderCancelSingleRequest orderCancelSingleRequest)
{
// verify the required parameter 'orderCancelSingleRequest' is set
if (orderCancelSingleRequest == null)
throw new ApiException(400, "Missing required parameter 'orderCancelSingleRequest' when calling OrdersApi->V1OrdersCancelPost");
var localVarPath = "/v1/orders/cancel";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderCancelSingleRequest != null && orderCancelSingleRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderCancelSingleRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderCancelSingleRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersCancelPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
/// <summary>
/// Cancel order request Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
public async System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersCancelPostAsync (OrderCancelSingleRequest orderCancelSingleRequest, CancellationToken cancellationToken = default(CancellationToken))
{
ApiResponse<OrderExecutionReport> localVarResponse = await V1OrdersCancelPostWithHttpInfoAsync(orderCancelSingleRequest, cancellationToken);
return localVarResponse.Data;
}
/// <summary>
/// Cancel order request Request cancel for an existing order. The order can be canceled using the `client_order_id` or `exchange_order_id`.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderCancelSingleRequest">OrderCancelSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersCancelPostWithHttpInfoAsync (OrderCancelSingleRequest orderCancelSingleRequest, CancellationToken cancellationToken = default(CancellationToken))
{
// verify the required parameter 'orderCancelSingleRequest' is set
if (orderCancelSingleRequest == null)
throw new ApiException(400, "Missing required parameter 'orderCancelSingleRequest' when calling OrdersApi->V1OrdersCancelPost");
var localVarPath = "/v1/orders/cancel";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderCancelSingleRequest != null && orderCancelSingleRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderCancelSingleRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderCancelSingleRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType, cancellationToken);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersCancelPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
/// <summary>
/// Get open orders Get last execution reports for open orders across all or single exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <returns>List<OrderExecutionReport></returns>
public List<OrderExecutionReport> V1OrdersGet (string exchangeId = default(string))
{
ApiResponse<List<OrderExecutionReport>> localVarResponse = V1OrdersGetWithHttpInfo(exchangeId);
return localVarResponse.Data;
}
/// <summary>
/// Get open orders Get last execution reports for open orders across all or single exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <returns>ApiResponse of List<OrderExecutionReport></returns>
public ApiResponse<List<OrderExecutionReport>> V1OrdersGetWithHttpInfo (string exchangeId = default(string))
{
var localVarPath = "/v1/orders";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (exchangeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "exchange_id", exchangeId)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<OrderExecutionReport>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(List<OrderExecutionReport>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderExecutionReport>)));
}
/// <summary>
/// Get open orders Get last execution reports for open orders across all or single exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of List<OrderExecutionReport></returns>
public async System.Threading.Tasks.Task<List<OrderExecutionReport>> V1OrdersGetAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
ApiResponse<List<OrderExecutionReport>> localVarResponse = await V1OrdersGetWithHttpInfoAsync(exchangeId, cancellationToken);
return localVarResponse.Data;
}
/// <summary>
/// Get open orders Get last execution reports for open orders across all or single exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="exchangeId">Filter the open orders to the specific exchange. (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (List<OrderExecutionReport>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<OrderExecutionReport>>> V1OrdersGetWithHttpInfoAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
var localVarPath = "/v1/orders";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (exchangeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "exchange_id", exchangeId)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType, cancellationToken);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<OrderExecutionReport>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(List<OrderExecutionReport>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<OrderExecutionReport>)));
}
/// <summary>
/// Send new order This request creating new order for the specific exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <returns>OrderExecutionReport</returns>
public OrderExecutionReport V1OrdersPost (OrderNewSingleRequest orderNewSingleRequest)
{
ApiResponse<OrderExecutionReport> localVarResponse = V1OrdersPostWithHttpInfo(orderNewSingleRequest);
return localVarResponse.Data;
}
/// <summary>
/// Send new order This request creating new order for the specific exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
public ApiResponse<OrderExecutionReport> V1OrdersPostWithHttpInfo (OrderNewSingleRequest orderNewSingleRequest)
{
// verify the required parameter 'orderNewSingleRequest' is set
if (orderNewSingleRequest == null)
throw new ApiException(400, "Missing required parameter 'orderNewSingleRequest' when calling OrdersApi->V1OrdersPost");
var localVarPath = "/v1/orders";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderNewSingleRequest != null && orderNewSingleRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderNewSingleRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderNewSingleRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
/// <summary>
/// Send new order This request creating new order for the specific exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
public async System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersPostAsync (OrderNewSingleRequest orderNewSingleRequest, CancellationToken cancellationToken = default(CancellationToken))
{
ApiResponse<OrderExecutionReport> localVarResponse = await V1OrdersPostWithHttpInfoAsync(orderNewSingleRequest, cancellationToken);
return localVarResponse.Data;
}
/// <summary>
/// Send new order This request creating new order for the specific exchange.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="orderNewSingleRequest">OrderNewSingleRequest object.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersPostWithHttpInfoAsync (OrderNewSingleRequest orderNewSingleRequest, CancellationToken cancellationToken = default(CancellationToken))
{
// verify the required parameter 'orderNewSingleRequest' is set
if (orderNewSingleRequest == null)
throw new ApiException(400, "Missing required parameter 'orderNewSingleRequest' when calling OrdersApi->V1OrdersPost");
var localVarPath = "/v1/orders";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"appliction/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (orderNewSingleRequest != null && orderNewSingleRequest.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(orderNewSingleRequest); // http body (model) parameter
}
else
{
localVarPostBody = orderNewSingleRequest; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType, cancellationToken);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersPost", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
/// <summary>
/// Get order execution report Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <returns>OrderExecutionReport</returns>
public OrderExecutionReport V1OrdersStatusClientOrderIdGet (string clientOrderId)
{
ApiResponse<OrderExecutionReport> localVarResponse = V1OrdersStatusClientOrderIdGetWithHttpInfo(clientOrderId);
return localVarResponse.Data;
}
/// <summary>
/// Get order execution report Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <returns>ApiResponse of OrderExecutionReport</returns>
public ApiResponse<OrderExecutionReport> V1OrdersStatusClientOrderIdGetWithHttpInfo (string clientOrderId)
{
// verify the required parameter 'clientOrderId' is set
if (clientOrderId == null)
throw new ApiException(400, "Missing required parameter 'clientOrderId' when calling OrdersApi->V1OrdersStatusClientOrderIdGet");
var localVarPath = "/v1/orders/status/{client_order_id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (clientOrderId != null) localVarPathParams.Add("client_order_id", this.Configuration.ApiClient.ParameterToString(clientOrderId)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersStatusClientOrderIdGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
/// <summary>
/// Get order execution report Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of OrderExecutionReport</returns>
public async System.Threading.Tasks.Task<OrderExecutionReport> V1OrdersStatusClientOrderIdGetAsync (string clientOrderId, CancellationToken cancellationToken = default(CancellationToken))
{
ApiResponse<OrderExecutionReport> localVarResponse = await V1OrdersStatusClientOrderIdGetWithHttpInfoAsync(clientOrderId, cancellationToken);
return localVarResponse.Data;
}
/// <summary>
/// Get order execution report Get the last order execution report for the specified order. The requested order does not need to be active or opened.
/// </summary>
/// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="clientOrderId">The unique identifier of the order assigned by the client.</param>
/// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param>
/// <returns>Task of ApiResponse (OrderExecutionReport)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OrderExecutionReport>> V1OrdersStatusClientOrderIdGetWithHttpInfoAsync (string clientOrderId, CancellationToken cancellationToken = default(CancellationToken))
{
// verify the required parameter 'clientOrderId' is set
if (clientOrderId == null)
throw new ApiException(400, "Missing required parameter 'clientOrderId' when calling OrdersApi->V1OrdersStatusClientOrderIdGet");
var localVarPath = "/v1/orders/status/{client_order_id}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new List<KeyValuePair<String, String>>();
var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (clientOrderId != null) localVarPathParams.Add("client_order_id", this.Configuration.ApiClient.ParameterToString(clientOrderId)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType, cancellationToken);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("V1OrdersStatusClientOrderIdGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OrderExecutionReport>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)),
(OrderExecutionReport) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(OrderExecutionReport)));
}
}
}
| |
using System.Collections;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.TeleTrust
{
/**
* elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation"
* http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt
*/
public class TeleTrusTNamedCurves
{
internal class BrainpoolP160r1Holder
: X9ECParametersHolder
{
private BrainpoolP160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP160r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q
new BigInteger("340E7BE2A280EB74E2BE61BADA745D97E8F7C300", 16), // a
new BigInteger("1E589A8595423412134FAA2DBDEC95C8D8675E58", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC31667CB477A1A8EC338F94741669C976316DA6321")), // G
new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP160t1Holder
: X9ECParametersHolder
{
private BrainpoolP160t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP160t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
// new BigInteger("24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B", 16), // Z
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q
new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620C", 16), // a'
new BigInteger("7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04B199B13B9B34EFC1397E64BAEB05ACC265FF2378ADD6718B7C7C1961F0991B842443772152C9E0AD")), // G
new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP192r1Holder
: X9ECParametersHolder
{
private BrainpoolP192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP192r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q
new BigInteger("6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", 16), // a
new BigInteger("469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD614B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F")), // G
new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP192t1Holder
: X9ECParametersHolder
{
private BrainpoolP192t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP192t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB") //Z
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q
new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294", 16), // a'
new BigInteger("13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("043AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9")), // G'
new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP224r1Holder
: X9ECParametersHolder
{
private BrainpoolP224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP224r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q
new BigInteger("68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", 16), // a
new BigInteger("2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD")), // G
new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n
new BigInteger("01", 16)); // n
}
}
internal class BrainpoolP224t1Holder
: X9ECParametersHolder
{
private BrainpoolP224t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP224t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F") //Z
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q
new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC", 16), // a'
new BigInteger("4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("046AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D5800374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C")), // G'
new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP256r1Holder
: X9ECParametersHolder
{
private BrainpoolP256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP256r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q
new BigInteger("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", 16), // a
new BigInteger("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997")), // G
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP256t1Holder
: X9ECParametersHolder
{
private BrainpoolP256t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP256t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0") //Z
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374", 16), // a'
new BigInteger("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F42D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE")), // G'
new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP320r1Holder
: X9ECParametersHolder
{
private BrainpoolP320r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP320r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q
new BigInteger("3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", 16), // a
new BigInteger("520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0443BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E2061114FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1")), // G
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP320t1Holder
: X9ECParametersHolder
{
private BrainpoolP320t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP320t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18FEFC3E5AB7496F3C7B1") //Z
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E24", 16), // a'
new BigInteger("A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547CEB5B4FEF422340353", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136FFF3357F624A21BED5263BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE71B1B9BC0455FB0D2C3")), // G'
new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP384r1Holder
: X9ECParametersHolder
{
private BrainpoolP384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP384r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q
new BigInteger("7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", 16), // a
new BigInteger("4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("041D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315")), // G
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP384t1Holder
: X9ECParametersHolder
{
private BrainpoolP384t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP384t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C") //Z
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC50", 16), // a'
new BigInteger("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0418DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928")), // G'
new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP512r1Holder
: X9ECParametersHolder
{
private BrainpoolP512r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP512r1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q
new BigInteger("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", 16), // a
new BigInteger("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", 16)); // b
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("0481AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F8227DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892")), // G
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n
new BigInteger("01", 16)); // h
}
}
internal class BrainpoolP512t1Holder
: X9ECParametersHolder
{
private BrainpoolP512t1Holder() {}
internal static readonly X9ECParametersHolder Instance = new BrainpoolP512t1Holder();
protected override X9ECParameters CreateParameters()
{
ECCurve curve = new FpCurve(
//new BigInteger("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB") //Z
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0", 16), // a'
new BigInteger("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16)); // b'
return new X9ECParameters(
curve,
curve.DecodePoint(Hex.Decode("04640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332")), // G'
new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n
new BigInteger("01", 16)); // h
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(name, oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static TeleTrusTNamedCurves()
{
DefineCurve("brainpoolp160r1", TeleTrusTObjectIdentifiers.BrainpoolP160R1, BrainpoolP160r1Holder.Instance);
DefineCurve("brainpoolp160t1", TeleTrusTObjectIdentifiers.BrainpoolP160T1, BrainpoolP160t1Holder.Instance);
DefineCurve("brainpoolp192r1", TeleTrusTObjectIdentifiers.BrainpoolP192R1, BrainpoolP192r1Holder.Instance);
DefineCurve("brainpoolp192t1", TeleTrusTObjectIdentifiers.BrainpoolP192T1, BrainpoolP192t1Holder.Instance);
DefineCurve("brainpoolp224r1", TeleTrusTObjectIdentifiers.BrainpoolP224R1, BrainpoolP224r1Holder.Instance);
DefineCurve("brainpoolp224t1", TeleTrusTObjectIdentifiers.BrainpoolP224T1, BrainpoolP224t1Holder.Instance);
DefineCurve("brainpoolp256r1", TeleTrusTObjectIdentifiers.BrainpoolP256R1, BrainpoolP256r1Holder.Instance);
DefineCurve("brainpoolp256t1", TeleTrusTObjectIdentifiers.BrainpoolP256T1, BrainpoolP256t1Holder.Instance);
DefineCurve("brainpoolp320r1", TeleTrusTObjectIdentifiers.BrainpoolP320R1, BrainpoolP320r1Holder.Instance);
DefineCurve("brainpoolp320t1", TeleTrusTObjectIdentifiers.BrainpoolP320T1, BrainpoolP320t1Holder.Instance);
DefineCurve("brainpoolp384r1", TeleTrusTObjectIdentifiers.BrainpoolP384R1, BrainpoolP384r1Holder.Instance);
DefineCurve("brainpoolp384t1", TeleTrusTObjectIdentifiers.BrainpoolP384T1, BrainpoolP384t1Holder.Instance);
DefineCurve("brainpoolp512r1", TeleTrusTObjectIdentifiers.BrainpoolP512R1, BrainpoolP512r1Holder.Instance);
DefineCurve("brainpoolp512t1", TeleTrusTObjectIdentifiers.BrainpoolP512T1, BrainpoolP512t1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = (DerObjectIdentifier)
objIds[Platform.ToLowerInvariant(name)];
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string) names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(objIds.Keys); }
}
public static DerObjectIdentifier GetOid(
short curvesize,
bool twisted)
{
return GetOid("brainpoolP" + curvesize + (twisted ? "t" : "r") + "1");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartTokenFormatterFormatTokenTests : FormatterTestsBase
{
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile1()
{
var code = @"{";
await ExpectException_SmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EmptyFile2()
{
var code = @"}";
await ExpectException_SmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 0,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace1()
{
var code = @"namespace NS
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace2()
{
var code = @"namespace NS
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 1,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Namespace3()
{
var code = @"namespace NS
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 2,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class1()
{
var code = @"namespace NS
{
class Class
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class2()
{
var code = @"namespace NS
{
class Class
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 3,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Class3()
{
var code = @"namespace NS
{
class Class
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 4,
expectedSpace: 4);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Method3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property1()
{
var code = @"namespace NS
{
class Class
{
int Foo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Property2()
{
var code = @"namespace NS
{
class Class
{
int Foo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event1()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Foo
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Event2()
{
var code = @"namespace NS
{
class Class
{
event EventHandler Foo
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer1()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Indexer2()
{
var code = @"namespace NS
{
class Class
{
int this[int index]
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 8);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{";
await AssertSmartTokenFormatterOpenBraceAsync(
code,
indentationLine: 6,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block2()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 6,
expectedSpace: 0);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task Block4()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
{
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 7,
expectedSpace: 12);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer1()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
var expected = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new [] {
}";
await AssertSmartTokenFormatterOpenBraceAsync(
expected,
code,
indentationLine: 6);
}
[Fact]
[WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
int[,] arr =
{
{1,1}, {2,2}
}
}";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 9,
expectedSpace: 12);
}
[Fact]
[WorkItem(543142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543142")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task EnterWithTrailingWhitespace()
{
var code = @"class Class
{
void Method(int i)
{
var a = new {
};
";
await AssertSmartTokenFormatterCloseBraceAsync(
code,
indentationLine: 5,
expectedSpace: 8);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task OpenBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
$${
}
#line default
#line hidden|]
}
}";
await AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(9216, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void CloseBraceWithBaseIndentation()
{
var markup = @"
class C
{
void M()
{
[|#line ""Default.aspx"", 273
if (true)
{
$$}
#line default
#line hidden|]
}
}";
AssertSmartTokenFormatterCloseBraceWithBaseIndentation(markup, baseIndentation: 7, expectedIndentation: 11);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestPreprocessor()
{
var code = @"
class C
{
void M()
{
#
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: '#');
Assert.Equal(0, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestRegion()
{
var code = @"
class C
{
void M()
{
#region
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n');
Assert.Equal(8, actualIndentation);
}
[WorkItem(766159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766159")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestEndRegion()
{
var code = @"
class C
{
void M()
{
#region
#endregion
}
}";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 5, ch: 'n');
Assert.Equal(8, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestSelect()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Foo()
{
return from a in new[] { 1, 2, 3 }
select
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 't');
Assert.Equal(15, actualIndentation);
}
[WorkItem(777467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/777467")]
[Fact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task TestWhere()
{
var code = @"
using System;
using System.Linq;
class Program
{
static IEnumerable<int> Foo()
{
return from a in new[] { 1, 2, 3 }
where
}
}
";
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine: 9, ch: 'e');
Assert.Equal(15, actualIndentation);
}
private Task AssertSmartTokenFormatterOpenBraceWithBaseIndentationAsync(string markup, int baseIndentation, int expectedIndentation)
{
string code;
int position;
TextSpan span;
MarkupTestFile.GetPositionAndSpan(markup, out code, out position, out span);
return AssertSmartTokenFormatterOpenBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
baseIndentation,
span);
}
private async Task AssertSmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default(TextSpan))
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{', baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private async Task AssertSmartTokenFormatterOpenBraceAsync(
string expected,
string code,
int indentationLine)
{
// create tree service
using (var workspace = await TestWorkspace.CreateCSharpAsync(code))
{
var buffer = workspace.Documents.First().GetTextBuffer();
var actual = await TokenFormatAsync(workspace, buffer, indentationLine, '{');
Assert.Equal(expected, actual);
}
}
private Task AssertSmartTokenFormatterCloseBraceWithBaseIndentation(string markup, int baseIndentation, int expectedIndentation)
{
string code;
int position;
TextSpan span;
MarkupTestFile.GetPositionAndSpan(markup, out code, out position, out span);
return AssertSmartTokenFormatterCloseBraceAsync(
code,
SourceText.From(code).Lines.IndexOf(position),
expectedIndentation,
baseIndentation,
span);
}
private async Task AssertSmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace,
int? baseIndentation = null,
TextSpan span = default(TextSpan))
{
var actualIndentation = await GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}', baseIndentation, span);
Assert.Equal(expectedSpace, actualIndentation);
}
private async Task ExpectException_SmartTokenFormatterOpenBraceAsync(
string code,
int indentationLine,
int expectedSpace)
{
Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '{')));
}
private async Task ExpectException_SmartTokenFormatterCloseBraceAsync(
string code,
int indentationLine,
int expectedSpace)
{
Assert.NotNull(await Record.ExceptionAsync(() => GetSmartTokenFormatterIndentationAsync(code, indentationLine, '}')));
}
}
}
| |
namespace MicroMapper
{
using System;
using System.Collections.Generic;
/// <summary>
/// Context information regarding resolution of a destination value
/// </summary>
public class ResolutionContext : IEquatable<ResolutionContext>
{
private static readonly ResolutionContext Empty = new ResolutionContext();
/// <summary>
/// Mapping operation options
/// </summary>
public MappingOperationOptions Options { get; }
/// <summary>
/// Current type map
/// </summary>
public TypeMap TypeMap { get; }
/// <summary>
/// Current property map
/// </summary>
public PropertyMap PropertyMap { get; }
/// <summary>
/// Initial source type
/// </summary>
public Type InitialSourceType { get; }
/// <summary>
/// Initial destination type
/// </summary>
public Type InitialDestinationType { get; }
/// <summary>
/// Current source type
/// </summary>
public Type SourceType { get; }
/// <summary>
/// Current attempted destination type
/// </summary>
public Type DestinationType { get; }
/// <summary>
/// Index of current collection mapping
/// </summary>
public int? ArrayIndex { get; }
/// <summary>
/// Source value
/// </summary>
public object SourceValue { get; }
/// <summary>
/// Destination value
/// </summary>
public object DestinationValue { get; }
/// <summary>
/// Parent resolution context
/// </summary>
public ResolutionContext Parent { get; }
/// <summary>
/// Instance cache for resolving circular references
/// </summary>
public Dictionary<ResolutionContext, object> InstanceCache { get; }
///// <summary>
///// Current mapping engine
///// </summary>
//public IMappingEngine Engine { get; }
/// <summary>
/// Current mapper context
/// </summary>
public IMapperContext MapperContext { get; }
private ResolutionContext()
{
}
private ResolutionContext(ResolutionContext context, object sourceValue, object destinationValue,
Type sourceType, Type destinationType = null, TypeMap typeMap = null)
{
if (context != Empty)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
Parent = context;
ArrayIndex = context.ArrayIndex;
PropertyMap = context.PropertyMap;
DestinationType = context.DestinationType;
InstanceCache = context.InstanceCache;
Options = context.Options;
MapperContext = context.MapperContext;
}
SourceValue = sourceValue;
DestinationValue = destinationValue;
InitialSourceType = sourceType;
InitialDestinationType = destinationType;
TypeMap = typeMap;
if (typeMap != null)
{
SourceType = typeMap.SourceType;
DestinationType = typeMap.DestinationType;
}
else
{
SourceType = sourceType;
DestinationType = destinationType;
}
}
public ResolutionContext(TypeMap typeMap, object sourceValue, Type sourceType, Type destinationType,
MappingOperationOptions options, IMapperContext mapperContext)
: this(typeMap, sourceValue, null, sourceType, destinationType, options, mapperContext)
{
}
public ResolutionContext(TypeMap typeMap, object sourceValue, object destinationValue, Type sourceType,
Type destinationType, MappingOperationOptions options, IMapperContext mapperContext)
{
TypeMap = typeMap;
SourceValue = sourceValue;
DestinationValue = destinationValue;
if (typeMap != null)
{
SourceType = typeMap.SourceType;
DestinationType = typeMap.DestinationType;
}
else
{
SourceType = sourceType;
DestinationType = destinationType;
}
InitialSourceType = sourceType;
InitialDestinationType = destinationType;
InstanceCache = new Dictionary<ResolutionContext, object>();
Options = options;
MapperContext = mapperContext;
}
private ResolutionContext(ResolutionContext context, object sourceValue, Type sourceType)
: this(context, sourceValue, context.DestinationValue, sourceType)
{
}
private ResolutionContext(ResolutionContext context, TypeMap memberTypeMap,
object sourceValue, object destinationValue, Type sourceType, Type destinationType)
: this(context, sourceValue, destinationValue, sourceType, destinationType, memberTypeMap)
{
}
private ResolutionContext(ResolutionContext context, object sourceValue, object destinationValue,
TypeMap memberTypeMap, PropertyMap propertyMap)
: this(context, sourceValue, destinationValue, null, null, memberTypeMap)
{
if(memberTypeMap == null)
{
throw new ArgumentNullException(nameof(memberTypeMap));
}
PropertyMap = propertyMap;
}
private ResolutionContext(ResolutionContext context, object sourceValue, object destinationValue,
Type sourceType, PropertyMap propertyMap) : this(context, sourceValue, destinationValue, sourceType)
{
PropertyMap = propertyMap;
var destinationMemberType = propertyMap.DestinationProperty.MemberType;
DestinationType = destinationMemberType == typeof(object) ? sourceType : destinationMemberType;
}
private ResolutionContext(ResolutionContext context, object sourceValue, TypeMap typeMap, Type sourceType,
Type destinationType, int arrayIndex) : this(context, sourceValue, null, sourceType, destinationType, typeMap)
{
ArrayIndex = arrayIndex;
}
public string MemberName => PropertyMap == null
? string.Empty
: (ArrayIndex == null
? PropertyMap.DestinationProperty.Name
: PropertyMap.DestinationProperty.Name + ArrayIndex.Value);
public bool IsSourceValueNull => Equals(null, SourceValue);
public ResolutionContext CreateValueContext(object sourceValue, Type sourceType)
{
return new ResolutionContext(this, sourceValue, sourceType);
}
public ResolutionContext CreateTypeContext(TypeMap memberTypeMap, object sourceValue, object destinationValue,
Type sourceType, Type destinationType)
{
return new ResolutionContext(this, memberTypeMap, sourceValue, destinationValue, sourceType, destinationType);
}
public ResolutionContext CreatePropertyMapContext(PropertyMap propertyMap)
{
return new ResolutionContext(this, SourceValue, DestinationValue, SourceType, propertyMap);
}
public ResolutionContext CreateMemberContext(TypeMap memberTypeMap, object memberValue, object destinationValue,
Type sourceMemberType, PropertyMap propertyMap)
{
return memberTypeMap != null
? new ResolutionContext(this, memberValue, destinationValue, memberTypeMap, propertyMap)
: new ResolutionContext(this, memberValue, destinationValue, sourceMemberType, propertyMap);
}
public ResolutionContext CreateElementContext(TypeMap elementTypeMap, object item, Type sourceElementType,
Type destinationElementType, int arrayIndex)
{
return new ResolutionContext(this, item, elementTypeMap, sourceElementType, destinationElementType,
arrayIndex);
}
public override string ToString()
{
return $"Trying to map {SourceType.Name} to {DestinationType.Name}.";
}
public TypeMap GetContextTypeMap()
{
TypeMap typeMap = TypeMap;
ResolutionContext parent = Parent;
while ((typeMap == null) && (parent != null))
{
typeMap = parent.TypeMap;
parent = parent.Parent;
}
return typeMap;
}
public PropertyMap GetContextPropertyMap()
{
PropertyMap propertyMap = PropertyMap;
ResolutionContext parent = Parent;
while ((propertyMap == null) && (parent != null))
{
propertyMap = parent.PropertyMap;
parent = parent.Parent;
}
return propertyMap;
}
public bool Equals(ResolutionContext other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.TypeMap, TypeMap) && Equals(other.SourceType, SourceType) &&
Equals(other.DestinationType, DestinationType) && Equals(other.SourceValue, SourceValue);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (ResolutionContext)) return false;
return Equals((ResolutionContext) obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (TypeMap != null ? TypeMap.GetHashCode() : 0);
result = (result*397) ^ (SourceType != null ? SourceType.GetHashCode() : 0);
result = (result*397) ^ (DestinationType != null ? DestinationType.GetHashCode() : 0);
result = (result*397) ^ (SourceValue != null ? SourceValue.GetHashCode() : 0);
return result;
}
}
public static ResolutionContext New<TSource>(TSource sourceValue)
{
//return new ResolutionContext(null, sourceValue, typeof (TSource), null, new MappingOperationOptions(),
// Mapper.Engine);
//TODO: add Mapper.Context, or new MapperContext, eventually...
return new ResolutionContext(null, sourceValue, typeof (TSource), null, new MappingOperationOptions(),
null);
}
internal void BeforeMap(object destination)
{
if(Parent == null)
{
Options.BeforeMapAction(SourceValue, destination);
}
}
internal void AfterMap(object destination)
{
if(Parent == null)
{
Options.AfterMapAction(SourceValue, destination);
}
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using Baseline;
using Baseline.Expressions;
using LamarCodeGeneration;
using LamarCodeGeneration.Frames;
using LamarCodeGeneration.Model;
using Marten.Schema;
using Marten.Util;
using Weasel.Postgresql;
using FindMembers = Marten.Linq.Parsing.FindMembers;
namespace Marten.Internal.CodeGeneration
{
internal static class FrameCollectionExtensions
{
public const string DocumentVariableName = "document";
public static void StoreInIdentityMap(this FramesCollection frames, DocumentMapping mapping)
{
frames.Code("_identityMap[id] = document;");
}
public static void StoreTracker(this FramesCollection frames)
{
frames.Code("StoreTracker({0}, document);", Use.Type<IMartenSession>());
}
public static void DeserializeDocument(this FramesCollection frames, DocumentMapping mapping, int index)
{
var documentType = mapping.DocumentType;
var document = new Variable(documentType, DocumentVariableName);
if (mapping is DocumentMapping d)
{
if (!d.IsHierarchy())
{
frames.Code($@"
{documentType.FullNameInCode()} document;
document = _serializer.FromJson<{documentType.FullNameInCode()}>(reader, {index});
").Creates(document);
}
else
{
// Hierarchy path is different
frames.Code($@"
{documentType.FullNameInCode()} document;
var typeAlias = reader.GetFieldValue<string>({index + 1});
document = ({documentType.FullNameInCode()}) _serializer.FromJson(_mapping.TypeFor(typeAlias), reader, {index});
").Creates(document);
}
}
}
public static void MarkAsLoaded(this FramesCollection frames)
{
frames.Code($"{{0}}.{nameof(IMartenSession.MarkAsDocumentLoaded)}(id, document);", Use.Type<IMartenSession>());
}
public static void DeserializeDocumentAsync(this FramesCollection frames, DocumentMapping mapping, int index)
{
var documentType = mapping.DocumentType;
var document = new Variable(documentType, DocumentVariableName);
if (!mapping.IsHierarchy())
{
frames.Code($@"
{documentType.FullNameInCode()} document;
document = _serializer.FromJson<{documentType.FullNameInCode()}>(reader, {index});
").Creates(document);
}
else
{
frames.CodeAsync($@"
{documentType.FullNameInCode()} document;
var typeAlias = await reader.GetFieldValueAsync<string>({index + 1}, {{0}});
document = ({documentType.FullNameInCode()}) (await _serializer.FromJsonAsync(_mapping.TypeFor(typeAlias), reader, {index}, {{0}}));
", Use.Type<CancellationToken>()).Creates(document);
}
}
/// <summary>
/// Generates the necessary setter code to set a value of a document.
/// Handles internal/private setters
/// </summary>
/// <param name="frames"></param>
/// <param name="member"></param>
/// <param name="variableName"></param>
/// <param name="documentType"></param>
/// <param name="generatedType"></param>
public static void SetMemberValue(this FramesCollection frames, MemberInfo member, string variableName, Type documentType, GeneratedType generatedType)
{
if (member is PropertyInfo property)
{
if (property.CanWrite)
{
if (property.SetMethod.IsPublic)
{
frames.SetPublicMemberValue(member, variableName, documentType);
}
else
{
var setterFieldName = generatedType.InitializeLambdaSetterProperty(member, documentType);
frames.Code($"{setterFieldName}({{0}}, {variableName});", new Use(documentType));
}
return;
}
}
else if (member is FieldInfo field)
{
if (field.IsPublic)
{
frames.SetPublicMemberValue(member, variableName, documentType);
}
else
{
var setterFieldName = generatedType.InitializeLambdaSetterProperty(member, documentType);
frames.Code($"{setterFieldName}({{0}}, {variableName});", new Use(documentType));
}
return;
}
throw new ArgumentOutOfRangeException(nameof(member), $"MemberInfo {member} is not valid in this usage. ");
}
public static string InitializeLambdaSetterProperty(this GeneratedType generatedType, MemberInfo member, Type documentType)
{
var setterFieldName = $"{member.Name}Writer";
if (generatedType.Setters.All(x => x.PropName != setterFieldName))
{
var memberType = member.GetRawMemberType();
var actionType = typeof(Action<,>).MakeGenericType(documentType, memberType);
var expression = $"{typeof(LambdaBuilder).GetFullName()}.{nameof(LambdaBuilder.Setter)}<{documentType.FullNameInCode()},{memberType.FullNameInCode()}>(typeof({documentType.FullNameInCode()}).GetProperty(\"{member.Name}\"))";
var constant = new Variable(actionType, expression);
var setter = Setter.StaticReadOnly(setterFieldName, constant);
generatedType.Setters.Add(setter);
}
return setterFieldName;
}
private static void SetPublicMemberValue(this FramesCollection frames, MemberInfo member, string variableName,
Type documentType)
{
frames.Code($"{{0}}.{member.Name} = {variableName};", new Use(documentType));
}
private interface ISetterBuilder
{
void Add(GeneratedType generatedType, MemberInfo member, string setterFieldName);
}
private class SetterBuilder<TTarget, TMember>: ISetterBuilder
{
public void Add(GeneratedType generatedType, MemberInfo member, string setterFieldName)
{
var writer = LambdaBuilder.Setter<TTarget, TMember>(member);
var setter =
new Setter(typeof(Action<TTarget, TMember>), setterFieldName)
{
InitialValue = writer, Type = SetterType.ReadWrite
};
generatedType.Setters.Add(setter);
}
}
public static void AssignMemberFromReader<T>(this GeneratedMethod method, GeneratedType generatedType, int index,
Expression<Func<T, object>> memberExpression)
{
var member = FindMembers.Determine(memberExpression).Single();
var variableName = member.Name.ToCamelCase();
method.Frames.Code($"var {variableName} = reader.GetFieldValue<{member.GetMemberType().FullNameInCode()}>({index});");
method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType);
}
public static void AssignMemberFromReader(this GeneratedMethod method, GeneratedType generatedType, int index,
Type documentType, string memberName)
{
var member = documentType.GetMember(memberName).Single();
var variableName = member.Name.ToCamelCase();
method.Frames.Code($"var {variableName} = reader.GetFieldValue<{member.GetMemberType().FullNameInCode()}>({index});");
method.Frames.SetMemberValue(member, variableName, documentType, generatedType);
}
public static void AssignMemberFromReaderAsync<T>(this GeneratedMethod method, GeneratedType generatedType, int index,
Expression<Func<T, object>> memberExpression)
{
var member = FindMembers.Determine(memberExpression).Single();
var variableName = member.Name.ToCamelCase();
method.Frames.Code($"var {variableName} = await reader.GetFieldValueAsync<{member.GetMemberType().FullNameInCode()}>({index}, {{0}});", Use.Type<CancellationToken>());
method.Frames.SetMemberValue(member, variableName, typeof(T), generatedType);
}
public static void AssignMemberFromReaderAsync(this GeneratedMethod method, GeneratedType generatedType, int index,
Type documentType, string memberName)
{
var member = documentType.GetMember(memberName).Single();
var variableName = member.Name.ToCamelCase();
method.Frames.Code($"var {variableName} = await reader.GetFieldValueAsync<{member.GetMemberType().FullNameInCode()}>({index}, {{0}});", Use.Type<CancellationToken>());
method.Frames.SetMemberValue(member, variableName, documentType, generatedType);
}
public static void IfDbReaderValueIsNotNull(this GeneratedMethod method, int index, Action action)
{
method.Frames.Code($"if (!reader.IsDBNull({index}))");
method.Frames.Code("{{");
action();
method.Frames.Code("}}");
}
public static void IfDbReaderValueIsNotNullAsync(this GeneratedMethod method, int index, Action action)
{
method.Frames.CodeAsync($"if (!(await reader.IsDBNullAsync({index}, token)))");
method.Frames.Code("{{");
action();
method.Frames.Code("}}");
}
public static void SetParameterFromMember<T>(this GeneratedMethod method, int index,
Expression<Func<T, object>> memberExpression)
{
var member = FindMembers.Determine(memberExpression).Single();
var memberType = member.GetMemberType();
var pgType = TypeMappings.ToDbType(memberType);
if (memberType == typeof(string))
{
method.Frames.Code($"parameters[{index}].Value = {{0}}.{member.Name} != null ? (object){{0}}.{member.Name} : {typeof(DBNull).FullNameInCode()}.Value;", Use.Type<T>());
method.Frames.Code($"parameters[{index}].NpgsqlDbType = {{0}};", pgType);
}
else
{
method.Frames.Code($"parameters[{index}].Value = {{0}}.{member.Name};", Use.Type<T>());
method.Frames.Code($"parameters[{index}].NpgsqlDbType = {{0}};", pgType);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityTest
{
public interface ITestComponent : IComparable<ITestComponent>
{
void EnableTest(bool enable);
bool IsTestGroup();
GameObject gameObject { get; }
string Name { get; }
ITestComponent GetTestGroup();
bool IsExceptionExpected(string exceptionType);
bool ShouldSucceedOnException();
double GetTimeout();
bool IsIgnored();
bool ShouldSucceedOnAssertions();
bool IsExludedOnThisPlatform();
}
public class TestComponent : MonoBehaviour, ITestComponent
{
public static ITestComponent NullTestComponent = new NullTestComponentImpl();
public float timeout = 5;
public bool ignored = false;
public bool succeedAfterAllAssertionsAreExecuted = false;
public bool expectException = false;
public string expectedExceptionList = "";
public bool succeedWhenExceptionIsThrown = false;
public IncludedPlatforms includedPlatforms = (IncludedPlatforms) ~0L;
public string[] platformsToIgnore = null;
public bool dynamic;
public string dynamicTypeName;
public bool IsExludedOnThisPlatform()
{
return platformsToIgnore != null && platformsToIgnore.Any(platform => platform == Application.platform.ToString());
}
static bool IsAssignableFrom(Type a, Type b)
{
#if !UNITY_METRO
return a.IsAssignableFrom(b);
#else
return false;
#endif
}
public bool IsExceptionExpected(string exception)
{
exception = exception.Trim();
if (!expectException)
return false;
if(string.IsNullOrEmpty(expectedExceptionList.Trim()))
return true;
foreach (var expectedException in expectedExceptionList.Split(',').Select(e => e.Trim()))
{
if (exception == expectedException)
return true;
var exceptionType = Type.GetType(exception) ?? GetTypeByName(exception);
var expectedExceptionType = Type.GetType(expectedException) ?? GetTypeByName(expectedException);
if (exceptionType != null && expectedExceptionType != null && IsAssignableFrom(expectedExceptionType, exceptionType))
return true;
}
return false;
}
public bool ShouldSucceedOnException()
{
return succeedWhenExceptionIsThrown;
}
public double GetTimeout()
{
return timeout;
}
public bool IsIgnored()
{
return ignored;
}
public bool ShouldSucceedOnAssertions()
{
return succeedAfterAllAssertionsAreExecuted;
}
private static Type GetTypeByName(string className)
{
#if !UNITY_METRO
return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(type => type.Name == className);
#else
return null;
#endif
}
public void OnValidate()
{
if (timeout < 0.01f) timeout = 0.01f;
}
// Legacy
[Flags]
public enum IncludedPlatforms
{
WindowsEditor = 1 << 0,
OSXEditor = 1 << 1,
WindowsPlayer = 1 << 2,
OSXPlayer = 1 << 3,
LinuxPlayer = 1 << 4,
MetroPlayerX86 = 1 << 5,
MetroPlayerX64 = 1 << 6,
MetroPlayerARM = 1 << 7,
WindowsWebPlayer = 1 << 8,
OSXWebPlayer = 1 << 9,
Android = 1 << 10,
// ReSharper disable once InconsistentNaming
IPhonePlayer = 1 << 11,
TizenPlayer = 1 << 12,
WP8Player = 1 << 13,
BB10Player = 1 << 14,
NaCl = 1 << 15,
PS3 = 1 << 16,
XBOX360 = 1 << 17,
WiiPlayer = 1 << 18,
PSP2 = 1 << 19,
PS4 = 1 << 20,
PSMPlayer = 1 << 21,
XboxOne = 1 << 22,
}
#region ITestComponent implementation
public void EnableTest(bool enable)
{
if (enable && dynamic)
{
Type t = Type.GetType(dynamicTypeName);
var s = gameObject.GetComponent(t) as MonoBehaviour;
if (s != null)
DestroyImmediate(s);
gameObject.AddComponent(t);
}
if (gameObject.activeSelf != enable) gameObject.SetActive(enable);
}
public int CompareTo(ITestComponent obj)
{
if (obj == NullTestComponent)
return 1;
var result = gameObject.name.CompareTo(obj.gameObject.name);
if (result == 0)
result = gameObject.GetInstanceID().CompareTo(obj.gameObject.GetInstanceID());
return result;
}
public bool IsTestGroup()
{
for (int i = 0; i < gameObject.transform.childCount; i++)
{
var childTc = gameObject.transform.GetChild(i).GetComponent(typeof(TestComponent));
if (childTc != null)
return true;
}
return false;
}
public string Name { get { return gameObject == null ? "" : gameObject.name; } }
public ITestComponent GetTestGroup()
{
var parent = gameObject.transform.parent;
if (parent == null)
return NullTestComponent;
return parent.GetComponent<TestComponent>();
}
public override bool Equals(object o)
{
if (o is TestComponent)
return this == (o as TestComponent);
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(TestComponent a, TestComponent b)
{
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
if (a.dynamic && b.dynamic)
return a.dynamicTypeName == b.dynamicTypeName;
if (a.dynamic || b.dynamic)
return false;
return a.gameObject == b.gameObject;
}
public static bool operator !=(TestComponent a, TestComponent b)
{
return !(a == b);
}
#endregion
#region Static helpers
public static TestComponent CreateDynamicTest(Type type)
{
var go = CreateTest(type.Name);
go.hideFlags |= HideFlags.DontSave;
go.SetActive(false);
var tc = go.GetComponent<TestComponent>();
tc.dynamic = true;
tc.dynamicTypeName = type.AssemblyQualifiedName;
#if !UNITY_METRO
foreach (var typeAttribute in type.GetCustomAttributes(false))
{
if (typeAttribute is IntegrationTest.TimeoutAttribute)
tc.timeout = (typeAttribute as IntegrationTest.TimeoutAttribute).timeout;
else if (typeAttribute is IntegrationTest.IgnoreAttribute)
tc.ignored = true;
else if (typeAttribute is IntegrationTest.SucceedWithAssertions)
tc.succeedAfterAllAssertionsAreExecuted = true;
else if (typeAttribute is IntegrationTest.ExcludePlatformAttribute)
tc.platformsToIgnore = (typeAttribute as IntegrationTest.ExcludePlatformAttribute).platformsToExclude;
else if (typeAttribute is IntegrationTest.ExpectExceptions)
{
var attribute = (typeAttribute as IntegrationTest.ExpectExceptions);
tc.expectException = true;
tc.expectedExceptionList = string.Join(",", attribute.exceptionTypeNames);
tc.succeedWhenExceptionIsThrown = attribute.succeedOnException;
}
}
go.AddComponent(type);
#endif // if !UNITY_METRO
return tc;
}
public static GameObject CreateTest()
{
return CreateTest("New Test");
}
private static GameObject CreateTest(string name)
{
var go = new GameObject(name);
go.AddComponent<TestComponent>();
#if UNITY_EDITOR
Undo.RegisterCreatedObjectUndo(go, "Created test");
#endif
return go;
}
public static List<TestComponent> FindAllTestsOnScene()
{
var tests = Resources.FindObjectsOfTypeAll (typeof(TestComponent)).Cast<TestComponent> ();
#if UNITY_EDITOR
tests = tests.Where( t => {var p = PrefabUtility.GetPrefabType(t); return p != PrefabType.Prefab && p != PrefabType.ModelPrefab;} );
#endif
return tests.ToList ();
}
public static List<TestComponent> FindAllTopTestsOnScene()
{
return FindAllTestsOnScene().Where(component => component.gameObject.transform.parent == null).ToList();
}
public static List<TestComponent> FindAllDynamicTestsOnScene()
{
return FindAllTestsOnScene().Where(t => t.dynamic).ToList();
}
public static void DestroyAllDynamicTests()
{
foreach (var dynamicTestComponent in FindAllDynamicTestsOnScene())
DestroyImmediate(dynamicTestComponent.gameObject);
}
public static void DisableAllTests()
{
foreach (var t in FindAllTestsOnScene()) t.EnableTest(false);
}
public static bool AnyTestsOnScene()
{
return FindAllTestsOnScene().Any();
}
public static bool AnyDynamicTestForCurrentScene()
{
#if UNITY_EDITOR
return TestComponent.GetTypesWithHelpAttribute(EditorApplication.currentScene).Any();
#else
return TestComponent.GetTypesWithHelpAttribute(Application.loadedLevelName).Any();
#endif
}
#endregion
private sealed class NullTestComponentImpl : ITestComponent
{
public int CompareTo(ITestComponent other)
{
if (other == this) return 0;
return -1;
}
public void EnableTest(bool enable)
{
}
public bool IsTestGroup()
{
throw new NotImplementedException();
}
public GameObject gameObject { get; private set; }
public string Name { get { return ""; } }
public ITestComponent GetTestGroup()
{
return null;
}
public bool IsExceptionExpected(string exceptionType)
{
throw new NotImplementedException();
}
public bool ShouldSucceedOnException()
{
throw new NotImplementedException();
}
public double GetTimeout()
{
throw new NotImplementedException();
}
public bool IsIgnored()
{
throw new NotImplementedException();
}
public bool ShouldSucceedOnAssertions()
{
throw new NotImplementedException();
}
public bool IsExludedOnThisPlatform()
{
throw new NotImplementedException();
}
}
public static IEnumerable<Type> GetTypesWithHelpAttribute(string sceneName)
{
#if !UNITY_METRO
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] types = null;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
Debug.LogError("Failed to load types from: " + assembly.FullName);
foreach (Exception loadEx in ex.LoaderExceptions)
Debug.LogException(loadEx);
}
if (types == null)
continue;
foreach (Type type in types)
{
var attributes = type.GetCustomAttributes(typeof(IntegrationTest.DynamicTestAttribute), true);
if (attributes.Length == 1)
{
var a = attributes.Single() as IntegrationTest.DynamicTestAttribute;
if (a.IncludeOnScene(sceneName)) yield return type;
}
}
}
#else // if !UNITY_METRO
yield break;
#endif // if !UNITY_METRO
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("DudeWorld/Dude")]
public class Dude : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float turnSpeed = 40.0f;
public int team = 0;
public GameObject hitEffect;
public GameObject blockEffect;
public bool blocking = false;
public float drag = 10.0f;
public bool applyGravity = true;
public bool flying = false;
public bool invincibleWhenHit = false;
public bool directionalBlock = false;
private float backstabAngle = 0.4f;
private float boardDistance = 1.0f;
private Vector3 moveVec;
private Vector3 forward;
public Vector3 velocity
{
get; set;
}
private bool grounded = false;
private bool invincible = false;
private CharacterController controller;
public GameObject attacker
{
get; private set;
}
void Start() {
velocity = Vector3.zero;
controller = (CharacterController)GetComponent(typeof(CharacterController));
}
void FixedUpdate()
{
Vector3 forcesVec = Vector3.zero;
forcesVec += this.Gravity();
//velocity += this.Gravity();
forcesVec += this.Forces();
if(forcesVec == Vector3.zero)
{
forcesVec = Vector3.up * 0.0001f;
}
//if(forcesVec != Vector3.zero)
//{
var flags = controller.Move(forcesVec * Time.fixedDeltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
//}
}
/// <summary>
/// Apply Gravity
/// </summary>
public Vector3 Gravity() {
Vector3 grav = Vector3.zero;
if(applyGravity && !grounded)
grav = new Vector3(0.0f,-5.0f,0.0f);
//controller.Move(new Vector3(0.0f,-6.0f * Time.fixedDeltaTime,0.0f));
if(flying && transform.position.y <= 0.25f)
{
grav = Vector3.zero;
}
return grav;
}
/// <summary>
/// Apply velocity and other forces
/// </summary>
public Vector3 Forces() {
Vector3 vec = Vector3.zero;
if(velocity != Vector3.zero)
{
//controller.Move(velocity * Time.fixedDeltaTime);
vec = velocity;
if(velocity.magnitude > 0.01f)
velocity -= (velocity * drag * Time.fixedDeltaTime);
else
velocity = Vector3.zero;
}
return vec;
}
public void AddForce(Vector3 force) {
velocity += force;
}
public Vector3 GetForce() {
return velocity;
}
public void Movement(float xaxis, float yaxis) {
if(xaxis == 0 && yaxis == 0) return;
//forward = transform.TransformDirection(Vector3.forward);
moveVec = transform.forward * moveSpeed * yaxis;
transform.position += moveVec;
transform.Rotate(0,xaxis * turnSpeed * Time.fixedDeltaTime,0);
}
public void RawMovement(Vector3 move) {
RawMovement(move, true, false);
}
public void RawMovement(Vector3 move, bool align)
{
RawMovement(move, align, false);
}
public void RawMovement(Vector3 move, bool align, bool forceLook) {
moveVec = move * moveSpeed;
//transform.position += moveVec;
if(align && move.magnitude > 0.15 && (transform.forward != move))
{
Vector3 lookVec = move;
//transform.rotation.SetFromToRotation(transform.forward, lookVec);
//var rotAngle = Vector3.Angle(transform.forward, lookVec);
//transform.Rotate(0.0f, rotAngle, 0.0f);
//var lookVec = moveVec;
Look(lookVec, !forceLook);
}
//controller.Move(moveVec);
var flags = controller.Move(moveVec * Time.fixedDeltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
}
public void RawMotion(Vector3 move)
{
var originalSpeed = moveSpeed;
moveSpeed = 1.0f;
RawMovement(move);
moveSpeed = originalSpeed;
}
public void Look()
{
this.Look(this.moveVec, 0.0f);
}
public void Look(Vector3 lookVec)
{
this.Look(lookVec, 0.0f);
}
// legacy : try to convert usages to the (vec, float) version
public void Look(Vector3 lookVec, bool smooth) {
var speed = 0.0f;
if(smooth)
{
speed = 0.2f;
}
this.Look(lookVec, speed);
}
public void Look(Vector3 lookVec, float speed) {
lookVec.y = 0.0f;
if(transform.forward == lookVec || lookVec == Vector3.zero) return;
if(speed > 0.0f)
{
// HACK : commented out for now, doesn't work on deployed builds
lookVec = Vector3.RotateTowards(transform.forward, lookVec, speed, 0.0f);
}
//iTween.Stop(gameObject, "LookTo");
//iTween.LookTo(gameObject, transform.position + moveVec, 0.5f);
//iTween.RotateTo(gameObject,
//transform.LookAt(transform.position + moveVec);
transform.rotation = Quaternion.LookRotation(lookVec, Vector3.up);
}
public void CardinalMovement(float xaxis, float yaxis) {
if(xaxis == 0 && yaxis == 0) return;
moveVec = new Vector3(xaxis, 0, yaxis);
moveVec *= moveSpeed;
//transform.position += moveVec;
var flags = controller.Move(moveVec * Time.fixedDeltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
if(moveVec.magnitude > 0.15f)
{
//iTween.Stop(gameObject, "LookTo");
//iTween.LookTo(gameObject, transform.position + moveVec, 1);
transform.LookAt(transform.position + moveVec);
//transform.rotation = Quaternion.RotateTowards(transform.rotation, );
}
}
public void OnKill()
{
Destroy(gameObject);
}
/// FIXME: this can become some static class someplace
public Vector3 GetGridPos(Vector3 pos) {
Vector3 snappedPos = pos;
snappedPos.x = Mathf.Round(snappedPos.x);
snappedPos.z = Mathf.Round(snappedPos.z);
return snappedPos;
}
/// FIXME: so can this
public Vector3 GetForwardGridPos() {
forward = transform.TransformDirection(Vector3.forward);
return GetGridPos(transform.position+forward);
}
/// return a list of colliders directly in front of me
public List<Collider> GetForwardColliders() {
// do a collision test in front of me
// snap collision to AABB grid
Vector3 snappedPos = GetForwardGridPos();
// if it collides, use Item and WorldObject as inputs to interaction rule logic
List<Collider> hits = new List<Collider>(Physics.OverlapSphere(snappedPos,0.25f));
hits.Remove(this.collider); // doesn't throw exception
return hits;
}
/*
public void OnTriggerEnter(Collider other) {
Debug.Log("oof! I bumped into a " + other.gameObject.name);
}
*/
public void SetMoveVec(Vector3 vec)
{
this.moveVec = vec;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.