context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.SystemColors
//
// Copyright (C) 2002 Ximian, Inc (http://www.ximian.com)
// Copyright (C) 2004-2005, 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Peter Dennis Bartok (pbartok@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
namespace System.Drawing
{
public sealed class SystemColors
{
private SystemColors()
{
}
static public Color ActiveBorder
{
get { return KnownColors.FromKnownColor(KnownColor.ActiveBorder); }
}
static public Color ActiveCaption
{
get { return KnownColors.FromKnownColor(KnownColor.ActiveCaption); }
}
static public Color ActiveCaptionText
{
get { return KnownColors.FromKnownColor(KnownColor.ActiveCaptionText); }
}
static public Color AppWorkspace
{
get { return KnownColors.FromKnownColor(KnownColor.AppWorkspace); }
}
static public Color Control
{
get { return KnownColors.FromKnownColor(KnownColor.Control); }
}
static public Color ControlDark
{
get { return KnownColors.FromKnownColor(KnownColor.ControlDark); }
}
static public Color ControlDarkDark
{
get { return KnownColors.FromKnownColor(KnownColor.ControlDarkDark); }
}
static public Color ControlLight
{
get { return KnownColors.FromKnownColor(KnownColor.ControlLight); }
}
static public Color ControlLightLight
{
get { return KnownColors.FromKnownColor(KnownColor.ControlLightLight); }
}
static public Color ControlText
{
get { return KnownColors.FromKnownColor(KnownColor.ControlText); }
}
static public Color Desktop
{
get { return KnownColors.FromKnownColor(KnownColor.Desktop); }
}
static public Color GrayText
{
get { return KnownColors.FromKnownColor(KnownColor.GrayText); }
}
static public Color Highlight
{
get { return KnownColors.FromKnownColor(KnownColor.Highlight); }
}
static public Color HighlightText
{
get { return KnownColors.FromKnownColor(KnownColor.HighlightText); }
}
static public Color HotTrack
{
get { return KnownColors.FromKnownColor(KnownColor.HotTrack); }
}
static public Color InactiveBorder
{
get { return KnownColors.FromKnownColor(KnownColor.InactiveBorder); }
}
static public Color InactiveCaption
{
get { return KnownColors.FromKnownColor(KnownColor.InactiveCaption); }
}
static public Color InactiveCaptionText
{
get { return KnownColors.FromKnownColor(KnownColor.InactiveCaptionText); }
}
static public Color Info
{
get { return KnownColors.FromKnownColor(KnownColor.Info); }
}
static public Color InfoText
{
get { return KnownColors.FromKnownColor(KnownColor.InfoText); }
}
static public Color Menu
{
get { return KnownColors.FromKnownColor(KnownColor.Menu); }
}
static public Color MenuText
{
get { return KnownColors.FromKnownColor(KnownColor.MenuText); }
}
static public Color ScrollBar
{
get { return KnownColors.FromKnownColor(KnownColor.ScrollBar); }
}
static public Color Window
{
get { return KnownColors.FromKnownColor(KnownColor.Window); }
}
static public Color WindowFrame
{
get { return KnownColors.FromKnownColor(KnownColor.WindowFrame); }
}
static public Color WindowText
{
get { return KnownColors.FromKnownColor(KnownColor.WindowText); }
}
static public Color ButtonFace
{
get { return KnownColors.FromKnownColor(KnownColor.ButtonFace); }
}
static public Color ButtonHighlight
{
get { return KnownColors.FromKnownColor(KnownColor.ButtonHighlight); }
}
static public Color ButtonShadow
{
get { return KnownColors.FromKnownColor(KnownColor.ButtonShadow); }
}
static public Color GradientActiveCaption
{
get { return KnownColors.FromKnownColor(KnownColor.GradientActiveCaption); }
}
static public Color GradientInactiveCaption
{
get { return KnownColors.FromKnownColor(KnownColor.GradientInactiveCaption); }
}
static public Color MenuBar
{
get { return KnownColors.FromKnownColor(KnownColor.MenuBar); }
}
static public Color MenuHighlight
{
get { return KnownColors.FromKnownColor(KnownColor.MenuHighlight); }
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// FXMaker
// Created by ismoon - 2012 - ismoonto@gmail.com
//
// ----------------------------------------------------------------------------------
// Attribute ------------------------------------------------------------------------
// Property -------------------------------------------------------------------------
// Loop Function --------------------------------------------------------------------
// Control Function -----------------------------------------------------------------
// Event Function -------------------------------------------------------------------
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Collections;
using System.IO;
using System.Reflection;
public class FxmPopup_Object : FxmPopup
{
// Attribute ------------------------------------------------------------------------
// popup
protected Object m_SelectedObject;
protected int m_nSelectedIndex;
protected int m_nButtonCount;
protected FXMakerHierarchy.OBJECT_TYPE m_SelObjectType;
// Property -------------------------------------------------------------------------
public bool ShowPopupWindow(FXMakerHierarchy.OBJECT_TYPE selObjType, Transform baseTransform, Object selObj, int selIndex)
{
m_SelectedTransform = baseTransform;
m_SelObjectType = selObjType;
m_nSelectedIndex = selIndex;
return ShowPopupWindow(selObj);
}
public override bool ShowPopupWindow(Object selObj)
{
m_nButtonCount = 20;
m_PopupPosition = FXMakerLayout.GetGUIMousePosition();
m_SelectedObject = selObj;
enabled = true;
base.ShowPopupWindow(null);
return enabled;
}
// -------------------------------------------------------------------------------------------
void Awake()
{
}
void Start()
{
}
void Update()
{
}
public override void OnGUIPopup()
{
// Popup Window ---------------------------------------------------------
FXMakerMain.inst.PopupFocusWindow(FXMakerLayout.GetWindowId(FXMakerLayout.WINDOWID.POPUP), GetPopupRect(), winPopup, "Right Menu");
}
// ==========================================================================================================
void winPopup(int id)
{
Rect baseRect = GetPopupRect();
Rect buttonRect;
Rect lineRect;
if (UnfocusClose(baseRect, -10, 0, 0, 0))
return;
baseRect = FXMakerLayout.GetChildVerticalRect(baseRect, 0, 1, 0, 1);
Transform transOriginalRoot = FXMakerMain.inst.GetOriginalEffectObject().transform;
int nButtonCount = m_nButtonCount*2;
int nDrawCount = 0;
bool bEnable = false;
// Copy
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Copy"), true))
{
FXMakerClipboard.inst.SetClipboardObject(m_SelectedObject);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Cut
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT: bEnable = ( m_SelectedTransform != transOriginalRoot); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: bEnable = false; break;
default : Debug.LogWarning("not declare"); break;
}
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Cut"), bEnable))
{
FXMakerClipboard.inst.SetClipboardObject(m_SelectedObject);
FXMakerHierarchy.inst.DeleteHierarchyObject(m_SelectedTransform, m_SelectedObject, m_nSelectedIndex);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Paste
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: bEnable = FXMakerClipboard.inst.IsObject(); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: bEnable = false; break;
default : Debug.LogWarning("not declare"); break;
}
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Paste", FXMakerClipboard.inst.GetName()), bEnable))
{
Object tarObj = FXMakerClipboard.inst.PasteClipboardObject(m_SelectedTransform.gameObject, m_SelectedObject, m_nSelectedIndex);
if (tarObj is GameObject)
SetAddObject((tarObj as GameObject), tarObj);
else SetAddObject(null, tarObj);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Overwrite
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM: bEnable = FXMakerClipboard.inst.IsTransform() && FXMakerClipboard.inst.GetObject().GetType() == m_SelectedObject.GetType(); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: bEnable = FXMakerClipboard.inst.IsComponent() && FXMakerClipboard.inst.GetObject().GetType() == m_SelectedObject.GetType(); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: bEnable = FXMakerClipboard.inst.IsMaterial() && FXMakerClipboard.inst.GetObject().GetType() == m_SelectedObject.GetType(); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: bEnable = FXMakerClipboard.inst.IsAnimationClip() && FXMakerClipboard.inst.GetObject().GetType() == m_SelectedObject.GetType(); break;
default: Debug.LogWarning("not declare"); break;
}
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Overwrite", FXMakerClipboard.inst.GetName()), bEnable))
{
FXMakerClipboard.inst.OverwriteClipboardObject(m_SelectedTransform.gameObject, m_SelectedObject, m_nSelectedIndex);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Draw line
lineRect = FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 1);
NgGUIDraw.DrawHorizontalLine(new Vector2(lineRect.x, lineRect.y+lineRect.height/2), (int)lineRect.width, Color.gray, 2, false);
nDrawCount += 1;
// Duplicate
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT: bEnable = (m_SelectedTransform != transOriginalRoot); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: bEnable = false; break;
default: Debug.LogWarning("not declare"); break;
}
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Duplicate"), bEnable))
{
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT: SetAddObject(FXMakerHierarchy.inst.AddGameObject(m_SelectedTransform.transform.parent.gameObject, m_SelectedTransform.gameObject), null); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM: break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE:
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: m_AddComObject = NgSerialized.CloneComponent(m_SelectedObject as Component, (m_SelectedObject as Component).gameObject, false); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: break;
default: Debug.LogWarning("not declare"); break;
}
ClosePopup(true);
return;
}
nDrawCount += 2;
// Disable
if (m_SelObjectType == FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT)
{
bool bObjEnable = (m_SelectedTransform.gameObject.GetComponent<NcDontActive>() == null);
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), (bObjEnable ? GetHelpContent("Disable") : GetHelpContent("Enable")), (m_SelectedTransform != transOriginalRoot)))
{
FXMakerHierarchy.inst.SetEnableGameObject(m_SelectedTransform.gameObject, !bObjEnable);
ClosePopup(true);
return;
}
} else {
buttonRect = FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2);
if (m_SelectedObject is Component)
{
int nObjEnable = EditorUtility.GetObjectEnabled(m_SelectedObject);
if (0 <= nObjEnable)
{
if (0 < nObjEnable)
{
if (GUI.Button(buttonRect, GetHelpContent("Disable")))
{
EditorUtility.SetObjectEnabled(m_SelectedObject, false);
FXMakerHierarchy.inst.OnEnableComponent(m_SelectedObject as Component, false);
ClosePopup(true);
return;
}
} else {
if (GUI.Button(buttonRect, GetHelpContent("Enable")))
{
EditorUtility.SetObjectEnabled(m_SelectedObject, true);
FXMakerHierarchy.inst.OnEnableComponent(m_SelectedObject as Component, true);
ClosePopup(true);
return;
}
}
} else {
FXMakerLayout.GUIButton(buttonRect, GetHelpContent("Disable"), false);
}
} else FXMakerLayout.GUIButton(buttonRect, GetHelpContent("Disable"), false);
}
nDrawCount += 2;
// Delete
switch (m_SelObjectType)
{
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT: bEnable = ( m_SelectedTransform != transOriginalRoot); break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_TRANSFORM: bEnable = false; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_EASYEFFECT: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_UNITYENGINE: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_OTHER: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL: bEnable = true; break;
case FXMakerHierarchy.OBJECT_TYPE.OBJECT_ANICLIP: bEnable = true; break;
default: Debug.LogWarning("not declare"); break;
}
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Delete"), bEnable))
{
FXMakerHierarchy.inst.DeleteHierarchyObject(m_SelectedTransform, m_SelectedObject, m_nSelectedIndex);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Draw line
lineRect = FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 1);
NgGUIDraw.DrawHorizontalLine(new Vector2(lineRect.x, lineRect.y+lineRect.height/2), (int)lineRect.width, Color.gray, 2, false);
nDrawCount += 1;
// -------------------------------------------------------------------------------------
if (m_SelectedObject is NcCurveAnimation)
{
// NcCurveAnimation
NcCurveAnimation curveCom = m_SelectedObject as NcCurveAnimation;
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("SaveCurves"), 0 < curveCom.GetCurveInfoCount()))
{
ClosePopup(true);
FxmPopupManager.inst.ShowNcCurveAnimationPopup(curveCom, true);
return;
}
nDrawCount += 2;
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("LoadCurves"), true))
{
ClosePopup(true);
FxmPopupManager.inst.ShowNcCurveAnimationPopup(curveCom, false);
return;
}
nDrawCount += 2;
}
// -------------------------------------------------------------------------------------
if (m_SelObjectType == FXMakerHierarchy.OBJECT_TYPE.OBJECT_GAMEOBJECT)
{
// Add Child
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Add Child"), true))
{
// GameObject newChild = new GameObject("GameObject");
// newChild.transform.parent = m_SelectedTransform;
// FXMakerHierarchy.inst.OnAddGameObject(newChild);
// SetAddObject(newChild, null);
// ClosePopup(true);
FXMakerHierarchy.inst.ShowAddObjectRightPopup();
ClosePopup(false);
return;
}
nDrawCount += 2;
// Add Parent
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Add Parent"), true))
{
GameObject newParent = new GameObject("GameObject");
newParent.transform.parent = m_SelectedTransform.parent;
m_SelectedTransform.parent = newParent.transform;
m_SelectedTransform.name = m_SelectedTransform.name.Replace("(Original)", "");
if (m_SelectedTransform == transOriginalRoot)
FXMakerMain.inst.ChangeRoot_OriginalEffectObject(newParent);
FXMakerHierarchy.inst.OnAddGameObject(newParent);
SetAddObject(newParent, null);
ClosePopup(true);
return;
}
nDrawCount += 2;
// MoveToParent
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("MoveToParent"), (m_SelectedTransform != transOriginalRoot && (m_SelectedTransform.parent != transOriginalRoot) || (m_SelectedTransform.parent == transOriginalRoot && transOriginalRoot.childCount==1))))
{
if (m_SelectedTransform.parent == transOriginalRoot && transOriginalRoot.childCount==1)
{
FXMakerMain.inst.SaveTool("");
m_SelectedTransform = FXMakerMain.inst.GetOriginalEffectObject().transform;
// root swap
Transform toolRoot = m_SelectedTransform.parent;
Transform newParent = m_SelectedTransform.GetChild(0);
Transform newChild = m_SelectedTransform;
newChild.parent = null;
newParent.parent = null;
newChild.parent = newParent;
newParent.parent = toolRoot;
m_SelectedTransform = newParent;
FXMakerMain.inst.ChangeRoot_OriginalEffectObject(m_SelectedTransform.gameObject);
SetAddObject(null, null);
} else {
m_SelectedTransform.parent = m_SelectedTransform.parent.parent;
}
ClosePopup(true);
return;
}
nDrawCount += 2;
// Add Component
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Add Component"), true))
{
ClosePopup(true);
FxmPopupManager.inst.ShowHierarchyObjectPopup("FxmPopup_GameObject", m_SelectedTransform.gameObject);
return;
}
nDrawCount += 2;
// Add Prefab
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Add Prefab"), true))
{
FxmPopupManager.inst.ShowAddPrefabPopup(m_SelectedTransform);
ClosePopup(true);
return;
}
nDrawCount += 2;
// Save Prefab
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Save Prefab"), true))
{
ClosePopup(true);
FxmPopupManager.inst.ShowSavePrefabPopup(m_SelectedTransform);
return;
}
nDrawCount += 2;
}
// -------------------------------------------------------------------------------------
if (m_SelObjectType == FXMakerHierarchy.OBJECT_TYPE.OBJECT_MATERIAL)
{
bEnable = NgMaterial.IsMaterialColor(m_SelectedObject as Material);
// Copy Color
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Copy Color"), bEnable))
{
FXMakerClipboard.inst.SetClipboardColor(NgMaterial.GetMaterialColor(m_SelectedObject as Material));
ClosePopup(true);
return;
}
if (bEnable)
{
Rect colorRect = FXMakerLayout.GetOffsetRect(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), -5);
colorRect.width = colorRect.height;
EditorGUIUtility.DrawColorSwatch(colorRect, NgMaterial.GetMaterialColor(m_SelectedObject as Material));
}
nDrawCount += 2;
// Paste Color
if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), GetHelpContent("Paste Color"), bEnable))
{
FXMakerClipboard.inst.PasteClipboardColor(m_SelectedTransform, m_nSelectedIndex, m_SelectedObject as Material);
ClosePopup(true);
return;
}
{
Rect colorRect = FXMakerLayout.GetOffsetRect(FXMakerLayout.GetInnerVerticalRect(baseRect, nButtonCount, nDrawCount, 2), -5);
colorRect.width = colorRect.height;
EditorGUIUtility.DrawColorSwatch(colorRect, FXMakerClipboard.inst.m_CopyColor);
}
nDrawCount += 2;
}
m_nButtonCount = nDrawCount/2;
FXMakerMain.inst.SaveTooltip();
}
// ----------------------------------------------------------------------------------------------------------
public override Rect GetPopupRect()
{
return GetPopupRectRight(110, m_nButtonCount*m_nButtonHeight + 22);
}
// Control Function -----------------------------------------------------------------
// Event Function -------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
GUIContent GetHelpContent(string text)
{
return FXMakerTooltip.GetHcPopup_GameObject(text, "");
}
GUIContent GetHelpContent(string text, string arg)
{
return FXMakerTooltip.GetHcPopup_GameObject(text, arg);
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
namespace System.Security.Permissions
{
using System;
#if FEATURE_CAS_POLICY
using SecurityElement = System.Security.SecurityElement;
#endif // FEATURE_CAS_POLICY
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class ZoneIdentityPermission : CodeAccessPermission, IBuiltInPermission
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
// Zone Enum Flag
// ----- ----- -----
// NoZone -1 0x00
// MyComputer 0 0x01 (1 << 0)
// Intranet 1 0x02 (1 << 1)
// Trusted 2 0x04 (1 << 2)
// Internet 3 0x08 (1 << 3)
// Untrusted 4 0x10 (1 << 4)
private const uint AllZones = 0x1f;
[OptionalField(VersionAdded = 2)]
private uint m_zones;
#if FEATURE_REMOTING
// This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
[OptionalField(VersionAdded = 2)]
private String m_serializedPermission;
// This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
private SecurityZone m_zone = SecurityZone.NoZone;
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
// v2.0 and beyond XML case
if (m_serializedPermission != null)
{
FromXml(SecurityElement.FromString(m_serializedPermission));
m_serializedPermission = null;
}
else //v1.x case where we read the m_zone value
{
SecurityZone = m_zone;
m_zone = SecurityZone.NoZone;
}
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
m_zone = SecurityZone;
}
}
[OnSerialized]
private void OnSerialized(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
m_serializedPermission = null;
m_zone = SecurityZone.NoZone;
}
}
#endif // FEATURE_REMOTING
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public ZoneIdentityPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_zones = AllZones;
}
else if (state == PermissionState.None)
{
m_zones = 0;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
public ZoneIdentityPermission( SecurityZone zone )
{
this.SecurityZone = zone;
}
internal ZoneIdentityPermission( uint zones )
{
m_zones = (zones & AllZones);
}
// Internal function to append all the Zone in this permission to the input ArrayList
internal void AppendZones(ArrayList zoneList)
{
int nEnum = 0;
uint nFlag;
for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
{
if((m_zones & nFlag) != 0)
{
zoneList.Add((SecurityZone)nEnum);
}
nEnum++;
}
}
//------------------------------------------------------
//
// PUBLIC ACCESSOR METHODS
//
//------------------------------------------------------
public SecurityZone SecurityZone
{
set
{
VerifyZone( value );
if(value == SecurityZone.NoZone)
m_zones = 0;
else
m_zones = (uint)1 << (int)value;
}
get
{
SecurityZone z = SecurityZone.NoZone;
int nEnum = 0;
uint nFlag;
for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
{
if((m_zones & nFlag) != 0)
{
if(z == SecurityZone.NoZone)
z = (SecurityZone)nEnum;
else
return SecurityZone.NoZone;
}
nEnum++;
}
return z;
}
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
//
//------------------------------------------------------
private static void VerifyZone( SecurityZone zone )
{
if (zone < SecurityZone.NoZone || zone > SecurityZone.Untrusted)
{
throw new ArgumentException( Environment.GetResourceString("Argument_IllegalZone") );
}
Contract.EndContractBlock();
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override IPermission Copy()
{
return new ZoneIdentityPermission(this.m_zones);
}
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
return this.m_zones == 0;
ZoneIdentityPermission that = target as ZoneIdentityPermission;
if (that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
return (this.m_zones & that.m_zones) == this.m_zones;
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
return null;
ZoneIdentityPermission that = target as ZoneIdentityPermission;
if (that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
uint newZones = this.m_zones & that.m_zones;
if(newZones == 0)
return null;
return new ZoneIdentityPermission(newZones);
}
public override IPermission Union(IPermission target)
{
if (target == null)
return this.m_zones != 0 ? this.Copy() : null;
ZoneIdentityPermission that = target as ZoneIdentityPermission;
if (that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
return new ZoneIdentityPermission(this.m_zones | that.m_zones);
}
#if FEATURE_CAS_POLICY
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" );
if (SecurityZone != SecurityZone.NoZone)
{
esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) );
}
else
{
int nEnum = 0;
uint nFlag;
for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
{
if((m_zones & nFlag) != 0)
{
SecurityElement child = new SecurityElement("Zone");
child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) );
esd.AddChild(child);
}
nEnum++;
}
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
m_zones = 0;
CodeAccessPermission.ValidateElement( esd, this );
String eZone = esd.Attribute( "Zone" );
if (eZone != null)
SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone );
if(esd.Children != null)
{
foreach(SecurityElement child in esd.Children)
{
eZone = child.Attribute( "Zone" );
int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone );
if(enm == (int)SecurityZone.NoZone)
continue;
m_zones |= ((uint)1 << enm);
}
}
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return ZoneIdentityPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.ZoneIdentityPermissionIndex;
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace IO.Swagger.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration
{
/// <summary>
/// Initializes a new instance of the Configuration class with different settings
/// </summary>
/// <param name="apiClient">Api client</param>
/// <param name="defaultHeader">Dictionary of default HTTP header</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="accessToken">accessToken</param>
/// <param name="apiKey">Dictionary of API key</param>
/// <param name="apiKeyPrefix">Dictionary of API key prefix</param>
/// <param name="tempFolderPath">Temp folder path</param>
/// <param name="dateTimeFormat">DateTime format string</param>
/// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
public Configuration(ApiClient apiClient = null,
Dictionary<String, String> defaultHeader = null,
string username = null,
string password = null,
string accessToken = null,
Dictionary<String, String> apiKey = null,
Dictionary<String, String> apiKeyPrefix = null,
string tempFolderPath = null,
string dateTimeFormat = null,
int timeout = 100000
)
{
if (apiClient == null)
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
Username = username;
Password = password;
AccessToken = accessToken;
if (defaultHeader != null)
DefaultHeader = defaultHeader;
if (apiKey != null)
ApiKey = apiKey;
if (apiKeyPrefix != null)
ApiKeyPrefix = apiKeyPrefix;
TempFolderPath = tempFolderPath;
DateTimeFormat = dateTimeFormat;
Timeout = timeout;
}
/// <summary>
/// Initializes a new instance of the Configuration class.
/// </summary>
/// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient)
{
if (apiClient == null)
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
}
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static Configuration Default = new Configuration();
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
/// <value>Timeout.</value>
public int Timeout
{
get { return ApiClient.RestClient.Timeout; }
set
{
ApiClient.RestClient.Timeout = value;
}
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public ApiClient ApiClient;
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the default header.
/// </summary>
public Dictionary<String, String> DefaultHeader
{
get { return _defaultHeaderMap; }
set
{
_defaultHeaderMap = value;
}
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value)
{
_defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public String Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public String Password { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
/// </summary>
/// <value>The access token.</value>
public String AccessToken { get; set; }
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public Dictionary<String, String> ApiKey = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>();
/// <summary>
/// Get the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
return apiKeyPrefix + " " + apiKeyValue;
else
return apiKeyValue;
}
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public String TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (String.IsNullOrEmpty(value))
{
_tempFolderPath = value;
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
Directory.CreateDirectory(value);
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
_tempFolderPath = value;
else
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
private const string ISO8601_DATETIME_FORMAT = "o";
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
/// <summary>
/// Gets or sets the the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public String DateTimeFormat
{
get
{
return _dateTimeFormat;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static String ToDebugReport()
{
String report = "C# SDK (IO.Swagger) Debug Report:\n";
report += " OS: " + Environment.OSVersion + "\n";
report += " .NET Framework Version: " + Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString() + "\n";
report += " Version of the API: 1.0.0\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PartnersOperations operations.
/// </summary>
internal partial class PartnersOperations : IServiceOperations<LogicManagementClient>, IPartnersOperations
{
/// <summary>
/// Initializes a new instance of the PartnersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PartnersOperations(LogicManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of integration account partners.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountPartner>>> ListByIntegrationAccountsWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountPartnerFilter> odataQuery = default(ODataQuery<IntegrationAccountPartnerFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccounts", 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.Logic/integrationAccounts/{integrationAccountName}/partners").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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<IPage<IntegrationAccountPartner>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountPartner>>(_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 an integration account partner.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='partnerName'>
/// The integration account partner name.
/// </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<IntegrationAccountPartner>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (partnerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "partnerName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("integrationAccountName", integrationAccountName);
tracingParameters.Add("partnerName", partnerName);
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.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{partnerName}", System.Uri.EscapeDataString(partnerName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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<IntegrationAccountPartner>();
_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<IntegrationAccountPartner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an integration account partner.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='partnerName'>
/// The integration account partner name.
/// </param>
/// <param name='partner'>
/// The integration account partner.
/// </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<IntegrationAccountPartner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, IntegrationAccountPartner partner, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (partnerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "partnerName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (partner == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "partner");
}
if (partner != null)
{
partner.Validate();
}
// 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("integrationAccountName", integrationAccountName);
tracingParameters.Add("partnerName", partnerName);
tracingParameters.Add("partner", partner);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{partnerName}", System.Uri.EscapeDataString(partnerName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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(partner != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(partner, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (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 = 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<IntegrationAccountPartner>();
_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<IntegrationAccountPartner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountPartner>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an integration account partner.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='partnerName'>
/// The integration account partner name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string partnerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (partnerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "partnerName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("integrationAccountName", integrationAccountName);
tracingParameters.Add("partnerName", partnerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{partnerName}", System.Uri.EscapeDataString(partnerName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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 a list of integration account partners.
/// </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<IntegrationAccountPartner>>> ListByIntegrationAccountsNextWithHttpMessagesAsync(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, "ListByIntegrationAccountsNext", 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 System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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<IPage<IntegrationAccountPartner>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IntegrationAccountPartner>>(_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;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime.Types {
public partial class OldInstance {
#region Generated OldInstance Operators
// *** BEGIN GENERATED CODE ***
// generated by function: oldinstance_operators from: generate_ops.py
[return: MaybeNotImplemented]
public static object operator +([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__add__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__radd__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator +(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__radd__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceAdd(object other) {
return InvokeOne(this, other, "__iadd__");
}
[return: MaybeNotImplemented]
public static object operator -([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__sub__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rsub__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator -(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rsub__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceSubtract(object other) {
return InvokeOne(this, other, "__isub__");
}
[return: MaybeNotImplemented]
[SpecialName]
public static object Power([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__pow__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rpow__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
[SpecialName]
public static object Power(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rpow__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlacePower(object other) {
return InvokeOne(this, other, "__ipow__");
}
[return: MaybeNotImplemented]
public static object operator *([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__mul__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rmul__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator *(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rmul__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceMultiply(object other) {
return InvokeOne(this, other, "__imul__");
}
[return: MaybeNotImplemented]
[SpecialName]
public static object FloorDivide([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__floordiv__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rfloordiv__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
[SpecialName]
public static object FloorDivide(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rfloordiv__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceFloorDivide(object other) {
return InvokeOne(this, other, "__ifloordiv__");
}
[return: MaybeNotImplemented]
public static object operator /([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__div__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rdiv__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator /(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rdiv__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceDivide(object other) {
return InvokeOne(this, other, "__idiv__");
}
[return: MaybeNotImplemented]
[SpecialName]
public static object TrueDivide([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__truediv__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rtruediv__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
[SpecialName]
public static object TrueDivide(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rtruediv__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceTrueDivide(object other) {
return InvokeOne(this, other, "__itruediv__");
}
[return: MaybeNotImplemented]
public static object operator %([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__mod__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rmod__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator %(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rmod__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceMod(object other) {
return InvokeOne(this, other, "__imod__");
}
[return: MaybeNotImplemented]
[SpecialName]
public static object LeftShift([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__lshift__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rlshift__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
[SpecialName]
public static object LeftShift(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rlshift__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceLeftShift(object other) {
return InvokeOne(this, other, "__ilshift__");
}
[return: MaybeNotImplemented]
[SpecialName]
public static object RightShift([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__rshift__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rrshift__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
[SpecialName]
public static object RightShift(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rrshift__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceRightShift(object other) {
return InvokeOne(this, other, "__irshift__");
}
[return: MaybeNotImplemented]
public static object operator &([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__and__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rand__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator &(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rand__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceBitwiseAnd(object other) {
return InvokeOne(this, other, "__iand__");
}
[return: MaybeNotImplemented]
public static object operator |([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__or__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__ror__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator |(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__ror__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceBitwiseOr(object other) {
return InvokeOne(this, other, "__ior__");
}
[return: MaybeNotImplemented]
public static object operator ^([NotNull]OldInstance self, object other) {
object res = InvokeOne(self, other, "__xor__");
if (res != NotImplementedType.Value) return res;
OldInstance otherOc = other as OldInstance;
if (otherOc != null) {
return InvokeOne(otherOc, self, "__rxor__");
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object operator ^(object other, [NotNull]OldInstance self) {
return InvokeOne(self, other, "__rxor__");
}
[return: MaybeNotImplemented]
[SpecialName]
public object InPlaceExclusiveOr(object other) {
return InvokeOne(this, other, "__ixor__");
}
// *** END GENERATED CODE ***
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="AdGroupCriterionLabelServiceClient"/> instances.</summary>
public sealed partial class AdGroupCriterionLabelServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupCriterionLabelServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupCriterionLabelServiceSettings"/>.</returns>
public static AdGroupCriterionLabelServiceSettings GetDefault() => new AdGroupCriterionLabelServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupCriterionLabelServiceSettings"/> object with default settings.
/// </summary>
public AdGroupCriterionLabelServiceSettings()
{
}
private AdGroupCriterionLabelServiceSettings(AdGroupCriterionLabelServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAdGroupCriterionLabelSettings = existing.GetAdGroupCriterionLabelSettings;
MutateAdGroupCriterionLabelsSettings = existing.MutateAdGroupCriterionLabelsSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupCriterionLabelServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionLabelServiceClient.GetAdGroupCriterionLabel</c> and
/// <c>AdGroupCriterionLabelServiceClient.GetAdGroupCriterionLabelAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetAdGroupCriterionLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCriterionLabelServiceClient.MutateAdGroupCriterionLabels</c> and
/// <c>AdGroupCriterionLabelServiceClient.MutateAdGroupCriterionLabelsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAdGroupCriterionLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AdGroupCriterionLabelServiceSettings"/> object.</returns>
public AdGroupCriterionLabelServiceSettings Clone() => new AdGroupCriterionLabelServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupCriterionLabelServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class AdGroupCriterionLabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionLabelServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupCriterionLabelServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupCriterionLabelServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupCriterionLabelServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupCriterionLabelServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionLabelServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupCriterionLabelServiceClient Build()
{
AdGroupCriterionLabelServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupCriterionLabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupCriterionLabelServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupCriterionLabelServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupCriterionLabelServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupCriterionLabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupCriterionLabelServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupCriterionLabelServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionLabelServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionLabelServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AdGroupCriterionLabelService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group criteria.
/// </remarks>
public abstract partial class AdGroupCriterionLabelServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupCriterionLabelService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AdGroupCriterionLabelService scopes.</summary>
/// <remarks>
/// The default AdGroupCriterionLabelService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AdGroupCriterionLabelServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionLabelServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
public static stt::Task<AdGroupCriterionLabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupCriterionLabelServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupCriterionLabelServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCriterionLabelServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
public static AdGroupCriterionLabelServiceClient Create() => new AdGroupCriterionLabelServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupCriterionLabelServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AdGroupCriterionLabelServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupCriterionLabelServiceClient"/>.</returns>
internal static AdGroupCriterionLabelServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionLabelServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient = new AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient(callInvoker);
return new AdGroupCriterionLabelServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AdGroupCriterionLabelService client</summary>
public virtual AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabel(new GetAdGroupCriterionLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabelAsync(new GetAdGroupCriterionLabelRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(gagvr::AdGroupCriterionLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabel(new GetAdGroupCriterionLabelRequest
{
ResourceNameAsAdGroupCriterionLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(gagvr::AdGroupCriterionLabelName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAdGroupCriterionLabelAsync(new GetAdGroupCriterionLabelRequest
{
ResourceNameAsAdGroupCriterionLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the ad group criterion label to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(gagvr::AdGroupCriterionLabelName resourceName, st::CancellationToken cancellationToken) =>
GetAdGroupCriterionLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupCriterionLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriterionLabels(new MutateAdGroupCriterionLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCriterionLabelsAsync(new MutateAdGroupCriterionLabelsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose ad group criterion labels are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on ad group criterion labels.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(string customerId, scg::IEnumerable<AdGroupCriterionLabelOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupCriterionLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupCriterionLabelService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage labels on ad group criteria.
/// </remarks>
public sealed partial class AdGroupCriterionLabelServiceClientImpl : AdGroupCriterionLabelServiceClient
{
private readonly gaxgrpc::ApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel> _callGetAdGroupCriterionLabel;
private readonly gaxgrpc::ApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse> _callMutateAdGroupCriterionLabels;
/// <summary>
/// Constructs a client wrapper for the AdGroupCriterionLabelService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupCriterionLabelServiceSettings"/> used within this client.
/// </param>
public AdGroupCriterionLabelServiceClientImpl(AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient, AdGroupCriterionLabelServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupCriterionLabelServiceSettings effectiveSettings = settings ?? AdGroupCriterionLabelServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAdGroupCriterionLabel = clientHelper.BuildApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel>(grpcClient.GetAdGroupCriterionLabelAsync, grpcClient.GetAdGroupCriterionLabel, effectiveSettings.GetAdGroupCriterionLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAdGroupCriterionLabel);
Modify_GetAdGroupCriterionLabelApiCall(ref _callGetAdGroupCriterionLabel);
_callMutateAdGroupCriterionLabels = clientHelper.BuildApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse>(grpcClient.MutateAdGroupCriterionLabelsAsync, grpcClient.MutateAdGroupCriterionLabels, effectiveSettings.MutateAdGroupCriterionLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupCriterionLabels);
Modify_MutateAdGroupCriterionLabelsApiCall(ref _callMutateAdGroupCriterionLabels);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetAdGroupCriterionLabelApiCall(ref gaxgrpc::ApiCall<GetAdGroupCriterionLabelRequest, gagvr::AdGroupCriterionLabel> call);
partial void Modify_MutateAdGroupCriterionLabelsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriterionLabelsRequest, MutateAdGroupCriterionLabelsResponse> call);
partial void OnConstruction(AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient grpcClient, AdGroupCriterionLabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupCriterionLabelService client</summary>
public override AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient GrpcClient { get; }
partial void Modify_GetAdGroupCriterionLabelRequest(ref GetAdGroupCriterionLabelRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAdGroupCriterionLabelsRequest(ref MutateAdGroupCriterionLabelsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::AdGroupCriterionLabel GetAdGroupCriterionLabel(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionLabelRequest(ref request, ref callSettings);
return _callGetAdGroupCriterionLabel.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(GetAdGroupCriterionLabelRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAdGroupCriterionLabelRequest(ref request, ref callSettings);
return _callGetAdGroupCriterionLabel.Async(request, callSettings);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriterionLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupCriterionLabels.Sync(request, callSettings);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(MutateAdGroupCriterionLabelsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCriterionLabelsRequest(ref request, ref callSettings);
return _callMutateAdGroupCriterionLabels.Async(request, callSettings);
}
}
}
| |
#define LINQ
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
namespace NDesk.Options {
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
TypeConverter conv = TypeDescriptor.GetConverter (typeof (T));
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, typeof (T).Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
#pragma warning disable 618
var def = GetOptionForName ("<>");
#pragma warning restore 618
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
#endif
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
List<string> lines = GetLines (localizer (GetDescription (p.Description)));
o.WriteLine (lines [0]);
string prefix = new string (' ', OptionWidth+2);
for (int i = 1; i < lines.Count; ++i) {
o.Write (prefix);
o.WriteLine (lines [i]);
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static List<string> GetLines (string description)
{
List<string> lines = new List<string> ();
if (string.IsNullOrEmpty (description)) {
lines.Add (string.Empty);
return lines;
}
int length = 80 - OptionWidth - 2;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
bool cont = false;
if (end < description.Length) {
char c = description [end];
if (c == '-' || (char.IsWhiteSpace (c) && c != '\n'))
++end;
else if (c != '\n') {
cont = true;
--end;
}
}
lines.Add (description.Substring (start, end - start));
if (cont) {
lines [lines.Count-1] += "-";
}
start = end;
if (start < description.Length && description [start] == '\n')
++start;
} while (end < description.Length);
return lines;
}
private static int GetLineEnd (int start, int length, string description)
{
int end = Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
switch (description [i]) {
case ' ':
case '\t':
case '\v':
case '-':
case ',':
case '.':
case ';':
sep = i;
break;
case '\n':
return i;
}
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Aspose.Email.Live.Demos.UI.Helpers.Html
{
public class WordSplitter
{
/// <summary>
/// Converts Html text into a list of words
/// </summary>
public static string[] ConvertHtmlToListOfWords(
string text,
IList<Regex> blockExpressions)
{
var mode = Mode.Character;
var currentWord = new List<char>();
var words = new List<string>();
var blockLocations = FindBlocks(text, blockExpressions);
var isBlockCheckRequired = blockLocations.Any();
var isGrouping = false;
var groupingUntil = -1;
for (var index = 0; index < text.Length; index++)
{
var character = text[index];
// Don't bother executing block checks if we don't have any blocks to check for!
if (isBlockCheckRequired)
{
// Check if we have completed grouping a text sequence/block
if (groupingUntil == index)
{
groupingUntil = -1;
isGrouping = false;
}
// Check if we need to group the next text sequence/block
int until = 0;
if (blockLocations.TryGetValue(index, out until))
{
isGrouping = true;
groupingUntil = until;
}
// if we are grouping, then we don't care about what type of character we have, it's going to be treated as a word
if (isGrouping)
{
currentWord.Add(character);
mode = Mode.Character;
continue;
}
}
switch (mode)
{
case Mode.Character:
if (Utils.IsStartOfTag(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add('<');
mode = Mode.Tag;
}
else if (Utils.IsStartOfEntity(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Entity;
}
else if (Utils.IsWhiteSpace(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Whitespace;
}
else if (Utils.IsWord(character)
&& (currentWord.Count == 0 || Utils.IsWord(currentWord.Last())))
{
currentWord.Add(character);
}
else
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
}
break;
case Mode.Tag:
if (Utils.IsEndOfTag(character))
{
currentWord.Add(character);
words.Add(new string(currentWord.ToArray()));
currentWord.Clear();
mode = Utils.IsWhiteSpace(character) ? Mode.Whitespace : Mode.Character;
}
else
{
currentWord.Add(character);
}
break;
case Mode.Whitespace:
if (Utils.IsStartOfTag(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Tag;
}
else if (Utils.IsStartOfEntity(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Entity;
}
else if (Utils.IsWhiteSpace(character))
{
currentWord.Add(character);
}
else
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Character;
}
break;
case Mode.Entity:
if (Utils.IsStartOfTag(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Tag;
}
else if (char.IsWhiteSpace(character))
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Whitespace;
}
else if (Utils.IsEndOfEntity(character))
{
var switchToNextMode = true;
if (currentWord.Count != 0)
{
currentWord.Add(character);
words.Add(new string(currentWord.ToArray()));
//join entity with last whitespace
if (words.Count > 2
&& Utils.IsWhiteSpace(words[words.Count - 2])
&& Utils.IsWhiteSpace(words[words.Count - 1]))
{
var w1 = words[words.Count - 2];
var w2 = words[words.Count - 1];
words.RemoveRange(words.Count - 2, 2);
currentWord.Clear();
currentWord.AddRange(w1);
currentWord.AddRange(w2);
mode = Mode.Whitespace;
switchToNextMode = false;
}
}
if (switchToNextMode)
{
currentWord.Clear();
mode = Mode.Character;
}
}
else if (Utils.IsWord(character))
{
currentWord.Add(character);
}
else
{
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
currentWord.Clear();
currentWord.Add(character);
mode = Mode.Character;
}
break;
}
}
if (currentWord.Count != 0)
{
words.Add(new string(currentWord.ToArray()));
}
return words.ToArray();
}
/// <summary>
/// Finds any blocks that need to be grouped
/// </summary>
private static Dictionary<int, int> FindBlocks(
string text,
IList<Regex> blockExpressions)
{
var blockLocations = new Dictionary<int, int>();
if (blockExpressions == null)
{
return blockLocations;
}
foreach (var exp in blockExpressions)
{
var matches = exp.Matches(text);
foreach (System.Text.RegularExpressions.Match match in matches)
{
try
{
blockLocations.Add(match.Index, match.Index + match.Length);
}
catch (ArgumentException)
{
var msg =
$"One or more block expressions result in a text sequence that overlaps. Current expression: {exp}";
throw new ArgumentException(msg);
}
}
}
return blockLocations;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Web;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
using OSDArray=OpenMetaverse.StructuredData.OSDArray;
using OSDMap=OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Region.CoreModules.InterGrid
{
public struct OGPState
{
public string first_name;
public string last_name;
public UUID agent_id;
public UUID local_agent_id;
public UUID region_id;
public uint circuit_code;
public UUID secure_session_id;
public UUID session_id;
public bool agent_access;
public string sim_access;
public uint god_level;
public bool god_overide;
public bool identified;
public bool transacted;
public bool age_verified;
public bool allow_redirect;
public int limited_to_estate;
public string inventory_host;
public bool src_can_see_mainland;
public int src_estate_id;
public int src_version;
public int src_parent_estate_id;
public bool visible_to_parent;
public string teleported_into_region;
}
public class OpenGridProtocolModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_scene = new List<Scene>();
private Dictionary<string, AgentCircuitData> CapsLoginID = new Dictionary<string, AgentCircuitData>();
private Dictionary<UUID, OGPState> m_OGPState = new Dictionary<UUID, OGPState>();
private Dictionary<string, string> m_loginToRegionState = new Dictionary<string, string>();
private string LastNameSuffix = "_EXTERNAL";
private string FirstNamePrefix = "";
private string httpsCN = "";
private bool httpSSL = false;
private uint httpsslport = 0;
// private bool GridMode = false;
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
bool enabled = false;
IConfig cfg = null;
IConfig httpcfg = null;
// IConfig startupcfg = null;
try
{
cfg = config.Configs["OpenGridProtocol"];
} catch (NullReferenceException)
{
enabled = false;
}
try
{
httpcfg = config.Configs["Network"];
}
catch (NullReferenceException)
{
}
// try
// {
// startupcfg = config.Configs["Startup"];
// }
// catch (NullReferenceException)
// {
//
// }
// if (startupcfg != null)
// {
// GridMode = enabled = startupcfg.GetBoolean("gridmode", false);
// }
if (cfg != null)
{
enabled = cfg.GetBoolean("ogp_enabled", false);
LastNameSuffix = cfg.GetString("ogp_lastname_suffix", "_EXTERNAL");
FirstNamePrefix = cfg.GetString("ogp_firstname_prefix", "");
if (enabled)
{
m_log.Warn("[OGP]: Open Grid Protocol is on, Listening for Clients on /agent/");
lock (m_scene)
{
if (m_scene.Count == 0)
{
MainServer.Instance.AddLLSDHandler("/agent/", ProcessAgentDomainMessage);
MainServer.Instance.AddLLSDHandler("/", ProcessRegionDomainSeed);
try
{
ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation;
}
catch (NotImplementedException)
{
try
{
#pragma warning disable 0612, 0618
// Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this!
ServicePointManager.CertificatePolicy = new MonoCert();
#pragma warning restore 0612, 0618
}
catch (Exception)
{
m_log.Error("[OGP]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions.");
}
}
}
// can't pick the region 'agent' because it would conflict with our agent domain handler
// a zero length region name would conflict with are base region seed cap
if (!SceneListDuplicateCheck(scene.RegionInfo.RegionName) && scene.RegionInfo.RegionName.ToLower() != "agent" && scene.RegionInfo.RegionName.Length > 0)
{
MainServer.Instance.AddLLSDHandler(
"/" + HttpUtility.UrlPathEncode(scene.RegionInfo.RegionName.ToLower()),
ProcessRegionDomainSeed);
}
if (!m_scene.Contains(scene))
m_scene.Add(scene);
}
}
}
lock (m_scene)
{
if (m_scene.Count == 1)
{
if (httpcfg != null)
{
httpSSL = httpcfg.GetBoolean("http_listener_ssl", false);
httpsCN = httpcfg.GetString("http_listener_cn", scene.RegionInfo.ExternalHostName);
if (httpsCN.Length == 0)
httpsCN = scene.RegionInfo.ExternalHostName;
httpsslport = (uint)httpcfg.GetInt("http_listener_sslport",((int)scene.RegionInfo.HttpPort + 1));
}
}
}
}
public void PostInitialise()
{
}
public void Close()
{
//scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
}
public string Name
{
get { return "OpenGridProtocolModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
public OSD ProcessRegionDomainSeed(string path, OSD request, string endpoint)
{
string[] pathSegments = path.Split('/');
if (pathSegments.Length <= 1)
{
return GenerateNoHandlerMessage();
}
return GenerateRezAvatarRequestMessage(pathSegments[1]);
//m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}",
// path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]);
//return new OSDMap();
}
public OSD ProcessAgentDomainMessage(string path, OSD request, string endpoint)
{
// /agent/*
string[] pathSegments = path.Split('/');
if (pathSegments.Length <= 1)
{
return GenerateNoHandlerMessage();
}
if (pathSegments[0].Length == 0 && pathSegments[1].Length == 0)
{
return GenerateRezAvatarRequestMessage("");
}
m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}",
path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]);
switch (pathSegments[pathSegments.Length - 1])
{
case "rez_avatar":
return RezAvatarMethod(path, request);
//break;
case "derez_avatar":
return DerezAvatarMethod(path, request);
//break;
}
if (path.Length < 2)
{
return GenerateNoHandlerMessage();
}
switch (pathSegments[pathSegments.Length - 2] + "/" + pathSegments[pathSegments.Length - 1])
{
case "rez_avatar/rez":
return RezAvatarMethod(path, request);
//break;
case "rez_avatar/request":
return RequestRezAvatarMethod(path, request);
case "rez_avatar/place":
return RequestRezAvatarMethod(path, request);
case "rez_avatar/derez":
return DerezAvatarMethod(path, request);
//break;
default:
return GenerateNoHandlerMessage();
}
//return null;
}
private OSD GenerateRezAvatarRequestMessage(string regionname)
{
Scene region = null;
bool usedroot = false;
if (regionname.Length == 0)
{
region = GetRootScene();
usedroot = true;
}
else
{
region = GetScene(HttpUtility.UrlDecode(regionname).ToLower());
}
// this shouldn't happen since we don't listen for a region that is down.. but
// it might if the region was taken down or is in the middle of restarting
if (region == null)
{
region = GetRootScene();
usedroot = true;
}
UUID statekeeper = UUID.Random();
RegionInfo reg = region.RegionInfo;
OSDMap responseMap = new OSDMap();
string rezHttpProtocol = "http://";
//string regionCapsHttpProtocol = "http://";
string httpaddr = reg.ExternalHostName;
string urlport = reg.HttpPort.ToString();
string requestpath = "/agent/" + statekeeper + "/rez_avatar/request";
if (!usedroot)
{
lock (m_loginToRegionState)
{
if (!m_loginToRegionState.ContainsKey(requestpath))
{
m_loginToRegionState.Add(requestpath, region.RegionInfo.RegionName.ToLower());
}
}
}
if (httpSSL)
{
rezHttpProtocol = "https://";
//regionCapsHttpProtocol = "https://";
urlport = httpsslport.ToString();
if (httpsCN.Length > 0)
httpaddr = httpsCN;
}
responseMap["connect"] = OSD.FromBoolean(true);
OSDMap capabilitiesMap = new OSDMap();
capabilitiesMap["rez_avatar/request"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + requestpath);
responseMap["capabilities"] = capabilitiesMap;
return responseMap;
}
// Using OpenSim.Framework.Capabilities.Caps here one time..
// so the long name is probably better then a using statement
public void OnRegisterCaps(UUID agentID, Caps caps)
{
/* If we ever want to register our own caps here....
*
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("CAPNAME",
new RestStreamHandler("POST", capsBase + CAPSPOSTFIX!,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return METHODHANDLER(request, path, param,
agentID, caps);
}));
*
*/
}
public OSD RequestRezAvatarMethod(string path, OSD request)
{
//m_log.Debug("[REQUESTREZAVATAR]: " + request.ToString());
OSDMap requestMap = (OSDMap)request;
Scene homeScene = null;
lock (m_loginToRegionState)
{
if (m_loginToRegionState.ContainsKey(path))
{
homeScene = GetScene(m_loginToRegionState[path]);
m_loginToRegionState.Remove(path);
if (homeScene == null)
homeScene = GetRootScene();
}
else
{
homeScene = GetRootScene();
}
}
// Homescene is still null, we must have no regions that are up
if (homeScene == null)
return GenerateNoHandlerMessage();
RegionInfo reg = homeScene.RegionInfo;
ulong regionhandle = GetOSCompatibleRegionHandle(reg);
//string RegionURI = reg.ServerURI;
//int RegionPort = (int)reg.HttpPort;
UUID RemoteAgentID = requestMap["agent_id"].AsUUID();
// will be used in the future. The client always connects with the aditi agentid currently
UUID LocalAgentID = RemoteAgentID;
string FirstName = requestMap["first_name"].AsString();
string LastName = requestMap["last_name"].AsString();
FirstName = FirstNamePrefix + FirstName;
LastName = LastName + LastNameSuffix;
OGPState userState = GetOGPState(LocalAgentID);
userState.first_name = requestMap["first_name"].AsString();
userState.last_name = requestMap["last_name"].AsString();
userState.age_verified = requestMap["age_verified"].AsBoolean();
userState.transacted = requestMap["transacted"].AsBoolean();
userState.agent_access = requestMap["agent_access"].AsBoolean();
userState.allow_redirect = requestMap["allow_redirect"].AsBoolean();
userState.identified = requestMap["identified"].AsBoolean();
userState.god_level = (uint)requestMap["god_level"].AsInteger();
userState.sim_access = requestMap["sim_access"].AsString();
userState.agent_id = RemoteAgentID;
userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger();
userState.src_can_see_mainland = requestMap["src_can_see_mainland"].AsBoolean();
userState.src_estate_id = requestMap["src_estate_id"].AsInteger();
userState.local_agent_id = LocalAgentID;
userState.teleported_into_region = reg.RegionName.ToLower();
UpdateOGPState(LocalAgentID, userState);
OSDMap responseMap = new OSDMap();
if (RemoteAgentID == UUID.Zero)
{
responseMap["connect"] = OSD.FromBoolean(false);
responseMap["message"] = OSD.FromString("No agent ID was specified in rez_avatar/request");
m_log.Error("[OGP]: rez_avatar/request failed because no avatar UUID was provided in the request body");
return responseMap;
}
responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName);
// DEPRECATED
responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString());
responseMap["connect"] = OSD.FromBoolean(true);
responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port);
responseMap["region_x"] = OSD.FromInteger(reg.RegionLocX * (uint)Constants.RegionSize); // LLX
responseMap["region_y"] = OSD.FromInteger(reg.RegionLocY * (uint)Constants.RegionSize); // LLY
responseMap["region_id"] = OSD.FromUUID(reg.originRegionID);
if (reg.RegionSettings.Maturity == 1)
{
responseMap["sim_access"] = OSD.FromString("Mature");
}
else if (reg.RegionSettings.Maturity == 2)
{
responseMap["sim_access"] = OSD.FromString("Adult");
}
else
{
responseMap["sim_access"] = OSD.FromString("PG");
}
// Generate a dummy agent for the user so we can get back a CAPS path
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = LocalAgentID;
agentData.BaseFolder = UUID.Zero;
agentData.CapsPath = CapsUtil.GetRandomCapsObjectPath();
agentData.child = false;
agentData.circuitcode = (uint)(Util.RandomClass.Next());
agentData.firstname = FirstName;
agentData.lastname = LastName;
agentData.SecureSessionID = UUID.Random();
agentData.SessionID = UUID.Random();
agentData.startpos = new Vector3(128f, 128f, 100f);
// Pre-Fill our region cache with information on the agent.
UserAgentData useragent = new UserAgentData();
useragent.AgentIP = "unknown";
useragent.AgentOnline = true;
useragent.AgentPort = (uint)0;
useragent.Handle = regionhandle;
useragent.InitialRegion = reg.originRegionID;
useragent.LoginTime = Util.UnixTimeSinceEpoch();
useragent.LogoutTime = 0;
useragent.Position = agentData.startpos;
useragent.Region = reg.originRegionID;
useragent.SecureSessionID = agentData.SecureSessionID;
useragent.SessionID = agentData.SessionID;
UserProfileData userProfile = new UserProfileData();
userProfile.AboutText = "OGP User";
userProfile.CanDoMask = (uint)0;
userProfile.Created = Util.UnixTimeSinceEpoch();
userProfile.CurrentAgent = useragent;
userProfile.CustomType = "OGP";
userProfile.FirstLifeAboutText = "I'm testing OpenGrid Protocol";
userProfile.FirstLifeImage = UUID.Zero;
userProfile.FirstName = agentData.firstname;
userProfile.GodLevel = 0;
userProfile.HomeLocation = agentData.startpos;
userProfile.HomeLocationX = agentData.startpos.X;
userProfile.HomeLocationY = agentData.startpos.Y;
userProfile.HomeLocationZ = agentData.startpos.Z;
userProfile.HomeLookAt = Vector3.Zero;
userProfile.HomeLookAtX = userProfile.HomeLookAt.X;
userProfile.HomeLookAtY = userProfile.HomeLookAt.Y;
userProfile.HomeLookAtZ = userProfile.HomeLookAt.Z;
userProfile.HomeRegion = reg.RegionHandle;
userProfile.HomeRegionID = reg.originRegionID;
userProfile.HomeRegionX = reg.RegionLocX;
userProfile.HomeRegionY = reg.RegionLocY;
userProfile.ID = agentData.AgentID;
userProfile.Image = UUID.Zero;
userProfile.LastLogin = Util.UnixTimeSinceEpoch();
userProfile.Partner = UUID.Zero;
userProfile.PasswordHash = "$1$";
userProfile.PasswordSalt = "";
userProfile.SurName = agentData.lastname;
//userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL;
userProfile.UserFlags = 0;
//userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL;
userProfile.WantDoMask = 0;
userProfile.WebLoginKey = UUID.Random();
// !!! REFACTORING PROBLEM. This needs to be changed for 0.7
//
//// Do caps registration
//// get seed capagentData.firstname = FirstName;agentData.lastname = LastName;
//if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode)
//{
// homeScene.CommsManager.UserAdminService.AddUser(
// agentData.firstname, agentData.lastname, CreateRandomStr(7), "",
// homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID);
// UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID);
// if (userProfile2 != null)
// {
// userProfile = userProfile2;
// userProfile.AboutText = "OGP USER";
// userProfile.FirstLifeAboutText = "OGP USER";
// homeScene.CommsManager.UserService.UpdateUserProfile(userProfile);
// }
//}
//// Stick our data in the cache so the region will know something about us
//homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile);
// Call 'new user' event handler
string reason;
if (!homeScene.NewUserConnection(agentData, (uint)TeleportFlags.ViaLogin, out reason))
{
responseMap["connect"] = OSD.FromBoolean(false);
responseMap["message"] = OSD.FromString(String.Format("Connection refused: {0}", reason));
m_log.ErrorFormat("[OGP]: rez_avatar/request failed: {0}", reason);
return responseMap;
}
//string raCap = string.Empty;
UUID AvatarRezCapUUID = LocalAgentID;
string rezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/rez";
string derezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/derez";
// Get a reference to the user's cap so we can pull out the Caps Object Path
Caps userCap
= homeScene.CapsModule.GetCapsHandlerForUser(agentData.AgentID);
string rezHttpProtocol = "http://";
string regionCapsHttpProtocol = "http://";
string httpaddr = reg.ExternalHostName;
string urlport = reg.HttpPort.ToString();
if (httpSSL)
{
rezHttpProtocol = "https://";
regionCapsHttpProtocol = "https://";
urlport = httpsslport.ToString();
if (httpsCN.Length > 0)
httpaddr = httpsCN;
}
// DEPRECATED
responseMap["seed_capability"]
= OSD.FromString(
regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath));
// REPLACEMENT
responseMap["region_seed_capability"]
= OSD.FromString(
regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath));
responseMap["rez_avatar"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath);
responseMap["rez_avatar/rez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath);
responseMap["rez_avatar/derez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + derezAvatarPath);
// Add the user to the list of CAPS that are outstanding.
// well allow the caps hosts in this dictionary
lock (CapsLoginID)
{
if (CapsLoginID.ContainsKey(rezAvatarPath))
{
CapsLoginID[rezAvatarPath] = agentData;
// This is a joke, if you didn't notice... It's so unlikely to happen, that I'll print this message if it does occur!
m_log.Error("[OGP]: Holy anomoly batman! Caps path already existed! All the UUID Duplication worries were founded!");
}
else
{
CapsLoginID.Add(rezAvatarPath, agentData);
}
}
//m_log.Debug("Response:" + responseMap.ToString());
return responseMap;
}
public OSD RezAvatarMethod(string path, OSD request)
{
m_log.WarnFormat("[REZAVATAR]: {0}", request.ToString());
OSDMap responseMap = new OSDMap();
AgentCircuitData userData = null;
// Only people we've issued a cap can go further
if (TryGetAgentCircuitData(path,out userData))
{
OSDMap requestMap = (OSDMap)request;
// take these values to start. There's a few more
UUID SecureSessionID=requestMap["secure_session_id"].AsUUID();
UUID SessionID = requestMap["session_id"].AsUUID();
int circuitcode = requestMap["circuit_code"].AsInteger();
OSDArray Parameter = new OSDArray();
if (requestMap.ContainsKey("parameter"))
{
Parameter = (OSDArray)requestMap["parameter"];
}
//int version = 1;
int estateID = 1;
int parentEstateID = 1;
UUID regionID = UUID.Zero;
bool visibleToParent = true;
for (int i = 0; i < Parameter.Count; i++)
{
OSDMap item = (OSDMap)Parameter[i];
// if (item.ContainsKey("version"))
// {
// version = item["version"].AsInteger();
// }
if (item.ContainsKey("estate_id"))
{
estateID = item["estate_id"].AsInteger();
}
if (item.ContainsKey("parent_estate_id"))
{
parentEstateID = item["parent_estate_id"].AsInteger();
}
if (item.ContainsKey("region_id"))
{
regionID = item["region_id"].AsUUID();
}
if (item.ContainsKey("visible_to_parent"))
{
visibleToParent = item["visible_to_parent"].AsBoolean();
}
}
//Update our Circuit data with the real values
userData.SecureSessionID = SecureSessionID;
userData.SessionID = SessionID;
OGPState userState = GetOGPState(userData.AgentID);
// Locate a home scene suitable for the user.
Scene homeScene = null;
homeScene = GetScene(userState.teleported_into_region);
if (homeScene == null)
homeScene = GetRootScene();
if (homeScene != null)
{
// Get a referenceokay - to their Cap object so we can pull out the capobjectroot
Caps userCap
= homeScene.CapsModule.GetCapsHandlerForUser(userData.AgentID);
//Update the circuit data in the region so this user is authorized
homeScene.UpdateCircuitData(userData);
homeScene.ChangeCircuitCode(userData.circuitcode,(uint)circuitcode);
// Load state
// Keep state changes
userState.first_name = requestMap["first_name"].AsString();
userState.secure_session_id = requestMap["secure_session_id"].AsUUID();
userState.age_verified = requestMap["age_verified"].AsBoolean();
userState.region_id = homeScene.RegionInfo.originRegionID; // replace 0000000 with our regionid
userState.transacted = requestMap["transacted"].AsBoolean();
userState.agent_access = requestMap["agent_access"].AsBoolean();
userState.inventory_host = requestMap["inventory_host"].AsString();
userState.identified = requestMap["identified"].AsBoolean();
userState.session_id = requestMap["session_id"].AsUUID();
userState.god_level = (uint)requestMap["god_level"].AsInteger();
userState.last_name = requestMap["last_name"].AsString();
userState.god_overide = requestMap["god_override"].AsBoolean();
userState.circuit_code = (uint)requestMap["circuit_code"].AsInteger();
userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger();
userState.src_estate_id = estateID;
userState.region_id = regionID;
userState.src_parent_estate_id = parentEstateID;
userState.visible_to_parent = visibleToParent;
// Save state changes
UpdateOGPState(userData.AgentID, userState);
// Get the region information for the home region.
RegionInfo reg = homeScene.RegionInfo;
// Dummy positional and look at info.. we don't have it.
OSDArray PositionArray = new OSDArray();
PositionArray.Add(OSD.FromInteger(128));
PositionArray.Add(OSD.FromInteger(128));
PositionArray.Add(OSD.FromInteger(40));
OSDArray LookAtArray = new OSDArray();
LookAtArray.Add(OSD.FromInteger(1));
LookAtArray.Add(OSD.FromInteger(1));
LookAtArray.Add(OSD.FromInteger(1));
// Our region's X and Y position in OpenSimulator space.
uint fooX = reg.RegionLocX;
uint fooY = reg.RegionLocY;
m_log.InfoFormat("[OGP]: region x({0}) region y({1})", fooX, fooY);
m_log.InfoFormat("[OGP]: region http {0} {1}", reg.ServerURI, reg.HttpPort);
m_log.InfoFormat("[OGO]: region UUID {0} ", reg.RegionID);
// Convert the X and Y position to LL space
responseMap["region_x"] = OSD.FromInteger(fooX * (uint)Constants.RegionSize); // convert it to LL X
responseMap["region_y"] = OSD.FromInteger(fooY * (uint)Constants.RegionSize); // convert it to LL Y
// Give em a new seed capability
responseMap["seed_capability"] = OSD.FromString("http://" + reg.ExternalHostName + ":" + reg.HttpPort + "/CAPS/" + userCap.CapsObjectPath + "0000/");
responseMap["region"] = OSD.FromUUID(reg.originRegionID);
responseMap["look_at"] = LookAtArray;
responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port);
responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName);// + ":" + reg.InternalEndPoint.Port.ToString());
// DEPRECATED
responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString());
responseMap["session_id"] = OSD.FromUUID(SessionID);
responseMap["secure_session_id"] = OSD.FromUUID(SecureSessionID);
responseMap["circuit_code"] = OSD.FromInteger(circuitcode);
responseMap["position"] = PositionArray;
responseMap["region_id"] = OSD.FromUUID(reg.originRegionID);
responseMap["sim_access"] = OSD.FromString("Mature");
responseMap["connect"] = OSD.FromBoolean(true);
m_log.InfoFormat("[OGP]: host: {0}, IP {1}", responseMap["sim_host"].ToString(), responseMap["sim_ip"].ToString());
}
}
return responseMap;
}
public OSD DerezAvatarMethod(string path, OSD request)
{
m_log.ErrorFormat("DerezPath: {0}, Request: {1}", path, request.ToString());
//LLSD llsdResponse = null;
OSDMap responseMap = new OSDMap();
string[] PathArray = path.Split('/');
m_log.InfoFormat("[OGP]: prefix {0}, uuid {1}, suffix {2}", PathArray[1], PathArray[2], PathArray[3]);
string uuidString = PathArray[2];
m_log.InfoFormat("[OGP]: Request to Derez avatar with UUID {0}", uuidString);
UUID userUUID = UUID.Zero;
if (UUID.TryParse(uuidString, out userUUID))
{
UUID RemoteID = (UUID)uuidString;
UUID LocalID = RemoteID;
// FIXME: TODO: Routine to map RemoteUUIDs to LocalUUIds
// would be done already.. but the client connects with the Aditi UUID
// regardless over the UDP stack
OGPState userState = GetOGPState(LocalID);
if (userState.agent_id != UUID.Zero)
{
//OSDMap outboundRequestMap = new OSDMap();
OSDMap inboundRequestMap = (OSDMap)request;
string rezAvatarString = inboundRequestMap["rez_avatar"].AsString();
if (rezAvatarString.Length == 0)
{
rezAvatarString = inboundRequestMap["rez_avatar/rez"].AsString();
}
OSDArray LookAtArray = new OSDArray();
LookAtArray.Add(OSD.FromInteger(1));
LookAtArray.Add(OSD.FromInteger(1));
LookAtArray.Add(OSD.FromInteger(1));
OSDArray PositionArray = new OSDArray();
PositionArray.Add(OSD.FromInteger(128));
PositionArray.Add(OSD.FromInteger(128));
PositionArray.Add(OSD.FromInteger(40));
OSDArray lookArray = new OSDArray();
lookArray.Add(OSD.FromInteger(128));
lookArray.Add(OSD.FromInteger(128));
lookArray.Add(OSD.FromInteger(40));
responseMap["connect"] = OSD.FromBoolean(true);// it's okay to give this user up
responseMap["look_at"] = LookAtArray;
m_log.WarnFormat("[OGP]: Invoking rez_avatar on host:{0} for avatar: {1} {2}", rezAvatarString, userState.first_name, userState.last_name);
OSDMap rezResponseMap = invokeRezAvatarCap(responseMap, rezAvatarString,userState);
// If invoking it returned an error, parse and end
if (rezResponseMap.ContainsKey("connect"))
{
if (rezResponseMap["connect"].AsBoolean() == false)
{
return responseMap;
}
}
string rezRespSeedCap = "";
// DEPRECATED
if (rezResponseMap.ContainsKey("seed_capability"))
rezRespSeedCap = rezResponseMap["seed_capability"].AsString();
// REPLACEMENT
if (rezResponseMap.ContainsKey("region_seed_capability"))
rezRespSeedCap = rezResponseMap["region_seed_capability"].AsString();
// REPLACEMENT
if (rezResponseMap.ContainsKey("rez_avatar/rez"))
rezRespSeedCap = rezResponseMap["rez_avatar/rez"].AsString();
// DEPRECATED
string rezRespSim_ip = rezResponseMap["sim_ip"].AsString();
string rezRespSim_host = rezResponseMap["sim_host"].AsString();
int rrPort = rezResponseMap["sim_port"].AsInteger();
int rrX = rezResponseMap["region_x"].AsInteger();
int rrY = rezResponseMap["region_y"].AsInteger();
m_log.ErrorFormat("X:{0}, Y:{1}", rrX, rrY);
UUID rrRID = rezResponseMap["region_id"].AsUUID();
OSDArray RezResponsePositionArray = null;
string rrAccess = rezResponseMap["sim_access"].AsString();
if (rezResponseMap.ContainsKey("position"))
{
RezResponsePositionArray = (OSDArray)rezResponseMap["position"];
}
// DEPRECATED
responseMap["seed_capability"] = OSD.FromString(rezRespSeedCap);
// REPLACEMENT r3
responseMap["region_seed_capability"] = OSD.FromString(rezRespSeedCap);
// DEPRECATED
responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(rezRespSim_ip).ToString());
responseMap["sim_host"] = OSD.FromString(rezRespSim_host);
responseMap["sim_port"] = OSD.FromInteger(rrPort);
responseMap["region_x"] = OSD.FromInteger(rrX);
responseMap["region_y"] = OSD.FromInteger(rrY);
responseMap["region_id"] = OSD.FromUUID(rrRID);
responseMap["sim_access"] = OSD.FromString(rrAccess);
if (RezResponsePositionArray != null)
{
responseMap["position"] = RezResponsePositionArray;
}
responseMap["look_at"] = lookArray;
responseMap["connect"] = OSD.FromBoolean(true);
ShutdownConnection(LocalID,this);
// PLEASE STOP CHANGING THIS TO an M_LOG, M_LOG DOESN'T WORK ON MULTILINE .TOSTRINGS
Console.WriteLine("RESPONSEDEREZ: " + responseMap.ToString());
return responseMap;
}
else
{
return GenerateNoStateMessage(LocalID);
}
}
else
{
return GenerateNoHandlerMessage();
}
//return responseMap;
}
private OSDMap invokeRezAvatarCap(OSDMap responseMap, string CapAddress, OGPState userState)
{
Scene reg = GetRootScene();
WebRequest DeRezRequest = WebRequest.Create(CapAddress);
DeRezRequest.Method = "POST";
DeRezRequest.ContentType = "application/xml+llsd";
OSDMap RAMap = new OSDMap();
OSDMap AgentParms = new OSDMap();
OSDMap RegionParms = new OSDMap();
OSDArray Parameter = new OSDArray(2);
OSDMap version = new OSDMap();
version["version"] = OSD.FromInteger(userState.src_version);
Parameter.Add(version);
OSDMap SrcData = new OSDMap();
SrcData["estate_id"] = OSD.FromInteger(reg.RegionInfo.EstateSettings.EstateID);
SrcData["parent_estate_id"] = OSD.FromInteger((reg.RegionInfo.EstateSettings.ParentEstateID == 100 ? 1 : reg.RegionInfo.EstateSettings.ParentEstateID));
SrcData["region_id"] = OSD.FromUUID(reg.RegionInfo.originRegionID);
SrcData["visible_to_parent"] = OSD.FromBoolean(userState.visible_to_parent);
Parameter.Add(SrcData);
AgentParms["first_name"] = OSD.FromString(userState.first_name);
AgentParms["last_name"] = OSD.FromString(userState.last_name);
AgentParms["agent_id"] = OSD.FromUUID(userState.agent_id);
RegionParms["region_id"] = OSD.FromUUID(userState.region_id);
AgentParms["circuit_code"] = OSD.FromInteger(userState.circuit_code);
AgentParms["secure_session_id"] = OSD.FromUUID(userState.secure_session_id);
AgentParms["session_id"] = OSD.FromUUID(userState.session_id);
AgentParms["agent_access"] = OSD.FromBoolean(userState.agent_access);
AgentParms["god_level"] = OSD.FromInteger(userState.god_level);
AgentParms["god_overide"] = OSD.FromBoolean(userState.god_overide);
AgentParms["identified"] = OSD.FromBoolean(userState.identified);
AgentParms["transacted"] = OSD.FromBoolean(userState.transacted);
AgentParms["age_verified"] = OSD.FromBoolean(userState.age_verified);
AgentParms["limited_to_estate"] = OSD.FromInteger(userState.limited_to_estate);
AgentParms["inventory_host"] = OSD.FromString(userState.inventory_host);
// version 1
RAMap = AgentParms;
// Planned for version 2
// RAMap["agent_params"] = AgentParms;
RAMap["region_params"] = RegionParms;
RAMap["parameter"] = Parameter;
string RAMapString = RAMap.ToString();
m_log.InfoFormat("[OGP] RAMap string {0}", RAMapString);
OSD LLSDofRAMap = RAMap; // RENAME if this works
m_log.InfoFormat("[OGP]: LLSD of map as string was {0}", LLSDofRAMap.ToString());
//m_log.InfoFormat("[OGP]: LLSD+XML: {0}", LLSDParser.SerializeXmlString(LLSDofRAMap));
byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
//string bufferDump = System.Text.Encoding.ASCII.GetString(buffer);
//m_log.InfoFormat("[OGP]: buffer form is {0}",bufferDump);
//m_log.InfoFormat("[OGP]: LLSD of map was {0}",buffer.Length);
Stream os = null;
try
{ // send the Post
DeRezRequest.ContentLength = buffer.Length; //Count bytes to send
os = DeRezRequest.GetRequestStream();
os.Write(buffer, 0, buffer.Length); //Send it
os.Close();
m_log.InfoFormat("[OGP]: Derez Avatar Posted Rez Avatar request to remote sim {0}", CapAddress);
}
catch (WebException ex)
{
m_log.InfoFormat("[OGP] Bad send on de_rez_avatar {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
m_log.Info("[OGP] waiting for a reply after rez avatar send");
string rez_avatar_reply = null;
{ // get the response
try
{
WebResponse webResponse = DeRezRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[OGP:] Null reply on rez_avatar post");
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
rez_avatar_reply = sr.ReadToEnd().Trim();
m_log.InfoFormat("[OGP]: rez_avatar reply was {0} ", rez_avatar_reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[OGP]: exception on read after send of rez avatar {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
OSD rezResponse = null;
try
{
rezResponse = OSDParser.DeserializeLLSDXml(rez_avatar_reply);
responseMap = (OSDMap)rezResponse;
}
catch (Exception ex)
{
m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
}
return responseMap;
}
public OSD GenerateNoHandlerMessage()
{
OSDMap map = new OSDMap();
map["reason"] = OSD.FromString("LLSDRequest");
map["message"] = OSD.FromString("No handler registered for LLSD Requests");
map["login"] = OSD.FromString("false");
map["connect"] = OSD.FromString("false");
return map;
}
public OSD GenerateNoStateMessage(UUID passedAvatar)
{
OSDMap map = new OSDMap();
map["reason"] = OSD.FromString("derez failed");
map["message"] = OSD.FromString("Unable to locate OGP state for avatar " + passedAvatar.ToString());
map["login"] = OSD.FromString("false");
map["connect"] = OSD.FromString("false");
return map;
}
private bool TryGetAgentCircuitData(string path, out AgentCircuitData userdata)
{
userdata = null;
lock (CapsLoginID)
{
if (CapsLoginID.ContainsKey(path))
{
userdata = CapsLoginID[path];
DiscardUsedCap(path);
return true;
}
}
return false;
}
private void DiscardUsedCap(string path)
{
CapsLoginID.Remove(path);
}
private Scene GetRootScene()
{
Scene ReturnScene = null;
lock (m_scene)
{
if (m_scene.Count > 0)
{
ReturnScene = m_scene[0];
}
}
return ReturnScene;
}
private Scene GetScene(string scenename)
{
Scene ReturnScene = null;
lock (m_scene)
{
foreach (Scene s in m_scene)
{
if (s.RegionInfo.RegionName.ToLower() == scenename)
{
ReturnScene = s;
break;
}
}
}
return ReturnScene;
}
private ulong GetOSCompatibleRegionHandle(RegionInfo reg)
{
return Util.UIntsToLong(reg.RegionLocX, reg.RegionLocY);
}
private OGPState InitializeNewState()
{
OGPState returnState = new OGPState();
returnState.first_name = "";
returnState.last_name = "";
returnState.agent_id = UUID.Zero;
returnState.local_agent_id = UUID.Zero;
returnState.region_id = UUID.Zero;
returnState.circuit_code = 0;
returnState.secure_session_id = UUID.Zero;
returnState.session_id = UUID.Zero;
returnState.agent_access = true;
returnState.god_level = 0;
returnState.god_overide = false;
returnState.identified = false;
returnState.transacted = false;
returnState.age_verified = false;
returnState.limited_to_estate = 1;
returnState.inventory_host = "http://inv4.mysql.aditi.lindenlab.com";
returnState.allow_redirect = true;
returnState.sim_access = "";
returnState.src_can_see_mainland = true;
returnState.src_estate_id = 1;
returnState.src_version = 1;
returnState.src_parent_estate_id = 1;
returnState.visible_to_parent = true;
returnState.teleported_into_region = "";
return returnState;
}
private OGPState GetOGPState(UUID agentId)
{
lock (m_OGPState)
{
if (m_OGPState.ContainsKey(agentId))
{
return m_OGPState[agentId];
}
else
{
return InitializeNewState();
}
}
}
public void DeleteOGPState(UUID agentId)
{
lock (m_OGPState)
{
if (m_OGPState.ContainsKey(agentId))
m_OGPState.Remove(agentId);
}
}
private void UpdateOGPState(UUID agentId, OGPState state)
{
lock (m_OGPState)
{
if (m_OGPState.ContainsKey(agentId))
{
m_OGPState[agentId] = state;
}
else
{
m_OGPState.Add(agentId,state);
}
}
}
private bool SceneListDuplicateCheck(string str)
{
// no lock, called from locked space!
bool found = false;
foreach (Scene s in m_scene)
{
if (s.RegionInfo.RegionName == str)
{
found = true;
break;
}
}
return found;
}
public void ShutdownConnection(UUID avatarId, OpenGridProtocolModule mod)
{
Scene homeScene = GetRootScene();
ScenePresence avatar = null;
if (homeScene.TryGetScenePresence(avatarId,out avatar))
{
KillAUser ku = new KillAUser(avatar,mod);
Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true);
}
}
// private string CreateRandomStr(int len)
// {
// Random rnd = new Random(Environment.TickCount);
// string returnstring = "";
// string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
//
// for (int i = 0; i < len; i++)
// {
// returnstring += chars.Substring(rnd.Next(chars.Length), 1);
// }
// return returnstring;
// }
// Temporary hack to allow teleporting to and from Vaak
private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
//if (cert.Subject == "E=root@lindenlab.com, CN=*.vaak.lindenlab.com, O=\"Linden Lab, Inc.\", L=San Francisco, S=California, C=US")
//{
return true;
//}
//return false;
}
}
public class KillAUser
{
private ScenePresence avToBeKilled = null;
private OpenGridProtocolModule m_mod = null;
public KillAUser(ScenePresence avatar, OpenGridProtocolModule mod)
{
avToBeKilled = avatar;
m_mod = mod;
}
public void ShutdownNoLogout()
{
UUID avUUID = UUID.Zero;
if (avToBeKilled != null)
{
avUUID = avToBeKilled.UUID;
avToBeKilled.MakeChildAgent();
avToBeKilled.ControllingClient.SendLogoutPacketWhenClosing = false;
int sleepMS = 30000;
while (sleepMS > 0)
{
Watchdog.UpdateThread();
Thread.Sleep(1000);
sleepMS -= 1000;
}
// test for child agent because they might have come back
if (avToBeKilled.IsChildAgent)
{
m_mod.DeleteOGPState(avUUID);
avToBeKilled.ControllingClient.Close();
}
}
Watchdog.RemoveThread();
}
}
public class MonoCert : ICertificatePolicy
{
#region ICertificatePolicy Members
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
{
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BluetoothSample.Bluetooth;
using Android.Bluetooth;
using Android.Util;
using System.Threading.Tasks;
using Java.Util;
using System.Threading;
namespace BluetoothSample.Droid
{
public class MyBluetooth : IBluetoothAdapter
{
// Intent request codes
// TODO: Make into Enums
private const int REQUEST_CONNECT_DEVICE = 1;
private const int REQUEST_ENABLE_BT = 2;
private List<BtDevice> devices;
private IBluetoothEventHandler eventHandler;
private BluetoothAdapter adapter;
private BluetoothSocket btsocket;
private Activity activity;
//private static UUID MY_UUID = UUID.FromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static UUID MY_UUID = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"); // Bluetooth Serial Port Profile
List<BtDevice> IBluetoothAdapter.devices
{
get
{
return this.devices;
}
}
IBluetoothEventHandler IBluetoothAdapter.eventHandler
{
set
{
this.eventHandler = value;
}
}
private DeviceState _deviceState;
public DeviceState deviceState
{
get
{
return _deviceState;
}
private set
{
_deviceState = value;
if(eventHandler != null)
{
eventHandler.StateChanged(deviceState);
}
}
}
public MyBluetooth(Activity activity)
{
// Register for broadcasts when a device is discovered
Receiver receiver = new Receiver(this);
var filter = new IntentFilter();
filter.AddAction(BluetoothDevice.ActionFound);
filter.AddAction(BluetoothAdapter.ActionDiscoveryFinished);
Android.App.Application.Context.RegisterReceiver(receiver, filter);
this.activity = activity;
adapter = BluetoothAdapter.DefaultAdapter;
devices = new List<BtDevice>();
this.deviceState = DeviceState.Disconnected;
var pairedDevices = adapter.BondedDevices;
foreach (var device in pairedDevices)
{
Log.Debug("BL-SAMPLE", device.Name + "\n" + device.Address);
}
}
public void scan()
{
// If BT is not on, request that it be enabled.
if (!adapter.IsEnabled)
{
Intent enableIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
activity.StartActivityForResult(enableIntent, REQUEST_ENABLE_BT);
eventHandler.DiscoverFinished();
return;
}
if (adapter.IsDiscovering)
{
adapter.CancelDiscovery();
}
adapter.StartDiscovery();
Log.Debug("BL-SAMPLE", "START DISCOVERY");
}
public void connect(BtDevice device)
{
if (device != null)
{
deviceState = DeviceState.Connecting;
BluetoothDevice deviceDroid = adapter.GetRemoteDevice(device.Address);
btsocket = deviceDroid.CreateInsecureRfcommSocketToServiceRecord(MY_UUID);
btsocket.Connect();
Thread oThread = new Thread(new ThreadStart(readBtSocket));
oThread.Start();
Log.Debug("BL-SAMPLE", "BluetoothDevice " + deviceDroid.Address);
deviceState = DeviceState.Connected;
}
else
{
throw new ArgumentNullException();
}
}
private void readBtSocket()
{
byte[] buffer = new byte[1024];
int bytes;
while (true)
{
bytes = btsocket.InputStream.Read(buffer, 0, buffer.Length);
if (bytes > 0)
{
eventHandler.BytesRecieved(bytes, buffer);
var str = System.Text.Encoding.Default.GetString(buffer);
Log.Debug("BL-SAMPLE", "bytes " + bytes);
Log.Debug("BL-SAMPLE", "input " + str);
}
Task.Delay(500).Wait();
}
}
public class Receiver : BroadcastReceiver
{
MyBluetooth myBluetooth;
public Receiver(MyBluetooth myBluetooth)
{
this.myBluetooth = myBluetooth;
}
public override void OnReceive(Context context, Intent intent)
{
string action = intent.Action;
// When discovery finds a device
if (action == BluetoothDevice.ActionFound)
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
// If it's already paired, skip it, because it's been listed already
//if (device.BondState != Bond.Bonded)
//{
// Notify bluetooth event handler that a device was found
myBluetooth.eventHandler.DeviceFound(new BtDevice {
Name = device.Name,
Address = device.Address
});
// Adds found device to list
myBluetooth.devices.Add(new BtDevice
{
Name = device.Name,
Address = device.Address
});
Log.Debug("BL-SAMPLE", device.Name + "-" + device.Address);
//}
// When discovery is finished, change the Activity title
}
else if (action == BluetoothAdapter.ActionDiscoveryFinished)
{
// Notify bluetooth event handler that the discover finished
myBluetooth.eventHandler.DiscoverFinished();
Log.Debug("BL-SAMPLE", "discovery finished");
}
}
}
}
}
| |
// 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.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal abstract class EditAndContinueTestHelpers
{
public abstract AbstractEditAndContinueAnalyzer Analyzer { get; }
public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span);
public abstract SyntaxTree ParseText(string source);
public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees);
public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method);
internal void VerifyUnchangedDocument(
string source,
ActiveStatementSpan[] oldActiveStatements,
TextSpan?[] trackingSpansOpt,
TextSpan[] expectedNewActiveStatements,
ImmutableArray<TextSpan>[] expectedOldExceptionRegions,
ImmutableArray<TextSpan>[] expectedNewExceptionRegions)
{
var text = SourceText.From(source);
var tree = ParseText(source);
var root = tree.GetRoot();
tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (trackingSpansOpt != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt);
}
else
{
trackingService = null;
}
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
Analyzer.AnalyzeUnchangedDocument(
oldActiveStatements.AsImmutable(),
text,
root,
documentId,
trackingService,
actualNewActiveStatements,
actualNewExceptionRegions);
// check active statements:
AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text);
// check new exception regions:
Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < expectedNewExceptionRegions.Length; i++)
{
AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text);
}
}
internal void VerifyRudeDiagnostics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription description,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var oldActiveStatements = description.OldSpans;
if (description.OldTrackingSpans != null)
{
Assert.Equal(oldActiveStatements.Length, description.OldTrackingSpans.Length);
}
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMemberInfo>();
var editMap = Analyzer.BuildEditMap(editScript);
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (description.OldTrackingSpans != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, description.OldTrackingSpans);
}
else
{
trackingService = null;
}
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
documentId,
trackingService,
oldActiveStatements.AsImmutable(),
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource, expectedDiagnostics);
// check active statements:
AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText);
if (diagnostics.Count == 0)
{
// check old exception regions:
for (int i = 0; i < oldActiveStatements.Length; i++)
{
var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
oldText,
editScript.Match.OldRoot,
oldActiveStatements[i].Span,
isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0);
AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
}
// check new exception regions:
Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < description.NewRegions.Length; i++)
{
AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
}
}
else
{
for (int i = 0; i < oldActiveStatements.Length; i++)
{
Assert.Equal(0, description.NewRegions[i].Length);
}
}
if (description.OldTrackingSpans != null)
{
// Verify that the new tracking spans are equal to the new active statements.
AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
}
}
internal void VerifyLineEdits(
EditScript<SyntaxNode> editScript,
IEnumerable<LineChange> expectedLineEdits,
IEnumerable<string> expectedNodeUpdates,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var editMap = Analyzer.BuildEditMap(editScript);
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n");
var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First());
AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n");
}
internal void VerifySemantics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription activeStatements,
IEnumerable<string> additionalOldSources = null,
IEnumerable<string> additionalNewSources = null,
SemanticEditDescription[] expectedSemanticEdits = null,
DiagnosticDescription expectedDeclarationError = null,
RudeEditDiagnosticDescription[] expectedDiagnostics = null)
{
var editMap = Analyzer.BuildEditMap(editScript);
var oldRoot = editScript.Match.OldRoot;
var newRoot = editScript.Match.NewRoot;
var oldSource = oldRoot.SyntaxTree.ToString();
var newSource = newRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };
if (additionalOldSources != null)
{
oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
}
if (additionalOldSources != null)
{
newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
}
var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
var newCompilation = CreateLibraryCompilation("New", newTrees);
var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);
var oldActiveStatements = activeStatements.OldSpans.AsImmutable();
var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMemberInfo>();
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
var actualSemanticEdits = new List<SemanticEdit>();
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length];
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
null,
null,
oldActiveStatements,
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource);
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource);
Analyzer.AnalyzeSemantics(
editScript,
editMap,
oldText,
oldActiveStatements,
triviaEdits,
updatedActiveMethodMatches,
oldModel,
newModel,
actualSemanticEdits,
diagnostics,
out var firstDeclarationErrorOpt,
default(CancellationToken));
var actualDeclarationErrors = (firstDeclarationErrorOpt != null) ? new[] { firstDeclarationErrorOpt } : Array.Empty<Diagnostic>();
var expectedDeclarationErrors = (expectedDeclarationError != null) ? new[] { expectedDeclarationError } : Array.Empty<DiagnosticDescription>();
actualDeclarationErrors.Verify(expectedDeclarationErrors);
diagnostics.Verify(newSource, expectedDiagnostics);
if (expectedSemanticEdits == null)
{
return;
}
Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);
for (int i = 0; i < actualSemanticEdits.Count; i++)
{
var editKind = expectedSemanticEdits[i].Kind;
Assert.Equal(editKind, actualSemanticEdits[i].Kind);
var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
var actualOldSymbol = actualSemanticEdits[i].OldSymbol;
var actualNewSymbol = actualSemanticEdits[i].NewSymbol;
Assert.Equal(expectedOldSymbol, actualOldSymbol);
Assert.Equal(expectedNewSymbol, actualNewSymbol);
var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap;
Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);
if (expectedSyntaxMap != null)
{
Assert.NotNull(actualSyntaxMap);
Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);
var newNodes = new List<SyntaxNode>();
foreach (var expectedSpanMapping in expectedSyntaxMap)
{
var newNode = FindNode(newRoot, expectedSpanMapping.Value);
var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
var actualOldNode = actualSyntaxMap(newNode);
Assert.Equal(expectedOldNode, actualOldNode);
newNodes.Add(newNode);
}
}
else if (!expectedSemanticEdits[i].PreserveLocalVariables)
{
Assert.Null(actualSyntaxMap);
}
}
}
private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText)
{
AssertEx.Equal(
expected,
actual.Select(span => newText.Lines.GetTextSpan(span)),
itemSeparator: "\r\n",
itemInspector: s => DisplaySpan(newSource, s));
}
private static string DisplaySpan(string source, TextSpan span)
{
return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]";
}
internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch)
{
Dictionary<SyntaxNode, AbstractEditAndContinueAnalyzer.LambdaInfo> lazyActiveOrMatchedLambdas = null;
var map = analyzer.ComputeMap(bodyMatch, Array.Empty<AbstractEditAndContinueAnalyzer.ActiveNode>(), ref lazyActiveOrMatchedLambdas, new List<RudeEditDiagnostic>());
var result = new Dictionary<SyntaxNode, SyntaxNode>();
foreach (var pair in map.Forward)
{
if (pair.Value == bodyMatch.NewRoot)
{
Assert.Same(pair.Key, bodyMatch.OldRoot);
continue;
}
result.Add(pair.Key, pair.Value);
}
return result;
}
public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match)
{
return ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot));
}
public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches)
{
return new MatchingPairs(matches
.OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start)
.ThenByDescending(partners => partners.Key.Span.Length)
.Select(partners => new MatchingPair
{
Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "),
New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ")
}));
}
private static IEnumerable<KeyValuePair<K, V>> ReverseMapping<K, V>(IEnumerable<KeyValuePair<V, K>> mapping)
{
foreach (var pair in mapping)
{
yield return KeyValuePair.Create(pair.Value, pair.Key);
}
}
}
internal static class EditScriptTestUtils
{
public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected)
{
AssertEx.Equal(
expected.Select(s => string.Format("\"{0}\"",s)),
actual.Edits.Select(e => string.Format("\"{0}\"", e.GetDebuggerDisplay())), itemSeparator: ",\r\n");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace Umbraco.Core.ObjectResolution
{
/// <summary>
/// The base class for all lazy many-objects resolvers.
/// </summary>
/// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam>
/// <typeparam name="TResolved">The type of the resolved objects.</typeparam>
/// <remarks>
/// <para>This is a special case resolver for when types get lazily resolved in order to resolve the actual types. This is useful
/// for when there is some processing overhead (i.e. Type finding in assemblies) to return the Types used to instantiate the instances.
/// In some these cases we don't want to have to type-find during application startup, only when we need to resolve the instances.</para>
/// <para>Important notes about this resolver: it does not support Insert or Remove and therefore does not support any ordering unless
/// the types are marked with the WeightedPluginAttribute.</para>
/// </remarks>
internal abstract class LazyManyObjectsResolverBase<TResolver, TResolved> : ManyObjectsResolverBase<TResolver, TResolved>
where TResolved : class
where TResolver : ResolverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(scope)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext)
: base(httpContext)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(scope)
{
AddTypes(lazyTypeList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list
/// of functions producing types, and an optional lifetime scope.
/// </summary>
/// <param name="typeListProducerList">The list of functions producing types.</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(scope)
{
_typeListProducerList.Add(typeListProducerList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of
/// lazy object types, with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <param name="lazyTypeList">The list of lazy object types.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(httpContext)
{
AddTypes(lazyTypeList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of
/// functions producing types, with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <param name="typeListProducerList">The list of functions producing types.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(httpContext)
{
_typeListProducerList.Add(typeListProducerList);
}
#endregion
private readonly List<Lazy<Type>> _lazyTypeList = new List<Lazy<Type>>();
private readonly List<Func<IEnumerable<Type>>> _typeListProducerList = new List<Func<IEnumerable<Type>>>();
private readonly List<Type> _excludedTypesList = new List<Type>();
private List<Type> _resolvedTypes = null;
private readonly ReaderWriterLockSlim _resolvedTypesLock = new ReaderWriterLockSlim();
/// <summary>
/// Gets a value indicating whether the resolver has resolved types to create instances from.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal bool HasResolvedTypes
{
get
{
using (new ReadLock(_resolvedTypesLock))
{
return _resolvedTypes != null;
}
}
}
/// <summary>
/// Gets the list of types to create instances from.
/// </summary>
/// <remarks>When called, will get the types from the lazy list.</remarks>
protected override IEnumerable<Type> InstanceTypes
{
get
{
using (var lck = new UpgradeableReadLock(_resolvedTypesLock))
{
if (_resolvedTypes == null)
{
lck.UpgradeToWriteLock();
_resolvedTypes = new List<Type>();
// get the types by evaluating the lazy & producers
var types = new List<Type>();
types.AddRange(_lazyTypeList.Select(x => x.Value));
types.AddRange(_typeListProducerList.SelectMany(x => x()));
// we need to validate each resolved type now since we could
// not do it before evaluating the lazy & producers
foreach (var type in types.Where(x => !_excludedTypesList.Contains(x)))
{
AddValidAndNoDuplicate(_resolvedTypes, type);
}
}
return _resolvedTypes;
}
}
}
/// <summary>
/// Ensures that type is valid and not a duplicate
/// then appends the type to the end of the list
/// </summary>
/// <param name="list"></param>
/// <param name="type"></param>
private void AddValidAndNoDuplicate(List<Type> list, Type type)
{
EnsureCorrectType(type);
if (list.Contains(type))
{
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", type.FullName));
}
list.Add(type);
}
#region Types collection manipulation
/// <summary>
/// Removes types from the list of types, once it has been lazily evaluated, and before actual objects are instanciated.
/// </summary>
/// <param name="value">The type to remove.</param>
public override void RemoveType(Type value)
{
EnsureSupportsRemove();
_excludedTypesList.Add(value);
}
/// <summary>
/// Lazily adds types from lazy types.
/// </summary>
/// <param name="types">The lazy types, to add.</param>
protected void AddTypes(IEnumerable<Lazy<Type>> types)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
foreach (var t in types)
{
_lazyTypeList.Add(t);
}
}
}
/// <summary>
/// Lazily adds types from a function producing types.
/// </summary>
/// <param name="typeListProducer">The functions producing types, to add.</param>
public void AddTypeListDelegate(Func<IEnumerable<Type>> typeListProducer)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_typeListProducerList.Add(typeListProducer);
}
}
/// <summary>
/// Lazily adds a type from a lazy type.
/// </summary>
/// <param name="value">The lazy type, to add.</param>
public void AddType(Lazy<Type> value)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Add(value);
}
}
/// <summary>
/// Lazily adds a type from an actual type.
/// </summary>
/// <param name="value">The actual type, to add.</param>
/// <remarks>The type is converted to a lazy type.</remarks>
public override void AddType(Type value)
{
AddType(new Lazy<Type>(() => value));
}
/// <summary>
/// Clears all lazy types
/// </summary>
public override void Clear()
{
EnsureSupportsClear();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Clear();
}
}
#endregion
#region Types collection manipulation support
/// <summary>
/// Gets a <c>false</c> value indicating that the resolver does NOT support inserting types.
/// </summary>
protected override bool SupportsInsert
{
get { return false; }
}
#endregion
}
}
| |
//
// ExtAudioFile.cs: ExtAudioFile wrapper class
//
// Authors:
// AKIHIRO Uehara (u-akihiro@reinforce-lab.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2010 Reinforce Lab.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.AudioToolbox;
namespace MonoMac.AudioUnit
{
public enum ExtAudioFileError
{
OK = 0,
CodecUnavailableInputConsumed = -66559,
CodecUnavailableInputNotConsumed = -66560,
InvalidProperty = -66561,
InvalidPropertySize = -66562,
NonPCMClientFormat = -66563,
InvalidChannelMap = -66564,
InvalidOperationOrder = -66565,
InvalidDataFormat = -66566,
MaxPacketSizeUnknown = -66567,
InvalidSeek = -66568,
AsyncWriteTooLarge = -66569,
AsyncWriteBufferOverflow = -66570,
// Shared error codes
NotOpenError = -38,
EndOfFileError = -39,
PositionError = -40,
FileNotFoundError = -43
}
public class ExtAudioFile : IDisposable
{
IntPtr _extAudioFile;
public uint? ClientMaxPacketSize {
get {
uint size = sizeof (uint);
uint value;
if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.ClientMaxPacketSize, ref size, out value) != ExtAudioFileError.OK)
return null;
return value;
}
}
public uint? FileMaxPacketSize {
get {
uint size = sizeof (uint);
uint value;
if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.FileMaxPacketSize, ref size, out value) != ExtAudioFileError.OK)
return null;
return value;
}
}
public IntPtr? AudioFile {
get {
uint size = (uint) Marshal.SizeOf (typeof (IntPtr));
IntPtr value;
if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.AudioFile, ref size, out value) != ExtAudioFileError.OK)
return null;
return value;
}
}
public AudioConverter AudioConverter {
get {
uint size = sizeof (uint);
IntPtr value;
if (ExtAudioFileGetProperty (_extAudioFile, PropertyIDType.AudioConverter, ref size, out value) != ExtAudioFileError.OK)
return null;
return new AudioConverter (value, false);
}
}
public long FileLengthFrames {
get {
long length;
uint size = sizeof (long);
var err = ExtAudioFileGetProperty(_extAudioFile, PropertyIDType.FileLengthFrames, ref size, out length);
if (err != 0)
{
throw new InvalidOperationException(String.Format("Error code:{0}", err));
}
return length;
}
}
public AudioStreamBasicDescription FileDataFormat
{
get
{
AudioStreamBasicDescription dc = new AudioStreamBasicDescription();
uint size = (uint)Marshal.SizeOf(typeof(AudioStreamBasicDescription));
int err = ExtAudioFileGetProperty(_extAudioFile, PropertyIDType.FileDataFormat, ref size, ref dc);
if (err != 0)
{
throw new InvalidOperationException(String.Format("Error code:{0}", err));
}
return dc;
}
}
public AudioStreamBasicDescription ClientDataFormat
{
set
{
int err = ExtAudioFileSetProperty(_extAudioFile, PropertyIDType.ClientDataFormat,
(uint)Marshal.SizeOf(value), ref value);
if (err != 0)
{
throw new InvalidOperationException(String.Format("Error code:{0}", err));
}
}
}
private ExtAudioFile(IntPtr ptr)
{
_extAudioFile = ptr;
}
~ExtAudioFile ()
{
Dispose (false);
}
public static ExtAudioFile OpenUrl (CFUrl url)
{
if (url == null)
throw new ArgumentNullException ("url");
ExtAudioFileError err;
IntPtr ptr;
unsafe {
err = ExtAudioFileOpenUrl(url.Handle, (IntPtr)(&ptr));
}
if (err != 0)
{
throw new ArgumentException(String.Format("Error code:{0}", err));
}
if (ptr == IntPtr.Zero)
{
throw new InvalidOperationException("Can not get object instance");
}
return new ExtAudioFile(ptr);
}
public static ExtAudioFile CreateWithUrl (CFUrl url,
AudioFileType fileType,
AudioStreamBasicDescription inStreamDesc,
//AudioChannelLayout channelLayout,
AudioFileFlags flag)
{
if (url == null)
throw new ArgumentNullException ("url");
int err;
IntPtr ptr = new IntPtr();
unsafe {
err = ExtAudioFileCreateWithUrl(url.Handle, fileType, ref inStreamDesc, IntPtr.Zero, (uint)flag,
(IntPtr)(&ptr));
}
if (err != 0)
{
throw new ArgumentException(String.Format("Error code:{0}", err));
}
if (ptr == IntPtr.Zero)
{
throw new InvalidOperationException("Can not get object instance");
}
return new ExtAudioFile(ptr);
}
public static ExtAudioFileError WrapAudioFileID (IntPtr audioFileID, bool forWriting, out ExtAudioFile outAudioFile)
{
IntPtr ptr;
ExtAudioFileError res;
unsafe {
res = ExtAudioFileWrapAudioFileID (audioFileID, forWriting, (IntPtr)(&ptr));
}
if (res != ExtAudioFileError.OK) {
outAudioFile = null;
return res;
}
outAudioFile = new ExtAudioFile (ptr);
return res;
}
public void Seek(long frameOffset)
{
int err = ExtAudioFileSeek(_extAudioFile, frameOffset);
if (err != 0)
{
throw new ArgumentException(String.Format("Error code:{0}", err));
}
}
public long FileTell()
{
long frame = 0;
int err = ExtAudioFileTell(_extAudioFile, ref frame);
if (err != 0)
{
throw new ArgumentException(String.Format("Error code:{0}", err));
}
return frame;
}
[Obsolete ("Use overload with AudioBuffers")]
public int Read(int numberFrames, AudioBufferList data)
{
if (data == null)
throw new ArgumentNullException ("data");
int err = ExtAudioFileRead(_extAudioFile, ref numberFrames, data);
if (err != 0)
{
throw new ArgumentException(String.Format("Error code:{0}", err));
}
return numberFrames;
}
public uint Read (uint numberFrames, AudioBuffers audioBufferList, out ExtAudioFileError status)
{
if (audioBufferList == null)
throw new ArgumentNullException ("audioBufferList");
status = ExtAudioFileRead (_extAudioFile, ref numberFrames, (IntPtr) audioBufferList);
return numberFrames;
}
[Obsolete ("Use overload with AudioBuffers")]
public void WriteAsync(int numberFrames, AudioBufferList data)
{
int err = ExtAudioFileWriteAsync(_extAudioFile, numberFrames, data);
if (err != 0) {
throw new ArgumentException(String.Format("Error code:{0}", err));
}
}
public ExtAudioFileError WriteAsync (uint numberFrames, AudioBuffers audioBufferList)
{
if (audioBufferList == null)
throw new ArgumentNullException ("audioBufferList");
return ExtAudioFileWriteAsync (_extAudioFile, numberFrames, (IntPtr) audioBufferList);
}
public ExtAudioFileError Write (uint numberFrames, AudioBuffers audioBufferList)
{
if (audioBufferList == null)
throw new ArgumentNullException ("audioBufferList");
return ExtAudioFileWrite (_extAudioFile, numberFrames, (IntPtr) audioBufferList);
}
public ExtAudioFileError SynchronizeAudioConverter ()
{
IntPtr value = IntPtr.Zero;
return ExtAudioFileSetProperty (_extAudioFile, PropertyIDType.ConverterConfig,
Marshal.SizeOf (value), value);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (_extAudioFile != IntPtr.Zero){
ExtAudioFileDispose (_extAudioFile);
_extAudioFile = IntPtr.Zero;
}
}
#region Interop
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileOpenURL")]
static extern ExtAudioFileError ExtAudioFileOpenUrl(IntPtr inUrl, IntPtr outExtAudioFile); // caution
[DllImport (MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileWrapAudioFileID (IntPtr inFileID, bool inForWriting, IntPtr outExtAudioFile);
[Obsolete]
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileRead")]
static extern int ExtAudioFileRead(IntPtr inExtAudioFile, ref int ioNumberFrames, AudioBufferList ioData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileRead (IntPtr inExtAudioFile, ref uint ioNumberFrames, IntPtr ioData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileWrite (IntPtr inExtAudioFile, uint inNumberFrames, IntPtr ioData);
[Obsolete]
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileWriteAsync")]
static extern int ExtAudioFileWriteAsync(IntPtr inExtAudioFile, int inNumberFrames, AudioBufferList ioData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileWriteAsync(IntPtr inExtAudioFile, uint inNumberFrames, IntPtr ioData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileDispose")]
static extern int ExtAudioFileDispose(IntPtr inExtAudioFile);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileSeek")]
static extern int ExtAudioFileSeek(IntPtr inExtAudioFile, long inFrameOffset);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileTell")]
static extern int ExtAudioFileTell(IntPtr inExtAudioFile, ref long outFrameOffset);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileCreateWithURL")]
static extern int ExtAudioFileCreateWithUrl(IntPtr inURL,
[MarshalAs(UnmanagedType.U4)] AudioFileType inFileType,
ref AudioStreamBasicDescription inStreamDesc,
IntPtr inChannelLayout, //AudioChannelLayout inChannelLayout, AudioChannelLayout results in compilation error (error code 134.)
UInt32 flags,
IntPtr outExtAudioFile);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileGetProperty")]
static extern int ExtAudioFileGetProperty(
IntPtr inExtAudioFile,
PropertyIDType inPropertyID,
ref uint ioPropertyDataSize,
IntPtr outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileGetProperty")]
static extern int ExtAudioFileGetProperty(
IntPtr inExtAudioFile,
PropertyIDType inPropertyID,
ref uint ioPropertyDataSize,
ref AudioStreamBasicDescription outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out IntPtr outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out long outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileGetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, ref uint ioPropertyDataSize, out uint outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary)]
static extern ExtAudioFileError ExtAudioFileSetProperty (IntPtr inExtAudioFile, PropertyIDType inPropertyID, int ioPropertyDataSize, IntPtr outPropertyData);
[DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "ExtAudioFileSetProperty")]
static extern int ExtAudioFileSetProperty(
IntPtr inExtAudioFile,
PropertyIDType inPropertyID,
uint ioPropertyDataSize,
ref AudioStreamBasicDescription outPropertyData);
enum PropertyIDType {
FileDataFormat = 0x66666d74, // 'ffmt'
//kExtAudioFileProperty_FileChannelLayout = 'fclo', // AudioChannelLayout
ClientDataFormat = 0x63666d74, //'cfmt', // AudioStreamBasicDescription
//kExtAudioFileProperty_ClientChannelLayout = 'cclo', // AudioChannelLayout
CodecManufacturer = 0x636d616e, // 'cman'
// read-only:
AudioConverter = 0x61636e76, // 'acnv'
AudioFile = 0x6166696c, // 'afil'
FileMaxPacketSize = 0x666d7073, // 'fmps'
ClientMaxPacketSize = 0x636d7073, // 'cmps'
FileLengthFrames = 0x2366726d, // '#frm'
// writable:
ConverterConfig = 0x61636366, // 'accf'
//kExtAudioFileProperty_IOBufferSizeBytes = 'iobs', // UInt32
//kExtAudioFileProperty_IOBuffer = 'iobf', // void *
//kExtAudioFileProperty_PacketTable = 'xpti' // AudioFilePacketTableInfo
};
#endregion
}
}
| |
#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
#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
return LoopReadAsync(cancellationToken);
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<bool> LoopReadAsync(CancellationToken cancellationToken)
{
while (_currentState == State.PostValue)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
}
}
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 '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(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;
}
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
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:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(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(ReadType.Read);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
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];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
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 (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
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;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(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;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
if (task.Status == TaskStatus.RanToCompletion)
{
case TaskStatus.RanToCompletion:
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
return task;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// 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 = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(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;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 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;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
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();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(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 async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
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
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(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 async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
#endif
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
using Spine;
/// <summary>Renders a skeleton.</summary>
[ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class SkeletonRenderer : MonoBehaviour {
public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer);
public SkeletonRendererDelegate OnReset;
public SkeletonDataAsset skeletonDataAsset;
public String initialSkinName;
#region Advanced
public bool calculateNormals, calculateTangents;
public float zSpacing;
public bool renderMeshes = true, immutableTriangles;
public bool frontFacing;
public bool logErrors = false;
// Submesh Separation
[SpineSlot] public string[] submeshSeparators = new string[0];
[HideInInspector] public List<Slot> submeshSeparatorSlots = new List<Slot>();
#endregion
[System.NonSerialized] public bool valid;
[System.NonSerialized] public Skeleton skeleton;
private MeshRenderer meshRenderer;
private MeshFilter meshFilter;
private Mesh mesh1, mesh2;
private bool useMesh1;
private float[] tempVertices = new float[8];
private Vector3[] vertices;
private Color32[] colors;
private Vector2[] uvs;
private Material[] sharedMaterials = new Material[0];
private MeshState meshState = new MeshState();
private readonly ExposedList<Material> submeshMaterials = new ExposedList<Material>();
private readonly ExposedList<Submesh> submeshes = new ExposedList<Submesh>();
private SkeletonUtilitySubmeshRenderer[] submeshRenderers;
#region Runtime Instantiation
/// <summary>Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime.</summary>
/// <typeparam name="T">T should be SkeletonRenderer or any of its derived classes.</typeparam>
public static T AddSpineComponent<T> (GameObject gameObject, SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
var c = gameObject.AddComponent<T>();
if (skeletonDataAsset != null) {
c.skeletonDataAsset = skeletonDataAsset;
c.Reset(); // TODO: Method name will change.
}
return c;
}
public static T NewSpineGameObject<T> (SkeletonDataAsset skeletonDataAsset) where T : SkeletonRenderer {
return SkeletonRenderer.AddSpineComponent<T>(new GameObject("New Spine GameObject"), skeletonDataAsset);
}
#endregion
public virtual void Awake () {
Reset();
}
public virtual void Reset () {
if (meshFilter != null)
meshFilter.sharedMesh = null;
meshRenderer = GetComponent<MeshRenderer>();
if (meshRenderer != null) meshRenderer.sharedMaterial = null;
if (mesh1 != null) {
if (Application.isPlaying)
Destroy(mesh1);
else
DestroyImmediate(mesh1);
}
if (mesh2 != null) {
if (Application.isPlaying)
Destroy(mesh2);
else
DestroyImmediate(mesh2);
}
meshState = new MeshState();
mesh1 = null;
mesh2 = null;
vertices = null;
colors = null;
uvs = null;
sharedMaterials = new Material[0];
submeshMaterials.Clear();
submeshes.Clear();
skeleton = null;
valid = false;
if (!skeletonDataAsset) {
if (logErrors)
Debug.LogError("Missing SkeletonData asset.", this);
return;
}
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);
if (skeletonData == null)
return;
valid = true;
meshFilter = GetComponent<MeshFilter>();
meshRenderer = GetComponent<MeshRenderer>();
mesh1 = newMesh();
mesh2 = newMesh();
vertices = new Vector3[0];
skeleton = new Skeleton(skeletonData);
if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default")
skeleton.SetSkin(initialSkinName);
submeshSeparatorSlots.Clear();
for (int i = 0; i < submeshSeparators.Length; i++) {
submeshSeparatorSlots.Add(skeleton.FindSlot(submeshSeparators[i]));
}
CollectSubmeshRenderers();
LateUpdate();
if (OnReset != null)
OnReset(this);
}
public void CollectSubmeshRenderers () {
submeshRenderers = GetComponentsInChildren<SkeletonUtilitySubmeshRenderer>();
}
public virtual void OnDestroy () {
if (mesh1 != null) {
if (Application.isPlaying)
Destroy(mesh1);
else
DestroyImmediate(mesh1);
}
if (mesh2 != null) {
if (Application.isPlaying)
Destroy(mesh2);
else
DestroyImmediate(mesh2);
}
mesh1 = null;
mesh2 = null;
}
private static Mesh newMesh () {
Mesh mesh = new Mesh();
mesh.name = "Skeleton Mesh";
mesh.hideFlags = HideFlags.HideAndDontSave;
mesh.MarkDynamic();
return mesh;
}
public virtual void LateUpdate () {
if (!valid)
return;
// Exit early if there is nothing to render
if (!meshRenderer.enabled && submeshRenderers.Length == 0)
return;
// Count vertices and submesh triangles.
int vertexCount = 0;
int submeshTriangleCount = 0, submeshFirstVertex = 0, submeshStartSlotIndex = 0;
Material lastMaterial = null;
ExposedList<Slot> drawOrder = skeleton.drawOrder;
var drawOrderItems = drawOrder.Items;
int drawOrderCount = drawOrder.Count;
int submeshSeparatorSlotsCount = submeshSeparatorSlots.Count;
bool renderMeshes = this.renderMeshes;
// Clear last state of attachments and submeshes
MeshState.SingleMeshState workingState = meshState.buffer;
var workingAttachments = workingState.attachments;
workingAttachments.Clear(true);
workingState.UpdateAttachmentCount(drawOrderCount);
var workingAttachmentsItems = workingAttachments.Items; // Make sure to not add to or remove from ExposedList inside the loop below
var workingFlips = workingState.attachmentsFlipState;
var workingFlipsItems = workingState.attachmentsFlipState.Items; // Make sure to not add to or remove from ExposedList inside the loop below
var workingSubmeshArguments = workingState.addSubmeshArguments; // Items array should not be cached. There is dynamic writing to this object.
workingSubmeshArguments.Clear(false);
MeshState.SingleMeshState storedState = useMesh1 ? meshState.stateMesh1 : meshState.stateMesh2;
var storedAttachments = storedState.attachments;
var storedAttachmentsItems = storedAttachments.Items; // Make sure to not add to or remove from ExposedList inside the loop below
var storedFlips = storedState.attachmentsFlipState;
var storedFlipsItems = storedFlips.Items; // Make sure to not add to or remove from ExposedList inside the loop below
bool mustUpdateMeshStructure = storedState.requiresUpdate || // Force update if the mesh was cleared. (prevents flickering due to incorrect state)
drawOrder.Count != storedAttachments.Count || // Number of slots changed (when does this happen?)
immutableTriangles != storedState.immutableTriangles; // Immutable Triangles flag changed.
for (int i = 0; i < drawOrderCount; i++) {
Slot slot = drawOrderItems[i];
Bone bone = slot.bone;
Attachment attachment = slot.attachment;
object rendererObject; // An AtlasRegion in plain Spine-Unity. Spine-TK2D hooks into TK2D's system. eventual source of Material object.
int attachmentVertexCount, attachmentTriangleCount;
// Handle flipping for normals (for lighting).
bool worldScaleIsSameSigns = ((bone.worldScaleY >= 0f) == (bone.worldScaleX >= 0f));
bool flip = frontFacing && ((bone.worldFlipX != bone.worldFlipY) == worldScaleIsSameSigns); // TODO: bone flipX and flipY will be removed in Spine 3.0
workingFlipsItems[i] = flip;
workingAttachmentsItems[i] = attachment;
mustUpdateMeshStructure = mustUpdateMeshStructure || // Always prefer short circuited or. || and not |=.
(attachment != storedAttachmentsItems[i]) || // Attachment order changed. // This relies on the drawOrder.Count != storedAttachments.Count check above as a bounds check.
(flip != storedFlipsItems[i]); // Flip states changed.
var regionAttachment = attachment as RegionAttachment;
if (regionAttachment != null) {
rendererObject = regionAttachment.RendererObject;
attachmentVertexCount = 4;
attachmentTriangleCount = 6;
} else {
if (!renderMeshes)
continue;
var meshAttachment = attachment as MeshAttachment;
if (meshAttachment != null) {
rendererObject = meshAttachment.RendererObject;
attachmentVertexCount = meshAttachment.vertices.Length >> 1;
attachmentTriangleCount = meshAttachment.triangles.Length;
} else {
var skinnedMeshAttachment = attachment as SkinnedMeshAttachment;
if (skinnedMeshAttachment != null) {
rendererObject = skinnedMeshAttachment.RendererObject;
attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1;
attachmentTriangleCount = skinnedMeshAttachment.triangles.Length;
} else
continue;
}
}
#if !SPINE_TK2D
Material material = (Material)((AtlasRegion)rendererObject).page.rendererObject;
#else
Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
#endif
// Populate submesh when material changes. (or when forced to separate by a submeshSeparator)
if ((lastMaterial != null && lastMaterial.GetInstanceID() != material.GetInstanceID()) ||
(submeshSeparatorSlotsCount > 0 && submeshSeparatorSlots.Contains(slot))) {
workingSubmeshArguments.Add(
new MeshState.AddSubmeshArguments {
material = lastMaterial,
startSlot = submeshStartSlotIndex,
endSlot = i,
triangleCount = submeshTriangleCount,
firstVertex = submeshFirstVertex,
isLastSubmesh = false
}
);
submeshTriangleCount = 0;
submeshFirstVertex = vertexCount;
submeshStartSlotIndex = i;
}
lastMaterial = material;
submeshTriangleCount += attachmentTriangleCount;
vertexCount += attachmentVertexCount;
}
workingSubmeshArguments.Add(
new MeshState.AddSubmeshArguments {
material = lastMaterial,
startSlot = submeshStartSlotIndex,
endSlot = drawOrderCount,
triangleCount = submeshTriangleCount,
firstVertex = submeshFirstVertex,
isLastSubmesh = true
}
);
mustUpdateMeshStructure = mustUpdateMeshStructure ||
this.sharedMaterials.Length != workingSubmeshArguments.Count || // Material array changed in size
CheckIfMustUpdateMeshStructure(workingSubmeshArguments); // Submesh Argument Array changed.
// CheckIfMustUpdateMaterialArray (workingMaterials, sharedMaterials)
if (!mustUpdateMeshStructure) {
// Narrow phase material array check.
var workingMaterials = workingSubmeshArguments.Items;
for (int i = 0, n = sharedMaterials.Length; i < n; i++) {
if (this.sharedMaterials[i] != workingMaterials[i].material) { // Bounds check is implied above.
mustUpdateMeshStructure = true;
break;
}
}
}
// NOT ELSE
if (mustUpdateMeshStructure) {
this.submeshMaterials.Clear();
var workingSubmeshArgumentsItems = workingSubmeshArguments.Items;
for (int i = 0, n = workingSubmeshArguments.Count; i < n; i++) {
AddSubmesh(workingSubmeshArgumentsItems[i], workingFlips);
}
// Set materials.
if (submeshMaterials.Count == sharedMaterials.Length)
submeshMaterials.CopyTo(sharedMaterials);
else
sharedMaterials = submeshMaterials.ToArray();
meshRenderer.sharedMaterials = sharedMaterials;
}
// Ensure mesh data is the right size.
Vector3[] vertices = this.vertices;
bool newTriangles = vertexCount > vertices.Length;
if (newTriangles) {
// Not enough vertices, increase size.
this.vertices = vertices = new Vector3[vertexCount];
this.colors = new Color32[vertexCount];
this.uvs = new Vector2[vertexCount];
mesh1.Clear();
mesh2.Clear();
meshState.stateMesh1.requiresUpdate = true;
meshState.stateMesh2.requiresUpdate = true;
} else {
// Too many vertices, zero the extra.
Vector3 zero = Vector3.zero;
for (int i = vertexCount, n = meshState.vertexCount; i < n; i++)
vertices[i] = zero;
}
meshState.vertexCount = vertexCount;
// Setup mesh.
float zSpacing = this.zSpacing;
float[] tempVertices = this.tempVertices;
Vector2[] uvs = this.uvs;
Color32[] colors = this.colors;
int vertexIndex = 0;
Color32 color;
float a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b;
Vector3 meshBoundsMin;
Vector3 meshBoundsMax;
if (vertexCount == 0) {
meshBoundsMin = new Vector3(0, 0, 0);
meshBoundsMax = new Vector3(0, 0, 0);
} else {
meshBoundsMin.x = int.MaxValue;
meshBoundsMin.y = int.MaxValue;
meshBoundsMax.x = int.MinValue;
meshBoundsMax.y = int.MinValue;
if (zSpacing > 0f) {
meshBoundsMin.z = 0f;
meshBoundsMax.z = zSpacing * (drawOrderCount - 1);
} else {
meshBoundsMin.z = zSpacing * (drawOrderCount - 1);
meshBoundsMax.z = 0f;
}
int i = 0;
do {
Slot slot = drawOrderItems[i];
Attachment attachment = slot.attachment;
RegionAttachment regionAttachment = attachment as RegionAttachment;
if (regionAttachment != null) {
regionAttachment.ComputeWorldVertices(slot.bone, tempVertices);
float z = i * zSpacing;
float x1 = tempVertices[RegionAttachment.X1], y1 = tempVertices[RegionAttachment.Y1];
float x2 = tempVertices[RegionAttachment.X2], y2 = tempVertices[RegionAttachment.Y2];
float x3 = tempVertices[RegionAttachment.X3], y3 = tempVertices[RegionAttachment.Y3];
float x4 = tempVertices[RegionAttachment.X4], y4 = tempVertices[RegionAttachment.Y4];
vertices[vertexIndex].x = x1;
vertices[vertexIndex].y = y1;
vertices[vertexIndex].z = z;
vertices[vertexIndex + 1].x = x4;
vertices[vertexIndex + 1].y = y4;
vertices[vertexIndex + 1].z = z;
vertices[vertexIndex + 2].x = x2;
vertices[vertexIndex + 2].y = y2;
vertices[vertexIndex + 2].z = z;
vertices[vertexIndex + 3].x = x3;
vertices[vertexIndex + 3].y = y3;
vertices[vertexIndex + 3].z = z;
color.a = (byte)(a * slot.a * regionAttachment.a);
color.r = (byte)(r * slot.r * regionAttachment.r * color.a);
color.g = (byte)(g * slot.g * regionAttachment.g * color.a);
color.b = (byte)(b * slot.b * regionAttachment.b * color.a);
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
colors[vertexIndex] = color;
colors[vertexIndex + 1] = color;
colors[vertexIndex + 2] = color;
colors[vertexIndex + 3] = color;
float[] regionUVs = regionAttachment.uvs;
uvs[vertexIndex].x = regionUVs[RegionAttachment.X1];
uvs[vertexIndex].y = regionUVs[RegionAttachment.Y1];
uvs[vertexIndex + 1].x = regionUVs[RegionAttachment.X4];
uvs[vertexIndex + 1].y = regionUVs[RegionAttachment.Y4];
uvs[vertexIndex + 2].x = regionUVs[RegionAttachment.X2];
uvs[vertexIndex + 2].y = regionUVs[RegionAttachment.Y2];
uvs[vertexIndex + 3].x = regionUVs[RegionAttachment.X3];
uvs[vertexIndex + 3].y = regionUVs[RegionAttachment.Y3];
// Calculate min/max X
if (x1 < meshBoundsMin.x)
meshBoundsMin.x = x1;
else if (x1 > meshBoundsMax.x)
meshBoundsMax.x = x1;
if (x2 < meshBoundsMin.x)
meshBoundsMin.x = x2;
else if (x2 > meshBoundsMax.x)
meshBoundsMax.x = x2;
if (x3 < meshBoundsMin.x)
meshBoundsMin.x = x3;
else if (x3 > meshBoundsMax.x)
meshBoundsMax.x = x3;
if (x4 < meshBoundsMin.x)
meshBoundsMin.x = x4;
else if (x4 > meshBoundsMax.x)
meshBoundsMax.x = x4;
// Calculate min/max Y
if (y1 < meshBoundsMin.y)
meshBoundsMin.y = y1;
else if (y1 > meshBoundsMax.y)
meshBoundsMax.y = y1;
if (y2 < meshBoundsMin.y)
meshBoundsMin.y = y2;
else if (y2 > meshBoundsMax.y)
meshBoundsMax.y = y2;
if (y3 < meshBoundsMin.y)
meshBoundsMin.y = y3;
else if (y3 > meshBoundsMax.y)
meshBoundsMax.y = y3;
if (y4 < meshBoundsMin.y)
meshBoundsMin.y = y4;
else if (y4 > meshBoundsMax.y)
meshBoundsMax.y = y4;
vertexIndex += 4;
} else {
if (!renderMeshes)
continue;
MeshAttachment meshAttachment = attachment as MeshAttachment;
if (meshAttachment != null) {
int meshVertexCount = meshAttachment.vertices.Length;
if (tempVertices.Length < meshVertexCount)
this.tempVertices = tempVertices = new float[meshVertexCount];
meshAttachment.ComputeWorldVertices(slot, tempVertices);
color.a = (byte)(a * slot.a * meshAttachment.a);
color.r = (byte)(r * slot.r * meshAttachment.r * color.a);
color.g = (byte)(g * slot.g * meshAttachment.g * color.a);
color.b = (byte)(b * slot.b * meshAttachment.b * color.a);
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
float[] meshUVs = meshAttachment.uvs;
float z = i * zSpacing;
for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) {
float x = tempVertices[ii], y = tempVertices[ii + 1];
vertices[vertexIndex].x = x;
vertices[vertexIndex].y = y;
vertices[vertexIndex].z = z;
colors[vertexIndex] = color;
uvs[vertexIndex].x = meshUVs[ii];
uvs[vertexIndex].y = meshUVs[ii + 1];
if (x < meshBoundsMin.x)
meshBoundsMin.x = x;
else if (x > meshBoundsMax.x)
meshBoundsMax.x = x;
if (y < meshBoundsMin.y)
meshBoundsMin.y = y;
else if (y > meshBoundsMax.y)
meshBoundsMax.y = y;
}
} else {
SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment;
if (skinnedMeshAttachment != null) {
int meshVertexCount = skinnedMeshAttachment.uvs.Length;
if (tempVertices.Length < meshVertexCount)
this.tempVertices = tempVertices = new float[meshVertexCount];
skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices);
color.a = (byte)(a * slot.a * skinnedMeshAttachment.a);
color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a);
color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a);
color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a);
if (slot.data.blendMode == BlendMode.additive) color.a = 0;
float[] meshUVs = skinnedMeshAttachment.uvs;
float z = i * zSpacing;
for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) {
float x = tempVertices[ii], y = tempVertices[ii + 1];
vertices[vertexIndex].x = x;
vertices[vertexIndex].y = y;
vertices[vertexIndex].z = z;
colors[vertexIndex] = color;
uvs[vertexIndex].x = meshUVs[ii];
uvs[vertexIndex].y = meshUVs[ii + 1];
if (x < meshBoundsMin.x)
meshBoundsMin.x = x;
else if (x > meshBoundsMax.x)
meshBoundsMax.x = x;
if (y < meshBoundsMin.y)
meshBoundsMin.y = y;
else if (y > meshBoundsMax.y)
meshBoundsMax.y = y;
}
}
}
}
} while (++i < drawOrderCount);
}
// Double buffer mesh.
Mesh mesh = useMesh1 ? mesh1 : mesh2;
meshFilter.sharedMesh = mesh;
mesh.vertices = vertices;
mesh.colors32 = colors;
mesh.uv = uvs;
if (mustUpdateMeshStructure) {
int submeshCount = submeshMaterials.Count;
mesh.subMeshCount = submeshCount;
for (int i = 0; i < submeshCount; ++i)
mesh.SetTriangles(submeshes.Items[i].triangles, i);
// Done updating mesh.
storedState.requiresUpdate = false;
}
Vector3 meshBoundsExtents = meshBoundsMax - meshBoundsMin;
Vector3 meshBoundsCenter = meshBoundsMin + meshBoundsExtents * 0.5f;
mesh.bounds = new Bounds(meshBoundsCenter, meshBoundsExtents);
if (newTriangles && calculateNormals) {
Vector3[] normals = new Vector3[vertexCount];
Vector3 normal = new Vector3(0, 0, -1);
for (int i = 0; i < vertexCount; i++)
normals[i] = normal;
(useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices.
mesh1.normals = normals;
mesh2.normals = normals;
if (calculateTangents) {
Vector4[] tangents = new Vector4[vertexCount];
Vector3 tangent = new Vector3(0, 0, 1);
for (int i = 0; i < vertexCount; i++)
tangents[i] = tangent;
mesh1.tangents = tangents;
mesh2.tangents = tangents;
}
}
// Update previous state
storedState.immutableTriangles = immutableTriangles;
storedAttachments.Clear(true);
storedAttachments.GrowIfNeeded(workingAttachments.Capacity);
storedAttachments.Count = workingAttachments.Count;
workingAttachments.CopyTo(storedAttachments.Items);
storedFlips.GrowIfNeeded(workingFlips.Capacity);
storedFlips.Count = workingFlips.Count;
workingFlips.CopyTo(storedFlips.Items);
storedState.addSubmeshArguments.GrowIfNeeded(workingSubmeshArguments.Capacity);
storedState.addSubmeshArguments.Count = workingSubmeshArguments.Count;
workingSubmeshArguments.CopyTo(storedState.addSubmeshArguments.Items);
// Submesh Renderers
if (submeshRenderers.Length > 0) {
for (int i = 0; i < submeshRenderers.Length; i++) {
SkeletonUtilitySubmeshRenderer submeshRenderer = submeshRenderers[i];
if (submeshRenderer.submeshIndex < sharedMaterials.Length) {
submeshRenderer.SetMesh(meshRenderer, useMesh1 ? mesh1 : mesh2, sharedMaterials[submeshRenderer.submeshIndex]);
} else {
submeshRenderer.GetComponent<Renderer>().enabled = false;
}
}
}
useMesh1 = !useMesh1;
}
private bool CheckIfMustUpdateMeshStructure (ExposedList<MeshState.AddSubmeshArguments> workingAddSubmeshArguments) {
#if UNITY_EDITOR
if (!Application.isPlaying)
return true;
#endif
// Check if any mesh settings were changed
MeshState.SingleMeshState currentMeshState = useMesh1 ? meshState.stateMesh1 : meshState.stateMesh2;
// Check if submesh structures has changed
ExposedList<MeshState.AddSubmeshArguments> addSubmeshArgumentsCurrentMesh = currentMeshState.addSubmeshArguments;
int submeshCount = workingAddSubmeshArguments.Count;
if (addSubmeshArgumentsCurrentMesh.Count != submeshCount)
return true;
for (int i = 0; i < submeshCount; i++) {
if (!addSubmeshArgumentsCurrentMesh.Items[i].Equals(ref workingAddSubmeshArguments.Items[i]))
return true;
}
return false;
}
private void AddSubmesh (MeshState.AddSubmeshArguments submeshArguments, ExposedList<bool> flipStates) { //submeshArguments is a struct, so it's ok.
int submeshIndex = submeshMaterials.Count;
submeshMaterials.Add(submeshArguments.material);
if (submeshes.Count <= submeshIndex)
submeshes.Add(new Submesh());
else if (immutableTriangles)
return;
Submesh currentSubmesh = submeshes.Items[submeshIndex];
int[] triangles = currentSubmesh.triangles;
int triangleCount = submeshArguments.triangleCount;
int firstVertex = submeshArguments.firstVertex;
int trianglesCapacity = triangles.Length;
if (submeshArguments.isLastSubmesh && trianglesCapacity > triangleCount) {
// Last submesh may have more triangles than required, so zero triangles to the end.
for (int i = triangleCount; i < trianglesCapacity; i++) {
triangles[i] = 0;
}
currentSubmesh.triangleCount = triangleCount;
} else if (trianglesCapacity != triangleCount) {
// Reallocate triangles when not the exact size needed.
currentSubmesh.triangles = triangles = new int[triangleCount];
currentSubmesh.triangleCount = 0;
}
if (!this.renderMeshes && !this.frontFacing) {
// Use stored triangles if possible.
if (currentSubmesh.firstVertex != firstVertex || currentSubmesh.triangleCount < triangleCount) { //|| currentSubmesh.triangleCount == 0
currentSubmesh.triangleCount = triangleCount;
currentSubmesh.firstVertex = firstVertex;
for (int i = 0; i < triangleCount; i += 6, firstVertex += 4) {
triangles[i] = firstVertex;
triangles[i + 1] = firstVertex + 2;
triangles[i + 2] = firstVertex + 1;
triangles[i + 3] = firstVertex + 2;
triangles[i + 4] = firstVertex + 3;
triangles[i + 5] = firstVertex + 1;
}
}
return;
}
// Iterate through all slots and store their triangles.
var drawOrderItems = skeleton.DrawOrder.Items; // Make sure to not modify ExposedList inside the loop below
var flipStatesItems = flipStates.Items; // Make sure to not modify ExposedList inside the loop below
int triangleIndex = 0; // Modified by loop
for (int i = submeshArguments.startSlot, n = submeshArguments.endSlot; i < n; i++) {
Attachment attachment = drawOrderItems[i].attachment;
bool flip = flipStatesItems[i];
// Add RegionAttachment triangles
if (attachment is RegionAttachment) {
if (!flip) {
triangles[triangleIndex] = firstVertex;
triangles[triangleIndex + 1] = firstVertex + 2;
triangles[triangleIndex + 2] = firstVertex + 1;
triangles[triangleIndex + 3] = firstVertex + 2;
triangles[triangleIndex + 4] = firstVertex + 3;
triangles[triangleIndex + 5] = firstVertex + 1;
} else {
triangles[triangleIndex] = firstVertex + 1;
triangles[triangleIndex + 1] = firstVertex + 2;
triangles[triangleIndex + 2] = firstVertex;
triangles[triangleIndex + 3] = firstVertex + 1;
triangles[triangleIndex + 4] = firstVertex + 3;
triangles[triangleIndex + 5] = firstVertex + 2;
}
triangleIndex += 6;
firstVertex += 4;
continue;
}
// Add (Skinned)MeshAttachment triangles
int[] attachmentTriangles;
int attachmentVertexCount;
var meshAttachment = attachment as MeshAttachment;
if (meshAttachment != null) {
attachmentVertexCount = meshAttachment.vertices.Length >> 1; // length/2
attachmentTriangles = meshAttachment.triangles;
} else {
var skinnedMeshAttachment = attachment as SkinnedMeshAttachment;
if (skinnedMeshAttachment != null) {
attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1; // length/2
attachmentTriangles = skinnedMeshAttachment.triangles;
} else
continue;
}
if (flip) {
for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii += 3, triangleIndex += 3) {
triangles[triangleIndex + 2] = firstVertex + attachmentTriangles[ii];
triangles[triangleIndex + 1] = firstVertex + attachmentTriangles[ii + 1];
triangles[triangleIndex] = firstVertex + attachmentTriangles[ii + 2];
}
} else {
for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) {
triangles[triangleIndex] = firstVertex + attachmentTriangles[ii];
}
}
firstVertex += attachmentVertexCount;
}
}
#if UNITY_EDITOR
void OnDrawGizmos () {
// Make selection easier by drawing a clear gizmo over the skeleton.
meshFilter = GetComponent<MeshFilter>();
if (meshFilter == null) return;
Mesh mesh = meshFilter.sharedMesh;
if (mesh == null) return;
Bounds meshBounds = mesh.bounds;
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube(meshBounds.center, meshBounds.size);
}
#endif
private class MeshState {
public int vertexCount;
public readonly SingleMeshState buffer = new SingleMeshState();
public readonly SingleMeshState stateMesh1 = new SingleMeshState();
public readonly SingleMeshState stateMesh2 = new SingleMeshState();
public class SingleMeshState {
public bool immutableTriangles;
public bool requiresUpdate;
public readonly ExposedList<Attachment> attachments = new ExposedList<Attachment>();
public readonly ExposedList<bool> attachmentsFlipState = new ExposedList<bool>();
public readonly ExposedList<AddSubmeshArguments> addSubmeshArguments = new ExposedList<AddSubmeshArguments>();
public void UpdateAttachmentCount (int attachmentCount) {
attachmentsFlipState.GrowIfNeeded(attachmentCount);
attachmentsFlipState.Count = attachmentCount;
attachments.GrowIfNeeded(attachmentCount);
attachments.Count = attachmentCount;
}
}
public struct AddSubmeshArguments {
public Material material;
public int startSlot;
public int endSlot;
public int triangleCount;
public int firstVertex;
public bool isLastSubmesh;
public bool Equals (ref AddSubmeshArguments other) {
return
//!ReferenceEquals(material, null) &&
//!ReferenceEquals(other.material, null) &&
//material.GetInstanceID() == other.material.GetInstanceID() &&
startSlot == other.startSlot &&
endSlot == other.endSlot &&
triangleCount == other.triangleCount &&
firstVertex == other.firstVertex;
}
}
}
}
class Submesh {
public int[] triangles = new int[0];
public int triangleCount;
public int firstVertex = -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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.Awaited_task_returns),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.no_value));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions_colon}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol)
{
await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol)
{
await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol)
{
AddDescriptionForMethod((IMethodSymbol)symbol);
}
else if (symbol is ILabelSymbol)
{
AddDescriptionForLabel((ILabelSymbol)symbol);
}
else if (symbol is INamedTypeSymbol)
{
await AddDescriptionForNamedTypeAsync((INamedTypeSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is INamespaceSymbol)
{
AddDescriptionForNamespace((INamespaceSymbol)symbol);
}
else if (symbol is IParameterSymbol)
{
await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol)
{
AddDescriptionForProperty((IPropertySymbol)symbol);
}
else if (symbol is IRangeVariableSymbol)
{
AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol);
}
else if (symbol is ITypeParameterSymbol)
{
AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol);
}
else if (symbol is IAliasSymbol)
{
await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToTaggedText());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
private async Task AddDescriptionForNamedTypeAsync(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = await _semanticModel.SyntaxTree.GetTouchingTokenAsync(_position, this.CancellationToken).ConfigureAwait(false);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.constant)
: Description(FeaturesResources.field),
parts);
}
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutableAndFree();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.local_constant)
: Description(FeaturesResources.local_variable),
parts);
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutableAndFree();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.range_variable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
if (symbol.IsOptional)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected void AddDescriptionForProperty(IPropertySymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.in_),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.is_));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
IList<SymbolDisplayPart> existingParts;
if (!_groupMap.TryGetValue(group, out existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
namespace Signum.Entities.DynamicQuery
{
[Serializable]
public abstract class BaseQueryRequest
{
public object QueryName { get; set; }
public List<Filter> Filters { get; set; }
public string QueryUrl { get; set; }
public override string ToString()
{
return "{0} {1}".FormatWith(GetType().Name, QueryName);
}
}
[Serializable]
public class QueryRequest : BaseQueryRequest
{
public bool GroupResults { get; set; }
public List<Column> Columns { get; set; }
public List<Order> Orders { get; set; }
public Pagination Pagination { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications()
{
HashSet<QueryToken> allTokens = new HashSet<QueryToken>(this.AllTokens());
return CollectionElementToken.GetElements(allTokens);
}
public List<QueryToken> AllTokens()
{
var allTokens = Columns.Select(a => a.Token).ToList();
if (Filters != null)
allTokens.AddRange(Filters.SelectMany(a => a.GetFilterConditions()).Select(a => a.Token));
if (Orders != null)
allTokens.AddRange(Orders.Select(a => a.Token));
return allTokens;
}
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum PaginationMode
{
All,
Firsts,
Paginate
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum SystemTimeMode
{
AsOf,
Between,
ContainedIn,
All
}
[DescriptionOptions(DescriptionOptions.Members)]
public enum SystemTimeProperty
{
SystemValidFrom,
SystemValidTo,
}
[Serializable]
public abstract class Pagination
{
public abstract PaginationMode GetMode();
public abstract int? GetElementsPerPage();
public abstract int? MaxElementIndex { get; }
[Serializable]
public class All : Pagination
{
public override int? MaxElementIndex
{
get { return null; }
}
public override PaginationMode GetMode()
{
return PaginationMode.All;
}
public override int? GetElementsPerPage()
{
return null;
}
}
[Serializable]
public class Firsts : Pagination
{
public static int DefaultTopElements = 20;
public Firsts(int topElements)
{
this.TopElements = topElements;
}
public int TopElements { get; private set; }
public override int? MaxElementIndex
{
get { return TopElements; }
}
public override PaginationMode GetMode()
{
return PaginationMode.Firsts;
}
public override int? GetElementsPerPage()
{
return TopElements;
}
}
[Serializable]
public class Paginate : Pagination
{
public static int DefaultElementsPerPage = 20;
public Paginate(int elementsPerPage, int currentPage = 1)
{
if (elementsPerPage <= 0)
throw new InvalidOperationException("elementsPerPage should be greater than zero");
if (currentPage <= 0)
throw new InvalidOperationException("currentPage should be greater than zero");
this.ElementsPerPage = elementsPerPage;
this.CurrentPage = currentPage;
}
public int ElementsPerPage { get; private set; }
public int CurrentPage { get; private set; }
public int StartElementIndex()
{
return (ElementsPerPage * (CurrentPage - 1)) + 1;
}
public int EndElementIndex(int rows)
{
return StartElementIndex() + rows - 1;
}
public int TotalPages(int totalElements)
{
return (totalElements + ElementsPerPage - 1) / ElementsPerPage; //Round up
}
public override int? MaxElementIndex
{
get { return (ElementsPerPage * (CurrentPage + 1)) - 1; }
}
public override PaginationMode GetMode()
{
return PaginationMode.Paginate;
}
public override int? GetElementsPerPage()
{
return ElementsPerPage;
}
public Paginate WithCurrentPage(int newPage)
{
return new Paginate(this.ElementsPerPage, newPage);
}
}
}
[Serializable]
public class QueryValueRequest : BaseQueryRequest
{
public QueryToken? ValueToken { get; set; }
public bool MultipleValues { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications
{
get
{
return CollectionElementToken.GetElements(Filters
.SelectMany(a => a.GetFilterConditions())
.Select(fc => fc.Token)
.PreAnd(ValueToken)
.NotNull()
.ToHashSet());
}
}
}
[Serializable]
public class UniqueEntityRequest : BaseQueryRequest
{
List<Order> orders;
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
UniqueType uniqueType;
public UniqueType UniqueType
{
get { return uniqueType; }
set { uniqueType = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters
.SelectMany(a => a.GetFilterConditions())
.Select(a => a.Token)
.Concat(Orders.Select(a => a.Token))
.ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
}
[Serializable]
public class QueryEntitiesRequest: BaseQueryRequest
{
List<Order> orders = new List<Order>();
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters.SelectMany(a=>a.GetFilterConditions()).Select(a => a.Token)
.Concat(Orders.Select(a => a.Token)).ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
public int? Count { get; set; }
public override string ToString() => QueryName.ToString()!;
}
[Serializable]
public class DQueryableRequest : BaseQueryRequest
{
List<Order> orders = new List<Order>();
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
List<Column> columns = new List<Column>();
public List<Column> Columns
{
get { return columns; }
set { columns = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
HashSet<QueryToken> allTokens =
Filters.SelectMany(a => a.GetFilterConditions()).Select(a => a.Token)
.Concat(Columns.Select(a => a.Token))
.Concat(Orders.Select(a => a.Token)).ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
public int? Count { get; set; }
public override string ToString() => QueryName.ToString()!;
}
}
| |
using UnityEngine;
using System;
using System.Runtime.InteropServices;
namespace FourthSky {
namespace Android {
public class ServiceConnection : AndroidWrapper {
// Delegates for service connection
public delegate void OnServiceConnectedDelegate(AndroidJavaObject componentName, AndroidJavaObject binder);
public delegate void OnServiceDisconnectedDelegate(AndroidJavaObject componentName);
public event OnServiceConnectedDelegate OnServiceConnected;
public event OnServiceDisconnectedDelegate OnServiceDisconnected;
#region internal delegate
// Delegates for service connection
private delegate void OnServiceConnectedInternal(IntPtr componentNamePtr, IntPtr binderPtr);
private delegate void OnServiceDisconnectedInternal(IntPtr componentNamePtr);
private OnServiceConnectedInternal onServiceConnectedInternal;
private GCHandle onServiceConnectedHandle;
private IntPtr onServiceConnectedPtr;
void OnServiceConnectedInternalImpl(IntPtr componentNamePtr, IntPtr binderPtr) {
if (OnServiceConnected != null) {
if (OnServiceConnected != null) {
AndroidJavaObject componentName = AndroidSystem.ConstructJavaObjectFromPtr (componentNamePtr);
AndroidJavaObject binder = AndroidSystem.ConstructJavaObjectFromPtr (binderPtr);
OnServiceConnected(componentName, binder);
}
}
}
private OnServiceDisconnectedInternal onServiceDisconnectedInternal;
private GCHandle onServiceDisconnectedHandle;
private IntPtr onServiceDisconnectedPtr;
void OnServiceDisconnectedInternalImpl(IntPtr componentNamePtr) {
if (OnServiceDisconnected != null) {
if (OnServiceDisconnected != null) {
AndroidJavaObject componentName = AndroidSystem.ConstructJavaObjectFromPtr (componentNamePtr);
OnServiceDisconnected(componentName);
}
}
}
#endregion
// Use this for initialization
public ServiceConnection() : base() {
}
~ServiceConnection() {
Dispose (false);
}
/// <summary>
/// Creates the service connection.
/// </summary>
/// <returns>
/// The service connection.
/// </returns>
/// <param name='onConnectedClbk'>
/// On connected clbk.
/// </param>
/// <param name='onDisconnectedClbk'>
/// On disconnected clbk.
/// </param>
/// <exception cref='System.ArgumentNullException'>
/// Is thrown when the argument null exception.
/// </exception>
public bool Bind(AndroidJavaClass serviceClass, int flags = /*BIND_AUTO_CREATED*/1) {
bool retValue = false;
#if UNITY_ANDROID
// Create java instance of broadcast receiver
if (mJavaObject == null) {
onServiceConnectedInternal = new OnServiceConnectedInternal(OnServiceConnectedInternalImpl);
onServiceConnectedHandle = GCHandle.Alloc(onServiceConnectedInternal);
onServiceConnectedPtr = Marshal.GetFunctionPointerForDelegate(onServiceConnectedInternal);
onServiceDisconnectedInternal = new OnServiceDisconnectedInternal(OnServiceDisconnectedInternalImpl);
onServiceDisconnectedHandle = GCHandle.Alloc(onServiceDisconnectedInternal);
onServiceDisconnectedPtr = Marshal.GetFunctionPointerForDelegate(onServiceDisconnectedInternal);
IntPtr connPtr = CreateJavaServiceConnection(onServiceConnectedPtr, onServiceDisconnectedPtr);
if (IntPtr.Zero != connPtr) {
mJavaObject = AndroidSystem.ConstructJavaObjectFromPtr(connPtr);
}
}
// Get application context
using (AndroidJavaObject context = AndroidSystem.UnityContext) {
using(AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", context, serviceClass)) {
// Now, bind to service
retValue = context.Call<bool>("bindService", intent, mJavaObject, flags);
}
}
#endif
return retValue;
}
/// <summary>
/// Binds to the Android service.
/// </summary>
/// <returns>
/// The service.
/// </returns>
/// <param name='intent'>
/// If set to <c>true</c> intent.
/// </param>
/// <param name='serviceConnection'>
/// If set to <c>true</c> service connection.
/// </param>
/// <param name='flags'>
/// If set to <c>true</c> flags.
/// </param>
/// <exception cref='System.ArgumentNullException'>
/// Is thrown when the argument null exception.
/// </exception>
public bool Bind(string action, int flags = /*Context.BIND_AUTO_CREATE*/1) {
if (action == null || "" == action) {
throw new System.ArgumentNullException("Intent action cannot be null");
}
bool retValue = false;
#if UNITY_ANDROID
// Create java instance of broadcast receiver
if (mJavaObject == null) {
onServiceConnectedInternal = new OnServiceConnectedInternal(OnServiceConnectedInternalImpl);
onServiceConnectedHandle = GCHandle.Alloc(onServiceConnectedInternal);
onServiceConnectedPtr = Marshal.GetFunctionPointerForDelegate(onServiceConnectedInternal);
onServiceDisconnectedInternal = new OnServiceDisconnectedInternal(OnServiceDisconnectedInternalImpl);
onServiceDisconnectedHandle = GCHandle.Alloc(onServiceDisconnectedInternal);
onServiceDisconnectedPtr = Marshal.GetFunctionPointerForDelegate(onServiceDisconnectedInternal);
IntPtr connPtr = CreateJavaServiceConnection(onServiceConnectedPtr, onServiceDisconnectedPtr);
if (IntPtr.Zero != connPtr) {
mJavaObject = AndroidSystem.ConstructJavaObjectFromPtr(connPtr);
}
}
// bind to the service
using (AndroidJavaObject activityInstance = AndroidSystem.UnityActivity) {
using (AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", action)) {
retValue = activityInstance.Call<bool>("bindService", intent, mJavaObject, flags);
}
}
#endif
return retValue;
}
/// <summary>
/// Unbinds from the Android service.
/// </summary>
/// <param name='serviceConnection'>
/// Service connection.
/// </param>
/// <exception cref='System.ArgumentNullException'>
/// Is thrown when the argument null exception.
/// </exception>
public void Unbind() {
#if UNITY_ANDROID
if (mJavaObject == null &&!Application.isEditor) {
throw new System.ArgumentNullException("Service connection cannot be null");
}
using (AndroidJavaObject activityInstance = AndroidSystem.UnityActivity) {
activityInstance.Call("unbindService", mJavaObject);
}
onServiceConnectedHandle.Free();
onServiceDisconnectedHandle.Free();
onServiceConnectedInternal = null;
onServiceDisconnectedInternal = null;
#endif
}
protected override void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
Unbind();
}
}
base.Dispose(disposing);
}
#if UNITY_ANDROID
/// <summary>
/// Native function used to create Android service connection
/// </summary>
/// <returns>
/// Object pointer to Android service connection.
/// </returns>
/// <param name='onConnectedClbk'>
/// On connected clbk.
/// </param>
/// <param name='onDisconnectedClbk'>
/// On disconnected clbk.
/// </param>
[DllImport("unityandroidsystem")]
private static extern IntPtr CreateJavaServiceConnection(IntPtr onConnectedClbk,
IntPtr onDisconnectedClbk);
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
** Class: AppDomainSetup
**
** Purpose: Defines the settings that the loader uses to find assemblies in an
** AppDomain
**
** Date: Dec 22, 2000
**
=============================================================================*/
namespace System {
using System;
#if FEATURE_CLICKONCE
using System.Deployment.Internal.Isolation;
using System.Deployment.Internal.Isolation.Manifest;
using System.Runtime.Hosting;
#endif
using System.Runtime.CompilerServices;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Globalization;
using Path = System.IO.Path;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Collections;
using System.Collections.Generic;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AppDomainSetup :
IAppDomainSetup
{
[Serializable]
internal enum LoaderInformation
{
// If you add a new value, add the corresponding property
// to AppDomain.GetData() and SetData()'s switch statements,
// as well as fusionsetup.h.
ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE
ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE
DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE
DevPathValue = 3, // LOADER_DEVPATH
ApplicationNameValue = 4, // LOADER_APPLICATION_NAME
PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH
PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE
ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES
ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES
CachePathValue = 9, // LOADER_CACHE_PATH
LicenseFileValue = 10, // LOADER_LICENSE_FILE
DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY
DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD
DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS
DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING
ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
LoaderMaximum = 18 // LOADER_MAXIMUM
}
// Constants from fusionsetup.h.
private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION";
private const string CONFIGURATION_EXTENSION = ".config";
private const string APPENV_RELATIVEPATH = "RELPATH";
private const string MACHINE_CONFIGURATION_FILE = "config\\machine.config";
private const string ACTAG_HOST_CONFIG_FILE = "HOST_CONFIG";
#if FEATURE_FUSION
private const string LICENSE_FILE = "LICENSE_FILE";
#endif
// Constants from fusionpriv.h
private const string ACTAG_APP_CONFIG_FILE = "APP_CONFIG_FILE";
private const string ACTAG_MACHINE_CONFIG = "MACHINE_CONFIG";
private const string ACTAG_APP_BASE_URL = "APPBASE";
private const string ACTAG_APP_NAME = "APP_NAME";
private const string ACTAG_BINPATH_PROBE_ONLY = "BINPATH_PROBE_ONLY";
private const string ACTAG_APP_CACHE_BASE = "CACHE_BASE";
private const string ACTAG_DEV_PATH = "DEV_PATH";
private const string ACTAG_APP_DYNAMIC_BASE = "DYNAMIC_BASE";
private const string ACTAG_FORCE_CACHE_INSTALL = "FORCE_CACHE_INSTALL";
private const string ACTAG_APP_PRIVATE_BINPATH = "PRIVATE_BINPATH";
private const string ACTAG_APP_SHADOW_COPY_DIRS = "SHADOW_COPY_DIRS";
private const string ACTAG_DISALLOW_APPLYPUBLISHERPOLICY = "DISALLOW_APP";
private const string ACTAG_CODE_DOWNLOAD_DISABLED = "CODE_DOWNLOAD_DISABLED";
private const string ACTAG_DISALLOW_APP_BINDING_REDIRECTS = "DISALLOW_APP_REDIRECTS";
private const string ACTAG_DISALLOW_APP_BASE_PROBING = "DISALLOW_APP_BASE_PROBING";
private const string ACTAG_APP_CONFIG_BLOB = "APP_CONFIG_BLOB";
// This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order
// of these fields or add new ones.
private string[] _Entries;
private LoaderOptimization _LoaderOptimization;
#pragma warning disable 169
private String _AppBase; // for compat with v1.1
#pragma warning restore 169
[OptionalField(VersionAdded = 2)]
private AppDomainInitializer _AppDomainInitializer;
[OptionalField(VersionAdded = 2)]
private string[] _AppDomainInitializerArguments;
#if FEATURE_CLICKONCE
[OptionalField(VersionAdded = 2)]
private ActivationArguments _ActivationArguments;
#endif
#if FEATURE_CORECLR
// On the CoreCLR, this contains just the name of the permission set that we install in the new appdomain.
// Not the ToXml().ToString() of an ApplicationTrust object.
#endif
[OptionalField(VersionAdded = 2)]
private string _ApplicationTrust;
[OptionalField(VersionAdded = 2)]
private byte[] _ConfigurationBytes;
#if FEATURE_COMINTEROP
[OptionalField(VersionAdded = 3)]
private bool _DisableInterfaceCache = false;
#endif // FEATURE_COMINTEROP
[OptionalField(VersionAdded = 4)]
private string _AppDomainManagerAssembly;
[OptionalField(VersionAdded = 4)]
private string _AppDomainManagerType;
#if FEATURE_APTCA
[OptionalField(VersionAdded = 4)]
private string[] _AptcaVisibleAssemblies;
#endif
// A collection of strings used to indicate which breaking changes shouldn't be applied
// to an AppDomain. We only use the keys, the values are ignored.
[OptionalField(VersionAdded = 4)]
private Dictionary<string, object> _CompatFlags;
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private String _TargetFrameworkName;
#if !FEATURE_CORECLR
[NonSerialized]
internal AppDomainSortingSetupInfo _AppDomainSortingSetupInfo;
#endif
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _CheckedForTargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _UseRandomizedStringHashing;
#endif
[SecuritySafeCritical]
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
if(copy != null) {
string[] other = copy.Value;
int mineSize = _Entries.Length;
int otherSize = other.Length;
int size = (otherSize < mineSize) ? otherSize : mineSize;
for (int i = 0; i < size; i++)
mine[i] = other[i];
if (size < mineSize)
{
// This case can happen when the copy is a deserialized version of
// an AppDomainSetup object serialized by Everett.
for (int i = size; i < mineSize; i++)
mine[i] = null;
}
_LoaderOptimization = copy._LoaderOptimization;
_AppDomainInitializerArguments = copy.AppDomainInitializerArguments;
#if FEATURE_CLICKONCE
_ActivationArguments = copy.ActivationArguments;
#endif
_ApplicationTrust = copy._ApplicationTrust;
if (copyDomainBoundData)
_AppDomainInitializer = copy.AppDomainInitializer;
else
_AppDomainInitializer = null;
_ConfigurationBytes = copy.GetConfigurationBytes();
#if FEATURE_COMINTEROP
_DisableInterfaceCache = copy._DisableInterfaceCache;
#endif // FEATURE_COMINTEROP
_AppDomainManagerAssembly = copy.AppDomainManagerAssembly;
_AppDomainManagerType = copy.AppDomainManagerType;
#if FEATURE_APTCA
_AptcaVisibleAssemblies = copy.PartialTrustVisibleAssemblies;
#endif
if (copy._CompatFlags != null)
{
SetCompatibilitySwitches(copy._CompatFlags.Keys);
}
#if !FEATURE_CORECLR
if(copy._AppDomainSortingSetupInfo != null)
{
_AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo(copy._AppDomainSortingSetupInfo);
}
#endif
_TargetFrameworkName = copy._TargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = copy._UseRandomizedStringHashing;
#endif
}
else
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
public AppDomainSetup()
{
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
#if FEATURE_CLICKONCE
// Creates an AppDomainSetup object from an application identity.
public AppDomainSetup (ActivationContext activationContext) : this (new ActivationArguments(activationContext)) {}
[System.Security.SecuritySafeCritical] // auto-generated
public AppDomainSetup (ActivationArguments activationArguments) {
if (activationArguments == null)
throw new ArgumentNullException(nameof(activationArguments));
Contract.EndContractBlock();
_LoaderOptimization = LoaderOptimization.NotSpecified;
ActivationArguments = activationArguments;
Contract.Assert(activationArguments.ActivationContext != null, "Cannot set base directory without activation context");
string entryPointPath = CmsUtils.GetEntryPointFullPath(activationArguments);
if (!String.IsNullOrEmpty(entryPointPath))
SetupDefaults(entryPointPath);
else
ApplicationBase = activationArguments.ActivationContext.ApplicationDirectory;
}
#endif // !FEATURE_CLICKONCE
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) {
char[] sep = {'\\', '/'};
int i = imageLocation.LastIndexOfAny(sep);
if (i == -1) {
ApplicationName = imageLocation;
}
else {
ApplicationName = imageLocation.Substring(i+1);
string appBase = imageLocation.Substring(0, i+1);
if (imageLocationAlreadyNormalized)
Value[(int) LoaderInformation.ApplicationBaseValue] = appBase;
else
ApplicationBase = appBase;
}
ConfigurationFile = ApplicationName + AppDomainSetup.ConfigurationExtension;
}
internal string[] Value
{
get {
if( _Entries == null)
_Entries = new String[(int)LoaderInformation.LoaderMaximum];
return _Entries;
}
}
internal String GetUnsecureApplicationBase()
{
return Value[(int) LoaderInformation.ApplicationBaseValue];
}
public string AppDomainManagerAssembly
{
get { return _AppDomainManagerAssembly; }
set { _AppDomainManagerAssembly = value; }
}
public string AppDomainManagerType
{
get { return _AppDomainManagerType; }
set { _AppDomainManagerType = value; }
}
#if FEATURE_APTCA
public string[] PartialTrustVisibleAssemblies
{
get { return _AptcaVisibleAssemblies; }
set {
if (value != null) {
_AptcaVisibleAssemblies = (string[])value.Clone();
Array.Sort<string>(_AptcaVisibleAssemblies, StringComparer.OrdinalIgnoreCase);
}
else {
_AptcaVisibleAssemblies = null;
}
}
}
#endif
public String ApplicationBase
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[Pure]
get {
return VerifyDir(GetUnsecureApplicationBase(), false);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
set {
Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
}
}
private String NormalizePath(String path, bool useAppBase)
{
if(path == null)
return null;
// If we add very long file name support ("\\?\") to the Path class then this is unnecesary,
// but we do not plan on doing this for now.
// Long path checks can be quirked, and as loading default quirks too early in the setup of an AppDomain is risky
// we'll avoid checking path lengths- we'll still fail at MAX_PATH later if we're !useAppBase when we call Path's
// NormalizePath.
if (!useAppBase)
path = Security.Util.URLString.PreProcessForExtendedPathRemoval(
checkPathLength: false,
url: path,
isFileUrl: false);
int len = path.Length;
if (len == 0)
return null;
#if !PLATFORM_UNIX
bool UNCpath = false;
#endif // !PLATFORM_UNIX
if ((len > 7) &&
(String.Compare( path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) {
int trim;
if (path[6] == '\\') {
if ((path[7] == '\\') || (path[7] == '/')) {
// Don't allow "file:\\\\", because we can't tell the difference
// with it for "file:\\" + "\\server" and "file:\\\" + "\localpath"
if ( (len > 8) &&
((path[8] == '\\') || (path[8] == '/')) )
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
// file:\\\ means local path
else
#if !PLATFORM_UNIX
trim = 8;
#else
// For Unix platform, trim the first 7 charcaters only.
// Trimming the first 8 characters will cause
// the root path separator to be trimmed away,
// and the absolute local path becomes a relative local path.
trim = 7;
#endif // !PLATFORM_UNIX
}
// file:\\ means remote server
else {
trim = 5;
#if !PLATFORM_UNIX
UNCpath = true;
#endif // !PLATFORM_UNIX
}
}
// local path
else if (path[7] == '/')
#if !PLATFORM_UNIX
trim = 8;
#else
// For Unix platform, trim the first 7 characters only.
// Trimming the first 8 characters will cause
// the root path separator to be trimmed away,
// and the absolute local path becomes a relative local path.
trim = 7;
#endif // !PLATFORM_UNIX
// remote
else {
// file://\\remote
if ( (len > 8) && (path[7] == '\\') && (path[8] == '\\') )
trim = 7;
else { // file://remote
trim = 5;
#if !PLATFORM_UNIX
// Create valid UNC path by changing
// all occurences of '/' to '\\' in path
System.Text.StringBuilder winPathBuilder =
new System.Text.StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = path[i];
if (c == '/')
winPathBuilder.Append('\\');
else
winPathBuilder.Append(c);
}
path = winPathBuilder.ToString();
#endif // !PLATFORM_UNIX
}
#if !PLATFORM_UNIX
UNCpath = true;
#endif // !PLATFORM_UNIX
}
path = path.Substring(trim);
len -= trim;
}
#if !PLATFORM_UNIX
bool localPath;
// UNC
if (UNCpath ||
( (len > 1) &&
( (path[0] == '/') || (path[0] == '\\') ) &&
( (path[1] == '/') || (path[1] == '\\') ) ))
localPath = false;
else {
int colon = path.IndexOf(':') + 1;
// protocol other than file:
if ((colon != 0) &&
(len > colon+1) &&
( (path[colon] == '/') || (path[colon] == '\\') ) &&
( (path[colon+1] == '/') || (path[colon+1] == '\\') ))
localPath = false;
else
localPath = true;
}
if (localPath)
#else
if ( (len == 1) ||
( (path[0] != '/') && (path[0] != '\\') ) )
#endif // !PLATFORM_UNIX
{
if (useAppBase &&
( (len == 1) || (path[1] != ':') )) {
String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
if ((appBase == null) || (appBase.Length == 0))
throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet"));
StringBuilder result = StringBuilderCache.Acquire();
bool slash = false;
if ((path[0] == '/') || (path[0] == '\\')) {
string pathRoot = AppDomain.NormalizePath(appBase, fullCheck: false);
pathRoot = pathRoot.Substring(0, IO.PathInternal.GetRootLength(pathRoot));
if (pathRoot.Length == 0) { // URL
int index = appBase.IndexOf(":/", StringComparison.Ordinal);
if (index == -1)
index = appBase.IndexOf(":\\", StringComparison.Ordinal);
// Get past last slashes of "url:http://"
int urlLen = appBase.Length;
for (index += 1;
(index < urlLen) && ((appBase[index] == '/') || (appBase[index] == '\\'));
index++);
// Now find the next slash to get domain name
for(; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\');
index++);
pathRoot = appBase.Substring(0, index);
}
result.Append(pathRoot);
slash = true;
}
else
result.Append(appBase);
// Make sure there's a slash separator (and only one)
int aLen = result.Length - 1;
if ((result[aLen] != '/') &&
(result[aLen] != '\\')) {
if (!slash) {
#if !PLATFORM_UNIX
if (appBase.IndexOf(":/", StringComparison.Ordinal) == -1)
result.Append('\\');
else
#endif // !PLATFORM_UNIX
result.Append('/');
}
}
else if (slash)
result.Remove(aLen, 1);
result.Append(path);
path = StringBuilderCache.GetStringAndRelease(result);
}
else
path = AppDomain.NormalizePath(path, fullCheck: true);
}
return path;
}
private bool IsFilePath(String path)
{
#if !PLATFORM_UNIX
return (path[1] == ':') || ( (path[0] == '\\') && (path[1] == '\\') );
#else
return (path[0] == '/');
#endif // !PLATFORM_UNIX
}
internal static String ApplicationBaseKey
{
get {
return ACTAG_APP_BASE_URL;
}
}
public String ConfigurationFile
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
}
set {
Value[(int) LoaderInformation.ConfigurationFileValue] = value;
}
}
// Used by the ResourceManager internally. This must not do any
// security checks to avoid infinite loops.
internal String ConfigurationFileInternal
{
get {
return NormalizePath(Value[(int) LoaderInformation.ConfigurationFileValue], true);
}
}
internal static String ConfigurationFileKey
{
get {
return ACTAG_APP_CONFIG_FILE;
}
}
public byte[] GetConfigurationBytes()
{
if (_ConfigurationBytes == null)
return null;
return (byte[]) _ConfigurationBytes.Clone();
}
public void SetConfigurationBytes(byte[] value)
{
_ConfigurationBytes = value;
}
private static String ConfigurationBytesKey
{
get {
return ACTAG_APP_CONFIG_BLOB;
}
}
// only needed by AppDomain.Setup(). Not really needed by users.
internal Dictionary<string, object> GetCompatibilityFlags()
{
return _CompatFlags;
}
public void SetCompatibilitySwitches(IEnumerable<String> switches)
{
#if !FEATURE_CORECLR
if(_AppDomainSortingSetupInfo != null)
{
_AppDomainSortingSetupInfo._useV2LegacySorting = false;
_AppDomainSortingSetupInfo._useV4LegacySorting = false;
}
#endif
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = false;
#endif
if (switches != null)
{
_CompatFlags = new Dictionary<string, object>();
foreach (String str in switches)
{
#if !FEATURE_CORECLR
if(StringComparer.OrdinalIgnoreCase.Equals("NetFx40_Legacy20SortingBehavior", str)) {
if(_AppDomainSortingSetupInfo == null)
{
_AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
}
_AppDomainSortingSetupInfo._useV2LegacySorting = true;
}
if(StringComparer.OrdinalIgnoreCase.Equals("NetFx45_Legacy40SortingBehavior", str)) {
if(_AppDomainSortingSetupInfo == null)
{
_AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
}
_AppDomainSortingSetupInfo._useV4LegacySorting = true;
}
#endif
#if FEATURE_RANDOMIZED_STRING_HASHING
if(StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) {
_UseRandomizedStringHashing = true;
}
#endif
_CompatFlags.Add(str, null);
}
}
else
{
_CompatFlags = null;
}
}
// A target Framework moniker, in a format parsible by the FrameworkName class.
public String TargetFrameworkName {
get {
return _TargetFrameworkName;
}
set {
_TargetFrameworkName = value;
}
}
internal bool CheckedForTargetFrameworkName
{
get { return _CheckedForTargetFrameworkName; }
set { _CheckedForTargetFrameworkName = value; }
}
#if !FEATURE_CORECLR
[SecurityCritical]
public void SetNativeFunction(string functionName, int functionVersion, IntPtr functionPointer)
{
if(functionName == null)
{
throw new ArgumentNullException(nameof(functionName));
}
if(functionPointer == IntPtr.Zero)
{
throw new ArgumentNullException(nameof(functionPointer));
}
if(String.IsNullOrWhiteSpace(functionName))
{
throw new ArgumentException(Environment.GetResourceString("Argument_NPMSInvalidName"), nameof(functionName));
}
Contract.EndContractBlock();
if(functionVersion < 1)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_MinSortingVersion", 1, functionName));
}
if(_AppDomainSortingSetupInfo == null)
{
_AppDomainSortingSetupInfo = new AppDomainSortingSetupInfo();
}
if(String.Equals(functionName, "IsNLSDefinedString", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnIsNLSDefinedString = functionPointer;
}
if (String.Equals(functionName, "CompareStringEx", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnCompareStringEx = functionPointer;
}
if (String.Equals(functionName, "LCMapStringEx", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnLCMapStringEx = functionPointer;
}
if (String.Equals(functionName, "FindNLSStringEx", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnFindNLSStringEx = functionPointer;
}
if (String.Equals(functionName, "CompareStringOrdinal", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnCompareStringOrdinal = functionPointer;
}
if (String.Equals(functionName, "GetNLSVersionEx", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnGetNLSVersionEx = functionPointer;
}
if (String.Equals(functionName, "FindStringOrdinal", StringComparison.OrdinalIgnoreCase))
{
_AppDomainSortingSetupInfo._pfnFindStringOrdinal = functionPointer;
}
}
#endif
public String DynamicBase
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.DynamicBaseValue], true);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
if (value == null)
Value[(int) LoaderInformation.DynamicBaseValue] = null;
else {
if(ApplicationName == null)
throw new MemberAccessException(Environment.GetResourceString("AppDomain_RequireApplicationName"));
StringBuilder s = new StringBuilder( NormalizePath(value, false) );
s.Append('\\');
string h = ParseNumbers.IntToString(ApplicationName.GetLegacyNonRandomizedHashCode(),
16, 8, '0', ParseNumbers.PrintAsI4);
s.Append(h);
Value[(int) LoaderInformation.DynamicBaseValue] = s.ToString();
}
}
}
internal static String DynamicBaseKey
{
get {
return ACTAG_APP_DYNAMIC_BASE;
}
}
public bool DisallowPublisherPolicy
{
get
{
return (Value[(int) LoaderInformation.DisallowPublisherPolicyValue] != null);
}
set
{
if (value)
Value[(int) LoaderInformation.DisallowPublisherPolicyValue]="true";
else
Value[(int) LoaderInformation.DisallowPublisherPolicyValue]=null;
}
}
public bool DisallowBindingRedirects
{
get
{
return (Value[(int) LoaderInformation.DisallowBindingRedirectsValue] != null);
}
set
{
if (value)
Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = "true";
else
Value[(int) LoaderInformation.DisallowBindingRedirectsValue] = null;
}
}
public bool DisallowCodeDownload
{
get
{
return (Value[(int) LoaderInformation.DisallowCodeDownloadValue] != null);
}
set
{
if (value)
Value[(int) LoaderInformation.DisallowCodeDownloadValue] = "true";
else
Value[(int) LoaderInformation.DisallowCodeDownloadValue] = null;
}
}
public bool DisallowApplicationBaseProbing
{
get
{
return (Value[(int) LoaderInformation.DisallowAppBaseProbingValue] != null);
}
set
{
if (value)
Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = "true";
else
Value[(int) LoaderInformation.DisallowAppBaseProbingValue] = null;
}
}
[System.Security.SecurityCritical] // auto-generated
private String VerifyDir(String dir, bool normalize)
{
if (dir != null) {
if (dir.Length == 0)
dir = null;
else {
if (normalize)
dir = NormalizePath(dir, true);
// The only way AppDomainSetup is exposed in coreclr is through the AppDomainManager
// and the AppDomainManager is a SecurityCritical type. Also, all callers of callstacks
// leading from VerifyDir are SecurityCritical. So we can remove the Demand because
// we have validated that all callers are SecurityCritical
#if !FEATURE_CORECLR
if (IsFilePath(dir))
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dir ).Demand();
#endif // !FEATURE_CORECLR
}
}
return dir;
}
[System.Security.SecurityCritical] // auto-generated
private void VerifyDirList(String dirs)
{
if (dirs != null) {
String[] dirArray = dirs.Split(';');
int len = dirArray.Length;
for (int i = 0; i < len; i++)
VerifyDir(dirArray[i], true);
}
}
internal String DeveloperPath
{
[System.Security.SecurityCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.DevPathValue];
VerifyDirList(dirs);
return dirs;
}
set {
if(value == null)
Value[(int) LoaderInformation.DevPathValue] = null;
else {
String[] directories = value.Split(';');
int size = directories.Length;
StringBuilder newPath = StringBuilderCache.Acquire();
bool fDelimiter = false;
for(int i = 0; i < size; i++) {
if(directories[i].Length != 0) {
if(fDelimiter)
newPath.Append(";");
else
fDelimiter = true;
newPath.Append(Path.GetFullPathInternal(directories[i]));
}
}
String newString = StringBuilderCache.GetStringAndRelease(newPath);
if (newString.Length == 0)
Value[(int) LoaderInformation.DevPathValue] = null;
else
Value[(int) LoaderInformation.DevPathValue] = newString;
}
}
}
internal static String DisallowPublisherPolicyKey
{
get
{
return ACTAG_DISALLOW_APPLYPUBLISHERPOLICY;
}
}
internal static String DisallowCodeDownloadKey
{
get
{
return ACTAG_CODE_DOWNLOAD_DISABLED;
}
}
internal static String DisallowBindingRedirectsKey
{
get
{
return ACTAG_DISALLOW_APP_BINDING_REDIRECTS;
}
}
internal static String DeveloperPathKey
{
get {
return ACTAG_DEV_PATH;
}
}
internal static String DisallowAppBaseProbingKey
{
get
{
return ACTAG_DISALLOW_APP_BASE_PROBING;
}
}
public String ApplicationName
{
get {
return Value[(int) LoaderInformation.ApplicationNameValue];
}
set {
Value[(int) LoaderInformation.ApplicationNameValue] = value;
}
}
internal static String ApplicationNameKey
{
get {
return ACTAG_APP_NAME;
}
}
[XmlIgnoreMember]
public AppDomainInitializer AppDomainInitializer
{
get {
return _AppDomainInitializer;
}
set {
_AppDomainInitializer = value;
}
}
public string[] AppDomainInitializerArguments
{
get {
return _AppDomainInitializerArguments;
}
set {
_AppDomainInitializerArguments = value;
}
}
#if FEATURE_CLICKONCE
[XmlIgnoreMember]
public ActivationArguments ActivationArguments {
[Pure]
get {
return _ActivationArguments;
}
set {
_ActivationArguments = value;
}
}
#endif // !FEATURE_CLICKONCE
internal ApplicationTrust InternalGetApplicationTrust()
{
if (_ApplicationTrust == null) return null;
#if FEATURE_CORECLR
ApplicationTrust grantSet = new ApplicationTrust(NamedPermissionSet.GetBuiltInSet(_ApplicationTrust));
#else
SecurityElement securityElement = SecurityElement.FromString(_ApplicationTrust);
ApplicationTrust grantSet = new ApplicationTrust();
grantSet.FromXml(securityElement);
#endif
return grantSet;
}
#if FEATURE_CORECLR
internal void InternalSetApplicationTrust(String permissionSetName)
{
_ApplicationTrust = permissionSetName;
}
#else
internal void InternalSetApplicationTrust(ApplicationTrust value)
{
if (value != null)
{
_ApplicationTrust = value.ToXml().ToString();
}
else
{
_ApplicationTrust = null;
}
}
#endif
#if FEATURE_CLICKONCE
[XmlIgnoreMember]
public ApplicationTrust ApplicationTrust
{
get {
return InternalGetApplicationTrust();
}
set {
InternalSetApplicationTrust(value);
}
}
#else // FEATURE_CLICKONCE
[XmlIgnoreMember]
internal ApplicationTrust ApplicationTrust
{
get {
return InternalGetApplicationTrust();
}
#if !FEATURE_CORECLR
set {
InternalSetApplicationTrust(value);
}
#endif
}
#endif // FEATURE_CLICKONCE
public String PrivateBinPath
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.PrivateBinPathValue];
VerifyDirList(dirs);
return dirs;
}
set {
Value[(int) LoaderInformation.PrivateBinPathValue] = value;
}
}
internal static String PrivateBinPathKey
{
get {
return ACTAG_APP_PRIVATE_BINPATH;
}
}
public String PrivateBinPathProbe
{
get {
return Value[(int) LoaderInformation.PrivateBinPathProbeValue];
}
set {
Value[(int) LoaderInformation.PrivateBinPathProbeValue] = value;
}
}
internal static String PrivateBinPathProbeKey
{
get {
return ACTAG_BINPATH_PROBE_ONLY;
}
}
public String ShadowCopyDirectories
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
VerifyDirList(dirs);
return dirs;
}
set {
Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] = value;
}
}
internal static String ShadowCopyDirectoriesKey
{
get {
return ACTAG_APP_SHADOW_COPY_DIRS;
}
}
public String ShadowCopyFiles
{
get {
return Value[(int) LoaderInformation.ShadowCopyFilesValue];
}
set {
if((value != null) &&
(String.Compare(value, "true", StringComparison.OrdinalIgnoreCase) == 0))
Value[(int) LoaderInformation.ShadowCopyFilesValue] = value;
else
Value[(int) LoaderInformation.ShadowCopyFilesValue] = null;
}
}
internal static String ShadowCopyFilesKey
{
get {
return ACTAG_FORCE_CACHE_INSTALL;
}
}
public String CachePath
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false);
}
set {
Value[(int) LoaderInformation.CachePathValue] = NormalizePath(value, false);
}
}
internal static String CachePathKey
{
get {
return ACTAG_APP_CACHE_BASE;
}
}
public String LicenseFile
{
[System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true);
}
set {
Value[(int) LoaderInformation.LicenseFileValue] = value;
}
}
public LoaderOptimization LoaderOptimization
{
get {
return _LoaderOptimization;
}
set {
_LoaderOptimization = value;
}
}
internal static string LoaderOptimizationKey
{
get {
return LOADER_OPTIMIZATION;
}
}
internal static string ConfigurationExtension
{
get {
return CONFIGURATION_EXTENSION;
}
}
internal static String PrivateBinPathEnvironmentVariable
{
get {
return APPENV_RELATIVEPATH;
}
}
internal static string RuntimeConfigurationFile
{
get {
return MACHINE_CONFIGURATION_FILE;
}
}
internal static string MachineConfigKey
{
get {
return ACTAG_MACHINE_CONFIG;
}
}
internal static string HostBindingKey
{
get {
return ACTAG_HOST_CONFIG_FILE;
}
}
#if FEATURE_FUSION
[SecurityCritical]
internal bool UpdateContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, String UpdatedField, IntPtr fusionContext, AppDomainSetup oldADS)
{
String FieldString = Value[(int) FieldValue],
OldFieldString = (oldADS == null ? null : oldADS.Value[(int) FieldValue]);
if (FieldString != OldFieldString) { // Compare references since strings are immutable
UpdateContextProperty(fusionContext, FieldKey, UpdatedField == null ? FieldString : UpdatedField);
return true;
}
return false;
}
[SecurityCritical]
internal void UpdateBooleanContextPropertyIfNeeded(LoaderInformation FieldValue, String FieldKey, IntPtr fusionContext, AppDomainSetup oldADS)
{
if (Value[(int) FieldValue] != null)
UpdateContextProperty(fusionContext, FieldKey, "true");
else if (oldADS != null && oldADS.Value[(int) FieldValue] != null)
UpdateContextProperty(fusionContext, FieldKey, "false");
}
[SecurityCritical]
internal static bool ByteArraysAreDifferent(Byte[] A, Byte[] B)
{
int length = A.Length;
if (length != B.Length)
return true;
for(int i = 0; i < length; i++) {
if (A[i] != B[i])
return true;
}
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static void UpdateByteArrayContextPropertyIfNeeded(Byte[] NewArray, Byte[] OldArray, String FieldKey, IntPtr fusionContext)
{
if ((NewArray != null && OldArray == null) ||
(NewArray == null && OldArray != null) ||
(NewArray != null && OldArray != null && ByteArraysAreDifferent(NewArray, OldArray)))
UpdateContextProperty(fusionContext, FieldKey, NewArray);
}
[System.Security.SecurityCritical] // auto-generated
internal void SetupFusionContext(IntPtr fusionContext, AppDomainSetup oldADS)
{
UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationBaseValue, ApplicationBaseKey, null, fusionContext, oldADS);
UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathValue, PrivateBinPathKey, null, fusionContext, oldADS);
UpdateContextPropertyIfNeeded(LoaderInformation.DevPathValue, DeveloperPathKey, null, fusionContext, oldADS);
UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowPublisherPolicyValue, DisallowPublisherPolicyKey, fusionContext, oldADS);
UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowCodeDownloadValue, DisallowCodeDownloadKey, fusionContext, oldADS);
UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowBindingRedirectsValue, DisallowBindingRedirectsKey, fusionContext, oldADS);
UpdateBooleanContextPropertyIfNeeded(LoaderInformation.DisallowAppBaseProbingValue, DisallowAppBaseProbingKey, fusionContext, oldADS);
if(UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyFilesValue, ShadowCopyFilesKey, ShadowCopyFiles, fusionContext, oldADS)) {
// If we are asking for shadow copy directories then default to
// only to the ones that are in the private bin path.
if(Value[(int) LoaderInformation.ShadowCopyDirectoriesValue] == null)
ShadowCopyDirectories = BuildShadowCopyDirectories();
UpdateContextPropertyIfNeeded(LoaderInformation.ShadowCopyDirectoriesValue, ShadowCopyDirectoriesKey, null, fusionContext, oldADS);
}
UpdateContextPropertyIfNeeded(LoaderInformation.CachePathValue, CachePathKey, null, fusionContext, oldADS);
UpdateContextPropertyIfNeeded(LoaderInformation.PrivateBinPathProbeValue, PrivateBinPathProbeKey, PrivateBinPathProbe, fusionContext, oldADS);
UpdateContextPropertyIfNeeded(LoaderInformation.ConfigurationFileValue, ConfigurationFileKey, null, fusionContext, oldADS);
UpdateByteArrayContextPropertyIfNeeded(_ConfigurationBytes, oldADS == null ? null : oldADS.GetConfigurationBytes(), ConfigurationBytesKey, fusionContext);
UpdateContextPropertyIfNeeded(LoaderInformation.ApplicationNameValue, ApplicationNameKey, ApplicationName, fusionContext, oldADS);
UpdateContextPropertyIfNeeded(LoaderInformation.DynamicBaseValue, DynamicBaseKey, null, fusionContext, oldADS);
// Always add the runtime configuration file to the appdomain
UpdateContextProperty(fusionContext, MachineConfigKey, RuntimeEnvironment.GetRuntimeDirectoryImpl() + RuntimeConfigurationFile);
String hostBindingFile = RuntimeEnvironment.GetHostBindingFile();
if(hostBindingFile != null || oldADS != null) // If oldADS != null, we don't know the old value of the hostBindingFile, so we force an update even when hostBindingFile == null.
UpdateContextProperty(fusionContext, HostBindingKey, hostBindingFile);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void UpdateContextProperty(IntPtr fusionContext, string key, Object value);
#endif // FEATURE_FUSION
static internal int Locate(String s)
{
if(String.IsNullOrEmpty(s))
return -1;
#if FEATURE_FUSION
// verify assumptions hardcoded into the switch below
Contract.Assert('A' == ACTAG_APP_CONFIG_FILE[0] , "Assumption violated");
Contract.Assert('A' == ACTAG_APP_NAME[0] , "Assumption violated");
Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
Contract.Assert('B' == ACTAG_BINPATH_PROBE_ONLY[0] , "Assumption violated");
Contract.Assert('C' == ACTAG_APP_CACHE_BASE[0] , "Assumption violated");
Contract.Assert('D' == ACTAG_DEV_PATH[0] , "Assumption violated");
Contract.Assert('D' == ACTAG_APP_DYNAMIC_BASE[0] , "Assumption violated");
Contract.Assert('F' == ACTAG_FORCE_CACHE_INSTALL[0] , "Assumption violated");
Contract.Assert('L' == LICENSE_FILE[0] , "Assumption violated");
Contract.Assert('P' == ACTAG_APP_PRIVATE_BINPATH[0] , "Assumption violated");
Contract.Assert('S' == ACTAG_APP_SHADOW_COPY_DIRS[0], "Assumption violated");
Contract.Assert('D' == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY[0], "Assumption violated");
Contract.Assert('C' == ACTAG_CODE_DOWNLOAD_DISABLED[0], "Assumption violated");
Contract.Assert('D' == ACTAG_DISALLOW_APP_BINDING_REDIRECTS[0], "Assumption violated");
Contract.Assert('D' == ACTAG_DISALLOW_APP_BASE_PROBING[0], "Assumption violated");
Contract.Assert('A' == ACTAG_APP_CONFIG_BLOB[0], "Assumption violated");
switch (s[0]) {
case 'A':
if (s == ACTAG_APP_CONFIG_FILE) return (int)LoaderInformation.ConfigurationFileValue;
if (s == ACTAG_APP_NAME) return (int)LoaderInformation.ApplicationNameValue;
if (s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue;
if (s == ACTAG_APP_CONFIG_BLOB) return (int)LoaderInformation.ConfigurationBytesValue;
break;
case 'B':
if (s == ACTAG_BINPATH_PROBE_ONLY) return (int)LoaderInformation.PrivateBinPathProbeValue;
break;
case 'C':
if (s == ACTAG_APP_CACHE_BASE) return (int)LoaderInformation.CachePathValue;
if (s == ACTAG_CODE_DOWNLOAD_DISABLED) return (int)LoaderInformation.DisallowCodeDownloadValue;
break;
case 'D':
if (s == ACTAG_DEV_PATH) return (int)LoaderInformation.DevPathValue;
if (s == ACTAG_APP_DYNAMIC_BASE) return (int)LoaderInformation.DynamicBaseValue;
if (s == ACTAG_DISALLOW_APPLYPUBLISHERPOLICY) return (int)LoaderInformation.DisallowPublisherPolicyValue;
if (s == ACTAG_DISALLOW_APP_BINDING_REDIRECTS) return (int)LoaderInformation.DisallowBindingRedirectsValue;
if (s == ACTAG_DISALLOW_APP_BASE_PROBING) return (int)LoaderInformation.DisallowAppBaseProbingValue;
break;
case 'F':
if (s == ACTAG_FORCE_CACHE_INSTALL) return (int)LoaderInformation.ShadowCopyFilesValue;
break;
case 'L':
if (s == LICENSE_FILE) return (int)LoaderInformation.LicenseFileValue;
break;
case 'P':
if (s == ACTAG_APP_PRIVATE_BINPATH) return (int)LoaderInformation.PrivateBinPathValue;
break;
case 'S':
if (s == ACTAG_APP_SHADOW_COPY_DIRS) return (int)LoaderInformation.ShadowCopyDirectoriesValue;
break;
}
#else
Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
if (s[0]=='A' && s == ACTAG_APP_BASE_URL)
return (int)LoaderInformation.ApplicationBaseValue;
#endif //FEATURE_FUSION
return -1;
}
#if FEATURE_FUSION
private string BuildShadowCopyDirectories()
{
// Default to only to the ones that are in the private bin path.
String binPath = Value[(int) LoaderInformation.PrivateBinPathValue];
if(binPath == null)
return null;
StringBuilder result = StringBuilderCache.Acquire();
String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
if(appBase != null) {
char[] sep = {';'};
string[] directories = binPath.Split(sep);
int size = directories.Length;
bool appendSlash = !( (appBase[appBase.Length-1] == '/') ||
(appBase[appBase.Length-1] == '\\') );
if (size == 0) {
result.Append(appBase);
if (appendSlash)
result.Append('\\');
result.Append(binPath);
}
else {
for(int i = 0; i < size; i++) {
result.Append(appBase);
if (appendSlash)
result.Append('\\');
result.Append(directories[i]);
if (i < size-1)
result.Append(';');
}
}
}
return StringBuilderCache.GetStringAndRelease(result);
}
#endif // FEATURE_FUSION
#if FEATURE_COMINTEROP
public bool SandboxInterop
{
get
{
return _DisableInterfaceCache;
}
set
{
_DisableInterfaceCache = value;
}
}
#endif // FEATURE_COMINTEROP
}
}
| |
// <copyright file="Retry.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Threading;
using System.Threading.Tasks;
using IX.Retry.Contexts;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
namespace IX.Retry
{
/// <summary>
/// A class for containing retry operations.
/// </summary>
[PublicAPI]
public static partial class Retry
{
/// <summary>
/// Retry now, with a default set of options.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
public static void Now(
[CanBeNull] Action action,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Run(
action,
new RetryOptions(),
cancellationToken);
}
/// <summary>
/// Retry now, asynchronously, with an optional cancellation token.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task" /> that can be awaited on.</returns>
public static Task NowAsync(
[CanBeNull] Action action,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
return RunAsync(
action,
new RetryOptions(),
cancellationToken);
}
/// <summary>
/// Retry now, with specified options.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="options">The retry options.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
public static void Now(
[CanBeNull] Action action,
[CanBeNull] RetryOptions options,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in options,
nameof(options));
Run(
action,
options,
cancellationToken);
}
/// <summary>
/// Retry now, asynchronously, with specified options and an optional cancellation token.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="options">The retry options.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task" /> that can be awaited on.</returns>
public static Task NowAsync(
[CanBeNull] Action action,
[CanBeNull] RetryOptions options,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in options,
nameof(options));
return RunAsync(
action,
options,
cancellationToken);
}
/// <summary>
/// Retry now, with a method to build up options.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="optionsSetter">A method to build up options on the fly.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
public static void Now(
[CanBeNull] Action action,
[CanBeNull] Action<RetryOptions> optionsSetter,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in optionsSetter,
nameof(optionsSetter));
var options = new RetryOptions();
optionsSetter(options);
Run(
action,
options,
cancellationToken);
}
/// <summary>
/// Retry now, asynchronously, with a method to build up options and an optional cancellation token.
/// </summary>
/// <param name="action">The action to try and retry.</param>
/// <param name="optionsSetter">A method to build up options on the fly.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>A <see cref="System.Threading.Tasks.Task" /> that can be awaited on.</returns>
public static async Task NowAsync(
[CanBeNull] Action action,
[CanBeNull] Action<RetryOptions> optionsSetter,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in optionsSetter,
nameof(optionsSetter));
var options = new RetryOptions();
optionsSetter(options);
await RunAsync(
action,
options,
cancellationToken).ConfigureAwait(false);
}
#pragma warning disable HAA0301 // Closure Allocation Source
#pragma warning disable HAA0302 // Display class allocation to capture closure - These are expected to happen here
#pragma warning disable HAA0603 // Delegate allocation from a method group
/// <summary>
/// Retry an action later.
/// </summary>
/// <param name="action">The action to retry.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>An <see cref="System.Action" /> that can be executed whenever required.</returns>
public static Action Later(
[CanBeNull] Action action,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
return () => Run(
action,
new RetryOptions(),
cancellationToken);
}
/// <summary>
/// Retry an action later, with retry options.
/// </summary>
/// <param name="action">The action to retry.</param>
/// <param name="options">The retry options.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>An <see cref="System.Action" /> that can be executed whenever required.</returns>
public static Action Later(
[CanBeNull] Action action,
[CanBeNull] RetryOptions options,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in options,
nameof(options));
return () => Run(
action,
options,
cancellationToken);
}
/// <summary>
/// Retry an action later, with a method to build up options.
/// </summary>
/// <param name="action">The action to retry.</param>
/// <param name="optionsSetter">A method to build up options on the fly.</param>
/// <param name="cancellationToken">The current operation's cancellation token.</param>
/// <returns>An <see cref="System.Action" /> that can be executed whenever required.</returns>
public static Action Later(
[CanBeNull] Action action,
[CanBeNull] Action<RetryOptions> optionsSetter,
CancellationToken cancellationToken = default)
{
Contract.RequiresNotNull(
in action,
nameof(action));
Contract.RequiresNotNull(
in optionsSetter,
nameof(optionsSetter));
var options = new RetryOptions();
optionsSetter(options);
return () => Run(
action,
options,
cancellationToken);
}
#pragma warning restore HAA0603 // Delegate allocation from a method group
#pragma warning restore HAA0302 // Display class allocation to capture closure
#pragma warning restore HAA0301 // Closure Allocation Source
/// <summary>
/// Retry for a number of times.
/// </summary>
/// <param name="times">The number of times to retry. Has to be greater than 0.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions Times(int times)
{
Contract.RequiresPositive(
in times,
nameof(times));
return new RetryOptions
{
Type = RetryType.Times,
RetryTimes = times,
};
}
/// <summary>
/// Retry once.
/// </summary>
/// <returns>The configured retry options.</returns>
public static RetryOptions Once() => new RetryOptions
{
Type = RetryType.Times,
RetryTimes = 1,
};
/// <summary>
/// Retry twice.
/// </summary>
/// <returns>The configured retry options.</returns>
public static RetryOptions Twice() => new RetryOptions
{
Type = RetryType.Times,
RetryTimes = 2,
};
/// <summary>
/// Retry three times.
/// </summary>
/// <returns>The configured retry options.</returns>
public static RetryOptions ThreeTimes() => new RetryOptions
{
Type = RetryType.Times,
RetryTimes = 3,
};
/// <summary>
/// Retry five times.
/// </summary>
/// <returns>The configured retry options.</returns>
public static RetryOptions FiveTimes() => new RetryOptions
{
Type = RetryType.Times,
RetryTimes = 5,
};
/// <summary>
/// Retries for a specific time span.
/// </summary>
/// <param name="timeSpan">How long to retry, as a time span.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions For(TimeSpan timeSpan)
{
Contract.RequiresPositive(
in timeSpan,
nameof(timeSpan));
return new RetryOptions
{
Type = RetryType.For,
RetryFor = timeSpan,
};
}
/// <summary>
/// Retries for a specific number of milliseconds.
/// </summary>
/// <param name="milliseconds">How long to retry, in milliseconds.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions For(int milliseconds)
{
Contract.RequiresNonNegative(
in milliseconds,
nameof(milliseconds));
return new RetryOptions
{
Type = RetryType.For,
RetryFor = TimeSpan.FromMilliseconds(milliseconds),
};
}
/// <summary>
/// Retries until a specific condition is reached.
/// </summary>
/// <param name="conditionMethod">The condition method to evaluate.</param>
/// <returns>The configured retry options.</returns>
/// <remarks>
/// <para>
/// Retrying happens while the <paramref name="conditionMethod" /> method, when executed, returns
/// <see langword="true" />.
/// </para>
/// <para>On first instance that the method return is <see langword="false" />, retrying stops.</para>
/// </remarks>
public static RetryOptions Until([CanBeNull] RetryConditionDelegate conditionMethod)
{
Contract.RequiresNotNull(
in conditionMethod,
nameof(conditionMethod));
return new RetryOptions
{
Type = RetryType.Until,
RetryUntil = conditionMethod,
};
}
/// <summary>
/// Configures an exception that, when thrown by the code being retried, prompts a retry.
/// </summary>
/// <typeparam name="T">The exception type to configure.</typeparam>
/// <returns>The configured retry options.</returns>
public static RetryOptions OnException<T>()
where T : Exception
{
var options = new RetryOptions();
#pragma warning disable HAA0303 // Lambda or anonymous method in a generic method allocates a delegate instance
options.RetryOnExceptions.Add(
new Tuple<Type, Func<Exception, bool>>(
typeof(T),
null));
#pragma warning restore HAA0303 // Lambda or anonymous method in a generic method allocates a delegate instance
return options;
}
/// <summary>
/// Configures an exception that, when thrown by the code being retried, prompts a retry, if the method to test for it
/// allows it.
/// </summary>
/// <typeparam name="T">The exception type to configure.</typeparam>
/// <param name="testExceptionFunc">The method to test the exceptions with.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions OnException<T>([CanBeNull] Func<Exception, bool> testExceptionFunc)
where T : Exception
{
Contract.RequiresNotNull(
in testExceptionFunc,
nameof(testExceptionFunc));
var options = new RetryOptions();
options.RetryOnExceptions.Add(
new Tuple<Type, Func<Exception, bool>>(
typeof(T),
testExceptionFunc));
return options;
}
/// <summary>
/// Configures retry options to throw an exception at the end of the retrying process, if it was unsuccessful.
/// </summary>
/// <returns>The configured retry options.</returns>
public static RetryOptions ThrowException() => new RetryOptions
{
ThrowExceptionOnLastRetry = true,
};
/// <summary>
/// Waiting time between retries.
/// </summary>
/// <param name="milliseconds">The number of milliseconds to wait for.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions WaitFor(int milliseconds)
{
Contract.RequiresPositive(
in milliseconds,
nameof(milliseconds));
return new RetryOptions
{
WaitBetweenRetriesType = WaitType.For,
WaitForDuration = TimeSpan.FromMilliseconds(milliseconds),
};
}
/// <summary>
/// Waiting time between retries.
/// </summary>
/// <param name="timeSpan">The time span to wait between retries.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions WaitFor(TimeSpan timeSpan)
{
Contract.RequiresPositive(
in timeSpan,
nameof(timeSpan));
return new RetryOptions
{
WaitBetweenRetriesType = WaitType.For,
WaitForDuration = timeSpan,
};
}
/// <summary>
/// Waits a time span that is configured by a given delegate.
/// </summary>
/// <param name="waitMethod">The waiting delegate to give the time span.</param>
/// <returns>The configured retry options.</returns>
public static RetryOptions WaitUntil([CanBeNull] RetryWaitDelegate waitMethod)
{
Contract.RequiresNotNull(
in waitMethod,
nameof(waitMethod));
return new RetryOptions
{
WaitBetweenRetriesType = WaitType.Until,
WaitUntilDelegate = waitMethod,
};
}
private static async Task RunAsync(
[CanBeNull] Action action,
[CanBeNull] RetryOptions options,
CancellationToken cancellationToken)
{
Contract.RequiresNotNullPrivate(
in action,
nameof(action));
Contract.RequiresNotNullPrivate(
in options,
nameof(options));
cancellationToken.ThrowIfCancellationRequested();
using (var context = new ActionRetryContext(
action,
options))
{
await context.BeginRetryProcessAsync(cancellationToken).ConfigureAwait(false);
}
}
private static void Run(
[CanBeNull] Action action,
[CanBeNull] RetryOptions options,
CancellationToken cancellationToken)
{
Contract.RequiresNotNullPrivate(
in action,
nameof(action));
Contract.RequiresNotNullPrivate(
in options,
nameof(options));
cancellationToken.ThrowIfCancellationRequested();
using (var context = new ActionRetryContext(
action,
options))
{
context.BeginRetryProcess(cancellationToken);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication.OAuth.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNetCore.Authentication.OpenIdConnect
{
/// <summary>
/// Configuration options for <see cref="OpenIdConnectHandler"/>
/// </summary>
public class OpenIdConnectOptions : RemoteAuthenticationOptions
{
private CookieBuilder _nonceCookieBuilder;
private readonly JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler();
/// <summary>
/// Initializes a new <see cref="OpenIdConnectOptions"/>
/// </summary>
/// <remarks>
/// Defaults:
/// <para>AddNonceToRequest: true.</para>
/// <para>BackchannelTimeout: 1 minute.</para>
/// <para>ProtocolValidator: new <see cref="OpenIdConnectProtocolValidator"/>.</para>
/// <para>RefreshOnIssuerKeyNotFound: true</para>
/// <para>ResponseType: <see cref="OpenIdConnectResponseType.IdToken"/></para>
/// <para>Scope: <see cref="OpenIdConnectScope.OpenIdProfile"/>.</para>
/// <para>TokenValidationParameters: new <see cref="TokenValidationParameters"/> with AuthenticationScheme = authenticationScheme.</para>
/// <para>UseTokenLifetime: false.</para>
/// </remarks>
public OpenIdConnectOptions()
{
CallbackPath = new PathString("/signin-oidc");
SignedOutCallbackPath = new PathString("/signout-callback-oidc");
RemoteSignOutPath = new PathString("/signout-oidc");
SecurityTokenValidator = _defaultHandler;
Events = new OpenIdConnectEvents();
Scope.Add("openid");
Scope.Add("profile");
ClaimActions.DeleteClaim("nonce");
ClaimActions.DeleteClaim("aud");
ClaimActions.DeleteClaim("azp");
ClaimActions.DeleteClaim("acr");
ClaimActions.DeleteClaim("iss");
ClaimActions.DeleteClaim("iat");
ClaimActions.DeleteClaim("nbf");
ClaimActions.DeleteClaim("exp");
ClaimActions.DeleteClaim("at_hash");
ClaimActions.DeleteClaim("c_hash");
ClaimActions.DeleteClaim("ipaddr");
ClaimActions.DeleteClaim("platf");
ClaimActions.DeleteClaim("ver");
// http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
ClaimActions.MapUniqueJsonKey("sub", "sub");
ClaimActions.MapUniqueJsonKey("name", "name");
ClaimActions.MapUniqueJsonKey("given_name", "given_name");
ClaimActions.MapUniqueJsonKey("family_name", "family_name");
ClaimActions.MapUniqueJsonKey("profile", "profile");
ClaimActions.MapUniqueJsonKey("email", "email");
_nonceCookieBuilder = new OpenIdConnectNonceCookieBuilder(this)
{
Name = OpenIdConnectDefaults.CookieNoncePrefix,
HttpOnly = true,
SameSite = SameSiteMode.None,
SecurePolicy = CookieSecurePolicy.SameAsRequest,
IsEssential = true,
};
}
/// <summary>
/// Check that the options are valid. Should throw an exception if things are not ok.
/// </summary>
public override void Validate()
{
base.Validate();
if (MaxAge.HasValue && MaxAge.Value < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(MaxAge), MaxAge.Value, "The value must not be a negative TimeSpan.");
}
if (string.IsNullOrEmpty(ClientId))
{
throw new ArgumentException("Options.ClientId must be provided", nameof(ClientId));
}
if (!CallbackPath.HasValue)
{
throw new ArgumentException("Options.CallbackPath must be provided.", nameof(CallbackPath));
}
if (ConfigurationManager == null)
{
throw new InvalidOperationException($"Provide {nameof(Authority)}, {nameof(MetadataAddress)}, "
+ $"{nameof(Configuration)}, or {nameof(ConfigurationManager)} to {nameof(OpenIdConnectOptions)}");
}
}
/// <summary>
/// Gets or sets the Authority to use when making OpenIdConnect calls.
/// </summary>
public string? Authority { get; set; }
/// <summary>
/// Gets or sets the 'client_id'.
/// </summary>
public string? ClientId { get; set; }
/// <summary>
/// Gets or sets the 'client_secret'.
/// </summary>
public string? ClientSecret { get; set; }
/// <summary>
/// Configuration provided directly by the developer. If provided, then MetadataAddress and the Backchannel properties
/// will not be used. This information should not be updated during request processing.
/// </summary>
public OpenIdConnectConfiguration? Configuration { get; set; }
/// <summary>
/// Responsible for retrieving, caching, and refreshing the configuration from metadata.
/// If not provided, then one will be created using the MetadataAddress and Backchannel properties.
/// </summary>
public IConfigurationManager<OpenIdConnectConfiguration>? ConfigurationManager { get; set; }
/// <summary>
/// Boolean to set whether the handler should go to user info endpoint to retrieve additional claims or not after creating an identity from id_token received from token endpoint.
/// The default is 'false'.
/// </summary>
public bool GetClaimsFromUserInfoEndpoint { get; set; }
/// <summary>
/// A collection of claim actions used to select values from the json user data and create Claims.
/// </summary>
public ClaimActionCollection ClaimActions { get; } = new ClaimActionCollection();
/// <summary>
/// Gets or sets if HTTPS is required for the metadata address or authority.
/// The default is true. This should be disabled only in development environments.
/// </summary>
public bool RequireHttpsMetadata { get; set; } = true;
/// <summary>
/// Gets or sets the discovery endpoint for obtaining metadata
/// </summary>
public string? MetadataAddress { get; set; }
/// <summary>
/// Gets or sets the <see cref="OpenIdConnectEvents"/> to notify when processing OpenIdConnect messages.
/// </summary>
public new OpenIdConnectEvents Events
{
get => (OpenIdConnectEvents)base.Events;
set => base.Events = value;
}
/// <summary>
/// Gets or sets the 'max_age'. If set the 'max_age' parameter will be sent with the authentication request. If the identity
/// provider has not actively authenticated the user within the length of time specified, the user will be prompted to
/// re-authenticate. By default no max_age is specified.
/// </summary>
public TimeSpan? MaxAge { get; set; }
/// <summary>
/// Gets or sets the <see cref="OpenIdConnectProtocolValidator"/> that is used to ensure that the 'id_token' received
/// is valid per: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
/// </summary>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public OpenIdConnectProtocolValidator ProtocolValidator { get; set; } = new OpenIdConnectProtocolValidator()
{
RequireStateValidation = false,
NonceLifetime = TimeSpan.FromMinutes(15)
};
/// <summary>
/// The request path within the application's base path where the user agent will be returned after sign out from the identity provider.
/// See post_logout_redirect_uri from http://openid.net/specs/openid-connect-session-1_0.html#RedirectionAfterLogout.
/// </summary>
public PathString SignedOutCallbackPath { get; set; }
/// <summary>
/// The uri where the user agent will be redirected to after application is signed out from the identity provider.
/// The redirect will happen after the SignedOutCallbackPath is invoked.
/// </summary>
/// <remarks>This URI can be out of the application's domain. By default it points to the root.</remarks>
public string SignedOutRedirectUri { get; set; } = "/";
/// <summary>
/// Gets or sets if a metadata refresh should be attempted after a SecurityTokenSignatureKeyNotFoundException. This allows for automatic
/// recovery in the event of a signature key rollover. This is enabled by default.
/// </summary>
public bool RefreshOnIssuerKeyNotFound { get; set; } = true;
/// <summary>
/// Gets or sets the method used to redirect the user agent to the identity provider.
/// </summary>
public OpenIdConnectRedirectBehavior AuthenticationMethod { get; set; } = OpenIdConnectRedirectBehavior.RedirectGet;
/// <summary>
/// Gets or sets the 'resource'.
/// </summary>
public string? Resource { get; set; }
/// <summary>
/// Gets or sets the 'response_mode'.
/// </summary>
public string ResponseMode { get; set; } = OpenIdConnectResponseMode.FormPost;
/// <summary>
/// Gets or sets the 'response_type'.
/// </summary>
public string ResponseType { get; set; } = OpenIdConnectResponseType.IdToken;
/// <summary>
/// Gets or sets the 'prompt'.
/// </summary>
public string? Prompt { get; set; }
/// <summary>
/// Gets the list of permissions to request.
/// </summary>
public ICollection<string> Scope { get; } = new HashSet<string>();
/// <summary>
/// Requests received on this path will cause the handler to invoke SignOut using the SignOutScheme.
/// </summary>
public PathString RemoteSignOutPath { get; set; }
/// <summary>
/// The Authentication Scheme to use with SignOut on the SignOutPath. SignInScheme will be used if this
/// is not set.
/// </summary>
public string? SignOutScheme { get; set; }
/// <summary>
/// Gets or sets the type used to secure data handled by the handler.
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; } = default!;
/// <summary>
/// Gets or sets the type used to secure strings used by the handler.
/// </summary>
public ISecureDataFormat<string> StringDataFormat { get; set; } = default!;
/// <summary>
/// Gets or sets the <see cref="ISecurityTokenValidator"/> used to validate identity tokens.
/// </summary>
public ISecurityTokenValidator SecurityTokenValidator { get; set; }
/// <summary>
/// Gets or sets the parameters used to validate identity tokens.
/// </summary>
/// <remarks>Contains the types and definitions required for validating a token.</remarks>
public TokenValidationParameters TokenValidationParameters { get; set; } = new TokenValidationParameters();
/// <summary>
/// Indicates that the authentication session lifetime (e.g. cookies) should match that of the authentication token.
/// If the token does not provide lifetime information then normal session lifetimes will be used.
/// This is disabled by default.
/// </summary>
public bool UseTokenLifetime { get; set; }
/// <summary>
/// Indicates if requests to the CallbackPath may also be for other components. If enabled the handler will pass
/// requests through that do not contain OpenIdConnect authentication responses. Disabling this and setting the
/// CallbackPath to a dedicated endpoint may provide better error handling.
/// This is disabled by default.
/// </summary>
public bool SkipUnrecognizedRequests { get; set; }
/// <summary>
/// Indicates whether telemetry should be disabled. When this feature is enabled,
/// the assembly version of the Microsoft IdentityModel packages is sent to the
/// remote OpenID Connect provider as an authorization/logout request parameter.
/// </summary>
public bool DisableTelemetry { get; set; }
/// <summary>
/// Determines the settings used to create the nonce cookie before the
/// cookie gets added to the response.
/// </summary>
/// <remarks>
/// The value of <see cref="CookieBuilder.Name"/> is treated as the prefix to the cookie name, and defaults to <see cref="OpenIdConnectDefaults.CookieNoncePrefix"/>.
/// </remarks>
public CookieBuilder NonceCookie
{
get => _nonceCookieBuilder;
set => _nonceCookieBuilder = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Enables or disables the use of the Proof Key for Code Exchange (PKCE) standard.
/// This only applies when the <see cref="ResponseType"/> is set to <see cref="OpenIdConnectResponseType.Code"/>.
/// See https://tools.ietf.org/html/rfc7636.
/// The default value is `true`.
/// </summary>
public bool UsePkce { get; set; } = true;
private class OpenIdConnectNonceCookieBuilder : RequestPathBaseCookieBuilder
{
private readonly OpenIdConnectOptions _options;
public OpenIdConnectNonceCookieBuilder(OpenIdConnectOptions oidcOptions)
{
_options = oidcOptions;
}
protected override string AdditionalPath => _options.CallbackPath;
public override CookieOptions Build(HttpContext context, DateTimeOffset expiresFrom)
{
var cookieOptions = base.Build(context, expiresFrom);
if (!Expiration.HasValue || !cookieOptions.Expires.HasValue)
{
cookieOptions.Expires = expiresFrom.Add(_options.ProtocolValidator.NonceLifetime);
}
return cookieOptions;
}
}
/// <summary>
/// 1 day is the default time interval that afterwards, <see cref="ConfigurationManager" /> will obtain new configuration.
/// </summary>
public TimeSpan AutomaticRefreshInterval { get; set; } = ConfigurationManager<OpenIdConnectConfiguration>.DefaultAutomaticRefreshInterval;
/// <summary>
/// The minimum time between <see cref="ConfigurationManager" /> retrievals, in the event that a retrieval failed, or that a refresh was explicitly requested. 30 seconds is the default.
/// </summary>
public TimeSpan RefreshInterval { get; set; } = ConfigurationManager<OpenIdConnectConfiguration>.DefaultRefreshInterval;
/// <summary>
/// Gets or sets the <see cref="MapInboundClaims"/> property on the default instance of <see cref="JwtSecurityTokenHandler"/> in SecurityTokenValidator, which is used when determining
/// whether or not to map claim types that are extracted when validating a <see cref="JwtSecurityToken"/>.
/// <para>If this is set to true, the Claim Type is set to the JSON claim 'name' after translating using this mapping. Otherwise, no mapping occurs.</para>
/// <para>The default value is true.</para>
/// </summary>
public bool MapInboundClaims
{
get => _defaultHandler.MapInboundClaims;
set => _defaultHandler.MapInboundClaims = value;
}
}
}
| |
//
// X509Extension.cs: Base class for all X.509 extensions.
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Text;
using Mono.Security;
namespace Mono.Security.X509 {
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* }
*/
internal class X509Extension {
protected string extnOid;
protected bool extnCritical;
protected ASN1 extnValue;
protected X509Extension ()
{
extnCritical = false;
}
public X509Extension (ASN1 asn1)
{
if ((asn1.Tag != 0x30) || (asn1.Count < 2))
throw new ArgumentException (Locale.GetText ("Invalid X.509 extension."));
if (asn1[0].Tag != 0x06)
throw new ArgumentException (Locale.GetText ("Invalid X.509 extension."));
extnOid = ASN1Convert.ToOid (asn1[0]);
extnCritical = ((asn1[1].Tag == 0x01) && (asn1[1].Value[0] == 0xFF));
// last element is an octet string which may need to be decoded
extnValue = asn1 [asn1.Count - 1];
if ((extnValue.Tag == 0x04) && (extnValue.Length > 0) && (extnValue.Count == 0)) {
try {
ASN1 encapsulated = new ASN1 (extnValue.Value);
extnValue.Value = null;
extnValue.Add (encapsulated);
}
catch {
// data isn't ASN.1
}
}
Decode ();
}
public X509Extension (X509Extension extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
if ((extension.Value == null) || (extension.Value.Tag != 0x04) || (extension.Value.Count != 1))
throw new ArgumentException (Locale.GetText ("Invalid X.509 extension."));
extnOid = extension.Oid;
extnCritical = extension.Critical;
extnValue = extension.Value;
Decode ();
}
// encode the extension *into* an OCTET STRING
protected virtual void Decode ()
{
}
// decode the extension from *inside* an OCTET STRING
protected virtual void Encode ()
{
}
public ASN1 ASN1 {
get {
ASN1 extension = new ASN1 (0x30);
extension.Add (ASN1Convert.FromOid (extnOid));
if (extnCritical)
extension.Add (new ASN1 (0x01, new byte [1] { 0xFF }));
Encode ();
extension.Add (extnValue);
return extension;
}
}
public string Oid {
get { return extnOid; }
}
public bool Critical {
get { return extnCritical; }
set { extnCritical = value; }
}
// this gets overrided with more meaningful names
public virtual string Name {
get { return extnOid; }
}
public ASN1 Value {
get {
if (extnValue == null) {
Encode ();
}
return extnValue;
}
}
public override bool Equals (object obj)
{
if (obj == null)
return false;
X509Extension ex = (obj as X509Extension);
if (ex == null)
return false;
if (extnCritical != ex.extnCritical)
return false;
if (extnOid != ex.extnOid)
return false;
if (extnValue.Length != ex.extnValue.Length)
return false;
for (int i=0; i < extnValue.Length; i++) {
if (extnValue [i] != ex.extnValue [i])
return false;
}
return true;
}
public byte[] GetBytes ()
{
return ASN1.GetBytes ();
}
public override int GetHashCode ()
{
// OID should be unique in a collection of extensions
return extnOid.GetHashCode ();
}
private void WriteLine (StringBuilder sb, int n, int pos)
{
byte[] value = extnValue.Value;
int p = pos;
for (int j=0; j < 8; j++) {
if (j < n) {
sb.Append (value [p++].ToString ("X2", CultureInfo.InvariantCulture));
sb.Append (" ");
}
else
sb.Append (" ");
}
sb.Append (" ");
p = pos;
for (int j=0; j < n; j++) {
byte b = value [p++];
if (b < 0x20)
sb.Append (".");
else
sb.Append (Convert.ToChar (b));
}
sb.Append (Environment.NewLine);
}
public override string ToString ()
{
StringBuilder sb = new StringBuilder ();
int div = (extnValue.Length >> 3);
int rem = (extnValue.Length - (div << 3));
int x = 0;
for (int i=0; i < div; i++) {
WriteLine (sb, 8, x);
x += 8;
}
WriteLine (sb, rem, x);
return sb.ToString ();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Convert.ToUInt16(string,int32)
/// </summary>
public class ConvertToUInt1617
{
public static int Main()
{
ConvertToUInt1617 convertToUInt1617 = new ConvertToUInt1617();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1617");
if (convertToUInt1617.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt16 from string 1");
try
{
string strVal = "1111";
ushort ushortVal1 = Convert.ToUInt16(strVal, 2);
ushort ushortVal2 = Convert.ToUInt16(strVal, 8);
ushort ushortVal3 = Convert.ToUInt16(strVal, 10);
ushort ushortVal4 = Convert.ToUInt16(strVal, 16);
if (ushortVal1 != (UInt16)(1*Math.Pow(2,3) + 1*Math.Pow(2,2) + 1*Math.Pow(2,1) + 1*Math.Pow(2,0)) ||
ushortVal2 != (UInt16)(1 * Math.Pow(8, 3) + 1 * Math.Pow(8, 2) + 1 * Math.Pow(8, 1) + 1 * Math.Pow(8, 0)) ||
ushortVal3 != (UInt16)(1 * Math.Pow(10, 3) + 1 * Math.Pow(10, 2) + 1 * Math.Pow(10, 1) + 1 * Math.Pow(10, 0)) ||
ushortVal4 != (UInt16)(1 * Math.Pow(16, 3) + 1 * Math.Pow(16, 2) + 1 * Math.Pow(16, 1) + 1 * Math.Pow(16, 0))
)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt16 from string 2");
try
{
int intVal = this.GetInt32(0, (int)UInt16.MaxValue);
string strVal = "+" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, 10);
if (ushortVal != (UInt16)intVal)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt16 from string 3");
try
{
string strVal = null;
ushort ushortVal1 = Convert.ToUInt16(strVal, 2);
ushort ushortVal2 = Convert.ToUInt16(strVal, 8);
ushort ushortVal3 = Convert.ToUInt16(strVal, 10);
ushort ushortVal4 = Convert.ToUInt16(strVal, 16);
if (ushortVal1 != 0 || ushortVal2 != 0 || ushortVal3 != 0 || ushortVal4 != 0)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt16 from string 4");
try
{
string strVal = "0xff";
ushort ushortVal = Convert.ToUInt16(strVal, 16);
if (ushortVal != (UInt16)(15 * Math.Pow(16, 1) + 15 * Math.Pow(16, 0)))
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter of fromBase is not 2, 8, 10, or 16");
try
{
string strVal = "1111";
ushort ushortVal = Convert.ToUInt16(strVal, 100);
TestLibrary.TestFramework.LogError("N001", "the parameter of fromBase is not 2, 8, 10, or 16 but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a non-base 10 signed number and is prefixed with a negative sign");
try
{
string strVal = "-0";
ushort ushortVal = Convert.ToUInt16(strVal, 2);
TestLibrary.TestFramework.LogError("N003", "the string represents a non-base 10 signed number and is prefixed with a negative sign but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string contains a character that is not a valid digit in the base specified by fromBase param 1");
try
{
string strVal = "1234";
ushort ushortVal = Convert.ToUInt16(strVal, 2);
TestLibrary.TestFramework.LogError("N005", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string contains a character that is not a valid digit in the base specified by fromBase param 2");
try
{
string strVal = "9999";
ushort ushortVal = Convert.ToUInt16(strVal, 8);
TestLibrary.TestFramework.LogError("N007", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: the string contains a character that is not a valid digit in the base specified by fromBase param 3");
try
{
string strVal = "abcd";
ushort ushortVal = Convert.ToUInt16(strVal, 10);
TestLibrary.TestFramework.LogError("N009", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: the string contains a character that is not a valid digit in the base specified by fromBase param 4");
try
{
string strVal = "gh";
ushort ushortVal = Convert.ToUInt16(strVal, 16);
TestLibrary.TestFramework.LogError("N011", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: the string represents base 10 number is less than UInt16.minValue");
try
{
int intVal = this.GetInt32(1, Int32.MaxValue);
string strVal = "-" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, 10);
TestLibrary.TestFramework.LogError("N013", "the string represent base 10 number is less than UInt16.minValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N014", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest8: the string represents base 10 number is greater than UInt16.maxValue");
try
{
int intVal = this.GetInt32((int)UInt16.MaxValue + 1, Int32.MaxValue);
string strVal = intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, 10);
TestLibrary.TestFramework.LogError("N015", "the string represent base 10 number is greater than UInt16.maxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N016", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DotVVM.Framework.Compilation.Parser.Binding.Tokenizer;
using DotVVM.Framework.Resources;
namespace DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer
{
/// <summary>
/// Reads the Dothtml content and returns tokens.
/// </summary>
public class DothtmlTokenizer : TokenizerBase<DothtmlToken, DothtmlTokenType>
{
public DothtmlTokenizer() : base(DothtmlTokenType.Text, DothtmlTokenType.WhiteSpace)
{
}
private static bool IsAllowedAttributeFirstChar(char ch)
{
return ch == '_' | ch == '[' | ch == '(';
}
private static bool IsAllowedAttributeChar(char ch)
{
// codegolfing at this point... nvm, this is a fast way to check if small (< 64) integer is in a set
// * create a bit mask for the target set
// - when needed, shift the integer by an offset to make it fit into the 64 bits
// ...would be nice if C# did this optimization automatically, but it doesn't
const int shift = '('; // 40
Debug.Assert(shift - '_' < 64);
const ulong magicBitMask = (1L << ':' - shift | 1L << '_' - shift | 1L << '-' - shift | 1L << '.' - shift | 1L << '[' - shift | 1L << ']' - shift | 1L << '(' - shift | 1L << ')' - shift);
uint c = (uint)ch - shift;
return c < 63 & 0 != ((1UL << (int)c) & magicBitMask);
}
private static bool IsAllowedIdentifierChar(char ch)
{
const int shift = '('; // 40
Debug.Assert(shift - '_' < 64);
const ulong magicBitMask = (1L << ':' - shift | 1L << '_' - shift | 1L << '-' - shift | 1 << '.' - shift);
uint c = (uint)ch - shift;
return c < 63 & 0 != ((1UL << (int)c) & magicBitMask);
}
public override void Tokenize(string sourceText)
{
TokenizeInternal(sourceText, () => { ReadDocument(); return true; });
}
public bool TokenizeBinding(string sourceText, bool usesDoubleBraces = false)
{
return TokenizeInternal(sourceText, () => {
ReadBinding(usesDoubleBraces);
//Finished?
Assert(Peek() == NullChar);
//Properly opened/closed
Assert((Tokens.FirstOrDefault()?.Length ?? 0) > 0);
Assert((Tokens.LastOrDefault()?.Length ?? 0) > 0);
return true;
});
}
/// <summary>
/// Tokenizes whole dothtml document from start to end.
/// </summary>
private void ReadDocument()
{
var directivesAllowed = true;
// read the body
while (Peek() != NullChar)
{
if (Peek() == '@' && directivesAllowed)
{
ReadDirective();
}
else if (Peek() == '<')
{
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.Text);
}
// HTML element
var elementType = ReadElement();
if (elementType != ReadElementType.Comment && elementType != ReadElementType.ServerComment)
{
directivesAllowed = false;
}
}
else if (Peek() == '{')
{
// possible binding
Read();
if (Peek() == '{')
{
if (DistanceSinceLastToken > 1)
{
CreateToken(DothtmlTokenType.Text, 1);
}
// it really is a binding
ReadBinding(true);
}
directivesAllowed = false;
}
else
{
if (!char.IsWhiteSpace(Peek()))
{
directivesAllowed = false;
}
// text content
Read();
}
}
// treat remaining content as text
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.Text);
}
}
private void ReadDirective()
{
if (DistanceSinceLastToken > 0)
{
CreateToken(DothtmlTokenType.WhiteSpace);
}
// the directive started
Read();
CreateToken(DothtmlTokenType.DirectiveStart, "@");
// identifier
if (!ReadIdentifier(DothtmlTokenType.DirectiveName))
{
CreateToken(DothtmlTokenType.DirectiveName, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveNameExpected));
}
SkipWhitespace(false);
// whitespace
if (LastToken!.Type != DothtmlTokenType.WhiteSpace)
{
CreateToken(DothtmlTokenType.WhiteSpace, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveValueExpected));
}
// directive value
if (Peek() == '\r' || Peek() == '\n' || Peek() == NullChar)
{
CreateToken(DothtmlTokenType.DirectiveValue, errorProvider: t => CreateTokenError(t, DothtmlTokenType.DirectiveStart, DothtmlTokenizerErrors.DirectiveValueExpected));
SkipWhitespace();
}
else
{
ReadTextUntilNewLine(DothtmlTokenType.DirectiveValue);
}
}
/// <summary>
/// Reads the identifier.
/// </summary>
private bool ReadIdentifier(DothtmlTokenType tokenType, char stopChar = '\0')
{
var ch = Peek();
// read first character
if ((!char.IsLetter(ch) && ch != '_') | stopChar == ch)
return false;
// read identifier
while ((Char.IsLetterOrDigit(ch) | IsAllowedIdentifierChar(ch)) & stopChar != ch)
{
Read();
ch = Peek();
}
CreateToken(tokenType);
return true;
}
/// <summary>
/// Reads the attribute name.
/// </summary>
private bool ReadAttributeName(DothtmlTokenType tokenType, char stopChar)
{
var ch = Peek();
// read first character
if ((!char.IsLetter(ch) && !IsAllowedAttributeFirstChar(ch)) | stopChar == ch)
return false;
// read identifier
while ((Char.IsLetterOrDigit(ch) | IsAllowedAttributeChar(ch)) & stopChar != ch)
{
Read();
ch = Peek();
}
CreateToken(tokenType);
return true;
}
/// <summary>
/// Reads the element.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private ReadElementType ReadElement(bool wasOpenBraceRead = false)
{
var isClosingTag = false;
if (!wasOpenBraceRead)
{
// open tag brace
Assert(Peek() == '<');
Read();
}
var firstChar = Peek();
if (firstChar == '!' | firstChar == '?' | firstChar == '%')
{
return ReadHtmlSpecial(true);
}
if (!char.IsLetterOrDigit(firstChar) & firstChar != '/' & firstChar != ':')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, "'<' char is not allowed in normal text"));
return ReadElementType.Error;
}
CreateToken(DothtmlTokenType.OpenTag, "<");
if (firstChar == '/')
{
// it is a closing tag
Read();
CreateToken(DothtmlTokenType.Slash, "/");
isClosingTag = true;
}
// read tag name
if (!ReadTagOrAttributeName(isAttributeName: false))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.TagNameExpected));
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError());
return ReadElementType.Error;
}
// read tag attributes
SkipWhitespace();
if (!isClosingTag)
{
while (Peek() != '/' && Peek() != '>')
{
if (Peek() == '<')
{
// comment inside element
Read();
if (Peek() == '!' || Peek() == '%')
{
var c = ReadOneOf("!--", "%--");
if (c == null) CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, ""));
else if (c == "!--") ReadComment();
else if (c == "%--") ReadServerComment();
else throw new Exception();
SkipWhitespace();
}
else
{
CreateToken(DothtmlTokenType.CloseTag, charsFromEndToSkip: 1, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.InvalidCharactersInTag, isCritical: true));
ReadElement(wasOpenBraceRead: true);
return ReadElementType.Error;
}
}
else
if (!ReadAttribute())
{
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.InvalidCharactersInTag, isCritical: true));
return ReadElementType.Error;
}
}
}
if (Peek() == '/' && !isClosingTag)
{
// self closing tag
Read();
CreateToken(DothtmlTokenType.Slash, "/");
}
if (Peek() != '>')
{
// tag is not closed
CreateToken(DothtmlTokenType.CloseTag, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.TagNotClosed));
return ReadElementType.Error;
}
Read();
CreateToken(DothtmlTokenType.CloseTag, ">");
return ReadElementType.ValidTag;
}
public enum ReadElementType
{
Error,
ValidTag,
CData,
Comment,
Doctype,
XmlProcessingInstruction,
ServerComment
}
public ReadElementType ReadHtmlSpecial(bool openBraceConsumed = false)
{
var s = ReadOneOf("![CDATA[", "!--", "!DOCTYPE", "?", "%--");
if (s == "![CDATA[")
{
return ReadCData();
}
else if (s == "!--")
{
return ReadComment();
}
else if (s == "%--")
{
return ReadServerComment();
}
else if (s == "!DOCTYPE")
{
return ReadDoctype();
}
else if (s == "?")
{
return ReadXmlPI();
}
return ReadElementType.Error;
}
private ReadElementType ReadCData()
{
CreateToken(DothtmlTokenType.OpenCData);
if (ReadTextUntil(DothtmlTokenType.CDataBody, "]]>", false))
{
CreateToken(DothtmlTokenType.CloseCData);
return ReadElementType.CData;
}
else
{
CreateToken(DothtmlTokenType.CDataBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseCData, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenCData, DothtmlTokenizerErrors.CDataNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadComment()
{
CreateToken(DothtmlTokenType.OpenComment, "<!--");
if (ReadTextUntil(DothtmlTokenType.CommentBody, "-->", false))
{
CreateToken(DothtmlTokenType.CloseComment, "-->");
return ReadElementType.Comment;
}
else
{
CreateToken(DothtmlTokenType.CommentBody);
CreateToken(DothtmlTokenType.CloseComment, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenComment, DothtmlTokenizerErrors.CommentNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadServerComment()
{
CreateToken(DothtmlTokenType.OpenServerComment, "<%--");
if (ReadTextUntil(DothtmlTokenType.CommentBody, "--%>", false, nestString: "<%--"))
{
CreateToken(DothtmlTokenType.CloseComment, "--%>");
return ReadElementType.ServerComment;
}
else
{
CreateToken(DothtmlTokenType.CommentBody);
CreateToken(DothtmlTokenType.CloseComment, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenComment, DothtmlTokenizerErrors.CommentNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadDoctype()
{
CreateToken(DothtmlTokenType.OpenDoctype);
if (ReadTextUntil(DothtmlTokenType.DoctypeBody, ">", true))
{
CreateToken(DothtmlTokenType.CloseDoctype);
return ReadElementType.Doctype;
}
else
{
CreateToken(DothtmlTokenType.DoctypeBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseDoctype, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenDoctype, DothtmlTokenizerErrors.DoctypeNotClosed));
return ReadElementType.Error;
}
}
private ReadElementType ReadXmlPI()
{
CreateToken(DothtmlTokenType.OpenXmlProcessingInstruction);
if (ReadTextUntil(DothtmlTokenType.XmlProcessingInstructionBody, "?>", true))
{
CreateToken(DothtmlTokenType.CloseXmlProcessingInstruction);
return ReadElementType.XmlProcessingInstruction;
}
else
{
CreateToken(DothtmlTokenType.XmlProcessingInstructionBody, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseXmlProcessingInstruction, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenXmlProcessingInstruction, DothtmlTokenizerErrors.XmlProcessingInstructionNotClosed));
return ReadElementType.Error;
}
}
private void Assert(bool expression)
{
if (!expression)
{
throw new Exception("Assertion failed!");
}
}
/// <summary>
/// Reads the name of the tag or attribute.
/// </summary>
private bool ReadTagOrAttributeName(bool isAttributeName)
{
var readIdentifierFunc = isAttributeName ? (Func<DothtmlTokenType, char, bool>)ReadAttributeName : (Func<DothtmlTokenType, char, bool>)ReadIdentifier;
if (Peek() != ':')
{
// read the identifier
if (!readIdentifierFunc(DothtmlTokenType.Text, ':'))
{
return false;
}
}
else
{
// missing tag prefix
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.MissingTagPrefix));
}
if (Peek() == ':')
{
Read();
CreateToken(DothtmlTokenType.Colon, ":");
if (!readIdentifierFunc(DothtmlTokenType.Text, '\0'))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenTag, DothtmlTokenizerErrors.MissingTagName));
return true;
}
}
SkipWhitespace();
return true;
}
/// <summary>
/// Reads the attribute of a tag.
/// </summary>
private bool ReadAttribute()
{
// attribute name
if (!ReadTagOrAttributeName(isAttributeName: true))
{
return false;
}
if (Peek() == '=')
{
// equals sign
Read();
CreateToken(DothtmlTokenType.Equals, "=");
SkipWhitespace();
// attribute value
if (Peek() == '\'' || Peek() == '"')
{
// single or double quotes
if (!ReadQuotedAttributeValue())
{
return false;
}
}
else
{
// unquoted value
if (!ReadUnquotedAttributeValue())
return false;
SkipWhitespace();
}
}
return true;
}
public bool ReadUnquotedAttributeValue()
{
if (Peek() == '{')
{
ReadBinding(false);
}
else
{
while (!char.IsWhiteSpace(Peek()) && Peek() != '/' && Peek() != '>')
{
if (Peek() == NullChar || Peek() == '<')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError());
return false;
}
Read();
}
if (DistanceSinceLastToken == 0)
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.Text, DothtmlTokenizerErrors.MissingAttributeValue));
return false;
}
CreateToken(DothtmlTokenType.Text);
}
return true;
}
/// <summary>
/// Reads the quoted attribute value.
/// </summary>
private bool ReadQuotedAttributeValue()
{
// read the beginning quotes
var quotes = Peek();
var quotesToken = quotes == '\'' ? DothtmlTokenType.SingleQuote : DothtmlTokenType.DoubleQuote;
Read();
CreateToken(quotesToken, quotesToken == DothtmlTokenType.SingleQuote ? "'" : "\"");
// read value
if (Peek() == '{')
{
// binding
ReadBinding(false);
}
else
{
// read text
while (Peek() != quotes)
{
var ch = Peek();
if (ch == NullChar || ch == '<' || ch == '>')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError());
CreateToken(quotesToken, errorProvider: t => CreateTokenError(t, quotesToken, DothtmlTokenizerErrors.AttributeValueNotClosed));
return false;
}
Read();
}
CreateToken(DothtmlTokenType.Text);
}
// read the ending quotes
if (Peek() != quotes)
{
CreateToken(quotesToken, errorProvider: t => CreateTokenError(t, quotesToken, DothtmlTokenizerErrors.AttributeValueNotClosed));
}
else
{
Read();
CreateToken(quotesToken, quotesToken == DothtmlTokenType.SingleQuote ? "'" : "\"");
SkipWhitespace();
}
return true;
}
/// <summary>
/// Reads the binding.
/// </summary>
private void ReadBinding(bool doubleCloseBrace)
{
// read open brace
Assert(Peek() == '{');
Read();
if (!doubleCloseBrace && Peek() == '{')
{
doubleCloseBrace = true;
Read();
}
CreateToken(DothtmlTokenType.OpenBinding, doubleCloseBrace ? "{{" : "{");
SkipWhitespace();
// read binding name
if (!ReadIdentifier(DothtmlTokenType.Text, ':'))
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
SkipWhitespace();
}
// colon
if (Peek() != ':')
{
CreateToken(DothtmlTokenType.Colon, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
Read();
CreateToken(DothtmlTokenType.Colon);
SkipWhitespace();
}
// binding value
if (Peek() == '}')
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingInvalidFormat));
}
else
{
char ch;
while ((ch = Peek()) != '}')
{
if (ch == '\'' || ch == '"')
{
// string literal - ignore curly braces inside
BindingTokenizer.ReadStringLiteral(Peek, Read, out _);
}
else if (ch == NullChar)
{
CreateToken(DothtmlTokenType.Text, errorProvider: t => CreateTokenError());
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingNotClosed));
return;
}
else
{
Read();
}
}
CreateToken(DothtmlTokenType.Text);
}
// close brace
if (Peek() != '}')
{
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.BindingNotClosed));
return;
}
Read();
if (doubleCloseBrace)
{
if (Peek() != '}')
{
CreateToken(DothtmlTokenType.CloseBinding, errorProvider: t => CreateTokenError(t, DothtmlTokenType.OpenBinding, DothtmlTokenizerErrors.DoubleBraceBindingNotClosed));
return;
}
Read();
}
CreateToken(DothtmlTokenType.CloseBinding, doubleCloseBrace ? "}}" : "}");
}
protected override DothtmlToken NewToken(string text, DothtmlTokenType type, int lineNumber, int columnNumber, int length, int startPosition)
{
return new DothtmlToken(text, type, lineNumber, columnNumber, length, startPosition);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace KaoriStudio.Tests.Collections.Generic
{
/// <summary>
/// Unit tests for the System.Collections.Generic.IDictionary interface
/// </summary>
/// <typeparam name="TKey">The key type</typeparam>
/// <typeparam name="TValue">The value type</typeparam>
public abstract class IDictionaryTest<TKey, TValue> : ICollectionTest<KeyValuePair<TKey, TValue>>
{
/// <summary>
/// Generate an IDictionary to test
/// </summary>
/// <param name="items">The items to populate the dictionary</param>
/// <returns>A dictionary with the items</returns>
protected abstract IDictionary<TKey, TValue> GenerateIDictionary(IEnumerable<KeyValuePair<TKey, TValue>> items);
/// <summary>
/// Generate an ICollection to test
/// </summary>
/// <param name="items">The items to populate the collection</param>
/// <returns>A collection with the items</returns>
protected override ICollection<KeyValuePair<TKey, TValue>> GenerateICollection(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return GenerateIDictionary(items);
}
private IDictionary<TKey, TValue> GenerateEmpty()
{
return GenerateIDictionary(Enumerable.Empty<KeyValuePair<TKey, TValue>>());
}
private void SkipReadOnly(IDictionary<TKey, TValue> collection)
{
if (collection.IsReadOnly)
Assert.Ignore("Not applicable to read-only dictionary");
}
/// <summary>
/// Tests the Item get property
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ItemGet(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
var blank = GenerateEmpty();
foreach (var item in items)
{
Assert.AreEqual(item.Value, collection[item.Key], "Item get property must return value equal to the one entered");
Assert.Catch<KeyNotFoundException>(() =>
{
var value = blank[item.Key];
}, "Item get property must throw KeyNotFoundException if the key does not exist");
}
}
/// <summary>
/// Tests the Item set property
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ItemSet(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
if (collection.IsReadOnly)
{
foreach (var item in items)
Assert.Catch<NotSupportedException>(() => collection[item.Key] = item.Value,
"Read-only dictionary must throw NotSupportedException when attempting to set item");
}
}
/// <summary>
/// Tests the Item set property with a null key
/// </summary>
[Test]
public virtual void ItemSetNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
Assert.Catch<ArgumentNullException>(() => collection[default(TKey)] = default(TValue),
"Item set property must throw ArgumentNullException if the key is null");
}
/// <summary>
/// Tests the Item get property with a null key
/// </summary>
[Test]
public virtual void ItemGetNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
Assert.Catch<ArgumentNullException>(() =>
{
var v = collection[default(TKey)];
},
"Item get property must throw ArgumentNullException if the key is null");
}
/// <summary>
/// Tests the Item set property and verifies it with the Item get property
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ItemSetAndGet(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateEmpty();
SkipReadOnly(collection);
foreach (var item in items)
{
collection[item.Key] = item.Value;
Assert.AreEqual(item.Value, collection[item.Key], "Item get property must return a value equal to the one entered with Item set");
}
}
/// <summary>
/// Tests the Item set property and verifies it with the Count property
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ItemSetAndCount(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateEmpty();
SkipReadOnly(collection);
int count = 0;
foreach (var item in items)
{
collection[item.Key] = item.Value;
count++;
Assert.AreEqual(count, collection.Count, "Count must increase as items are added with Item set");
}
}
/// <summary>
/// Tests the Add(TKey, TValue) method with a null key
/// </summary>
[Test]
public virtual void AddKVNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
Assert.Catch<ArgumentNullException>(() => collection.Add(default(TKey), default(TValue)),
"Add(TKey, TValue) method must throw ArgumentNullException if the key is null");
}
/// <summary>
/// Tests the Add(TKey, TValue) method with duplicate keys
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void AddKVDuplicate(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
SkipReadOnly(collection);
foreach (var item in items)
Assert.Catch<ArgumentException>(() => collection.Add(item.Key, item.Value),
"Add(TKey, TValue) method must throw an ArgumentException if the key already exists in the dictionary");
}
/// <summary>
/// Tests the Add method with duplicate keys
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void AddDuplicate(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
SkipReadOnly(collection);
foreach (var item in items)
Assert.Catch<ArgumentException>(() => collection.Add(item),
"Add method must throw an ArgumentException if the key already exists in the dictionary");
}
/// <summary>
/// Tests the Add(TKey, TValue) method and verifies it with the Contains method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void AddKVAndContains(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateEmpty();
SkipReadOnly(collection);
foreach (var item in items)
{
collection.Add(item.Key, item.Value);
Assert.IsTrue(collection.Contains(item), "Items added must be found with Contains");
}
}
/// <summary>
/// Tests the Add(TKey, TValue) meathod and verifies it with the ContainsKey method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void AddKVAndContainsKey(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateEmpty();
SkipReadOnly(collection);
foreach (var item in items)
{
collection.Add(item.Key, item.Value);
Assert.IsTrue(collection.ContainsKey(item.Key), "Items added must be found with ContainsKey");
}
}
/// <summary>
/// Tests the ContainsKey method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ContainsKey(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
foreach (var item in items)
Assert.IsTrue(collection.ContainsKey(item.Key), "ContainsKey must return true for items in the dictionary");
}
/// <summary>
/// Tests the ContainsKey method with a null key
/// </summary>
[Test]
public virtual void ContainsKeyNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
{
Assert.Catch<ArgumentNullException>(() =>
{
var v = collection.ContainsKey(default(TKey));
}, "ContainsKey must throw an ArgumentNullException if the key is null");
}
}
/// <summary>
/// Tests the Remove(TKey) method with a null key
/// </summary>
[Test]
public virtual void RemoveKNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
Assert.Catch<ArgumentNullException>(() => collection.Remove(default(TKey)),
"Remove(TKey) must throw an ArgumentNullException if the key is null");
}
/// <summary>
/// Tests the Remove(TKey) method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void RemoveK(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
var blank = GenerateEmpty();
if (collection.IsReadOnly)
{
foreach (var item in items)
Assert.Catch<NotSupportedException>(() => collection.Remove(item.Key),
"Read-only dictionary must throw a NotSupportedException when Remove(TKey) is called");
}
else
{
foreach (var item in items)
{
Assert.IsTrue(collection.Remove(item.Key), "Remove(TKey) must return true for a key in the dictionary");
Assert.IsFalse(blank.Remove(item.Key), "Remove(TKey) must return false for a key not in the dictionary");
}
}
}
/// <summary>
/// Tests the Remove(TKey) method and verifies it with the Contains method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void RemoveKAndContains(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
SkipReadOnly(collection);
foreach (var item in items)
{
collection.Remove(item.Key);
Assert.IsFalse(collection.Contains(item), "Contains method must return false for an item removed by the Remove(TKey) method");
}
}
/// <summary>
/// Tests the Remove(TKey) method and verifies it with the ContainsKey method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void RemoveKAndContainsKey(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
SkipReadOnly(collection);
foreach (var item in items)
{
collection.Remove(item.Key);
Assert.IsFalse(collection.ContainsKey(item.Key), "ContainsKey method must return false for an item removed by the Remove(TKey) method");
}
}
/// <summary>
/// Tests the Remove(TKey) method and verifies it with the Count property
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void RemoveKAndCount(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
SkipReadOnly(collection);
int count = collection.Count;
foreach (var item in items)
{
collection.Remove(item.Key);
count--;
Assert.AreEqual(count, collection.Count, "Count property must decrease when an item is removed by the Remove(TKey) method");
}
}
/// <summary>
/// Tests the TryGetValue method with a null key
/// </summary>
[Test]
public virtual void TryGetValueNull()
{
var collection = GenerateEmpty();
if (!typeof(TKey).IsValueType)
{
Assert.Catch<ArgumentNullException>(() =>
{
TValue value;
collection.TryGetValue(default(TKey), out value);
}, "TryGetValue method must throw an ArgumentNullException if the key is null");
}
}
/// <summary>
/// Tests the TryGetValue method
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void TryGetValue(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
var blank = GenerateEmpty();
foreach (var item in items)
{
TValue value;
Assert.IsTrue(collection.TryGetValue(item.Key, out value), "TryGetValue must return true for an item that exists");
Assert.AreEqual(item.Value, value, "TryGetValue must put the item value into the passed output");
Assert.IsFalse(blank.TryGetValue(item.Key, out value), "TryGetValue must return false for an item that does not exist");
Assert.AreEqual(default(TValue), value, "TryGetValue must put default(TValue) into the passed output for a non-existent key");
}
}
/// <summary>
/// Tests the Keys property and Values property are in the same order
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void KeysValuesOrder(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
var array = items.ToArray();
using (var keysEnumerator = collection.Keys.GetEnumerator())
using (var valuesEnumerator = collection.Values.GetEnumerator())
{
while (keysEnumerator.MoveNext() && valuesEnumerator.MoveNext())
{
Assert.IsTrue(array.Contains(new KeyValuePair<TKey, TValue>(keysEnumerator.Current, valuesEnumerator.Current)),
"The dictionary must contain the pairs generated by reading the Keys property and Values property in order");
}
}
}
/// <summary>
/// Tests the Keys property and verifies it has the same Count as the dictionary
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void KeysCount(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
Assert.AreEqual(collection.Count, collection.Keys.Count, "The Keys property must have the same Count as the dictionary");
}
/// <summary>
/// Tests the Values property and verifies it has the same Count as the dictionary
/// </summary>
/// <param name="items">The items to test</param>
[Test]
public virtual void ValuesCount(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
Assert.AreEqual(collection.Count, collection.Values.Count, "The Values property must have the same Count as the dictionary");
}
/// <summary>
/// Tests the Keys property and verifies its contents with the ContainsKey method
/// </summary>
/// <param name="items">The items to add</param>
[Test]
public virtual void KeysAndContainsKey(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var collection = GenerateIDictionary(items);
var ckeys = collection.Keys;
foreach (var item in items)
Assert.IsTrue(ckeys.Contains(item.Key), "The Keys property must contain each key in the dictionary");
}
}
}
| |
// 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;
namespace System.Text
{
// ASCIIEncoding
//
// Note that ASCIIEncoding is optomized with no best fit and ? for fallback.
// It doesn't come in other flavors.
//
// Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit).
//
// Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd
// use fallbacks, and we cannot guarantee that fallbacks are normalized.
//
[System.Runtime.InteropServices.ComVisible(true)]
public class ASCIIEncoding : Encoding
{
// Used by Encoding.ASCII for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly ASCIIEncoding s_default = new ASCIIEncoding();
public ASCIIEncoding() : base(Encoding.CodePageASCII)
{
}
internal override void SetDefaultFallbacks()
{
// For ASCIIEncoding we just use default replacement fallback
this.encoderFallback = EncoderFallback.ReplacementFallback;
this.decoderFallback = DecoderFallback.ReplacementFallback;
}
// WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...)
// WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted,
// WARNING: or it'll break VB's way of calling these.
// NOTE: Many methods in this class forward to EncodingForwarder for
// validating arguments/wrapping the unsafe methods in this class
// which do the actual work. That class contains
// shared logic for doing this which is used by
// ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
// UTF7Encoding, and UTF8Encoding.
// The reason the code is separated out into a static class, rather
// than a base class which overrides all of these methods for us
// (which is what EncodingNLS is for internal Encodings) is because
// that's really more of an implementation detail so it's internal.
// At the same time, C# doesn't allow a public class subclassing an
// internal/private one, so we end up having to re-override these
// methods in all of the public Encodings + EncodingNLS.
// Returns the number of bytes required to encode a range of characters in
// a character array.
public override int GetByteCount(char[] chars, int index, int count)
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
public override int GetByteCount(String chars)
{
return EncodingForwarder.GetByteCount(this, chars);
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
public override int GetBytes(String chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
public override String GetString(byte[] bytes, int byteIndex, int byteCount)
{
return EncodingForwarder.GetString(this, bytes, byteIndex, byteCount);
}
// End of overridden methods which use EncodingForwarder
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// Start by assuming default count, then +/- for fallback characters
char* charEnd = chars + charCount;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
}
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
// if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
// throw new ArgumentException(SR.FormatSR.Argument_EncoderFallbackNotEmpty,
// this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// If we have an encoder AND we aren't using default fallback,
// then we may have a complicated count.
if (fallback != null && fallback.MaxCharCount == 1)
{
// Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
// same as input size.
// Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
// We could however have 1 extra byte if the last call had an encoder and a funky fallback and
// if we don't use the funky fallback this time.
// Do we have an extra char left over from last time?
if (charLeftOver > 0)
charCount++;
return (charCount);
}
// Count is more complicated if you have a funky fallback
// For fallback we may need a fallback buffer, we know we're not default fallback
int byteCount = 0;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// no chars >= 0x80 are allowed.
if (ch > 0x7f)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
}
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
byte* byteStart = bytes;
char* charStart = chars;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
// encoder.FallbackBuffer.Remaining > 0)
// throw new ArgumentException(SR.FormatSR.Argument_EncoderFallbackNotEmpty,
// this.EncodingName, encoder.Fallback.GetType()));
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// See if we do the fast default or slightly slower fallback
if (fallback != null && fallback.MaxCharCount == 1)
{
// Fast version
char cReplacement = fallback.DefaultString[0];
// Check for replacements in range, otherwise fall back to slow version.
if (cReplacement <= (char)0x7f)
{
// We should have exactly as many output bytes as input bytes, unless there's a left
// over character, in which case we may need one more.
// If we had a left over character will have to add a ? (This happens if they had a funky
// fallback last time, but not this time.) (We can't spit any out though
// because with fallback encoder each surrogate is treated as a seperate code point)
if (charLeftOver > 0)
{
// Have to have room
// Throw even if doing no throw version because this is just 1 char,
// so buffer will never be big enough
if (byteCount == 0)
ThrowBytesOverflow(encoder, true);
// This'll make sure we still have more room and also make sure our return value is correct.
*(bytes++) = (byte)cReplacement;
byteCount--; // We used one of the ones we were counting.
}
// This keeps us from overrunning our output buffer
if (byteCount < charCount)
{
// Throw or make buffer smaller?
ThrowBytesOverflow(encoder, byteCount < 1);
// Just use what we can
charEnd = chars + byteCount;
}
// We just do a quick copy
while (chars < charEnd)
{
char ch2 = *(chars++);
if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement;
else *(bytes++) = unchecked((byte)(ch2));
}
// Clear encoder
if (encoder != null)
{
encoder.charLeftOver = (char)0;
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
}
// Slower version, have to do real fallback.
// prepare our end
byte* byteEnd = bytes + byteCount;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
// Initialize the buffer
Contract.Assert(encoder != null,
"[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// All characters >= 0x80 must fall back.
if (ch > 0x7f)
{
// Initialize the buffer
if (fallbackBuffer == null)
{
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Go ahead & continue (& do the fallback)
continue;
}
// We'll use this one
// Bounds check
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
Contract.Assert(chars > charStart || bytes == byteStart,
"[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious();
// Are we throwing or using buffer?
ThrowBytesOverflow(encoder, bytes == byteStart); // throw?
break; // don't throw, stop
}
// Go ahead and add it
*bytes = unchecked((byte)ch);
bytes++;
}
// Need to do encoder stuff
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
(encoder != null && !encoder.m_throwOnOverflow),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have a decoder fallback.
return count;
}
// Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII
DecoderFallbackBuffer fallbackBuffer = null;
// Have to do it the hard way.
// Assume charCount will be == count
int charCount = count;
byte[] byteBuffer = new byte[1];
// Do it our fast way
byte* byteEnd = bytes + count;
// Quick loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *bytes;
bytes++;
// If unknown we have to do fallback count
if (b >= 0x80)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - count, null);
}
// Use fallback buffer
byteBuffer[0] = b;
charCount--; // Have to unreserve the one we already allocated for b
charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
}
}
// Fallback buffer must be empty
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
// Converted sequence is same length as input
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
// Do it fast way if using ? replacement fallback
byte* byteEnd = bytes + byteCount;
byte* byteStart = bytes;
char* charStart = chars;
// Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f
// Only need decoder fallback buffer if not using ? fallback.
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Try it the fast way
char replacementChar = fallback.DefaultString[0];
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
{
// Need at least 1 output byte, throw if must throw
ThrowCharsOverflow(decoder, charCount < 1);
// Not throwing, use what we can
byteEnd = bytes + charCount;
}
// Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
while (bytes < byteEnd)
{
byte b = *(bytes++);
if (b >= 0x80)
// This is an invalid byte in the ASCII encoding.
*(chars++) = replacementChar;
else
*(chars++) = unchecked((char)b);
}
// bytes & chars used are the same
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
return (int)(chars - charStart);
}
// Slower way's going to need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
byte[] byteBuffer = new byte[1];
char* charEnd = chars + charCount;
// Not quite so fast loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *(bytes);
bytes++;
if (b >= 0x80)
{
// This is an invalid byte in the ASCII encoding.
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Use fallback buffer
byteBuffer[0] = b;
// Note that chars won't get updated unless this succeeds
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
Contract.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
bytes--; // unused byte
fallbackBuffer.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Make sure we have buffer space
if (chars >= charEnd)
{
Contract.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
*(chars) = unchecked((char)b);
chars++;
}
}
// Might have had decoder fallback stuff.
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
long charCount = (long)byteCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
[System.Runtime.InteropServices.ComVisible(false)]
public override bool IsSingleByte
{
get
{
return true;
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcicv = Google.Cloud.Iam.Credentials.V1;
using sys = System;
namespace Google.Cloud.Iam.Credentials.V1
{
/// <summary>Resource name for the <c>ServiceAccount</c> resource.</summary>
public sealed partial class ServiceAccountName : gax::IResourceName, sys::IEquatable<ServiceAccountName>
{
/// <summary>The possible contents of <see cref="ServiceAccountName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </summary>
ProjectServiceAccount = 1,
}
private static gax::PathTemplate s_projectServiceAccount = new gax::PathTemplate("projects/{project}/serviceAccounts/{service_account}");
/// <summary>Creates a <see cref="ServiceAccountName"/> 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="ServiceAccountName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceAccountName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceAccountName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ServiceAccountName"/> with the pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceAccountName"/> constructed from the provided ids.</returns>
public static ServiceAccountName FromProjectServiceAccount(string projectId, string serviceAccountId) =>
new ServiceAccountName(ResourceNameType.ProjectServiceAccount, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceAccountName"/> with pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceAccountName"/> with pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </returns>
public static string Format(string projectId, string serviceAccountId) =>
FormatProjectServiceAccount(projectId, serviceAccountId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceAccountName"/> with pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceAccountName"/> with pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>.
/// </returns>
public static string FormatProjectServiceAccount(string projectId, string serviceAccountId) =>
s_projectServiceAccount.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item>
/// </list>
/// </remarks>
/// <param name="serviceAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceAccountName"/> if successful.</returns>
public static ServiceAccountName Parse(string serviceAccountName) => Parse(serviceAccountName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceAccountName">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="ServiceAccountName"/> if successful.</returns>
public static ServiceAccountName Parse(string serviceAccountName, bool allowUnparsed) =>
TryParse(serviceAccountName, allowUnparsed, out ServiceAccountName 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="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item>
/// </list>
/// </remarks>
/// <param name="serviceAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceAccountName"/>, 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 serviceAccountName, out ServiceAccountName result) =>
TryParse(serviceAccountName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceAccountName"/> 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}/serviceAccounts/{service_account}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceAccountName">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="ServiceAccountName"/>, 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 serviceAccountName, bool allowUnparsed, out ServiceAccountName result)
{
gax::GaxPreconditions.CheckNotNull(serviceAccountName, nameof(serviceAccountName));
gax::TemplatedResourceName resourceName;
if (s_projectServiceAccount.TryParseName(serviceAccountName, out resourceName))
{
result = FromProjectServiceAccount(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceAccountName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceAccountName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string serviceAccountId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
ServiceAccountId = serviceAccountId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceAccountName"/> class from the component parts of pattern
/// <c>projects/{project}/serviceAccounts/{service_account}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceAccountId">The <c>ServiceAccount</c> ID. Must not be <c>null</c> or empty.</param>
public ServiceAccountName(string projectId, string serviceAccountId) : this(ResourceNameType.ProjectServiceAccount, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceAccountId, nameof(serviceAccountId)))
{
}
/// <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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>ServiceAccount</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ServiceAccountId { 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.ProjectServiceAccount: return s_projectServiceAccount.Expand(ProjectId, ServiceAccountId);
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 ServiceAccountName);
/// <inheritdoc/>
public bool Equals(ServiceAccountName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceAccountName a, ServiceAccountName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceAccountName a, ServiceAccountName b) => !(a == b);
}
public partial class GenerateAccessTokenRequest
{
/// <summary>
/// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcicv::ServiceAccountName ServiceAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SignBlobRequest
{
/// <summary>
/// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcicv::ServiceAccountName ServiceAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SignJwtRequest
{
/// <summary>
/// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcicv::ServiceAccountName ServiceAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GenerateIdTokenRequest
{
/// <summary>
/// <see cref="gcicv::ServiceAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcicv::ServiceAccountName ServiceAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gcicv::ServiceAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using LumiSoft.Net.SIP.Message;
namespace LumiSoft.Net.SIP.Stack
{
/// <summary>
/// This is base class for SIP client and server transaction.
/// </summary>
public abstract class SIP_Transaction : IDisposable
{
private SIP_TransactionState m_State;
private SIP_Stack m_pStack = null;
private SIP_Flow m_pFlow = null;
private SIP_Request m_pRequest = null;
private string m_Method = "";
private string m_ID = "";
private string m_Key = "";
private DateTime m_CreateTime;
private List<SIP_Response> m_pResponses = null;
private object m_pTag = null;
private object m_pLock = new object();
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stack">Owner SIP stack.</param>
/// <param name="flow">Transaction data flow.</param>
/// <param name="request">SIP request that transaction will handle.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception>
public SIP_Transaction(SIP_Stack stack,SIP_Flow flow,SIP_Request request)
{
if(stack == null){
throw new ArgumentNullException("stack");
}
if(flow == null){
throw new ArgumentNullException("flow");
}
if(request == null){
throw new ArgumentNullException("request");
}
m_pStack = stack;
m_pFlow = flow;
m_pRequest = request;
m_Method = request.RequestLine.Method;
m_CreateTime = DateTime.Now;
m_pResponses = new List<SIP_Response>();
// Validate Via:
SIP_t_ViaParm via = request.Via.GetTopMostValue();
if(via == null){
throw new ArgumentException("Via: header is missing !");
}
if(via.Branch == null){
throw new ArgumentException("Via: header 'branch' parameter is missing !");
}
m_ID = via.Branch;
if(this is SIP_ServerTransaction){
/*
We use branch and sent-by as indexing key for transaction, the only special what we need to
do is to handle CANCEL, because it has same branch as transaction to be canceled.
For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key.
ACK has also same branch, but we won't do transaction for ACK, so it isn't problem.
*/
string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy;
if(request.RequestLine.Method == SIP_Methods.CANCEL){
key += "-CANCEL";
}
m_Key = key;
}
else{
m_Key = m_ID + "-" + request.RequestLine.Method;
}
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public virtual void Dispose()
{
SetState(SIP_TransactionState.Disposed);
OnDisposed();
m_pStack = null;
m_pFlow = null;
m_pRequest = null;
this.StateChanged = null;
this.Disposed = null;
this.TimedOut = null;
this.TransportError = null;
}
#endregion
#region method Cancel
/// <summary>
/// Cancels current transaction.
/// </summary>
public abstract void Cancel();
#endregion
#region method SetState
/// <summary>
/// Changes transaction state.
/// </summary>
/// <param name="state">New transaction state.</param>
protected void SetState(SIP_TransactionState state)
{
// Log
if(this.Stack.Logger != null){
this.Stack.Logger.AddText(this.ID,"Transaction [branch='" + this.ID + "';method='" + this.Method + "';IsServer=" + (this is SIP_ServerTransaction) + "] swtiched to '" + state.ToString() + "' state.");
}
m_State = state;
OnStateChanged();
if(m_State == SIP_TransactionState.Terminated){
Dispose();
}
}
#endregion
#region method AddResponse
/// <summary>
/// Adds specified response to transaction responses collection.
/// </summary>
/// <param name="response">SIP response.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception>
protected void AddResponse(SIP_Response response)
{
if(response == null){
throw new ArgumentNullException("response");
}
// Don't store more than 15 responses, otherwise hacker may try todo buffer overrun with provisional responses.
if(m_pResponses.Count < 15 || response.StatusCode >= 200){
m_pResponses.Add(response);
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets an object that can be used to synchronize access to the dialog.
/// </summary>
public object SyncRoot
{
get{ return m_pLock; }
}
/// <summary>
/// Gets if transaction is disposed.
/// </summary>
public bool IsDisposed
{
get{ return m_State == SIP_TransactionState.Disposed; }
}
/// <summary>
/// Gets current transaction state.
/// </summary>
public SIP_TransactionState State
{
get{ return m_State; }
}
/// <summary>
/// Gets owner SIP stack.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Stack Stack
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pStack;
}
}
/// <summary>
/// Gets transaction data flow.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Flow Flow
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pFlow;
}
}
/// <summary>
/// Gets SIP request what caused this transaction creation.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Request Request
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pRequest;
}
}
/// <summary>
/// Gets request method that transaction handles.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string Method
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_Method;
}
}
/// <summary>
/// Gets transaction ID (Via: branch parameter value).
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public string ID
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_ID;
}
}
/// <summary>
/// Gets time when this transaction was created.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public DateTime CreateTime
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_CreateTime;
}
}
/// <summary>
/// Gets transaction processed responses.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Response[] Responses
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pResponses.ToArray();
}
}
/// <summary>
/// Gets transaction final(1xx) response from responses collection. Returns null if no provisional responses.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Response LastProvisionalResponse
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
for(int i=this.Responses.Length - 1;i>-1;i--){
if(this.Responses[i].StatusCodeType == SIP_StatusCodeType.Provisional){
return this.Responses[i];
}
}
return null;
}
}
/// <summary>
/// Gets transaction final(2xx - 699) response from responses collection. Returns null if no final responses.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public SIP_Response FinalResponse
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
foreach(SIP_Response response in this.Responses){
if(response.StatusCodeType != SIP_StatusCodeType.Provisional){
return response;
}
}
return null;
}
}
/// <summary>
/// Gets if transaction has any provisional(1xx) in responses collection.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this property is accessed.</exception>
public bool HasProvisionalResponse
{
get{
if(this.State == SIP_TransactionState.Disposed){
throw new ObjectDisposedException(this.GetType().Name);
}
foreach(SIP_Response response in m_pResponses){
if(response.StatusCodeType == SIP_StatusCodeType.Provisional){
return true;
}
}
return false;
}
}
/// <summary>
/// Gets transaction related SIP dialog. Returns null if no dialog available.
/// </summary>
public SIP_Dialog Dialog
{
// FIX ME:
get{ return null; }
}
/// <summary>
/// Gets or sets user data.
/// </summary>
public object Tag
{
get{ return m_pTag; }
set{ m_pTag = value; }
}
/// <summary>
/// Gets transaction indexing key.
/// </summary>
internal string Key
{
get{ return m_Key; }
}
#endregion
#region Events Implementation
/// <summary>
/// Is raised when transaction state has changed.
/// </summary>
public event EventHandler StateChanged = null;
#region method OnStateChanged
/// <summary>
/// Raises event <b>StateChanged</b>.
/// </summary>
private void OnStateChanged()
{
if(this.StateChanged != null){
this.StateChanged(this,new EventArgs());
}
}
#endregion
/// <summary>
/// Is raised when transaction is disposed.
/// </summary>
public event EventHandler Disposed = null;
#region method OnDisposed
/// <summary>
/// Raises event <b>Disposed</b>.
/// </summary>
protected void OnDisposed()
{
if(this.Disposed != null){
this.Disposed(this,new EventArgs());
}
}
#endregion
/// <summary>
/// Is raised if transaction is timed out.
/// </summary>
public event EventHandler TimedOut = null;
#region method OnTimedOut
/// <summary>
/// Raises TimedOut event.
/// </summary>
protected void OnTimedOut()
{
if(this.TimedOut != null){
this.TimedOut(this,new EventArgs());
}
}
#endregion
/// <summary>
/// Is raised when there is transport error.
/// </summary>
public event EventHandler<ExceptionEventArgs> TransportError = null;
#region method TransportError
/// <summary>
/// Raises TimedOut event.
/// </summary>
/// <param name="exception">Transport exception.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>exception</b> is null reference.</exception>
protected void OnTransportError(Exception exception)
{
if(exception == null){
throw new ArgumentNullException("exception");
}
if(this.TransportError != null){
this.TransportError(this,new ExceptionEventArgs(exception));
}
}
#endregion
/// <summary>
/// Is raised when there is transaction error. For example this is raised when server transaction never
/// gets ACK.
/// </summary>
public event EventHandler TransactionError = null;
#region method OnTransactionError
/// <summary>
/// Raises TransactionError event.
/// </summary>
/// <param name="errorText">Text describing error.</param>
protected void OnTransactionError(string errorText)
{
if(this.TransactionError != null){
this.TransactionError(this,new EventArgs());
}
}
#endregion
#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.
#if WINDOWS
using System.Linq;
using Microsoft.Xunit.Performance.Sdk;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
/// <summary>
/// This file contains a number of GC-related metrics that are provided to xunit-performance.
/// Each one of these derives from GCMetric, which manages the creation of the GC object model
/// from an ETL trace - these classes are only responsible for using it to produce a meaningful
/// metric.
///
/// Each one of these metrics should be fairly self-explanatory.
/// </summary>
namespace GCPerfTestFramework.Metrics
{
#region Maximum Pause Duration
internal class GCMaxPauseMetric : GCMetric
{
public GCMaxPauseMetric()
: base("GCMaxPause", "Maximum GC Pause Duraction", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCMaxPauseEvaluator(context);
}
}
internal class GCMaxPauseEvaluator : GCEvaluator
{
public GCMaxPauseEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.MaxPauseDurationMSec;
}
}
#endregion
#region Mean Pause Duration
internal class GCMeanPauseMetric : GCMetric
{
public GCMeanPauseMetric()
: base("GCMeanPause", "Mean GC Pause Duraction", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCMeanPauseEvaluator(context);
}
}
internal class GCMeanPauseEvaluator : GCEvaluator
{
public GCMeanPauseEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.MeanPauseDurationMSec;
}
}
#endregion
#region Peak Virtual Memory Size
internal class GCPeakVirtualMemoryMetric : GCMetric
{
public GCPeakVirtualMemoryMetric()
: base("GCPeakVirtualMemory", "Process Peak Virtual Memory", PerformanceMetricUnits.Bytes)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCPeakVirtualMemoryMetricEvaluator(context);
}
}
internal class GCPeakVirtualMemoryMetricEvaluator : GCEvaluator
{
public GCPeakVirtualMemoryMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.PeakVirtualMB * GCMetric.BytesInMegabyte;
}
}
#endregion
#region Peak Working Set Size
internal class GCPeakWorkingSetMetric : GCMetric
{
public GCPeakWorkingSetMetric()
: base("GCPeakWorkingSet", "Process Peak Working Set", PerformanceMetricUnits.Bytes)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCPeakWorkingSetMetricEvaluator(context);
}
}
internal class GCPeakWorkingSetMetricEvaluator : GCEvaluator
{
public GCPeakWorkingSetMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.PeakWorkingSetMB * GCMetric.BytesInMegabyte;
}
}
#endregion
#region Total Pause Time
internal class GCTotalPauseTimeMetric : GCMetric
{
public GCTotalPauseTimeMetric()
: base("GCTotalPauseTime", "Total time spent paused due to GC activity", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCTotalPauseTimeMetricEvaluator(context);
}
}
internal class GCTotalPauseTimeMetricEvaluator : GCEvaluator
{
public GCTotalPauseTimeMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.TotalPauseTimeMSec;
}
}
#endregion
#region CPU time in GC
internal class GCCpuTimeInGCMetric : GCMetric
{
public GCCpuTimeInGCMetric()
: base("GCCpuTimeInGC", "Total CPU time spent in GC activity", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCCpuTimeInGCMetricEvaluator(context);
}
}
internal class GCCpuTimeInGCMetricEvaluator : GCEvaluator
{
public GCCpuTimeInGCMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.TotalGCCpuMSec;
}
}
#endregion
#region Generation Zero Mean Pause Duration
internal class GCGenZeroMeanPauseDuration : GCMetric
{
public GCGenZeroMeanPauseDuration()
: base("GCGenZeroMeanPauseDuration", "Mean pause duration for Gen0 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenZeroMeanPauseDurationEvaluator(context);
}
}
internal class GCGenZeroMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenZeroMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[0].MeanPauseDurationMSec;
}
}
#endregion
#region Generation One Mean Pause Duration
internal class GCGenOneMeanPauseDuration : GCMetric
{
public GCGenOneMeanPauseDuration()
: base("GCGenOneMeanPauseDuration", "Mean pause duration for Gen1 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenOneMeanPauseDurationEvaluator(context);
}
}
internal class GCGenOneMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenOneMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[0].MeanPauseDurationMSec;
}
}
#endregion
#region Generation Two Mean Pause Duration
internal class GCGenTwoMeanPauseDuration : GCMetric
{
public GCGenTwoMeanPauseDuration()
: base("GCGenTwoMeanPauseDuration", "Mean pause duration for Gen2 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoMeanPauseDurationEvaluator(context);
}
}
internal class GCGenTwoMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenTwoMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[2].MeanPauseDurationMSec;
}
}
#endregion
#region Generation Zero GC Count
internal class GCGenZeroCount : GCMetric
{
public GCGenZeroCount()
: base("GCGenZeroCount", "Number of Generation 0 GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenZeroCountEvaluator(context);
}
}
internal class GCGenZeroCountEvaluator : GCEvaluator
{
public GCGenZeroCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[0].GCCount;
}
}
#endregion
#region Generation One GC Count
internal class GCGenOneCount : GCMetric
{
public GCGenOneCount()
: base("GCGenOneCount", "Number of Generation 1 GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenOneCountEvaluator(context);
}
}
internal class GCGenOneCountEvaluator : GCEvaluator
{
public GCGenOneCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[1].GCCount;
}
}
#endregion
#region Generation 2 Background GC Count
internal class GCGenTwoBGCCount : GCMetric
{
public GCGenTwoBGCCount()
: base("GCGenTwoBGCCount", "Number of Generation 2 background GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoBGCCountEvaluator(context);
}
}
internal class GCGenTwoBGCCountEvaluator : GCEvaluator
{
public GCGenTwoBGCCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Events.Count(e => e.Generation == 2 && e.Type == GCType.BackgroundGC);
}
}
#endregion
#region Generation 2 Blocking GC Count
internal class GCGenTwoGCCount : GCMetric
{
public GCGenTwoGCCount()
: base("GCGenTwoGCCount", "Number of Generation 2 blocking GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoGCCountEvaluator(context);
}
}
internal class GCGenTwoGCCountEvaluator : GCEvaluator
{
public GCGenTwoGCCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Events.Count(e => e.Generation == 2 && e.Type == GCType.NonConcurrentGC);
}
}
#endregion
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
public enum TestEnum
{
VALUE_0,
VALUE_1
}
public class TestGenericComparer<T> : Comparer<T>
{
public TestGenericComparer() : base() { }
public override int Compare(T x, T y)
{
if (!(x is ValueType))
{
// reference type
Object ox = x as Object;
Object oy = y as Object;
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
}
if (x is IComparable<T>)
{
IComparable<T> comparer = x as IComparable<T>;
return comparer.CompareTo(y);
}
if (x is IComparable)
{
IComparable comparer = x as IComparable;
return comparer.CompareTo(y);
}
throw new ArgumentException();
}
}
public class TestClass : IComparable<TestClass>
{
public int Value;
public TestClass(int value)
{
Value = value;
}
public int CompareTo(TestClass other)
{
return this.Value - other.Value;
}
}
public class TestClass1 : IComparable
{
public int Value;
public TestClass1(int value)
{
Value = value;
}
public int CompareTo(object obj)
{
TestClass1 other = obj as TestClass1;
if (other != null)
{
return Value - other.Value;
}
if (obj is int)
{
int i = (int)obj;
return Value - i;
}
throw new ArgumentException("Must be instance of TestClass1 or Int32");
}
}
/// <summary>
/// System.Collections.IComparer.Compare(System.Object,System.Object)
/// </summary>
public class ComparerCompare2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Compare to compare two value type instance");
try
{
IComparer comparer = new TestGenericComparer<ValueType>() as IComparer;
retVal = VerificationHelper(comparer, 1, 2, -1, "001.1") && retVal;
retVal = VerificationHelper(comparer, 2, 1, 1, "001.2") && retVal;
retVal = VerificationHelper(comparer, 1, 1, 0, "001.3") && retVal;
retVal = VerificationHelper(comparer, 1.0, 2.0, -1, "001.4") && retVal;
retVal = VerificationHelper(comparer, 1, (int)TestEnum.VALUE_0, 1, "001.5") && retVal;
retVal = VerificationHelper(comparer, 1, (int)TestEnum.VALUE_1, 0, "001.6") && retVal;
retVal = VerificationHelper(comparer, 'a', 'A', 32, "001.7") && retVal;
retVal = VerificationHelper(comparer, 'a', 'a', 0, "001.8") && retVal;
retVal = VerificationHelper(comparer, 'A', 'a', -32, "001.9") && retVal;
comparer = new TestGenericComparer<int>() as IComparer;
retVal = VerificationHelper(comparer, 1, 2, -1, "001.10") && retVal;
retVal = VerificationHelper(comparer, 2, 1, 1, "001.11") && retVal;
retVal = VerificationHelper(comparer, 1, 1, 0, "001.12") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Compare with one or both parameters are null reference");
try
{
IComparer comparer = new TestGenericComparer<TestClass>() as IComparer;
retVal = VerificationHelper(comparer, null, new TestClass(1), -1, "002.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), null, 1, "002.2") && retVal;
retVal = VerificationHelper(comparer, null, null, 0, "002.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Compare when T implements IComparable<T>");
try
{
IComparer comparer = new TestGenericComparer<TestClass>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass(0), new TestClass(1), -1, "003.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), new TestClass(0), 1, "003.2") && retVal;
retVal = VerificationHelper(comparer, new TestClass(1), new TestClass(1), 0, "003.3") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Compare when T implements IComparable");
try
{
IComparer comparer = new TestGenericComparer<TestClass1>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass1(0), new TestClass1(1), -1, "004.1") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), new TestClass1(0), 1, "004.2") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), new TestClass1(1), 0, "004.3") && retVal;
comparer = new TestGenericComparer<Object>() as IComparer;
retVal = VerificationHelper(comparer, new TestClass1(0), 1, -1, "004.4") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), 0, 1, "004.5") && retVal;
retVal = VerificationHelper(comparer, new TestClass1(1), 1, 0, "004.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentException should be thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
try
{
TestGenericComparer<ComparerCompare2> comparer = new TestGenericComparer<ComparerCompare2>();
IComparer icompare = comparer as IComparer;
icompare.Compare(new ComparerCompare2(), new ComparerCompare2());
TestLibrary.TestFramework.LogError("101.1", "ArgumentException is not thrown when Type T does not implement either the System.IComparable generic interface or the System.IComparable interface.");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentException should be thrown when x is of a type that cannot be cast to type T");
try
{
TestGenericComparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
IComparer icompare = comparer as IComparer;
icompare.Compare('a', new TestClass1(1));
TestLibrary.TestFramework.LogError("102.1", "ArgumentException is not thrown when x is of a type that cannot be cast to type T");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException should be thrown when y is of a type that cannot be cast to type T");
try
{
TestGenericComparer<TestClass1> comparer = new TestGenericComparer<TestClass1>();
IComparer icompare = comparer as IComparer;
icompare.Compare(new TestClass1(1), 'a');
TestLibrary.TestFramework.LogError("103.1", "ArgumentException is not thrown when y is of a type that cannot be cast to type T");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ComparerCompare2 test = new ComparerCompare2();
TestLibrary.TestFramework.BeginTestCase("ComparerCompare2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(IComparer comparer, object x, object y, int expected, string errorno)
{
bool retVal = true;
int actual = comparer.Compare(x, y);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorno, "Compare returns unexpected value");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] x = " + x + ", y = " + y + ", expected = " + expected + ", actual = " + actual);
retVal = false;
}
return retVal;
}
#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.
#if WINDOWS
using System.Linq;
using Microsoft.Xunit.Performance.Sdk;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
/// <summary>
/// This file contains a number of GC-related metrics that are provided to xunit-performance.
/// Each one of these derives from GCMetric, which manages the creation of the GC object model
/// from an ETL trace - these classes are only responsible for using it to produce a meaningful
/// metric.
///
/// Each one of these metrics should be fairly self-explanatory.
/// </summary>
namespace GCPerfTestFramework.Metrics
{
#region Maximum Pause Duration
internal class GCMaxPauseMetric : GCMetric
{
public GCMaxPauseMetric()
: base("GCMaxPause", "Maximum GC Pause Duraction", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCMaxPauseEvaluator(context);
}
}
internal class GCMaxPauseEvaluator : GCEvaluator
{
public GCMaxPauseEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.MaxPauseDurationMSec;
}
}
#endregion
#region Mean Pause Duration
internal class GCMeanPauseMetric : GCMetric
{
public GCMeanPauseMetric()
: base("GCMeanPause", "Mean GC Pause Duraction", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCMeanPauseEvaluator(context);
}
}
internal class GCMeanPauseEvaluator : GCEvaluator
{
public GCMeanPauseEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.MeanPauseDurationMSec;
}
}
#endregion
#region Peak Virtual Memory Size
internal class GCPeakVirtualMemoryMetric : GCMetric
{
public GCPeakVirtualMemoryMetric()
: base("GCPeakVirtualMemory", "Process Peak Virtual Memory", PerformanceMetricUnits.Bytes)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCPeakVirtualMemoryMetricEvaluator(context);
}
}
internal class GCPeakVirtualMemoryMetricEvaluator : GCEvaluator
{
public GCPeakVirtualMemoryMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.PeakVirtualMB * GCMetric.BytesInMegabyte;
}
}
#endregion
#region Peak Working Set Size
internal class GCPeakWorkingSetMetric : GCMetric
{
public GCPeakWorkingSetMetric()
: base("GCPeakWorkingSet", "Process Peak Working Set", PerformanceMetricUnits.Bytes)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCPeakWorkingSetMetricEvaluator(context);
}
}
internal class GCPeakWorkingSetMetricEvaluator : GCEvaluator
{
public GCPeakWorkingSetMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.PeakWorkingSetMB * GCMetric.BytesInMegabyte;
}
}
#endregion
#region Total Pause Time
internal class GCTotalPauseTimeMetric : GCMetric
{
public GCTotalPauseTimeMetric()
: base("GCTotalPauseTime", "Total time spent paused due to GC activity", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCTotalPauseTimeMetricEvaluator(context);
}
}
internal class GCTotalPauseTimeMetricEvaluator : GCEvaluator
{
public GCTotalPauseTimeMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.TotalPauseTimeMSec;
}
}
#endregion
#region CPU time in GC
internal class GCCpuTimeInGCMetric : GCMetric
{
public GCCpuTimeInGCMetric()
: base("GCCpuTimeInGC", "Total CPU time spent in GC activity", PerformanceMetricUnits.Milliseconds)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCCpuTimeInGCMetricEvaluator(context);
}
}
internal class GCCpuTimeInGCMetricEvaluator : GCEvaluator
{
public GCCpuTimeInGCMetricEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Total.TotalGCCpuMSec;
}
}
#endregion
#region Generation Zero Mean Pause Duration
internal class GCGenZeroMeanPauseDuration : GCMetric
{
public GCGenZeroMeanPauseDuration()
: base("GCGenZeroMeanPauseDuration", "Mean pause duration for Gen0 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenZeroMeanPauseDurationEvaluator(context);
}
}
internal class GCGenZeroMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenZeroMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[0].MeanPauseDurationMSec;
}
}
#endregion
#region Generation One Mean Pause Duration
internal class GCGenOneMeanPauseDuration : GCMetric
{
public GCGenOneMeanPauseDuration()
: base("GCGenOneMeanPauseDuration", "Mean pause duration for Gen1 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenOneMeanPauseDurationEvaluator(context);
}
}
internal class GCGenOneMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenOneMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[1].MeanPauseDurationMSec;
}
}
#endregion
#region Generation Two Mean Pause Duration
internal class GCGenTwoMeanPauseDuration : GCMetric
{
public GCGenTwoMeanPauseDuration()
: base("GCGenTwoMeanPauseDuration", "Mean pause duration for Gen2 collections", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoMeanPauseDurationEvaluator(context);
}
}
internal class GCGenTwoMeanPauseDurationEvaluator : GCEvaluator
{
public GCGenTwoMeanPauseDurationEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[2].MeanPauseDurationMSec;
}
}
#endregion
#region Generation Zero GC Count
internal class GCGenZeroCount : GCMetric
{
public GCGenZeroCount()
: base("GCGenZeroCount", "Number of Generation 0 GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenZeroCountEvaluator(context);
}
}
internal class GCGenZeroCountEvaluator : GCEvaluator
{
public GCGenZeroCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[0].GCCount;
}
}
#endregion
#region Generation One GC Count
internal class GCGenOneCount : GCMetric
{
public GCGenOneCount()
: base("GCGenOneCount", "Number of Generation 1 GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenOneCountEvaluator(context);
}
}
internal class GCGenOneCountEvaluator : GCEvaluator
{
public GCGenOneCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Generations[1].GCCount;
}
}
#endregion
#region Generation 2 Background GC Count
internal class GCGenTwoBGCCount : GCMetric
{
public GCGenTwoBGCCount()
: base("GCGenTwoBGCCount", "Number of Generation 2 background GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoBGCCountEvaluator(context);
}
}
internal class GCGenTwoBGCCountEvaluator : GCEvaluator
{
public GCGenTwoBGCCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Events.Count(e => e.Generation == 2 && e.Type == GCType.BackgroundGC);
}
}
#endregion
#region Generation 2 Blocking GC Count
internal class GCGenTwoGCCount : GCMetric
{
public GCGenTwoGCCount()
: base("GCGenTwoGCCount", "Number of Generation 2 blocking GCs", PerformanceMetricUnits.Count)
{
}
public override PerformanceMetricEvaluator CreateEvaluator(PerformanceMetricEvaluationContext context)
{
return new GCGenTwoGCCountEvaluator(context);
}
}
internal class GCGenTwoGCCountEvaluator : GCEvaluator
{
public GCGenTwoGCCountEvaluator(PerformanceMetricEvaluationContext context)
: base(context)
{
}
protected override double YieldMetric()
{
return ProcessInfo.Events.Count(e => e.Generation == 2 && e.Type == GCType.NonConcurrentGC);
}
}
#endregion
}
#endif
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using L10NSharp;
using SIL.Archiving.Generic;
using SIL.Code;
using SIL.IO;
namespace SIL.Archiving
{
/// ------------------------------------------------------------------------------------
public abstract class ArchivingDlgViewModel
{
[Flags]
protected enum MetadataProperties
{
Audience = 1 << 0,
Domains = 1 << 1,
ContentLanguages = 1 << 2,
CreationDate = 1 << 3,
ModifiedDate = 1 << 4,
SchemaConformance = 1 << 5,
DatasetExtent = 1 << 6,
SubjectLanguage = 1 << 7,
SoftwareRequirements = 1 << 8,
Contributors = 1 << 9,
RecordingExtent = 1 << 10,
GeneralDescription = 1 << 11,
AbstractDescription = 1 << 12,
Promotion = 1 << 13,
Stage = 1 << 14,
Type = 1 << 15,
Title = 1 << 16,
Files = 1 << 17,
}
#region Data members
protected readonly string _id; // ID/Name of the top-level element being archived (can be either a session or a project)
protected readonly string _appSpecificArchivalProcessInfo;
protected readonly Dictionary<string, string> _titles = new Dictionary<string, string>(); //Titles of elements being archived (keyed by element id)
private Dictionary<string, MetadataProperties> _propertiesSet = new Dictionary<string, MetadataProperties>(); // Metadata properties that have been set (keyed by element id)
private Action<ArchivingDlgViewModel> _setFilesToArchive;
protected bool _cancelProcess;
protected readonly Dictionary<string, string> _progressMessages = new Dictionary<string, string>();
/// <summary>
/// Keyed and grouped according to whatever logical grouping makes sense in the
/// calling application. The key for each group will be supplied back to the calling app
/// for use in "normalizing" file names. In the Tuple for each group, Item1 contains the
/// enumerable list of files to include, and Item2 contains a progress message to be
/// displayed when that group of files is being processed.
/// </summary>
protected IDictionary<string, Tuple<IEnumerable<string>, string>> _fileLists = new Dictionary<string, Tuple<IEnumerable<string>, string>>();
protected BackgroundWorker _worker;
#endregion
#region Delegates and Events
/// ------------------------------------------------------------------------------------
public enum MessageType
{
/// <summary>Normal (bold) text</summary>
Normal,
/// <summary>Blue text, with "Warning:" label (not localizable)</summary>
Warning,
/// <summary>Red text, followed by new line</summary>
Error,
/// <summary>Non-bold, indented with tab</summary>
Detail,
/// <summary>New line</summary>
Progress,
/// <summary>Non-bold, indented 8 spaces, with bullet character (U+00B7)</summary>
Bullet,
/// <summary>New line, Dark Green text</summary>
Success,
/// <summary>New line, indented 4 spaces</summary>
Indented,
/// <summary>Normal text, which will cause display to be cleared when the next message is to be displayed</summary>
Volatile,
}
/// <summary>Delegate for OnDisplayMessage event</summary>
/// <param name="msg">Message to display</param>
/// <param name="type">Type of message (which handler can use to determine appropriate color, style, indentation, etc.</param>
public delegate void DisplayMessageEventHandler(string msg, MessageType type);
/// <summary>
/// Notifiers subscribers of a message to display.
/// </summary>
public event DisplayMessageEventHandler OnDisplayMessage;
/// <summary>Delegate for DisplayError event</summary>
/// <param name="msg">Message to display</param>
/// <param name="packageTitle">Title of package being created</param>
/// <param name="e">Exception (can be null)</param>
public delegate void DisplayErrorEventHandler(string msg, string packageTitle, Exception e);
/// <summary>
/// Notifiers subscribers of an error message to report.
/// </summary>
public event DisplayErrorEventHandler OnDisplayError;
/// <summary>Action raised when progress happens</summary>
public Action IncrementProgressBarAction { protected get; set; }
#endregion
#region properties
/// ------------------------------------------------------------------------------------
/// <summary>
/// Short name/description of the archiving program or standard used for this type of
/// archiving. (Should fit in the frame "Archive using ___".)
/// </summary>
/// ------------------------------------------------------------------------------------
internal abstract string ArchiveType { get; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Short name of the archiving program to launch once package is created.
/// </summary>
/// ------------------------------------------------------------------------------------
public abstract string NameOfProgramToLaunch { get; }
/// ------------------------------------------------------------------------------------
public abstract string InformativeText { get; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Implement ArchiveInfoHyperlinkText to define text (first occurrence only) in the
/// InformativeText that will be makred as a hyperlink to ArchiveInfoUrl.
/// </summary>
/// ------------------------------------------------------------------------------------
public abstract string ArchiveInfoHyperlinkText { get; }
/// ------------------------------------------------------------------------------------
public abstract string ArchiveInfoUrl { get; }
/// ------------------------------------------------------------------------------------
/// <summary>Path to the program to launch</summary>
/// ------------------------------------------------------------------------------------
public string PathToProgramToLaunch { get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>Path to the generated package</summary>
/// ------------------------------------------------------------------------------------
public string PackagePath { get; protected set; }
/// ------------------------------------------------------------------------------------
public string AppName { get; private set; }
/// ------------------------------------------------------------------------------------
public bool IsBusy { get; protected set; }
#endregion
#region callbacks
/// ------------------------------------------------------------------------------------
/// <summary>
/// Callback function to allow the application to modify the contents of a file rather
/// than merely copying it. If application performs the "copy" for the given file,
/// it should return true; otherwise, false.
/// </summary>
/// ------------------------------------------------------------------------------------
public Func<ArchivingDlgViewModel, string, string, bool> FileCopyOverride { protected get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Callback to do application-specific normalization of filenames to be added to
/// archive based on the file-list key (param 1) and the filename (param 2).
/// The StringBuilder (param 3) has the normalized name which the app can alter as needed.
/// </summary>
/// ------------------------------------------------------------------------------------
public Action<string, string, StringBuilder> AppSpecificFilenameNormalization { private get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Callback to allow application to do special handling of exceptions or other error
/// conditions. The exception parameter can be null.
/// </summary>
/// ------------------------------------------------------------------------------------
public Action<Exception, string> HandleNonFatalError { private get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Callback to allow application to handle display of initial summary in log box. If
/// the application implements this, then the default summary display will be suppressed.
/// </summary>
/// ------------------------------------------------------------------------------------
public Action<IDictionary<string, Tuple<IEnumerable<string>, string>>> OverrideDisplayInitialSummary { private get; set; }
#endregion
#region construction and initialization
/// ------------------------------------------------------------------------------------
/// <summary>Constructor</summary>
/// <param name="appName">The application name</param>
/// <param name="title">Title of the submission</param>
/// <param name="id">Identifier (used as filename) for the package being created</param>
/// <param name="appSpecificArchivalProcessInfo">Application can use this to pass
/// additional information that will be displayed to the user in the dialog to explain
/// any application-specific details about the archival process.</param>
/// <param name="setFilesToArchive">Delegate to request client to call methods to set
/// which files should be archived (this is deferred to allow display of progress message)</param>
/// ------------------------------------------------------------------------------------
protected ArchivingDlgViewModel(string appName, string title, string id,
string appSpecificArchivalProcessInfo, Action<ArchivingDlgViewModel> setFilesToArchive)
{
if (appName == null)
throw new ArgumentNullException("appName");
AppName = appName;
if (title == null)
throw new ArgumentNullException("title");
if (id == null)
throw new ArgumentNullException("id");
_id = id;
_appSpecificArchivalProcessInfo = appSpecificArchivalProcessInfo;
_setFilesToArchive = setFilesToArchive;
_titles[id] = title;
_propertiesSet[id] = MetadataProperties.Title;
AdditionalMessages = new Dictionary<string, MessageType>();
}
/// ------------------------------------------------------------------------------------
public bool Initialize()
{
IsBusy = true;
try
{
if (!DoArchiveSpecificInitialization())
return false;
_setFilesToArchive(this);
foreach (var fileList in _fileLists.Where(fileList => fileList.Value.Item1.Any()))
{
string normalizedName = NormalizeFilename(fileList.Key, Path.GetFileName(fileList.Value.Item1.First()));
_progressMessages[normalizedName] = fileList.Value.Item2;
}
DisplayInitialSummary();
return true;
}
finally
{
IsBusy = false;
}
}
/// ------------------------------------------------------------------------------------
protected abstract bool DoArchiveSpecificInitialization();
/// ------------------------------------------------------------------------------------
public abstract int CalculateMaxProgressBarValue();
/// ------------------------------------------------------------------------------------
public virtual void AddFileGroup(string groupId, IEnumerable<string> files, string progressMessage)
{
Guard.AgainstNull(groupId, nameof(groupId));
if (_fileLists.ContainsKey(groupId))
throw new ArgumentException("Duplicate file group ID: " + groupId, nameof(groupId));
_fileLists[groupId] = Tuple.Create(files, progressMessage);
}
/// ------------------------------------------------------------------------------------
private void DisplayInitialSummary()
{
if (OverrideDisplayInitialSummary != null)
OverrideDisplayInitialSummary(_fileLists);
else if (OnDisplayMessage != null)
{
OnDisplayMessage(LocalizationManager.GetString("DialogBoxes.ArchivingDlg.PrearchivingStatusMsg",
"The following files will be added to the archive:"), MessageType.Normal);
foreach (var kvp in _fileLists)
{
string msg = FileGroupDisplayMessage(kvp.Key);
if (msg != string.Empty)
OnDisplayMessage(msg, MessageType.Indented);
foreach (var file in kvp.Value.Item1)
OnDisplayMessage(Path.GetFileName(file), MessageType.Bullet);
}
}
}
protected virtual string FileGroupDisplayMessage(string groupKey)
{
return groupKey;
}
#endregion
#region Helper methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to detect when caller tries to set a property (for the top-level
/// element) that has already been set and throw an InvalidOperationException if so.
/// </summary>
/// <param name="property">The property to check (and add to the list of properties that
/// can no longer be set again).</param>
/// ------------------------------------------------------------------------------------
protected void PreventDuplicateMetadataProperty(MetadataProperties property)
{
PreventDuplicateMetadataProperty(_id, property);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to detect when caller tries to set a property (for the specified
/// element) that has already been set and throw an InvalidOperationException if so.
/// </summary>
/// <param name="elementId">The element id </param>
/// <param name="property">The property to check (and add to the list of properties that
/// can no longer be set again).</param>
/// ------------------------------------------------------------------------------------
protected void PreventDuplicateMetadataProperty(string elementId, MetadataProperties property)
{
MetadataProperties propertiesSet;
if (_propertiesSet.TryGetValue(elementId, out propertiesSet))
{
if (propertiesSet.HasFlag(property))
throw new InvalidOperationException(string.Format("{0} has already been set", property.ToString()));
_propertiesSet[elementId] |= property;
}
else
_propertiesSet[elementId] = property;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to determine if the given property (for the top-level element) has
/// already been set.
/// </summary>
/// ------------------------------------------------------------------------------------
protected bool IsMetadataPropertySet(MetadataProperties property)
{
return IsMetadataPropertySet(_id, property);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to determine if the given property (for the specified element) has
/// already been set.
/// </summary>
/// ------------------------------------------------------------------------------------
protected bool IsMetadataPropertySet(string elementId, MetadataProperties property)
{
MetadataProperties propertiesSet;
if (!_propertiesSet.TryGetValue(elementId, out propertiesSet))
return false;
return propertiesSet.HasFlag(property);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to note that the given property (for the top-level element) has
/// been set.
/// </summary>
/// ------------------------------------------------------------------------------------
protected void MarkMetadataPropertyAsSet(MetadataProperties property)
{
MarkMetadataPropertyAsSet(_id, property);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Helper method to note that the given property (for the specified element) has
/// been set.
/// </summary>
/// ------------------------------------------------------------------------------------
protected void MarkMetadataPropertyAsSet(string elementId, MetadataProperties property)
{
if (!_propertiesSet.ContainsKey(elementId))
_propertiesSet[elementId] = property;
_propertiesSet[elementId] |= property;
}
#endregion
#region Methods for setting common fields
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets an abstract/description for this resource in a single language
/// </summary>
/// <param name="description">The abstract description</param>
/// <param name="language">ISO 639-2 3-letter language code (can be left empty if
/// language is not known)</param>
/// ------------------------------------------------------------------------------------
public void SetAbstract(string description, string language)
{
IDictionary<string, string> dictionary = new Dictionary<string, string>(1);
dictionary[language] = description;
SetAbstract(dictionary);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets abstracts/descriptions for this resource in (potentially) multiple languages
/// </summary>
/// <param name="descriptions">Dictionary of language->abstract, where the keys are ISO
/// 639-2 3-letter language codes</param>
/// ------------------------------------------------------------------------------------
public void SetAbstract(IDictionary<string, string> descriptions)
{
if (descriptions == null)
throw new ArgumentNullException("descriptions");
if (descriptions.Count == 0)
return;
if (descriptions.Count > 1)
{
if (descriptions.Keys.Any(k => k.Length != 3))
throw new ArgumentException();
}
PreventDuplicateMetadataProperty(MetadataProperties.AbstractDescription);
SetAbstract_Impl(descriptions);
}
#region Abstract versions of methods
/// ------------------------------------------------------------------------------------
protected abstract void SetAbstract_Impl(IDictionary<string, string> descriptions);
#endregion
#endregion
/// ------------------------------------------------------------------------------------
public void DisplayMessage(string msg, MessageType type)
{
if (OnDisplayMessage != null)
OnDisplayMessage(msg, type);
}
/// ------------------------------------------------------------------------------------
public abstract string GetMetadata();
/// ------------------------------------------------------------------------------------
internal abstract void LaunchArchivingProgram();
/// ------------------------------------------------------------------------------------
protected void LaunchArchivingProgram(Action HandleInvalidOperation)
{
if (string.IsNullOrEmpty(PathToProgramToLaunch) || !File.Exists(PathToProgramToLaunch))
return;
try
{
var prs = new Process();
prs.StartInfo.FileName = PathToProgramToLaunch;
if (!string.IsNullOrEmpty(PackagePath))
prs.StartInfo.Arguments = "\"" + PackagePath + "\"";
prs.Start();
}
catch (Exception e)
{
if (e is InvalidOperationException && HandleInvalidOperation != null)
HandleInvalidOperation();
else
{
ReportError(e, string.Format(LocalizationManager.GetString("DialogBoxes.ArchivingDlg.StartingRampErrorMsg",
"There was an error attempting to open the archive package in {0}."), PathToProgramToLaunch));
}
}
}
/// ------------------------------------------------------------------------------------
public abstract bool CreatePackage();
/// ------------------------------------------------------------------------------------
protected virtual StringBuilder DoArchiveSpecificFilenameNormalization(string key, string fileName)
{
return AppSpecificFilenameNormalization != null ? new StringBuilder(fileName) : null;
}
/// ------------------------------------------------------------------------------------
public virtual string NormalizeFilename(string key, string fileName)
{
StringBuilder bldr = DoArchiveSpecificFilenameNormalization(key, fileName);
if (AppSpecificFilenameNormalization != null)
AppSpecificFilenameNormalization(key, fileName, bldr);
return bldr.ToString();
}
/// ------------------------------------------------------------------------------------
const int CopyBufferSize = 64 * 1024;
/// ------------------------------------------------------------------------------------
protected static void CopyFile(string src, string dest)
{
using (var outputFile = File.OpenWrite(dest))
{
using (var inputFile = File.OpenRead(src))
{
var buffer = new byte[CopyBufferSize];
int bytesRead;
while ((bytesRead = inputFile.Read(buffer, 0, CopyBufferSize)) != 0)
{
outputFile.Write(buffer, 0, bytesRead);
}
}
}
}
/// ------------------------------------------------------------------------------------
public virtual void Cancel()
{
if (_cancelProcess)
return;
_cancelProcess = true;
if (_worker != null)
{
DisplayMessage(Environment.NewLine + LocalizationManager.GetString(
"DialogBoxes.ArchivingDlg.CancellingMsg", "Canceling..."), MessageType.Error);
_worker.CancelAsync();
while (_worker.IsBusy)
Application.DoEvents();
}
}
/// ------------------------------------------------------------------------------------
protected void ReportError(Exception e, string msg)
{
if (OnDisplayError != null)
OnDisplayError(msg, _titles[_id], e);
else if (e != null)
throw e;
if (HandleNonFatalError != null)
HandleNonFatalError(e, msg);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// The file locations are different on Linux than on Windows
/// </summary>
/// ------------------------------------------------------------------------------------
public static bool IsMono
{
get { return (Type.GetType("Mono.Runtime") != null); }
}
/// <summary></summary>
/// <param name="sessionId"></param>
public abstract IArchivingSession AddSession(string sessionId);
/// <summary></summary>
public abstract IArchivingPackage ArchivingPackage { get; }
/// <remarks/>
public Dictionary<string, MessageType> AdditionalMessages { get; private set; }
public bool IsPathWritable(string directory)
{
try
{
if (DirectoryUtilities.IsDirectoryWritable(directory))
return true;
}
catch (Exception e)
{
DisplayMessage(e.Message, MessageType.Warning);
return false;
}
var msg = LocalizationManager.GetString(
"DialogBoxes.ArchivingDlg.PathNotWritableMsg",
"The path is not writable: {0}");
DisplayMessage(string.Format(msg, directory), MessageType.Warning);
return false;
}
}
public interface ISupportMetadataOnly
{
bool MetadataOnly { get; set; }
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#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.IO;
using System.Globalization;
using System.Numerics;
using System.Threading.Tasks;
using PlayFab.Json.Linq;
using PlayFab.Json.Utilities;
using System.Xml;
using PlayFab.Json.Converters;
using PlayFab.Json.Serialization;
using System.Text;
using System.Xml.Linq;
namespace PlayFab.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\PlayFab.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
public static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings> DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
return text;
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
return (!nullable) ? "0.0" : Null;
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text = null;
text = value.ToString("D");
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
return Null;
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter)
{
if (delimiter != '"' && delimiter != '\'')
throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value);
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string) value);
case PrimitiveTypeCode.Char:
return ToString((char) value);
case PrimitiveTypeCode.Boolean:
return ToString((bool) value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte) value);
case PrimitiveTypeCode.Int16:
return ToString((short) value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort) value);
case PrimitiveTypeCode.Int32:
return ToString((int) value);
case PrimitiveTypeCode.Byte:
return ToString((byte) value);
case PrimitiveTypeCode.UInt32:
return ToString((uint) value);
case PrimitiveTypeCode.Int64:
return ToString((long) value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong) value);
case PrimitiveTypeCode.Single:
return ToString((float) value);
case PrimitiveTypeCode.Double:
return ToString((double) value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime) value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal) value);
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset) value);
case PrimitiveTypeCode.Guid:
return ToString((Guid) value);
case PrimitiveTypeCode.Uri:
return ToString((Uri) value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan) value);
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, Formatting.None, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
/// Specifing the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value)
{
return SerializeObjectAsync(value, Formatting.None, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using formatting.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
{
return SerializeObjectAsync(value, formatting, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// Serialization will happen on a new thread.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
}
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T) DeserializeObject(value, typeof (T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T) DeserializeObject(value, typeof (T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, "value");
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
jsonSerializer.CheckAdditionalContent = true;
return jsonSerializer.Deserialize(new JsonTextReader(sr), type);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// Deserialization will happen on a new thread.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value)
{
return DeserializeObjectAsync<T>(value, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// Deserialization will happen on a new thread.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// Deserialization will happen on a new thread.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value)
{
return DeserializeObjectAsync(value, null, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// Deserialization will happen on a new thread.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
}
#endregion
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
/// <summary>
/// Asynchronously populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous populate operation.
/// </returns>
public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment specified by <paramref name="deserializeRootElementName"/>
/// and writes a .NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XDocument) DeserializeObject(value, typeof (XDocument), converter);
}
}
}
#endif
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.ProjectModel;
using NuGet.Frameworks;
namespace Microsoft.DotNet.ProjectModel.Workspaces
{
public class ProjectJsonWorkspace : Workspace
{
private Dictionary<string, AssemblyMetadata> _cache = new Dictionary<string, AssemblyMetadata>();
private readonly string[] _projectPaths;
public ProjectJsonWorkspace(string projectPath) : this(new[] { projectPath })
{
}
public ProjectJsonWorkspace(string[] projectPaths) : base(MefHostServices.DefaultHost, "Custom")
{
_projectPaths = projectPaths;
Initialize();
}
private void Initialize()
{
foreach (var projectPath in _projectPaths)
{
AddProject(projectPath);
}
}
private void AddProject(string projectPath)
{
// Get all of the specific projects (there is a project per framework)
foreach (var p in ProjectContext.CreateContextForEachFramework(projectPath))
{
AddProject(p);
}
}
private ProjectId AddProject(ProjectContext project)
{
// Create the framework specific project and add it to the workspace
var projectInfo = ProjectInfo.Create(
ProjectId.CreateNewId(),
VersionStamp.Create(),
project.ProjectFile.Name + "+" + project.TargetFramework,
project.ProjectFile.Name,
LanguageNames.CSharp,
project.ProjectFile.ProjectFilePath);
OnProjectAdded(projectInfo);
// TODO: ctor argument?
var configuration = "Debug";
var compilationOptions = project.ProjectFile.GetCompilerOptions(project.TargetFramework, configuration);
var compilationSettings = ToCompilationSettings(compilationOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory);
OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines));
OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);
foreach (var file in project.ProjectFile.Files.SourceFiles)
{
AddSourceFile(projectInfo, file);
}
var exporter = project.CreateExporter(configuration);
foreach (var dependency in exporter.GetDependencies())
{
var projectDependency = dependency.Library as ProjectDescription;
if (projectDependency != null)
{
var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework);
var id = AddProject(projectDependencyContext);
OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id));
}
else
{
foreach (var asset in dependency.CompilationAssemblies)
{
OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath));
}
}
foreach (var file in dependency.SourceReferences)
{
AddSourceFile(projectInfo, file);
}
}
return projectInfo.Id;
}
private void AddSourceFile(ProjectInfo projectInfo, string file)
{
using (var stream = File.OpenRead(file))
{
var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
var id = DocumentId.CreateNewId(projectInfo.Id);
var version = VersionStamp.Create();
var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));
OnDocumentAdded(DocumentInfo.Create(id, file, filePath: file, loader: loader));
}
}
private MetadataReference GetMetadataReference(string path)
{
AssemblyMetadata assemblyMetadata;
if (!_cache.TryGetValue(path, out assemblyMetadata))
{
using (var stream = File.OpenRead(path))
{
var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);
_cache[path] = assemblyMetadata;
}
}
return assemblyMetadata.GetReference();
}
private static CompilationSettings ToCompilationSettings(CommonCompilerOptions compilerOptions,
NuGetFramework targetFramework,
string projectDirectory)
{
var options = GetCompilationOptions(compilerOptions, projectDirectory);
// Disable 1702 until roslyn turns this off by default
options = options.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>
{
{ "CS1701", ReportDiagnostic.Suppress }, // Binding redirects
{ "CS1702", ReportDiagnostic.Suppress },
{ "CS1705", ReportDiagnostic.Suppress }
});
AssemblyIdentityComparer assemblyIdentityComparer =
targetFramework.IsDesktop() ?
DesktopAssemblyIdentityComparer.Default :
null;
options = options.WithAssemblyIdentityComparer(assemblyIdentityComparer);
LanguageVersion languageVersion;
if (!Enum.TryParse<LanguageVersion>(value: compilerOptions.LanguageVersion,
ignoreCase: true,
result: out languageVersion))
{
languageVersion = LanguageVersion.CSharp6;
}
var settings = new CompilationSettings
{
LanguageVersion = languageVersion,
Defines = compilerOptions.Defines ?? Enumerable.Empty<string>(),
CompilationOptions = options
};
return settings;
}
private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory)
{
var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ?
OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary;
var options = new CSharpCompilationOptions(outputKind);
string platformValue = compilerOptions.Platform;
bool allowUnsafe = compilerOptions.AllowUnsafe ?? false;
bool optimize = compilerOptions.Optimize ?? false;
bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false;
Platform platform;
if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform))
{
platform = Platform.AnyCpu;
}
options = options
.WithAllowUnsafe(allowUnsafe)
.WithPlatform(platform)
.WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
.WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug);
return AddSigningOptions(options, compilerOptions, projectDirectory);
}
private static CSharpCompilationOptions AddSigningOptions(CSharpCompilationOptions options, CommonCompilerOptions compilerOptions, string projectDirectory)
{
var useOssSigning = compilerOptions.UseOssSigning == true;
var keyFile = compilerOptions.KeyFile;
if (!string.IsNullOrEmpty(keyFile))
{
keyFile = Path.GetFullPath(Path.Combine(projectDirectory, compilerOptions.KeyFile));
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || useOssSigning)
{
return options.WithCryptoPublicKey(
SnkUtils.ExtractPublicKey(File.ReadAllBytes(keyFile)));
}
options = options.WithCryptoKeyFile(keyFile);
return options.WithDelaySign(compilerOptions.DelaySign);
}
return options;
}
private class CompilationSettings
{
public LanguageVersion LanguageVersion { get; set; }
public IEnumerable<string> Defines { get; set; }
public CSharpCompilationOptions CompilationOptions { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MixColumns_Vector128_Byte()
{
var test = new AesUnaryOpTest__MixColumns_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class AesUnaryOpTest__MixColumns_Vector128_Byte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(AesUnaryOpTest__MixColumns_Vector128_Byte testClass)
{
var result = Aes.MixColumns(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(AesUnaryOpTest__MixColumns_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld = &_fld)
{
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(pFld))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data = new Byte[16] {0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88};
private static Byte[] _expectedRet = new Byte[16] {0xAB, 0x01, 0xEF, 0x45, 0x23, 0x89, 0x67, 0xCD, 0xDD, 0x88, 0xFF, 0xAA, 0x99, 0xCC, 0xBB, 0xEE};
private static Vector128<Byte> _clsVar;
private Vector128<Byte> _fld;
private DataTable _dataTable;
static AesUnaryOpTest__MixColumns_Vector128_Byte()
{
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public AesUnaryOpTest__MixColumns_Vector128_Byte()
{
Succeeded = true;
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
_dataTable = new DataTable(_data, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Aes.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Aes.MixColumns(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult( _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Aes).GetMethod(nameof(Aes.MixColumns), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Aes).GetMethod(nameof(Aes.MixColumns), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Aes.MixColumns(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar = &_clsVar)
{
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(pClsVar))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var result = Aes.MixColumns(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var result = Aes.MixColumns(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new AesUnaryOpTest__MixColumns_Vector128_Byte();
var result = Aes.MixColumns(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new AesUnaryOpTest__MixColumns_Vector128_Byte();
fixed (Vector128<Byte>* pFld = &test._fld)
{
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(pFld))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Aes.MixColumns(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld = &_fld)
{
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(pFld))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Aes.MixColumns(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Aes.MixColumns(
AdvSimd.LoadVector128((Byte*)(&test._fld))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(void* result, [CallerMemberName] string method = "")
{
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(outArray, method);
}
private void ValidateResult(Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < result.Length; i++)
{
if (result[i] != _expectedRet[i] )
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Aes)}.{nameof(Aes.MixColumns)}<Byte>(Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TangoInspector.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using Tango;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Custom editor for the TangoApplication.
/// </summary>
[CustomEditor(typeof(TangoApplication))]
public class TangoInspector : Editor
{
private TangoApplication m_tangoApplication;
/// <summary>
/// Raises the inspector GUI event.
/// </summary>
public override void OnInspectorGUI()
{
m_tangoApplication.m_autoConnectToService = EditorGUILayout.Toggle("Auto-connect to Service",
m_tangoApplication.m_autoConnectToService);
if (m_tangoApplication.m_autoConnectToService && m_tangoApplication.m_enableAreaDescriptions &&
!m_tangoApplication.m_enableDriftCorrection)
{
EditorGUILayout.HelpBox("Note that auto-connect does not supply a chance "
+ "to specify an Area Description.", MessageType.Warning);
}
EditorGUILayout.Space();
_DrawMotionTrackingOptions(m_tangoApplication);
_DrawAreaDescriptionOptions(m_tangoApplication);
_DrawDepthOptions(m_tangoApplication);
_DrawVideoOverlayOptions(m_tangoApplication);
_Draw3DReconstructionOptions(m_tangoApplication);
_DrawPerformanceOptions(m_tangoApplication);
_DrawEmulationOptions(m_tangoApplication);
_DrawDevelopmentOptions(m_tangoApplication);
if (GUI.changed)
{
EditorUtility.SetDirty(m_tangoApplication);
}
}
/// <summary>
/// Raises the enable event.
/// </summary>
private void OnEnable()
{
m_tangoApplication = (TangoApplication)target;
// Fixup the old state of TangoApplication before there were two checkboxes. If only m_enableVideoOverlay was
// set, then that meant to use the Byte Buffer method.
if (m_tangoApplication.m_enableVideoOverlay && !m_tangoApplication.m_videoOverlayUseTextureMethod
&& !m_tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& !m_tangoApplication.m_videoOverlayUseByteBufferMethod)
{
m_tangoApplication.m_videoOverlayUseByteBufferMethod = true;
}
}
/// <summary>
/// Draw motion tracking options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawMotionTrackingOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableMotionTracking = EditorGUILayout.Toggle(
"Enable Motion Tracking", tangoApplication.m_enableMotionTracking);
if (tangoApplication.m_enableMotionTracking)
{
++EditorGUI.indentLevel;
tangoApplication.m_motionTrackingAutoReset = EditorGUILayout.Toggle(
"Auto Reset", tangoApplication.m_motionTrackingAutoReset);
--EditorGUI.indentLevel;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw area description options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawAreaDescriptionOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableAreaDescriptions = EditorGUILayout.Toggle(
"Enable Area Descriptions", tangoApplication.m_enableAreaDescriptions);
if (tangoApplication.m_enableAreaDescriptions)
{
++EditorGUI.indentLevel;
string[] options = new string[]
{
"Drift Correction",
"Learning",
"Load Existing",
};
int selectedOption;
if (tangoApplication.m_enableDriftCorrection)
{
selectedOption = 0;
}
else if (tangoApplication.m_areaDescriptionLearningMode)
{
selectedOption = 1;
}
else
{
selectedOption = 2;
}
switch (EditorGUILayout.Popup("Mode", selectedOption, options))
{
case 0:
tangoApplication.m_enableDriftCorrection = true;
tangoApplication.m_areaDescriptionLearningMode = false;
break;
case 1:
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_areaDescriptionLearningMode = true;
break;
default:
tangoApplication.m_enableDriftCorrection = false;
tangoApplication.m_areaDescriptionLearningMode = false;
break;
}
if (m_tangoApplication.m_enableDriftCorrection)
{
EditorGUILayout.HelpBox("Drift correction mode is experimental.", MessageType.Warning);
}
--EditorGUI.indentLevel;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw depth options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawDepthOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableDepth = EditorGUILayout.Toggle("Enable Depth", tangoApplication.m_enableDepth);
EditorGUILayout.Space();
}
/// <summary>
/// Draw video overlay options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawVideoOverlayOptions(TangoApplication tangoApplication)
{
tangoApplication.m_enableVideoOverlay = EditorGUILayout.Toggle(
"Enable Video Overlay", tangoApplication.m_enableVideoOverlay);
if (tangoApplication.m_enableVideoOverlay)
{
EditorGUI.indentLevel++;
string[] options = new string[]
{
"Texture (ITangoCameraTexture)",
"YUV Texture (IExperimentalTangoVideoOverlay)",
"Raw Bytes (ITangoVideoOverlay)",
"Texture and Raw Bytes",
"YUV Texture and Raw Bytes",
"Texture and YUV Texture",
"All",
};
int selectedOption;
if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 6;
}
else if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseYUVTextureIdMethod)
{
selectedOption = 5;
}
else if (tangoApplication.m_videoOverlayUseYUVTextureIdMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 4;
}
else if (tangoApplication.m_videoOverlayUseTextureMethod
&& tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 3;
}
else if (tangoApplication.m_videoOverlayUseByteBufferMethod)
{
selectedOption = 2;
}
else if (tangoApplication.m_videoOverlayUseYUVTextureIdMethod)
{
selectedOption = 1;
}
else
{
selectedOption = 0;
}
switch (EditorGUILayout.Popup("Method", selectedOption, options))
{
case 0:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 1:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 2:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 3:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 4:
tangoApplication.m_videoOverlayUseTextureMethod = false;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
case 5:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
case 6:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = true;
tangoApplication.m_videoOverlayUseByteBufferMethod = true;
break;
default:
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
break;
}
EditorGUI.indentLevel--;
}
else
{
tangoApplication.m_videoOverlayUseTextureMethod = true;
tangoApplication.m_videoOverlayUseYUVTextureIdMethod = false;
tangoApplication.m_videoOverlayUseByteBufferMethod = false;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draw motion tracking options.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _Draw3DReconstructionOptions(TangoApplication tangoApplication)
{
GUILayout.Label("Enable 3D Reconstruction", GUILayout.ExpandWidth(true));
tangoApplication.m_enable3DReconstruction = EditorGUILayout.Toggle("(Experimental)",
tangoApplication.m_enable3DReconstruction);
if (tangoApplication.m_enable3DReconstruction)
{
if (!tangoApplication.m_enableMotionTracking)
{
EditorGUILayout.HelpBox("Motion tracking is required for 3D Reconstruction.", MessageType.Warning);
}
if (!tangoApplication.m_enableDepth)
{
EditorGUILayout.HelpBox("Depth is required for 3D Reconstruction.", MessageType.Warning);
}
EditorGUI.indentLevel++;
tangoApplication.m_3drResolutionMeters = EditorGUILayout.FloatField(
"Resolution (meters)", tangoApplication.m_3drResolutionMeters);
tangoApplication.m_3drResolutionMeters = Mathf.Max(tangoApplication.m_3drResolutionMeters, 0.001f);
tangoApplication.m_3drGenerateColor = EditorGUILayout.Toggle(
"Generate Color", tangoApplication.m_3drGenerateColor);
if (tangoApplication.m_3drGenerateColor
&& (!tangoApplication.m_enableVideoOverlay || !tangoApplication.m_videoOverlayUseByteBufferMethod))
{
EditorGUILayout.HelpBox("Video Overlay must be enabled and set to \"Raw Bytes\" or \"Both\""
+ " in order to use 3D Reconstruction with color.", MessageType.Warning);
}
tangoApplication.m_3drGenerateNormal = EditorGUILayout.Toggle(
"Generate Normals", tangoApplication.m_3drGenerateNormal);
tangoApplication.m_3drGenerateTexCoord = EditorGUILayout.Toggle(
"Generate UVs", tangoApplication.m_3drGenerateTexCoord);
tangoApplication.m_3drSpaceClearing = EditorGUILayout.Toggle(
"Space Clearing", tangoApplication.m_3drSpaceClearing);
tangoApplication.m_3drUpdateMethod = (Tango3DReconstruction.UpdateMethod)EditorGUILayout.EnumPopup(
"Update Method", tangoApplication.m_3drUpdateMethod);
string tooltip = "If non-zero, any mesh that has less than this number of vertices is assumed to be "
+ "noise and will not be generated.";
int newMinNumVertices = EditorGUILayout.IntField(new GUIContent("Mesh Min Vertices", tooltip),
tangoApplication.m_3drMinNumVertices);
tangoApplication.m_3drMinNumVertices = Mathf.Max(newMinNumVertices, 0);
tangoApplication.m_3drUseAreaDescriptionPose = EditorGUILayout.Toggle(
"Use Area Description Pose", tangoApplication.m_3drUseAreaDescriptionPose);
if (tangoApplication.m_3drUseAreaDescriptionPose && !tangoApplication.m_enableAreaDescriptions)
{
EditorGUILayout.HelpBox("Area Descriptions must be enabled in order for "
+ "3D Reconstruction to use them.", MessageType.Warning);
}
else if (!tangoApplication.m_3drUseAreaDescriptionPose && tangoApplication.m_enableAreaDescriptions)
{
EditorGUILayout.HelpBox("Area Descriptions are enabled, but \"Use Area Description Pose\" is disabled "
+ "for 3D Reconstruction.\n\nIf left as-is, 3D Reconstruction will use the Start of "
+ "Service pose, even if an area description is loaded and/or area learning is enabled.",
MessageType.Warning);
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
}
/// <summary>
/// Draws options for performance management.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawPerformanceOptions(TangoApplication tangoApplication)
{
tangoApplication.m_showPerformanceOptionsInInspector =
EditorGUILayout.Foldout(tangoApplication.m_showPerformanceOptionsInInspector, "Performance Options");
if (tangoApplication.m_showPerformanceOptionsInInspector)
{
EditorGUI.indentLevel++;
m_tangoApplication.m_initialPointCloudMaxPoints = EditorGUILayout.IntField(
new GUIContent("Point Cloud Max Points",
"Set an upper limit on the number of points in the point cloud. If value is 0, no limit is imposed."),
m_tangoApplication.m_initialPointCloudMaxPoints);
tangoApplication.m_adjustScreenResolution = EditorGUILayout.Toggle(
new GUIContent("Reduce Resolution",
"Whether to adjust the size of the application's main render buffer for performance reasons"),
tangoApplication.m_adjustScreenResolution);
EditorGUI.indentLevel++;
GUI.enabled = tangoApplication.m_adjustScreenResolution;
tangoApplication.m_targetResolution = EditorGUILayout.IntField(
new GUIContent("Target Resolution",
"Target resolution to reduce resolution to when m_adjustScreenResolution is enabled."),
tangoApplication.m_targetResolution);
string oversizedResolutionTooltip = "If true, resolution adjustment will allow adjusting to a resolution " +
"larger than the display of the current device. This is generally discouraged.";
tangoApplication.m_allowOversizedScreenResolutions = EditorGUILayout.Toggle(
new GUIContent("Allow Oversized", oversizedResolutionTooltip), tangoApplication.m_allowOversizedScreenResolutions);
GUI.enabled = true;
if (!tangoApplication.m_adjustScreenResolution)
{
EditorGUILayout.HelpBox("Some Tango devices have very high-resolution displays.\n\n" +
"Consider limiting application resolution here or elsewhere in your application.", MessageType.Warning);
}
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
}
}
/// <summary>
/// Draws development options.
///
/// These should only be set while in development.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawDevelopmentOptions(TangoApplication tangoApplication)
{
GUILayout.Label("Development Options (Disable these before publishing)", GUILayout.ExpandWidth(true));
EditorGUI.indentLevel++;
tangoApplication.m_allowOutOfDateTangoAPI = EditorGUILayout.Toggle(
"Allow out of date API", m_tangoApplication.m_allowOutOfDateTangoAPI);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
/// <summary>
/// Draws editor emulation options.
///
/// These will only have any effect while in the Unity Editor.
/// </summary>
/// <param name="tangoApplication">Tango application.</param>
private void _DrawEmulationOptions(TangoApplication tangoApplication)
{
tangoApplication.m_showEmulationOptionsInInspector =
EditorGUILayout.Foldout(tangoApplication.m_showEmulationOptionsInInspector, "Editor Emulation");
if (tangoApplication.m_showEmulationOptionsInInspector)
{
EditorGUI.indentLevel++;
tangoApplication.m_doSlowEmulation = EditorGUILayout.Toggle(
new GUIContent("Depth and Video",
"Simulate depth and color camera data based on a specified mesh. Disable for editor performance."),
tangoApplication.m_doSlowEmulation);
if (tangoApplication.m_doSlowEmulation)
{
EditorGUI.indentLevel++;
tangoApplication.m_emulationEnvironment = (Mesh)EditorGUILayout.ObjectField(
new GUIContent("Mesh For Emulation", "Mesh to use as the world when simulating color camera and depth data."),
m_tangoApplication.m_emulationEnvironment, typeof(Mesh), false);
tangoApplication.m_emulationEnvironmentTexture = (Texture)EditorGUILayout.ObjectField(
new GUIContent("Texture for Emulation", "(Optional) Texture to use on emulated environment mesh."),
m_tangoApplication.m_emulationEnvironmentTexture, typeof(Texture), false);
m_tangoApplication.m_emulationVideoOverlaySimpleLighting = EditorGUILayout.Toggle(
new GUIContent("Simulate Lighting", "Use simple lighting in simulating camera feed"),
m_tangoApplication.m_emulationVideoOverlaySimpleLighting);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
tangoApplication.m_emulatedAreaDescriptionStartOffset = EditorGUILayout.Vector3Field(
new GUIContent("Area Description Offset",
"Simulate difference between Start of Service and Area Description origins with a simple positional offset"),
tangoApplication.m_emulatedAreaDescriptionStartOffset);
EditorGUI.indentLevel--;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Layouts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Layouts;
[TestFixture]
public class CsvLayoutTests : NLogTestBase
{
#if !SILVERLIGHT
[Test]
public void EndToEndTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd1.txt'>
<layout type='CSVLayout'>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd1.txt"))
{
Assert.AreEqual("level,message,counter", sr.ReadLine());
Assert.AreEqual("Debug,msg,1", sr.ReadLine());
Assert.AreEqual("Info,msg2,2", sr.ReadLine());
Assert.AreEqual("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
[Test]
public void NoHeadersTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='CSVLayoutEndToEnd2.txt'>
<layout type='CSVLayout' withHeader='false'>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText("CSVLayoutEndToEnd2.txt"))
{
Assert.AreEqual("Debug,msg,1", sr.ReadLine());
Assert.AreEqual("Info,msg2,2", sr.ReadLine());
Assert.AreEqual("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
#endif
[Test]
public void CsvLayoutRenderingNoQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Nothing,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.AreEqual("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev));
Assert.AreEqual("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev));
}
}
[Test]
public void CsvLayoutRenderingFullQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.All,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.AreEqual("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev));
Assert.AreEqual("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev));
}
}
[Test]
public void CsvLayoutRenderingAutoQuoting()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
// no quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;hello, world",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
}));
// multi-line string - requires quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello\rworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\rworld"
}));
// multi-line string - requires quoting
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello\nworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\nworld"
}));
// quote character used in string, will be quoted and doubled
Assert.AreEqual(
"2010-01-01 12:34:56.0000;Info;'hello''world'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello'world"
}));
Assert.AreEqual("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent()));
}
[Test]
public void CsvLayoutCachingTest()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
var e1 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
};
var e2 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57),
Level = LogLevel.Info,
Message = "hello, world"
};
var r11 = csvLayout.Render(e1);
var r12 = csvLayout.Render(e1);
var r21 = csvLayout.Render(e2);
var r22 = csvLayout.Render(e2);
var h11 = csvLayout.Header.Render(e1);
var h12 = csvLayout.Header.Render(e1);
var h21 = csvLayout.Header.Render(e2);
var h22 = csvLayout.Header.Render(e2);
Assert.AreSame(r11, r12);
Assert.AreSame(r21, r22);
Assert.AreNotSame(r11, r21);
Assert.AreNotSame(r12, r22);
Assert.AreSame(h11, h12);
Assert.AreSame(h21, h22);
Assert.AreNotSame(h11, h21);
Assert.AreNotSame(h12, h22);
}
}
}
| |
//
// 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.
//
namespace DiscUtils.Vmdk
{
using System;
using System.Collections.Generic;
using System.IO;
internal abstract class CommonSparseExtentStream : MappedStream
{
/// <summary>
/// Stream containing the sparse extent.
/// </summary>
protected Stream _fileStream;
/// <summary>
/// Indicates if this object controls the lifetime of _fileStream.
/// </summary>
protected Ownership _ownsFileStream;
/// <summary>
/// Offset of this extent within the disk.
/// </summary>
protected long _diskOffset;
/// <summary>
/// The stream containing the unstored bytes.
/// </summary>
protected SparseStream _parentDiskStream;
/// <summary>
/// Indicates if this object controls the lifetime of _parentDiskStream.
/// </summary>
protected Ownership _ownsParentDiskStream;
/// <summary>
/// The Global Directory for this extent.
/// </summary>
protected uint[] _globalDirectory;
/// <summary>
/// The Redundant Global Directory for this extent.
/// </summary>
protected uint[] _redundantGlobalDirectory;
/// <summary>
/// The header from the start of the extent.
/// </summary>
protected CommonSparseExtentHeader _header;
/// <summary>
/// The number of bytes controlled by a single grain table.
/// </summary>
protected long _gtCoverage;
/// <summary>
/// The current grain that's loaded into _grainTable.
/// </summary>
protected int _currentGrainTable;
/// <summary>
/// The data corresponding to the current grain (or null).
/// </summary>
protected byte[] _grainTable;
/// <summary>
/// Current position in the extent.
/// </summary>
protected long _position;
/// <summary>
/// Indicator to whether end-of-stream has been reached.
/// </summary>
protected bool _atEof;
/// <summary>
/// Cache of recently used grain tables.
/// </summary>
private ObjectCache<int, byte[]> _grainTableCache = new ObjectCache<int, byte[]>();
public override bool CanRead
{
get
{
CheckDisposed();
return true;
}
}
public override bool CanSeek
{
get
{
CheckDisposed();
return true;
}
}
public override bool CanWrite
{
get
{
CheckDisposed();
return _fileStream.CanWrite;
}
}
public override long Length
{
get
{
CheckDisposed();
return _header.Capacity * Sizes.Sector;
}
}
public override long Position
{
get
{
CheckDisposed();
return _position;
}
set
{
CheckDisposed();
_position = value;
_atEof = false;
}
}
public override IEnumerable<StreamExtent> Extents
{
get { return GetExtentsInRange(0, Length); }
}
public override void Flush()
{
CheckDisposed();
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
if (_position > Length)
{
_atEof = true;
throw new IOException("Attempt to read beyond end of stream");
}
if (_position == Length)
{
if (_atEof)
{
throw new IOException("Attempt to read beyond end of stream");
}
else
{
_atEof = true;
return 0;
}
}
int maxToRead = (int)Math.Min(count, Length - _position);
int totalRead = 0;
int numRead;
do
{
int grainTable = (int)(_position / _gtCoverage);
int grainTableOffset = (int)(_position - (((long)grainTable) * _gtCoverage));
numRead = 0;
if (!LoadGrainTable(grainTable))
{
// Read from parent stream, to at most the end of grain table's coverage
_parentDiskStream.Position = _position + _diskOffset;
numRead = _parentDiskStream.Read(buffer, offset + totalRead, (int)Math.Min(maxToRead - totalRead, _gtCoverage - grainTableOffset));
}
else
{
int grainSize = (int)(_header.GrainSize * Sizes.Sector);
int grain = grainTableOffset / grainSize;
int grainOffset = grainTableOffset - (grain * grainSize);
int numToRead = Math.Min(maxToRead - totalRead, grainSize - grainOffset);
if (GetGrainTableEntry(grain) == 0)
{
_parentDiskStream.Position = _position + _diskOffset;
numRead = _parentDiskStream.Read(buffer, offset + totalRead, numToRead);
}
else
{
int bufferOffset = offset + totalRead;
long grainStart = ((long)GetGrainTableEntry(grain)) * Sizes.Sector;
numRead = ReadGrain(buffer, bufferOffset, grainStart, grainOffset, numToRead);
}
}
_position += numRead;
totalRead += numRead;
}
while (numRead != 0 && totalRead < maxToRead);
return totalRead;
}
public override void SetLength(long value)
{
CheckDisposed();
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += _header.Capacity * Sizes.Sector;
}
_atEof = false;
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of disk");
}
else
{
_position = effectiveOffset;
return _position;
}
}
public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
CheckDisposed();
long maxCount = Math.Min(Length, start + count) - start;
if (maxCount < 0)
{
return new StreamExtent[0];
}
var parentExtents = _parentDiskStream.GetExtentsInRange(_diskOffset + start, maxCount);
parentExtents = StreamExtent.Offset(parentExtents, -_diskOffset);
var result = StreamExtent.Union(LayerExtents(start, maxCount), parentExtents);
result = StreamExtent.Intersect(result, new StreamExtent[] { new StreamExtent(start, maxCount) });
return result;
}
public override IEnumerable<StreamExtent> MapContent(long start, long length)
{
CheckDisposed();
if (start < Length)
{
long end = Math.Min(start + length, Length);
long pos = start;
do
{
int grainTable = (int)(pos / _gtCoverage);
int grainTableOffset = (int)(pos - (((long)grainTable) * _gtCoverage));
if (LoadGrainTable(grainTable))
{
int grainSize = (int)(_header.GrainSize * Sizes.Sector);
int grain = grainTableOffset / grainSize;
int grainOffset = grainTableOffset - (grain * grainSize);
int numToRead = (int)Math.Min(end - pos, grainSize - grainOffset);
if (GetGrainTableEntry(grain) != 0)
{
long grainStart = ((long)GetGrainTableEntry(grain)) * Sizes.Sector;
yield return MapGrain(grainStart, grainOffset, numToRead);
}
pos += numToRead;
}
else
{
pos = (grainTable + 1) * _gtCoverage;
}
}
while (pos < end);
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_ownsFileStream == Ownership.Dispose && _fileStream != null)
{
_fileStream.Dispose();
}
_fileStream = null;
if (_ownsParentDiskStream == Ownership.Dispose && _parentDiskStream != null)
{
_parentDiskStream.Dispose();
}
_parentDiskStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
protected uint GetGrainTableEntry(int grain)
{
return Utilities.ToUInt32LittleEndian(_grainTable, grain * 4);
}
protected void SetGrainTableEntry(int grain, uint value)
{
Utilities.WriteBytesLittleEndian(value, _grainTable, grain * 4);
}
protected virtual int ReadGrain(byte[] buffer, int bufferOffset, long grainStart, int grainOffset, int numToRead)
{
_fileStream.Position = grainStart + grainOffset;
return _fileStream.Read(buffer, bufferOffset, numToRead);
}
protected virtual StreamExtent MapGrain(long grainStart, int grainOffset, int numToRead)
{
return new StreamExtent(grainStart + grainOffset, numToRead);
}
protected virtual void LoadGlobalDirectory()
{
int numGTs = (int)Utilities.Ceil(_header.Capacity * Sizes.Sector, _gtCoverage);
_globalDirectory = new uint[numGTs];
_fileStream.Position = _header.GdOffset * Sizes.Sector;
byte[] gdAsBytes = Utilities.ReadFully(_fileStream, numGTs * 4);
for (int i = 0; i < _globalDirectory.Length; ++i)
{
_globalDirectory[i] = Utilities.ToUInt32LittleEndian(gdAsBytes, i * 4);
}
}
protected bool LoadGrainTable(int index)
{
// Current grain table, so early-out
if (_grainTable != null && _currentGrainTable == index)
{
return true;
}
// This grain table not present in grain directory, so can't load it...
if (_globalDirectory[index] == 0)
{
return false;
}
// Cached grain table?
byte[] cachedGrainTable = _grainTableCache[index];
if (cachedGrainTable != null)
{
_currentGrainTable = index;
_grainTable = cachedGrainTable;
return true;
}
// Not cached, so read
_fileStream.Position = ((long)_globalDirectory[index]) * Sizes.Sector;
byte[] newGrainTable = Utilities.ReadFully(_fileStream, (int)_header.NumGTEsPerGT * 4);
_currentGrainTable = index;
_grainTable = newGrainTable;
_grainTableCache[index] = newGrainTable;
return true;
}
protected void CheckDisposed()
{
if (_fileStream == null)
{
throw new ObjectDisposedException("CommonSparseExtentStream");
}
}
private IEnumerable<StreamExtent> LayerExtents(long start, long count)
{
long maxPos = start + count;
long pos = FindNextPresentGrain(Utilities.RoundDown(start, _header.GrainSize * Sizes.Sector), maxPos);
while (pos < maxPos)
{
long end = FindNextAbsentGrain(pos, maxPos);
yield return new StreamExtent(pos, end - pos);
pos = FindNextPresentGrain(end, maxPos);
}
}
private long FindNextPresentGrain(long pos, long maxPos)
{
int grainSize = (int)(_header.GrainSize * Sizes.Sector);
bool foundStart = false;
while (pos < maxPos && !foundStart)
{
int grainTable = (int)(pos / _gtCoverage);
if (!LoadGrainTable(grainTable))
{
pos += _gtCoverage;
}
else
{
int grainTableOffset = (int)(pos - (grainTable * _gtCoverage));
int grain = grainTableOffset / grainSize;
if (GetGrainTableEntry(grain) == 0)
{
pos += grainSize;
}
else
{
foundStart = true;
}
}
}
return Math.Min(pos, maxPos);
}
private long FindNextAbsentGrain(long pos, long maxPos)
{
int grainSize = (int)(_header.GrainSize * Sizes.Sector);
bool foundEnd = false;
while (pos < maxPos && !foundEnd)
{
int grainTable = (int)(pos / _gtCoverage);
if (!LoadGrainTable(grainTable))
{
foundEnd = true;
}
else
{
int grainTableOffset = (int)(pos - (grainTable * _gtCoverage));
int grain = grainTableOffset / grainSize;
if (GetGrainTableEntry(grain) == 0)
{
foundEnd = true;
}
else
{
pos += grainSize;
}
}
}
return Math.Min(pos, maxPos);
}
}
}
| |
// Lucene version compatibility level 4.8.1
using YAF.Lucene.Net.Analysis.Standard.Std31;
using YAF.Lucene.Net.Analysis.Standard.Std34;
using YAF.Lucene.Net.Analysis.Standard.Std40;
using YAF.Lucene.Net.Analysis.TokenAttributes;
using YAF.Lucene.Net.Util;
using System;
using System.IO;
namespace YAF.Lucene.Net.Analysis.Standard
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A grammar-based tokenizer constructed with JFlex.
/// <para>
/// As of Lucene version 3.1, this class implements the Word Break rules from the
/// Unicode Text Segmentation algorithm, as specified in
/// <a href="http://unicode.org/reports/tr29/">Unicode Standard Annex #29</a>.
/// <p/>
/// </para>
/// <para>Many applications have specific tokenizer needs. If this tokenizer does
/// not suit your application, please consider copying this source code
/// directory to your project and maintaining your own grammar-based tokenizer.
///
/// </para>
/// <para>You must specify the required <see cref="LuceneVersion"/>
/// compatibility when creating <see cref="StandardTokenizer"/>:
/// <list type="bullet">
/// <item><description> As of 3.4, Hiragana and Han characters are no longer wrongly split
/// from their combining characters. If you use a previous version number,
/// you get the exact broken behavior for backwards compatibility.</description></item>
/// <item><description> As of 3.1, StandardTokenizer implements Unicode text segmentation.
/// If you use a previous version number, you get the exact behavior of
/// <see cref="ClassicTokenizer"/> for backwards compatibility.</description></item>
/// </list>
/// </para>
/// </summary>
public sealed class StandardTokenizer : Tokenizer
{
/// <summary>
/// A private instance of the JFlex-constructed scanner </summary>
private IStandardTokenizerInterface scanner;
public const int ALPHANUM = 0;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int APOSTROPHE = 1;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int ACRONYM = 2;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int COMPANY = 3;
public const int EMAIL = 4;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int HOST = 5;
public const int NUM = 6;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int CJ = 7;
/// @deprecated (3.1)
[Obsolete("(3.1)")]
public const int ACRONYM_DEP = 8;
public const int SOUTHEAST_ASIAN = 9;
public const int IDEOGRAPHIC = 10;
public const int HIRAGANA = 11;
public const int KATAKANA = 12;
public const int HANGUL = 13;
/// <summary>
/// String token types that correspond to token type int constants </summary>
public static readonly string[] TOKEN_TYPES = {
"<ALPHANUM>",
"<APOSTROPHE>",
"<ACRONYM>",
"<COMPANY>",
"<EMAIL>",
"<HOST>",
"<NUM>",
"<CJ>",
"<ACRONYM_DEP>",
"<SOUTHEAST_ASIAN>",
"<IDEOGRAPHIC>",
"<HIRAGANA>",
"<KATAKANA>",
"<HANGUL>"
};
private int skippedPositions;
private int maxTokenLength = StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH;
/// <summary>
/// Set the max allowed token length. Any token longer
/// than this is skipped.
/// </summary>
public int MaxTokenLength
{
get => maxTokenLength;
set
{
if (value < 1)
{
throw new ArgumentException("maxTokenLength must be greater than zero");
}
this.maxTokenLength = value;
}
}
/// <summary>
/// Creates a new instance of the <see cref="StandardTokenizer"/>. Attaches
/// the <paramref name="input"/> to the newly created JFlex-generated (then ported to .NET) scanner.
/// </summary>
/// <param name="matchVersion"> Lucene compatibility version - See <see cref="StandardTokenizer"/> </param>
/// <param name="input"> The input reader
///
/// See http://issues.apache.org/jira/browse/LUCENE-1068 </param>
public StandardTokenizer(LuceneVersion matchVersion, TextReader input)
: base(input)
{
Init(matchVersion);
}
/// <summary>
/// Creates a new <see cref="StandardTokenizer"/> with a given <see cref="AttributeSource.AttributeFactory"/>
/// </summary>
public StandardTokenizer(LuceneVersion matchVersion, AttributeFactory factory, TextReader input)
: base(factory, input)
{
Init(matchVersion);
}
private void Init(LuceneVersion matchVersion)
{
#pragma warning disable 612, 618
if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_47))
{
this.scanner = new StandardTokenizerImpl(m_input);
}
else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_40))
{
this.scanner = new StandardTokenizerImpl40(m_input);
}
else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_34))
{
this.scanner = new StandardTokenizerImpl34(m_input);
}
else if (matchVersion.OnOrAfter(LuceneVersion.LUCENE_31))
{
this.scanner = new StandardTokenizerImpl31(m_input);
}
#pragma warning restore 612, 618
else
{
this.scanner = new ClassicTokenizerImpl(m_input);
}
termAtt = AddAttribute<ICharTermAttribute>();
posIncrAtt = AddAttribute<IPositionIncrementAttribute>();
offsetAtt = AddAttribute<IOffsetAttribute>();
typeAtt = AddAttribute<ITypeAttribute>();
}
// this tokenizer generates three attributes:
// term offset, positionIncrement and type
private ICharTermAttribute termAtt;
private IOffsetAttribute offsetAtt;
private IPositionIncrementAttribute posIncrAtt;
private ITypeAttribute typeAtt;
/*
* (non-Javadoc)
*
* @see org.apache.lucene.analysis.TokenStream#next()
*/
public override sealed bool IncrementToken()
{
ClearAttributes();
skippedPositions = 0;
while (true)
{
int tokenType = scanner.GetNextToken();
if (tokenType == StandardTokenizerInterface.YYEOF)
{
return false;
}
if (scanner.YyLength <= maxTokenLength)
{
posIncrAtt.PositionIncrement = skippedPositions + 1;
scanner.GetText(termAtt);
int start = scanner.YyChar;
offsetAtt.SetOffset(CorrectOffset(start), CorrectOffset(start + termAtt.Length));
// This 'if' should be removed in the next release. For now, it converts
// invalid acronyms to HOST. When removed, only the 'else' part should
// remain.
#pragma warning disable 612, 618
if (tokenType == StandardTokenizer.ACRONYM_DEP)
{
typeAtt.Type = StandardTokenizer.TOKEN_TYPES[StandardTokenizer.HOST];
#pragma warning restore 612, 618
termAtt.Length = termAtt.Length - 1; // remove extra '.'
}
else
{
typeAtt.Type = StandardTokenizer.TOKEN_TYPES[tokenType];
}
return true;
}
else
// When we skip a too-long term, we still increment the
// position increment
{
skippedPositions++;
}
}
}
public override sealed void End()
{
base.End();
// set final offset
int finalOffset = CorrectOffset(scanner.YyChar + scanner.YyLength);
offsetAtt.SetOffset(finalOffset, finalOffset);
// adjust any skipped tokens
posIncrAtt.PositionIncrement = posIncrAtt.PositionIncrement + skippedPositions;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
scanner.YyReset(m_input);
}
}
public override void Reset()
{
base.Reset();
scanner.YyReset(m_input);
skippedPositions = 0;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IProductCostHistoryOriginalData : ISchemaBaseOriginalData
{
System.DateTime StartDate { get; }
System.DateTime EndDate { get; }
string StandardCost { get; }
Product Product { get; }
}
public partial class ProductCostHistory : OGM<ProductCostHistory, ProductCostHistory.ProductCostHistoryData, System.String>, ISchemaBase, INeo4jBase, IProductCostHistoryOriginalData
{
#region Initialize
static ProductCostHistory()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, ProductCostHistory> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.ProductCostHistoryAlias, IWhereQuery> query)
{
q.ProductCostHistoryAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.ProductCostHistory.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"ProductCostHistory => StartDate : {this.StartDate}, EndDate : {this.EndDate}, StandardCost : {this.StandardCost}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new ProductCostHistoryData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.StartDate == null)
throw new PersistenceException(string.Format("Cannot save ProductCostHistory with key '{0}' because the StartDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.EndDate == null)
throw new PersistenceException(string.Format("Cannot save ProductCostHistory with key '{0}' because the EndDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.StandardCost == null)
throw new PersistenceException(string.Format("Cannot save ProductCostHistory with key '{0}' because the StandardCost cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save ProductCostHistory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class ProductCostHistoryData : Data<System.String>
{
public ProductCostHistoryData()
{
}
public ProductCostHistoryData(ProductCostHistoryData data)
{
StartDate = data.StartDate;
EndDate = data.EndDate;
StandardCost = data.StandardCost;
Product = data.Product;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "ProductCostHistory";
Product = new EntityCollection<Product>(Wrapper, Members.Product);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("StartDate", Conversion<System.DateTime, long>.Convert(StartDate));
dictionary.Add("EndDate", Conversion<System.DateTime, long>.Convert(EndDate));
dictionary.Add("StandardCost", StandardCost);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("StartDate", out value))
StartDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("EndDate", out value))
EndDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("StandardCost", out value))
StandardCost = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IProductCostHistory
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public string StandardCost { get; set; }
public EntityCollection<Product> Product { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IProductCostHistory
public System.DateTime StartDate { get { LazyGet(); return InnerData.StartDate; } set { if (LazySet(Members.StartDate, InnerData.StartDate, value)) InnerData.StartDate = value; } }
public System.DateTime EndDate { get { LazyGet(); return InnerData.EndDate; } set { if (LazySet(Members.EndDate, InnerData.EndDate, value)) InnerData.EndDate = value; } }
public string StandardCost { get { LazyGet(); return InnerData.StandardCost; } set { if (LazySet(Members.StandardCost, InnerData.StandardCost, value)) InnerData.StandardCost = value; } }
public Product Product
{
get { return ((ILookupHelper<Product>)InnerData.Product).GetItem(null); }
set
{
if (LazySet(Members.Product, ((ILookupHelper<Product>)InnerData.Product).GetItem(null), value))
((ILookupHelper<Product>)InnerData.Product).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static ProductCostHistoryMembers members = null;
public static ProductCostHistoryMembers Members
{
get
{
if (members == null)
{
lock (typeof(ProductCostHistory))
{
if (members == null)
members = new ProductCostHistoryMembers();
}
}
return members;
}
}
public class ProductCostHistoryMembers
{
internal ProductCostHistoryMembers() { }
#region Members for interface IProductCostHistory
public Property StartDate { get; } = Datastore.AdventureWorks.Model.Entities["ProductCostHistory"].Properties["StartDate"];
public Property EndDate { get; } = Datastore.AdventureWorks.Model.Entities["ProductCostHistory"].Properties["EndDate"];
public Property StandardCost { get; } = Datastore.AdventureWorks.Model.Entities["ProductCostHistory"].Properties["StandardCost"];
public Property Product { get; } = Datastore.AdventureWorks.Model.Entities["ProductCostHistory"].Properties["Product"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static ProductCostHistoryFullTextMembers fullTextMembers = null;
public static ProductCostHistoryFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(ProductCostHistory))
{
if (fullTextMembers == null)
fullTextMembers = new ProductCostHistoryFullTextMembers();
}
}
return fullTextMembers;
}
}
public class ProductCostHistoryFullTextMembers
{
internal ProductCostHistoryFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(ProductCostHistory))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["ProductCostHistory"];
}
}
return entity;
}
private static ProductCostHistoryEvents events = null;
public static ProductCostHistoryEvents Events
{
get
{
if (events == null)
{
lock (typeof(ProductCostHistory))
{
if (events == null)
events = new ProductCostHistoryEvents();
}
}
return events;
}
}
public class ProductCostHistoryEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<ProductCostHistory, EntityEventArgs> onNew;
public event EventHandler<ProductCostHistory, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<ProductCostHistory, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<ProductCostHistory, EntityEventArgs> onDelete;
public event EventHandler<ProductCostHistory, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<ProductCostHistory, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<ProductCostHistory, EntityEventArgs> onSave;
public event EventHandler<ProductCostHistory, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<ProductCostHistory, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnStartDate
private static bool onStartDateIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onStartDate;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnStartDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
Members.StartDate.Events.OnChange += onStartDateProxy;
onStartDateIsRegistered = true;
}
onStartDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStartDate -= value;
if (onStartDate == null && onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
onStartDateIsRegistered = false;
}
}
}
}
private static void onStartDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onStartDate;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnEndDate
private static bool onEndDateIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onEndDate;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnEndDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
Members.EndDate.Events.OnChange += onEndDateProxy;
onEndDateIsRegistered = true;
}
onEndDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEndDate -= value;
if (onEndDate == null && onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
onEndDateIsRegistered = false;
}
}
}
}
private static void onEndDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onEndDate;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnStandardCost
private static bool onStandardCostIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onStandardCost;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnStandardCost
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStandardCostIsRegistered)
{
Members.StandardCost.Events.OnChange -= onStandardCostProxy;
Members.StandardCost.Events.OnChange += onStandardCostProxy;
onStandardCostIsRegistered = true;
}
onStandardCost += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStandardCost -= value;
if (onStandardCost == null && onStandardCostIsRegistered)
{
Members.StandardCost.Events.OnChange -= onStandardCostProxy;
onStandardCostIsRegistered = false;
}
}
}
}
private static void onStandardCostProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onStandardCost;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnProduct
private static bool onProductIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onProduct;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnProduct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
Members.Product.Events.OnChange += onProductProxy;
onProductIsRegistered = true;
}
onProduct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onProduct -= value;
if (onProduct == null && onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
onProductIsRegistered = false;
}
}
}
}
private static void onProductProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onProduct;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onModifiedDate;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<ProductCostHistory, PropertyEventArgs> onUid;
public static event EventHandler<ProductCostHistory, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<ProductCostHistory, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((ProductCostHistory)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IProductCostHistoryOriginalData
public IProductCostHistoryOriginalData OriginalVersion { get { return this; } }
#region Members for interface IProductCostHistory
System.DateTime IProductCostHistoryOriginalData.StartDate { get { return OriginalData.StartDate; } }
System.DateTime IProductCostHistoryOriginalData.EndDate { get { return OriginalData.EndDate; } }
string IProductCostHistoryOriginalData.StandardCost { get { return OriginalData.StandardCost; } }
Product IProductCostHistoryOriginalData.Product { get { return ((ILookupHelper<Product>)OriginalData.Product).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Collections.Generic;
namespace Microsoft.AspNetCore.Routing.Patterns
{
internal class DefaultRoutePatternTransformer : RoutePatternTransformer
{
private readonly ParameterPolicyFactory _policyFactory;
public DefaultRoutePatternTransformer(ParameterPolicyFactory policyFactory)
{
if (policyFactory == null)
{
throw new ArgumentNullException(nameof(policyFactory));
}
_policyFactory = policyFactory;
}
public override RoutePattern SubstituteRequiredValues(RoutePattern original, object requiredValues)
{
if (original == null)
{
throw new ArgumentNullException(nameof(original));
}
return SubstituteRequiredValuesCore(original, new RouteValueDictionary(requiredValues));
}
private RoutePattern SubstituteRequiredValuesCore(RoutePattern original, RouteValueDictionary requiredValues)
{
// Process each required value in sequence. Bail if we find any rejection criteria. The goal
// of rejection is to avoid creating RoutePattern instances that can't *ever* match.
//
// If we succeed, then we need to create a new RoutePattern with the provided required values.
//
// Substitution can merge with existing RequiredValues already on the RoutePattern as long
// as all of the success criteria are still met at the end.
foreach (var kvp in requiredValues)
{
// There are three possible cases here:
// 1. Required value is null-ish
// 2. Required value is *any*
// 3. Required value corresponds to a parameter
// 4. Required value corresponds to a matching default value
//
// If none of these are true then we can reject this substitution.
RoutePatternParameterPart parameter;
if (RouteValueEqualityComparer.Default.Equals(kvp.Value, string.Empty))
{
// 1. Required value is null-ish - check to make sure that this route doesn't have a
// parameter or filter-like default.
if (original.GetParameter(kvp.Key) != null)
{
// Fail: we can't 'require' that a parameter be null. In theory this would be possible
// for an optional parameter, but that's not really in line with the usage of this feature
// so we don't handle it.
//
// Ex: {controller=Home}/{action=Index}/{id?} - with required values: { controller = "" }
return null;
}
else if (original.Defaults.TryGetValue(kvp.Key, out var defaultValue) &&
!RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue))
{
// Fail: this route has a non-parameter default that doesn't match.
//
// Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" } - with required values: { area = "" }
return null;
}
// Success: (for this parameter at least)
//
// Ex: {controller=Home}/{action=Index}/{id?} - with required values: { area = "", ... }
continue;
}
else if (RoutePattern.IsRequiredValueAny(kvp.Value))
{
// 2. Required value is *any* - this is allowed for a parameter with a default, but not
// a non-parameter default.
if (original.GetParameter(kvp.Key) == null &&
original.Defaults.TryGetValue(kvp.Key, out var defaultValue) &&
!RouteValueEqualityComparer.Default.Equals(string.Empty, defaultValue))
{
// Fail: this route as a non-parameter default that is stricter than *any*.
//
// Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" } - with required values: { area = *any* }
return null;
}
// Success: (for this parameter at least)
//
// Ex: {controller=Home}/{action=Index}/{id?} - with required values: { controller = *any*, ... }
continue;
}
else if ((parameter = original.GetParameter(kvp.Key)) != null)
{
// 3. Required value corresponds to a parameter - check to make sure that this value matches
// any IRouteConstraint implementations.
if (!MatchesConstraints(original, parameter, kvp.Key, requiredValues))
{
// Fail: this route has a constraint that failed.
//
// Ex: Admin/{controller:regex(Home|Login)}/{action=Index}/{id?} - with required values: { controller = "Store" }
return null;
}
// Success: (for this parameter at least)
//
// Ex: {area}/{controller=Home}/{action=Index}/{id?} - with required values: { area = "", ... }
continue;
}
else if (original.Defaults.TryGetValue(kvp.Key, out var defaultValue) &&
RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue))
{
// 4. Required value corresponds to a matching default value - check to make sure that this value matches
// any IRouteConstraint implementations. It's unlikely that this would happen in practice but it doesn't
// hurt for us to check.
if (!MatchesConstraints(original, parameter: null, kvp.Key, requiredValues))
{
// Fail: this route has a constraint that failed.
//
// Ex:
// Admin/Home/{action=Index}/{id?}
// defaults: { area = "Admin" }
// constraints: { area = "Blog" }
// with required values: { area = "Admin" }
return null;
}
// Success: (for this parameter at least)
//
// Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" }- with required values: { area = "Admin", ... }
continue;
}
else
{
// Fail: this is a required value for a key that doesn't appear in the templates, or the route
// pattern has a different default value for a non-parameter.
//
// Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" }- with required values: { area = "Blog", ... }
// OR (less likely)
// Ex: Admin/{controller=Home}/{action=Index}/{id?} with required values: { page = "/Index", ... }
return null;
}
}
List<RoutePatternParameterPart> updatedParameters = null;
List<RoutePatternPathSegment> updatedSegments = null;
RouteValueDictionary updatedDefaults = null;
// So if we get here, we're ready to update the route pattern. We need to update two things:
// 1. Remove any default values that conflict with the required values.
// 2. Merge any existing required values
foreach (var kvp in requiredValues)
{
var parameter = original.GetParameter(kvp.Key);
// We only need to handle the case where the required value maps to a parameter. That's the only
// case where we allow a default and a required value to disagree, and we already validated the
// other cases.
//
// If the required value is *any* then don't remove the default.
if (parameter != null &&
!RoutePattern.IsRequiredValueAny(kvp.Value) &&
original.Defaults.TryGetValue(kvp.Key, out var defaultValue) &&
!RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue))
{
if (updatedDefaults == null && updatedSegments == null && updatedParameters == null)
{
updatedDefaults = new RouteValueDictionary(original.Defaults);
updatedSegments = new List<RoutePatternPathSegment>(original.PathSegments);
updatedParameters = new List<RoutePatternParameterPart>(original.Parameters);
}
updatedDefaults.Remove(kvp.Key);
RemoveParameterDefault(updatedSegments, updatedParameters, parameter);
}
}
foreach (var kvp in original.RequiredValues)
{
requiredValues.TryAdd(kvp.Key, kvp.Value);
}
return new RoutePattern(
original.RawText,
updatedDefaults ?? original.Defaults,
original.ParameterPolicies,
requiredValues,
updatedParameters ?? original.Parameters,
updatedSegments ?? original.PathSegments);
}
private bool MatchesConstraints(RoutePattern pattern, RoutePatternParameterPart parameter, string key, RouteValueDictionary requiredValues)
{
if (pattern.ParameterPolicies.TryGetValue(key, out var policies))
{
for (var i = 0; i < policies.Count; i++)
{
var policy = _policyFactory.Create(parameter, policies[i]);
if (policy is IRouteConstraint constraint)
{
if (!constraint.Match(httpContext: null, NullRouter.Instance, key, requiredValues, RouteDirection.IncomingRequest))
{
return false;
}
}
}
}
return true;
}
private static void RemoveParameterDefault(List<RoutePatternPathSegment> segments, List<RoutePatternParameterPart> parameters, RoutePatternParameterPart parameter)
{
// We know that a parameter can only appear once, so we only need to rewrite one segment and one parameter.
for (var i = 0; i < segments.Count; i++)
{
var segment = segments[i];
for (var j = 0; j < segment.Parts.Count; j++)
{
if (object.ReferenceEquals(parameter, segment.Parts[j]))
{
// Found it!
var updatedParameter = RoutePatternFactory.ParameterPart(parameter.Name, @default: null, parameter.ParameterKind, parameter.ParameterPolicies);
var updatedParts = new List<RoutePatternPart>(segment.Parts);
updatedParts[j] = updatedParameter;
segments[i] = RoutePatternFactory.Segment(updatedParts);
for (var k = 0; k < parameters.Count; k++)
{
if (ReferenceEquals(parameter, parameters[k]))
{
parameters[k] = updatedParameter;
break;
}
}
return;
}
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/taxed_reservation_nightly_quote.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Folio {
/// <summary>Holder for reflection information generated from folio/taxed_reservation_nightly_quote.proto</summary>
public static partial class TaxedReservationNightlyQuoteReflection {
#region Descriptor
/// <summary>File descriptor for folio/taxed_reservation_nightly_quote.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TaxedReservationNightlyQuoteReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Citmb2xpby90YXhlZF9yZXNlcnZhdGlvbl9uaWdodGx5X3F1b3RlLnByb3Rv",
"EhFob2xtcy50eXBlcy5mb2xpbxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3Vu",
"dC5wcm90bxojZm9saW8vdGF4X2Fzc2Vzc21lbnRfZXN0aW1hdGUucHJvdG8a",
"HXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnByb3RvItoBChxUYXhlZFJlc2Vy",
"dmF0aW9uTmlnaHRseVF1b3RlEjMKB29wc2RhdGUYASABKAsyIi5ob2xtcy50",
"eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGUSRAoVcHJldGF4X2xvZGdpbmdf",
"Y2hhcmdlGAIgASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5",
"QW1vdW50Ej8KDXRheF9lc3RpbWF0ZXMYAyADKAsyKC5ob2xtcy50eXBlcy5m",
"b2xpby5UYXhBc3Nlc3NtZW50RXN0aW1hdGVCG1oFZm9saW+qAhFIT0xNUy5U",
"eXBlcy5Gb2xpb2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Folio.TaxAssessmentEstimateReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Folio.TaxedReservationNightlyQuote), global::HOLMS.Types.Folio.TaxedReservationNightlyQuote.Parser, new[]{ "Opsdate", "PretaxLodgingCharge", "TaxEstimates" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class TaxedReservationNightlyQuote : pb::IMessage<TaxedReservationNightlyQuote> {
private static readonly pb::MessageParser<TaxedReservationNightlyQuote> _parser = new pb::MessageParser<TaxedReservationNightlyQuote>(() => new TaxedReservationNightlyQuote());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TaxedReservationNightlyQuote> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Folio.TaxedReservationNightlyQuoteReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationNightlyQuote() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationNightlyQuote(TaxedReservationNightlyQuote other) : this() {
Opsdate = other.opsdate_ != null ? other.Opsdate.Clone() : null;
PretaxLodgingCharge = other.pretaxLodgingCharge_ != null ? other.PretaxLodgingCharge.Clone() : null;
taxEstimates_ = other.taxEstimates_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxedReservationNightlyQuote Clone() {
return new TaxedReservationNightlyQuote(this);
}
/// <summary>Field number for the "opsdate" field.</summary>
public const int OpsdateFieldNumber = 1;
private global::HOLMS.Types.Primitive.PbLocalDate opsdate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate Opsdate {
get { return opsdate_; }
set {
opsdate_ = value;
}
}
/// <summary>Field number for the "pretax_lodging_charge" field.</summary>
public const int PretaxLodgingChargeFieldNumber = 2;
private global::HOLMS.Types.Primitive.MonetaryAmount pretaxLodgingCharge_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount PretaxLodgingCharge {
get { return pretaxLodgingCharge_; }
set {
pretaxLodgingCharge_ = value;
}
}
/// <summary>Field number for the "tax_estimates" field.</summary>
public const int TaxEstimatesFieldNumber = 3;
private static readonly pb::FieldCodec<global::HOLMS.Types.Folio.TaxAssessmentEstimate> _repeated_taxEstimates_codec
= pb::FieldCodec.ForMessage(26, global::HOLMS.Types.Folio.TaxAssessmentEstimate.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessmentEstimate> taxEstimates_ = new pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessmentEstimate>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Folio.TaxAssessmentEstimate> TaxEstimates {
get { return taxEstimates_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TaxedReservationNightlyQuote);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TaxedReservationNightlyQuote other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Opsdate, other.Opsdate)) return false;
if (!object.Equals(PretaxLodgingCharge, other.PretaxLodgingCharge)) return false;
if(!taxEstimates_.Equals(other.taxEstimates_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (opsdate_ != null) hash ^= Opsdate.GetHashCode();
if (pretaxLodgingCharge_ != null) hash ^= PretaxLodgingCharge.GetHashCode();
hash ^= taxEstimates_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (opsdate_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Opsdate);
}
if (pretaxLodgingCharge_ != null) {
output.WriteRawTag(18);
output.WriteMessage(PretaxLodgingCharge);
}
taxEstimates_.WriteTo(output, _repeated_taxEstimates_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (opsdate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Opsdate);
}
if (pretaxLodgingCharge_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PretaxLodgingCharge);
}
size += taxEstimates_.CalculateSize(_repeated_taxEstimates_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TaxedReservationNightlyQuote other) {
if (other == null) {
return;
}
if (other.opsdate_ != null) {
if (opsdate_ == null) {
opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
Opsdate.MergeFrom(other.Opsdate);
}
if (other.pretaxLodgingCharge_ != null) {
if (pretaxLodgingCharge_ == null) {
pretaxLodgingCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
PretaxLodgingCharge.MergeFrom(other.PretaxLodgingCharge);
}
taxEstimates_.Add(other.taxEstimates_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (opsdate_ == null) {
opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(opsdate_);
break;
}
case 18: {
if (pretaxLodgingCharge_ == null) {
pretaxLodgingCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(pretaxLodgingCharge_);
break;
}
case 26: {
taxEstimates_.AddEntriesFrom(input, _repeated_taxEstimates_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//-----------------------------------------------------------------------
// <copyright file="DepthEffect.cs" company="Google LLC">
//
// Copyright 2020 Google LLC. 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.Common
{
using UnityEngine;
using UnityEngine.Rendering;
/// <summary>
/// A component that controls the full-screen occlusion effect.
/// Exposes parameters to control the occlusion effect, which get applied every time update
/// gets called.
/// </summary>
[RequireComponent(typeof(Camera))]
public class DepthEffect : MonoBehaviour
{
/// <summary>
/// The global shader property name for the camera texture.
/// </summary>
public const string BackgroundTexturePropertyName = "_BackgroundTexture";
/// <summary>
/// The image effect shader to blit every frame with.
/// </summary>
public Shader OcclusionShader;
/// <summary>
/// The blur kernel size applied to the camera feed. In pixels.
/// </summary>
[Space]
public float BlurSize = 20f;
/// <summary>
/// The number of times occlusion map is downsampled before blurring. Useful for
/// performance optimization. The value of 1 means no downsampling, each next one
/// downsamples by 2.
/// </summary>
public int BlurDownsample = 2;
/// <summary>
/// Maximum occlusion transparency. The value of 1.0 means completely invisible when
/// occluded.
/// </summary>
[Range(0, 1)]
public float OcclusionTransparency = 1.0f;
/// <summary>
/// The bias added to the estimated depth. Useful to avoid occlusion of objects anchored
/// to planes. In meters.
/// </summary>
[Space]
public float OcclusionOffset = 0.08f;
/// <summary>
/// Velocity occlusions effect fades in/out when being enabled/disabled.
/// </summary>
public float OcclusionFadeVelocity = 4.0f;
/// <summary>
/// Instead of a hard z-buffer test, allows the asset to fade into the background
/// gradually. The parameter is unitless, it is a fraction of the distance between the
/// camera and the virtual object where blending is applied.
/// </summary>
public float TransitionSize = 0.1f;
private static readonly string k_CurrentDepthTexturePropertyName = "_CurrentDepthTexture";
private static readonly string k_TopLeftRightPropertyName = "_UvTopLeftRight";
private static readonly string k_BottomLeftRightPropertyName = "_UvBottomLeftRight";
private Camera m_Camera;
private Material m_DepthMaterial;
private Texture2D m_DepthTexture;
private float m_CurrentOcclusionTransparency = 1.0f;
private ARCoreBackgroundRenderer m_BackgroundRenderer;
private CommandBuffer m_DepthBuffer;
private CommandBuffer m_BackgroundBuffer;
private int m_BackgroundTextureID = -1;
/// <summary>
/// Unity's Awake() method.
/// </summary>
public void Awake()
{
m_CurrentOcclusionTransparency = OcclusionTransparency;
Debug.Assert(OcclusionShader != null, "Occlusion Shader parameter must be set.");
m_DepthMaterial = new Material(OcclusionShader);
m_DepthMaterial.SetFloat("_OcclusionTransparency", m_CurrentOcclusionTransparency);
m_DepthMaterial.SetFloat("_OcclusionOffsetMeters", OcclusionOffset);
m_DepthMaterial.SetFloat("_TransitionSize", TransitionSize);
// Default texture, will be updated each frame.
m_DepthTexture = new Texture2D(2, 2);
m_DepthTexture.filterMode = FilterMode.Bilinear;
m_DepthMaterial.SetTexture(k_CurrentDepthTexturePropertyName, m_DepthTexture);
m_Camera = Camera.main;
m_Camera.depthTextureMode |= DepthTextureMode.Depth;
m_DepthBuffer = new CommandBuffer();
m_DepthBuffer.name = "Auxilary occlusion textures";
// Creates the occlusion map.
int occlusionMapTextureID = Shader.PropertyToID("_OcclusionMap");
m_DepthBuffer.GetTemporaryRT(occlusionMapTextureID, -1, -1, 0, FilterMode.Bilinear);
// Pass #0 renders an auxilary buffer - occlusion map that indicates the
// regions of virtual objects that are behind real geometry.
m_DepthBuffer.Blit(
BuiltinRenderTextureType.CameraTarget,
occlusionMapTextureID, m_DepthMaterial, /*pass=*/ 0);
// Blurs the occlusion map.
m_DepthBuffer.SetGlobalTexture("_OcclusionMapBlurred", occlusionMapTextureID);
m_Camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, m_DepthBuffer);
m_Camera.AddCommandBuffer(CameraEvent.AfterGBuffer, m_DepthBuffer);
m_BackgroundRenderer = FindObjectOfType<ARCoreBackgroundRenderer>();
if (m_BackgroundRenderer == null)
{
Debug.LogError("BackgroundTextureProvider requires ARCoreBackgroundRenderer " +
"anywhere in the scene.");
return;
}
m_BackgroundBuffer = new CommandBuffer();
m_BackgroundBuffer.name = "Camera texture";
m_BackgroundTextureID = Shader.PropertyToID(BackgroundTexturePropertyName);
m_BackgroundBuffer.GetTemporaryRT(m_BackgroundTextureID,
/*width=*/
-1, /*height=*/ -1,
/*depthBuffer=*/
0, FilterMode.Bilinear);
var material = m_BackgroundRenderer.BackgroundMaterial;
if (material != null)
{
m_BackgroundBuffer.Blit(material.mainTexture, m_BackgroundTextureID, material);
}
m_BackgroundBuffer.SetGlobalTexture(
BackgroundTexturePropertyName, m_BackgroundTextureID);
m_Camera.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, m_BackgroundBuffer);
m_Camera.AddCommandBuffer(CameraEvent.BeforeGBuffer, m_BackgroundBuffer);
}
/// <summary>
/// Unity's Update() method.
/// </summary>
public void Update()
{
m_CurrentOcclusionTransparency +=
(OcclusionTransparency - m_CurrentOcclusionTransparency) *
Time.deltaTime * OcclusionFadeVelocity;
m_CurrentOcclusionTransparency =
Mathf.Clamp(m_CurrentOcclusionTransparency, 0.0f, OcclusionTransparency);
m_DepthMaterial.SetFloat("_OcclusionTransparency", m_CurrentOcclusionTransparency);
m_DepthMaterial.SetFloat("_TransitionSize", TransitionSize);
Shader.SetGlobalFloat("_BlurSize", BlurSize / BlurDownsample);
// Gets the latest depth map from ARCore.
Frame.CameraImage.UpdateDepthTexture(ref m_DepthTexture);
// Updates the screen orientation for each material.
_UpdateScreenOrientationOnMaterial();
}
/// <summary>
/// Unity's OnEnable() method.
/// </summary>
public void OnEnable()
{
if (m_DepthBuffer != null)
{
m_Camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, m_DepthBuffer);
m_Camera.AddCommandBuffer(CameraEvent.AfterGBuffer, m_DepthBuffer);
}
if (m_BackgroundBuffer != null)
{
m_Camera.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, m_BackgroundBuffer);
m_Camera.AddCommandBuffer(CameraEvent.BeforeGBuffer, m_BackgroundBuffer);
}
}
/// <summary>
/// Unity's OnDisable() method.
/// </summary>
public void OnDisable()
{
if (m_DepthBuffer != null)
{
m_Camera.RemoveCommandBuffer(CameraEvent.AfterForwardOpaque, m_DepthBuffer);
m_Camera.RemoveCommandBuffer(CameraEvent.AfterGBuffer, m_DepthBuffer);
}
if (m_BackgroundBuffer != null)
{
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeForwardOpaque, m_BackgroundBuffer);
m_Camera.RemoveCommandBuffer(CameraEvent.BeforeGBuffer, m_BackgroundBuffer);
}
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
// Only render the image when tracking.
if (Session.Status != SessionStatus.Tracking)
{
return;
}
// Pass #1 combines virtual and real cameras based on the occlusion map.
Graphics.Blit(source, destination, m_DepthMaterial, /*pass=*/ 1);
}
/// <summary>
/// Updates the screen orientation of the depth map.
/// </summary>
private void _UpdateScreenOrientationOnMaterial()
{
var uvQuad = Frame.CameraImage.TextureDisplayUvs;
m_DepthMaterial.SetVector(
k_TopLeftRightPropertyName,
new Vector4(
uvQuad.TopLeft.x, uvQuad.TopLeft.y, uvQuad.TopRight.x, uvQuad.TopRight.y));
m_DepthMaterial.SetVector(
k_BottomLeftRightPropertyName,
new Vector4(uvQuad.BottomLeft.x, uvQuad.BottomLeft.y, uvQuad.BottomRight.x,
uvQuad.BottomRight.y));
}
}
}
| |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace Aardvark.Base.Benchmarks
{
// AUTO GENERATED CODE - DO NOT CHANGE!
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
// Uncomment following lines for assembly output, need to add
// <DebugType>pdbonly</DebugType>
// <DebugSymbols>true</DebugSymbols>
// to Aardvark.Base.csproj for Release configuration.
// [DisassemblyDiagnoser(printAsm: true, printSource: true)]
public class DistanceRot3f
{
const int count = 10000000;
readonly Rot3f[] A = new Rot3f[count];
readonly Rot3f[] B = new Rot3f[count];
readonly float[] angles = new float[count];
private static V3f RndAxis(RandomSystem rnd)
=> rnd.UniformV3fDirection();
private static float RndAngle(RandomSystem rnd)
=> rnd.UniformFloat() * (float)Constant.Pi;
private static Rot3f RndRot(RandomSystem rnd)
=> Rot3f.Rotation(RndAxis(rnd), RndAngle(rnd));
public DistanceRot3f()
{
var rnd = new RandomSystem(1);
A.SetByIndex(i => RndRot(rnd));
angles.SetByIndex(i =>
{
float a = 0;
do { a = RndAngle(rnd); }
while (a == 0);
return a;
});
B.SetByIndex(i =>
{
var r = Rot3f.Rotation(RndAxis(rnd), angles[i]);
return r * A[i];
});
}
private double[] ComputeRelativeError(Func<Rot3f, Rot3f, float> f)
{
double[] error = new double[count];
for (int i = 0; i < count; i++)
{
var v = (double)angles[i];
var va = (double)f(A[i], B[i]);
error[i] = Fun.Abs(v - va) / Fun.Abs(v);
}
return error;
}
public void BenchmarkNumericalStability()
{
var methods = new Dictionary<string, Func<Rot3f, Rot3f, float>>()
{
{ "Stable", Rot.Distance },
{ "Fast", Rot.DistanceFast }
};
Console.WriteLine("Benchmarking numerical stability for Rot3f distance");
Console.WriteLine();
foreach (var m in methods)
{
var errors = ComputeRelativeError(m.Value);
var min = errors.Min();
var max = errors.Max();
var mean = errors.Mean();
var var = errors.Variance();
Report.Begin("Relative error for '{0}'", m.Key);
Report.Line("Min = {0}", min);
Report.Line("Max = {0}", max);
Report.Line("Mean = {0}", mean);
Report.Line("Variance = {0}", var);
Report.End();
Console.WriteLine();
}
}
[Benchmark]
public float DistanceStable()
{
float sum = 0;
for (int i = 0; i < count; i++)
{
sum += A[i].Distance(B[i]);
}
return sum;
}
[Benchmark]
public float DistanceFast()
{
float sum = 0;
for (int i = 0; i < count; i++)
{
sum += A[i].DistanceFast(B[i]);
}
return sum;
}
[Test]
public void ConsistentAndCorrect()
{
for (int i = 0; i < count / 100; i++)
{
var x = Rot.Distance(A[i], B[i]);
var y = Rot.DistanceFast(A[i], B[i]);
// Consistency
Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.01f),
"Solutions do not match{0} != {1}", x, y);
// Correctness
Assert.GreaterOrEqual(x, 0);
Assert.LessOrEqual(x, (float)Constant.Pi);
Assert.IsTrue(Fun.ApproximateEquals(x, angles[i], 0.01f),
"Solution does not match reference {0} != {1}", x, angles[i]);
}
}
}
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
// Uncomment following lines for assembly output, need to add
// <DebugType>pdbonly</DebugType>
// <DebugSymbols>true</DebugSymbols>
// to Aardvark.Base.csproj for Release configuration.
// [DisassemblyDiagnoser(printAsm: true, printSource: true)]
public class DistanceRot3d
{
const int count = 10000000;
readonly Rot3d[] A = new Rot3d[count];
readonly Rot3d[] B = new Rot3d[count];
readonly double[] angles = new double[count];
private static V3d RndAxis(RandomSystem rnd)
=> rnd.UniformV3dDirection();
private static double RndAngle(RandomSystem rnd)
=> rnd.UniformDouble() * Constant.Pi;
private static Rot3d RndRot(RandomSystem rnd)
=> Rot3d.Rotation(RndAxis(rnd), RndAngle(rnd));
public DistanceRot3d()
{
var rnd = new RandomSystem(1);
A.SetByIndex(i => RndRot(rnd));
angles.SetByIndex(i =>
{
double a = 0;
do { a = RndAngle(rnd); }
while (a == 0);
return a;
});
B.SetByIndex(i =>
{
var r = Rot3d.Rotation(RndAxis(rnd), angles[i]);
return r * A[i];
});
}
private double[] ComputeRelativeError(Func<Rot3d, Rot3d, double> f)
{
double[] error = new double[count];
for (int i = 0; i < count; i++)
{
var v = (double)angles[i];
var va = (double)f(A[i], B[i]);
error[i] = Fun.Abs(v - va) / Fun.Abs(v);
}
return error;
}
public void BenchmarkNumericalStability()
{
var methods = new Dictionary<string, Func<Rot3d, Rot3d, double>>()
{
{ "Stable", Rot.Distance },
{ "Fast", Rot.DistanceFast }
};
Console.WriteLine("Benchmarking numerical stability for Rot3d distance");
Console.WriteLine();
foreach (var m in methods)
{
var errors = ComputeRelativeError(m.Value);
var min = errors.Min();
var max = errors.Max();
var mean = errors.Mean();
var var = errors.Variance();
Report.Begin("Relative error for '{0}'", m.Key);
Report.Line("Min = {0}", min);
Report.Line("Max = {0}", max);
Report.Line("Mean = {0}", mean);
Report.Line("Variance = {0}", var);
Report.End();
Console.WriteLine();
}
}
[Benchmark]
public double DistanceStable()
{
double sum = 0;
for (int i = 0; i < count; i++)
{
sum += A[i].Distance(B[i]);
}
return sum;
}
[Benchmark]
public double DistanceFast()
{
double sum = 0;
for (int i = 0; i < count; i++)
{
sum += A[i].DistanceFast(B[i]);
}
return sum;
}
[Test]
public void ConsistentAndCorrect()
{
for (int i = 0; i < count / 100; i++)
{
var x = Rot.Distance(A[i], B[i]);
var y = Rot.DistanceFast(A[i], B[i]);
// Consistency
Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.0001),
"Solutions do not match{0} != {1}", x, y);
// Correctness
Assert.GreaterOrEqual(x, 0);
Assert.LessOrEqual(x, (double)Constant.Pi);
Assert.IsTrue(Fun.ApproximateEquals(x, angles[i], 0.0001),
"Solution does not match reference {0} != {1}", x, angles[i]);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ADMINS
{
using System;
using System.Web.Services.Protocols;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// The capture requirement part of adapter's implementation
/// </summary>
public partial class MS_ADMINSAdapter : ManagedAdapterBase, IMS_ADMINSAdapter
{
/// <summary>
/// Verify the requirements of the transport when the response is received successfully.
/// </summary>
private void VerifyTransportRelatedRequirements()
{
TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", this.Site);
switch (transport)
{
case TransportProtocol.HTTP:
// As response successfully returned, the transport related requirements can be captured.
Site.CaptureRequirement(
1,
@"[In Transport]Protocol servers MUST support SOAP over HTTP.");
break;
case TransportProtocol.HTTPS:
if (Common.IsRequirementEnabled(1002, this.Site))
{
// Having received the response successfully have proved the HTTPS transport is supported. If the HTTPS transport is not supported, the response can't be received successfully.
Site.CaptureRequirement(
1002,
@"[In Transport]Implementation does additionally support SOAP over HTTPS for securing communication with clients.(Windows SharePoint Services 3.0 and above products follow this behavior.)");
}
break;
default:
Site.Debug.Fail("Unknown transport type " + transport);
break;
}
// Add the log information.
Site.Log.Add(Microsoft.Protocols.TestTools.LogEntryKind.Comment, "The protocol message is formatted as version: {0}", this.adminService.SoapVersion);
// Verify MS-ADMINS requirement: MS-ADMINS_R4.
bool isR4Verified = this.adminService.SoapVersion == SoapProtocolVersion.Soap11 || this.adminService.SoapVersion == SoapProtocolVersion.Soap12;
Site.CaptureRequirementIfIsTrue(
isR4Verified,
4,
@" [In Transport]Protocol messages MUST be formatted as specified either in [SOAP1.1], section 4 ""SOAP Envelope"" or in [SOAP1.2/1], section 5 ""SOAP Message Construct.""");
// Having received the response successfully have proved the XML Schema is used. If the structures do not use XML Schema, the response can't be received successfully.
Site.CaptureRequirement(
6,
@"[In Common Message Syntax]The syntax of the definitions uses XML schema as defined in [XMLSCHEMA1/2] and [XMLSCHEMA2/2], and WSDL as defined in [WSDL].");
}
/// <summary>
/// Verify the requirements of the SOAP fault when the SOAP fault is received.
/// </summary>
/// <param name="soapExp">The returned SOAP fault</param>
private void VerifySoapFaultRequirements(SoapException soapExp)
{
// If a SOAP fault is returned and the SOAP fault is not null, which means protocol server faults are returned using SOAP faults, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
soapExp,
3000,
@" [In Transport]Protocol server faults MUST be returned using SOAP faults as specified either in [SOAP1.1], section 4.4 ""SOAP Fault"" or in [SOAP1.2-1/2007], section 5.4 ""SOAP Fault.""");
// The schemas are validated during invoking the operations and an XmlSchemaValidationException will be thrown if anyone of the schemas is incorrect, there is no such exception thrown, so the following requirement can be captured.
Site.CaptureRequirement(
7,
@"[In SOAPFaultDetails]The schema of SOAPFaultDetails is defined as: <s:schema xmlns:s=""http://www.w3.org/2001/XMLSchema"" targetNamespace="" http://schemas.microsoft.com/sharepoint/soap"">
<s:complexType name=""SOAPFaultDetails"">
<s:sequence>
<s:element name=""errorstring"" type=""s:string""/>
<s:element name=""errorcode"" type=""s:string"" minOccurs=""0""/>
</s:sequence>
</s:complexType>
</s:schema>");
// Extract the errorcode from SOAP fault.
string strErrorCode = Common.ExtractErrorCodeFromSoapFault(soapExp);
if (strErrorCode != null)
{
Site.Assert.IsTrue(strErrorCode.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase), "The error code value should start with '0x'.");
Site.Assert.IsTrue(strErrorCode.Length == 10, "The error code value's length should be 10.");
// If the value of the errorcode starts with "0x" and the length is 10, which means the format of the value is 0xAAAAAAAA, then the following requirement can be captured.
Site.CaptureRequirement(
2015,
@"[In SOAPFaultDetails]The format inside the string [errorcode] MUST be 0xAAAAAAAA.");
}
// If a SOAP fault is returned and the SOAP fault is not null, which means protocol server faults are returned using SOAP faults, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
soapExp,
2019,
@"[In Protocol Details]This protocol [MS-ADMINS] allows protocol servers to notify protocol clients of application-level faults using SOAP faults.");
// The schemas are validated during invoking the operations and an XmlSchemaValidationException will be thrown if anyone of the schemas is incorrect, there is no such exception thrown and only SOAPFaultDetails complex type is included in the schemas, which means the detail element in the SOAP faults is conforms to the SOAPFaultDetails complex type, so the following requirement can be captured.
Site.CaptureRequirement(
2020,
@"[In Protocol Details]This protocol [MS-ADMINS] allows protocol servers to provide additional details for SOAP faults by including a detail element as specified either in [SOAP1.1], section 4.4 ""SOAP Fault"" or [SOAP1.2-1/2007], section 5.4 ""SOAP Fault"" that conforms to the XML schema of the SOAPFaultDetails complex type specified in section 2.2.4.1.");
}
/// <summary>
/// Validate CreateSite's response data CreateSiteResult when the response is received successfully.
/// </summary>
/// <param name="createSiteResult">CreateSite's response data.</param>
private void ValidateCreateSiteResponseData(string createSiteResult)
{
// If the response data is not null, which means the response have been received successfully, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
createSiteResult,
2033,
@"[In CreateSite][The schema of CreateSite operation is defined as:] <wsdl:operation name=""CreateSite"">
<wsdl:input message=""tns:CreateSiteSoapIn"" />
<wsdl:output message=""tns:CreateSiteSoapOut"" />
</wsdl:operation>");
// If the response data is not null, which means the response have been received successfully, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
createSiteResult,
12,
@"[In CreateSite]The client sends a CreateSiteSoapIn request message, the server responds with a CreateSiteSoapOut response message.");
// The response have been received successfully, then the following requirement can be captured.
// If the response is not received and parsed successfully, the test case will fail before this requirement is captured.
Site.CaptureRequirement(
81,
@"[In CreateSiteSoapOut]The SOAP body contains a CreateSiteResponse element.");
// The response have been received successfully, then the following requirement can be captured.
// If the response is not received and parsed successfully, the test case will fail before this requirement is captured.
Site.CaptureRequirement(
2063,
@"[In CreateSiteResponse][The schema of CreateSiteResponse element is defined as:] <s:element name=""CreateSiteResponse"">
<s:complexType>
<s:sequence>
<s:element minOccurs=""0"" maxOccurs=""1"" name=""CreateSiteResult"" type=""s:string""/>
</s:sequence>
</s:complexType>
</s:element>");
// If the response have been received successfully and the response is a valid URL, then the following requirement can be captured.
Site.CaptureRequirementIfIsTrue(
Uri.IsWellFormedUriString(createSiteResult, UriKind.Absolute),
1077,
@"[In CreateSiteResponse]CreateSiteResult: Specifies the URL of the new site collection.");
}
/// <summary>
/// Validate DeleteSite's response when the response is received successfully.
/// </summary>
private void ValidateDeleteSiteResponse()
{
// The response have been received successfully, then the following requirement can be captured.
// If the following requirement is fail, the response can't be received successfully.
Site.CaptureRequirement(
2065,
@"[In DeleteSite][The schema of DeleteSite operation is defined as:] <wsdl:operation name=""DeleteSite"">
<wsdl:input message=""tns:DeleteSiteSoapIn"" />
<wsdl:output message=""tns:DeleteSiteSoapOut"" />
</wsdl:operation>");
// The response have been received successfully, then the following requirement can be captured.
// If the following requirement is fail, the response can't be received successfully.
Site.CaptureRequirement(
82,
@"[In DeleteSite]The client sends a DeleteSiteSoapIn request message and the server responds with a DeleteSiteSoapOut response message.");
// The response have been received successfully, then the following requirement can be captured.
// If the response is not received and parsed successfully, the test case will fail before this requirement is captured.
Site.CaptureRequirement(
92,
@"[In DeleteSiteSoapOut]The SOAP body contains a DeleteSiteResponse element.");
// The response have been received successfully, then the following requirement can be captured.
// If the response is not received and parsed successfully, the test case will fail before this requirement is captured.
Site.CaptureRequirement(
2073,
@"[In DeleteSiteResponse][The schema of DeleteSiteResponse element is defined as:]
<s:element name=""DeleteSiteResponse""> <s:complexType/></s:element>");
}
/// <summary>
/// Validate GetLanguages response data getLanguagesResult when the response is received successfully.
/// </summary>
/// <param name="getLanguagesResult">The return value of GetLanguages operation.</param>
private void ValidateGetLanguagesResponseData(GetLanguagesResponseGetLanguagesResult getLanguagesResult)
{
// If the response data is not null, which means the response have been received successfully, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
getLanguagesResult,
2075,
@"[In GetLanguages][The schema of GetLanguages operation is defined as:] <wsdl:operation name=""GetLanguages"">
<wsdl:input message=""tns:GetLanguagesSoapIn"" />
<wsdl:output message=""tns:GetLanguagesSoapOut"" />
</wsdl:operation>");
// If the response data is not null, which means the response have been received successfully, then the following requirement can be captured.
Site.CaptureRequirementIfIsNotNull(
getLanguagesResult,
2082,
@"[In GetLanguagesResponse][The schema of DeleteSiteResponse element is defined as:] <s:element name=""GetLanguagesResponse"">
<s:complexType>
<s:sequence>
<s:element minOccurs=""1"" maxOccurs=""1"" name=""GetLanguagesResult"">
<s:complexType>
<s:sequence>
<s:element name=""Languages"">
<s:complexType>
<s:sequence>
<s:element maxOccurs=""unbounded"" name=""LCID"" type=""s:int"" />
</s:sequence>
</s:complexType>
</s:element>
</s:sequence>
</s:complexType>
</s:element>
</s:sequence>
</s:complexType>
</s:element>");
// The response have been received successfully, then the following requirement can be captured.
// If the following requirement is failed, the response can't be received successfully.
Site.CaptureRequirement(
93,
@"[In GetLanguages]The client sends a GetLanguagesSoapIn request message and the server responds with a GetLanguagesSoapOut response message.");
// The response have been received successfully, then the following requirement can be captured.
// If the response is not received and parsed successfully, the test case will fail before this requirement is captured.
Site.CaptureRequirement(
98,
@"[In GetLanguagesSoapOut]The SOAP body contains a GetLanguagesResponse element.");
// If the lcid list in the response is not empty, then the following requirement can be captured.
Site.CaptureRequirementIfIsTrue(
getLanguagesResult.Languages.Length > 0,
94,
@"[In GetLanguagesResponse]GetLanguagesResult: Provides the locale identifiers (LCIDs) of languages used in the deployment.");
Site.CaptureRequirementIfIsTrue(
getLanguagesResult.Languages.Length > 0,
94001,
@"[In GetLanguagesResponse] Languages: Specifies the languages used in the deployment.");
Site.CaptureRequirementIfIsTrue(
getLanguagesResult.Languages.Length > 0,
94002,
@"[In GetLanguagesResponse] LCID: Specifies the locale identifier (LCID) of a language used in the deployment.");
}
}
}
| |
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Nethereum.Contracts.ContractHandlers;
using Nethereum.ENS.Registrar.ContractDefinition;
using Nethereum.RPC.Eth.DTOs;
namespace Nethereum.ENS
{
public partial class RegistrarService
{
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, RegistrarDeployment registrarDeployment, CancellationTokenSource cancellationTokenSource = null)
{
return web3.Eth.GetContractDeploymentHandler<RegistrarDeployment>().SendRequestAndWaitForReceiptAsync(registrarDeployment, cancellationTokenSource);
}
public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, RegistrarDeployment registrarDeployment)
{
return web3.Eth.GetContractDeploymentHandler<RegistrarDeployment>().SendRequestAsync(registrarDeployment);
}
public static async Task<RegistrarService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, RegistrarDeployment registrarDeployment, CancellationTokenSource cancellationTokenSource = null)
{
var receipt = await DeployContractAndWaitForReceiptAsync(web3, registrarDeployment, cancellationTokenSource);
return new RegistrarService(web3, receipt.ContractAddress);
}
protected Nethereum.Web3.Web3 Web3{ get; }
public ContractHandler ContractHandler { get; }
public RegistrarService(Nethereum.Web3.Web3 web3, string contractAddress)
{
Web3 = web3;
ContractHandler = web3.Eth.GetContractHandler(contractAddress);
}
public Task<string> ReleaseDeedRequestAsync(ReleaseDeedFunction releaseDeedFunction)
{
return ContractHandler.SendRequestAsync(releaseDeedFunction);
}
public Task<TransactionReceipt> ReleaseDeedRequestAndWaitForReceiptAsync(ReleaseDeedFunction releaseDeedFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(releaseDeedFunction, cancellationToken);
}
public Task<string> ReleaseDeedRequestAsync(byte[] hash)
{
var releaseDeedFunction = new ReleaseDeedFunction();
releaseDeedFunction.Hash = hash;
return ContractHandler.SendRequestAsync(releaseDeedFunction);
}
public Task<TransactionReceipt> ReleaseDeedRequestAndWaitForReceiptAsync(byte[] hash, CancellationTokenSource cancellationToken = null)
{
var releaseDeedFunction = new ReleaseDeedFunction();
releaseDeedFunction.Hash = hash;
return ContractHandler.SendRequestAndWaitForReceiptAsync(releaseDeedFunction, cancellationToken);
}
public Task<BigInteger> GetAllowedTimeQueryAsync(GetAllowedTimeFunction getAllowedTimeFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetAllowedTimeFunction, BigInteger>(getAllowedTimeFunction, blockParameter);
}
public Task<BigInteger> GetAllowedTimeQueryAsync(byte[] hash, BlockParameter blockParameter = null)
{
var getAllowedTimeFunction = new GetAllowedTimeFunction();
getAllowedTimeFunction.Hash = hash;
return ContractHandler.QueryAsync<GetAllowedTimeFunction, BigInteger>(getAllowedTimeFunction, blockParameter);
}
public Task<string> InvalidateNameRequestAsync(InvalidateNameFunction invalidateNameFunction)
{
return ContractHandler.SendRequestAsync(invalidateNameFunction);
}
public Task<TransactionReceipt> InvalidateNameRequestAndWaitForReceiptAsync(InvalidateNameFunction invalidateNameFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(invalidateNameFunction, cancellationToken);
}
public Task<string> InvalidateNameRequestAsync(string unhashedName)
{
var invalidateNameFunction = new InvalidateNameFunction();
invalidateNameFunction.UnhashedName = unhashedName;
return ContractHandler.SendRequestAsync(invalidateNameFunction);
}
public Task<TransactionReceipt> InvalidateNameRequestAndWaitForReceiptAsync(string unhashedName, CancellationTokenSource cancellationToken = null)
{
var invalidateNameFunction = new InvalidateNameFunction();
invalidateNameFunction.UnhashedName = unhashedName;
return ContractHandler.SendRequestAndWaitForReceiptAsync(invalidateNameFunction, cancellationToken);
}
public Task<byte[]> ShaBidQueryAsync(ShaBidFunction shaBidFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<ShaBidFunction, byte[]>(shaBidFunction, blockParameter);
}
public Task<byte[]> ShaBidQueryAsync(byte[] hash, string owner, BigInteger value, byte[] salt, BlockParameter blockParameter = null)
{
var shaBidFunction = new ShaBidFunction();
shaBidFunction.Hash = hash;
shaBidFunction.Owner = owner;
shaBidFunction.Value = value;
shaBidFunction.Salt = salt;
return ContractHandler.QueryAsync<ShaBidFunction, byte[]>(shaBidFunction, blockParameter);
}
public Task<string> CancelBidRequestAsync(CancelBidFunction cancelBidFunction)
{
return ContractHandler.SendRequestAsync(cancelBidFunction);
}
public Task<TransactionReceipt> CancelBidRequestAndWaitForReceiptAsync(CancelBidFunction cancelBidFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(cancelBidFunction, cancellationToken);
}
public Task<string> CancelBidRequestAsync(string bidder, byte[] seal)
{
var cancelBidFunction = new CancelBidFunction();
cancelBidFunction.Bidder = bidder;
cancelBidFunction.Seal = seal;
return ContractHandler.SendRequestAsync(cancelBidFunction);
}
public Task<TransactionReceipt> CancelBidRequestAndWaitForReceiptAsync(string bidder, byte[] seal, CancellationTokenSource cancellationToken = null)
{
var cancelBidFunction = new CancelBidFunction();
cancelBidFunction.Bidder = bidder;
cancelBidFunction.Seal = seal;
return ContractHandler.SendRequestAndWaitForReceiptAsync(cancelBidFunction, cancellationToken);
}
public Task<EntriesOutputDTO> EntriesQueryAsync(EntriesFunction entriesFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<EntriesFunction, EntriesOutputDTO>(entriesFunction, blockParameter);
}
public Task<EntriesOutputDTO> EntriesQueryAsync(byte[] hash, BlockParameter blockParameter = null)
{
var entriesFunction = new EntriesFunction();
entriesFunction.Hash = hash;
return ContractHandler.QueryDeserializingToObjectAsync<EntriesFunction, EntriesOutputDTO>(entriesFunction, blockParameter);
}
public Task<string> EnsQueryAsync(EnsFunction ensFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<EnsFunction, string>(ensFunction, blockParameter);
}
public Task<string> EnsQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<EnsFunction, string>(null, blockParameter);
}
public Task<string> UnsealBidRequestAsync(UnsealBidFunction unsealBidFunction)
{
return ContractHandler.SendRequestAsync(unsealBidFunction);
}
public Task<TransactionReceipt> UnsealBidRequestAndWaitForReceiptAsync(UnsealBidFunction unsealBidFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(unsealBidFunction, cancellationToken);
}
public Task<string> UnsealBidRequestAsync(byte[] hash, BigInteger value, byte[] salt)
{
var unsealBidFunction = new UnsealBidFunction();
unsealBidFunction.Hash = hash;
unsealBidFunction.Value = value;
unsealBidFunction.Salt = salt;
return ContractHandler.SendRequestAsync(unsealBidFunction);
}
public Task<TransactionReceipt> UnsealBidRequestAndWaitForReceiptAsync(byte[] hash, BigInteger value, byte[] salt, CancellationTokenSource cancellationToken = null)
{
var unsealBidFunction = new UnsealBidFunction();
unsealBidFunction.Hash = hash;
unsealBidFunction.Value = value;
unsealBidFunction.Salt = salt;
return ContractHandler.SendRequestAndWaitForReceiptAsync(unsealBidFunction, cancellationToken);
}
public Task<string> TransferRegistrarsRequestAsync(TransferRegistrarsFunction transferRegistrarsFunction)
{
return ContractHandler.SendRequestAsync(transferRegistrarsFunction);
}
public Task<TransactionReceipt> TransferRegistrarsRequestAndWaitForReceiptAsync(TransferRegistrarsFunction transferRegistrarsFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferRegistrarsFunction, cancellationToken);
}
public Task<string> TransferRegistrarsRequestAsync(byte[] hash)
{
var transferRegistrarsFunction = new TransferRegistrarsFunction();
transferRegistrarsFunction.Hash = hash;
return ContractHandler.SendRequestAsync(transferRegistrarsFunction);
}
public Task<TransactionReceipt> TransferRegistrarsRequestAndWaitForReceiptAsync(byte[] hash, CancellationTokenSource cancellationToken = null)
{
var transferRegistrarsFunction = new TransferRegistrarsFunction();
transferRegistrarsFunction.Hash = hash;
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferRegistrarsFunction, cancellationToken);
}
public Task<string> SealedBidsQueryAsync(SealedBidsFunction sealedBidsFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<SealedBidsFunction, string>(sealedBidsFunction, blockParameter);
}
public Task<string> SealedBidsQueryAsync(string returnValue1, byte[] returnValue2, BlockParameter blockParameter = null)
{
var sealedBidsFunction = new SealedBidsFunction();
sealedBidsFunction.ReturnValue1 = returnValue1;
sealedBidsFunction.ReturnValue2 = returnValue2;
return ContractHandler.QueryAsync<SealedBidsFunction, string>(sealedBidsFunction, blockParameter);
}
public Task<byte> StateQueryAsync(StateFunction stateFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<StateFunction, byte>(stateFunction, blockParameter);
}
public Task<byte> StateQueryAsync(byte[] hash, BlockParameter blockParameter = null)
{
var stateFunction = new StateFunction();
stateFunction.Hash = hash;
return ContractHandler.QueryAsync<StateFunction, byte>(stateFunction, blockParameter);
}
public Task<string> TransferRequestAsync(TransferFunction transferFunction)
{
return ContractHandler.SendRequestAsync(transferFunction);
}
public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(TransferFunction transferFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken);
}
public Task<string> TransferRequestAsync(byte[] hash, string newOwner)
{
var transferFunction = new TransferFunction();
transferFunction.Hash = hash;
transferFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAsync(transferFunction);
}
public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(byte[] hash, string newOwner, CancellationTokenSource cancellationToken = null)
{
var transferFunction = new TransferFunction();
transferFunction.Hash = hash;
transferFunction.NewOwner = newOwner;
return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken);
}
public Task<bool> IsAllowedQueryAsync(IsAllowedFunction isAllowedFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<IsAllowedFunction, bool>(isAllowedFunction, blockParameter);
}
public Task<bool> IsAllowedQueryAsync(byte[] hash, BigInteger timestamp, BlockParameter blockParameter = null)
{
var isAllowedFunction = new IsAllowedFunction();
isAllowedFunction.Hash = hash;
isAllowedFunction.Timestamp = timestamp;
return ContractHandler.QueryAsync<IsAllowedFunction, bool>(isAllowedFunction, blockParameter);
}
public Task<string> FinalizeAuctionRequestAsync(FinalizeAuctionFunction finalizeAuctionFunction)
{
return ContractHandler.SendRequestAsync(finalizeAuctionFunction);
}
public Task<TransactionReceipt> FinalizeAuctionRequestAndWaitForReceiptAsync(FinalizeAuctionFunction finalizeAuctionFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(finalizeAuctionFunction, cancellationToken);
}
public Task<string> FinalizeAuctionRequestAsync(byte[] hash)
{
var finalizeAuctionFunction = new FinalizeAuctionFunction();
finalizeAuctionFunction.Hash = hash;
return ContractHandler.SendRequestAsync(finalizeAuctionFunction);
}
public Task<TransactionReceipt> FinalizeAuctionRequestAndWaitForReceiptAsync(byte[] hash, CancellationTokenSource cancellationToken = null)
{
var finalizeAuctionFunction = new FinalizeAuctionFunction();
finalizeAuctionFunction.Hash = hash;
return ContractHandler.SendRequestAndWaitForReceiptAsync(finalizeAuctionFunction, cancellationToken);
}
public Task<BigInteger> RegistryStartedQueryAsync(RegistryStartedFunction registryStartedFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistryStartedFunction, BigInteger>(registryStartedFunction, blockParameter);
}
public Task<BigInteger> RegistryStartedQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RegistryStartedFunction, BigInteger>(null, blockParameter);
}
public Task<uint> LaunchLengthQueryAsync(LaunchLengthFunction launchLengthFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<LaunchLengthFunction, uint>(launchLengthFunction, blockParameter);
}
public Task<uint> LaunchLengthQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<LaunchLengthFunction, uint>(null, blockParameter);
}
public Task<string> NewBidRequestAsync(NewBidFunction newBidFunction)
{
return ContractHandler.SendRequestAsync(newBidFunction);
}
public Task<TransactionReceipt> NewBidRequestAndWaitForReceiptAsync(NewBidFunction newBidFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(newBidFunction, cancellationToken);
}
public Task<string> NewBidRequestAsync(byte[] sealedBid)
{
var newBidFunction = new NewBidFunction();
newBidFunction.SealedBid = sealedBid;
return ContractHandler.SendRequestAsync(newBidFunction);
}
public Task<TransactionReceipt> NewBidRequestAndWaitForReceiptAsync(byte[] sealedBid, CancellationTokenSource cancellationToken = null)
{
var newBidFunction = new NewBidFunction();
newBidFunction.SealedBid = sealedBid;
return ContractHandler.SendRequestAndWaitForReceiptAsync(newBidFunction, cancellationToken);
}
public Task<string> EraseNodeRequestAsync(EraseNodeFunction eraseNodeFunction)
{
return ContractHandler.SendRequestAsync(eraseNodeFunction);
}
public Task<TransactionReceipt> EraseNodeRequestAndWaitForReceiptAsync(EraseNodeFunction eraseNodeFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(eraseNodeFunction, cancellationToken);
}
public Task<string> EraseNodeRequestAsync(List<byte[]> labels)
{
var eraseNodeFunction = new EraseNodeFunction();
eraseNodeFunction.Labels = labels;
return ContractHandler.SendRequestAsync(eraseNodeFunction);
}
public Task<TransactionReceipt> EraseNodeRequestAndWaitForReceiptAsync(List<byte[]> labels, CancellationTokenSource cancellationToken = null)
{
var eraseNodeFunction = new EraseNodeFunction();
eraseNodeFunction.Labels = labels;
return ContractHandler.SendRequestAndWaitForReceiptAsync(eraseNodeFunction, cancellationToken);
}
public Task<string> StartAuctionsRequestAsync(StartAuctionsFunction startAuctionsFunction)
{
return ContractHandler.SendRequestAsync(startAuctionsFunction);
}
public Task<TransactionReceipt> StartAuctionsRequestAndWaitForReceiptAsync(StartAuctionsFunction startAuctionsFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionsFunction, cancellationToken);
}
public Task<string> StartAuctionsRequestAsync(List<byte[]> hashes)
{
var startAuctionsFunction = new StartAuctionsFunction();
startAuctionsFunction.Hashes = hashes;
return ContractHandler.SendRequestAsync(startAuctionsFunction);
}
public Task<TransactionReceipt> StartAuctionsRequestAndWaitForReceiptAsync(List<byte[]> hashes, CancellationTokenSource cancellationToken = null)
{
var startAuctionsFunction = new StartAuctionsFunction();
startAuctionsFunction.Hashes = hashes;
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionsFunction, cancellationToken);
}
public Task<string> AcceptRegistrarTransferRequestAsync(AcceptRegistrarTransferFunction acceptRegistrarTransferFunction)
{
return ContractHandler.SendRequestAsync(acceptRegistrarTransferFunction);
}
public Task<TransactionReceipt> AcceptRegistrarTransferRequestAndWaitForReceiptAsync(AcceptRegistrarTransferFunction acceptRegistrarTransferFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(acceptRegistrarTransferFunction, cancellationToken);
}
public Task<string> AcceptRegistrarTransferRequestAsync(byte[] hash, string deed, BigInteger registrationDate)
{
var acceptRegistrarTransferFunction = new AcceptRegistrarTransferFunction();
acceptRegistrarTransferFunction.Hash = hash;
acceptRegistrarTransferFunction.Deed = deed;
acceptRegistrarTransferFunction.RegistrationDate = registrationDate;
return ContractHandler.SendRequestAsync(acceptRegistrarTransferFunction);
}
public Task<TransactionReceipt> AcceptRegistrarTransferRequestAndWaitForReceiptAsync(byte[] hash, string deed, BigInteger registrationDate, CancellationTokenSource cancellationToken = null)
{
var acceptRegistrarTransferFunction = new AcceptRegistrarTransferFunction();
acceptRegistrarTransferFunction.Hash = hash;
acceptRegistrarTransferFunction.Deed = deed;
acceptRegistrarTransferFunction.RegistrationDate = registrationDate;
return ContractHandler.SendRequestAndWaitForReceiptAsync(acceptRegistrarTransferFunction, cancellationToken);
}
public Task<string> StartAuctionRequestAsync(StartAuctionFunction startAuctionFunction)
{
return ContractHandler.SendRequestAsync(startAuctionFunction);
}
public Task<TransactionReceipt> StartAuctionRequestAndWaitForReceiptAsync(StartAuctionFunction startAuctionFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionFunction, cancellationToken);
}
public Task<string> StartAuctionRequestAsync(byte[] hash)
{
var startAuctionFunction = new StartAuctionFunction();
startAuctionFunction.Hash = hash;
return ContractHandler.SendRequestAsync(startAuctionFunction);
}
public Task<TransactionReceipt> StartAuctionRequestAndWaitForReceiptAsync(byte[] hash, CancellationTokenSource cancellationToken = null)
{
var startAuctionFunction = new StartAuctionFunction();
startAuctionFunction.Hash = hash;
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionFunction, cancellationToken);
}
public Task<byte[]> RootNodeQueryAsync(RootNodeFunction rootNodeFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RootNodeFunction, byte[]>(rootNodeFunction, blockParameter);
}
public Task<byte[]> RootNodeQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RootNodeFunction, byte[]>(null, blockParameter);
}
public Task<string> StartAuctionsAndBidRequestAsync(StartAuctionsAndBidFunction startAuctionsAndBidFunction)
{
return ContractHandler.SendRequestAsync(startAuctionsAndBidFunction);
}
public Task<TransactionReceipt> StartAuctionsAndBidRequestAndWaitForReceiptAsync(StartAuctionsAndBidFunction startAuctionsAndBidFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionsAndBidFunction, cancellationToken);
}
public Task<string> StartAuctionsAndBidRequestAsync(List<byte[]> hashes, byte[] sealedBid)
{
var startAuctionsAndBidFunction = new StartAuctionsAndBidFunction();
startAuctionsAndBidFunction.Hashes = hashes;
startAuctionsAndBidFunction.SealedBid = sealedBid;
return ContractHandler.SendRequestAsync(startAuctionsAndBidFunction);
}
public Task<TransactionReceipt> StartAuctionsAndBidRequestAndWaitForReceiptAsync(List<byte[]> hashes, byte[] sealedBid, CancellationTokenSource cancellationToken = null)
{
var startAuctionsAndBidFunction = new StartAuctionsAndBidFunction();
startAuctionsAndBidFunction.Hashes = hashes;
startAuctionsAndBidFunction.SealedBid = sealedBid;
return ContractHandler.SendRequestAndWaitForReceiptAsync(startAuctionsAndBidFunction, cancellationToken);
}
}
}
| |
/**
* Copyright 2013 Mehran Ziadloo
* WSS: A WebSocket Server written in C# and .Net (Mono)
* (https://github.com/ziadloo/WSS)
*
* 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.Net.Sockets;
using System.Collections.Generic;
using System.Threading;
using System.Collections;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;
namespace Base
{
public abstract class Application
{
protected ILogger logger;
protected string version = "1.0";
protected List<IConnection> connections;
private List<IConnection> connectionsToBeAdded;
private List<IConnection> connectionsToBeRemoved;
private Thread connectionWorker_Thread;
private EventWaitHandle[] connectionWorker_Eventhandlers = new EventWaitHandle[2];
private ManualResetEvent connectionWorker_ExitSignal = new ManualResetEvent(false);
private AutoResetEvent connectionWorker_ProduceSignal = new AutoResetEvent(false);
private ManualResetEvent connectionWorker_DoneSignal = new ManualResetEvent(true);
protected IConnection CurrentConnection
{
set { CallContext.SetData("CurrentConnection", value); }
get { return (IConnection)CallContext.GetData("CurrentConnection"); }
}
protected Session CurrentSession
{
set { CallContext.SetData("CurrentSession", value); }
get { return (Session)CallContext.GetData("CurrentSession"); }
}
public string Version
{
get { return version; }
}
protected bool isStarted = false;
public bool IsStarted
{
get { return isStarted; }
}
public IServer Server
{
get;
set;
}
public Application()
{
connections = new List<IConnection>();
connectionsToBeAdded = new List<IConnection>();
connectionsToBeRemoved = new List<IConnection>();
connectionWorker_Eventhandlers[0] = connectionWorker_ExitSignal;
connectionWorker_Eventhandlers[1] = connectionWorker_ProduceSignal;
}
public virtual void SetLogger(ILogger logger)
{
this.logger = logger;
}
public void AddConnection(IConnection client)
{
lock (((ICollection)connectionsToBeAdded).SyncRoot) {
if (!connectionsToBeAdded.Contains (client)) {
connectionsToBeAdded.Add(client);
connectionWorker_ProduceSignal.Set();
}
}
}
public void RemoveConnection(IConnection client)
{
lock (((ICollection)connectionsToBeRemoved).SyncRoot) {
if (!connectionsToBeRemoved.Contains (client)) {
connectionsToBeRemoved.Add (client);
connectionWorker_ProduceSignal.Set ();
}
}
}
public virtual void Start()
{
if (!isStarted) {
isStarted = true;
connectionWorker_ProduceSignal.Reset();
connectionWorker_ExitSignal.Reset();
connectionWorker_DoneSignal.Reset();
connectionWorker_Thread = new Thread(connectionWorker);
connectionWorker_Thread.Start();
}
}
public virtual void Stop()
{
if (isStarted) {
isStarted = false;
lock (((ICollection)connections).SyncRoot) {
lock (((ICollection)connectionsToBeRemoved).SyncRoot) {
foreach (IConnection c in connections) {
if (!connectionsToBeRemoved.Contains(c)) {
connectionsToBeRemoved.Add(c);
}
}
}
}
connectionWorker_ProduceSignal.Set();
Task.Run(async delegate
{
await Task.Delay(1000);
connectionWorker_ExitSignal.Set();
}
);
connectionWorker_DoneSignal.WaitOne();
}
}
public void EnqueueIncomingFrame(Frame frame)
{
CurrentConnection = frame.Connection;
CurrentSession = (Session)CurrentConnection.Session;
OnData(frame);
}
public long GetConnectionCount()
{
lock (((ICollection)connections).SyncRoot) {
return connections.Count;
}
}
private void connectionWorker()
{
while (WaitHandle.WaitAny(connectionWorker_Eventhandlers) == 1) {
List<IConnection> _connectionsToBeAdded;
List<IConnection> _connectionsToBeRemoved;
lock (((ICollection)connectionsToBeAdded).SyncRoot) {
_connectionsToBeAdded = new List<IConnection>(connectionsToBeAdded);
connectionsToBeAdded.Clear();
}
lock (((ICollection)connectionsToBeRemoved).SyncRoot) {
_connectionsToBeRemoved = new List<IConnection>(connectionsToBeRemoved);
connectionsToBeRemoved.Clear();
}
lock (((ICollection)connections).SyncRoot) {
foreach (IConnection client in connections) {
if (!client.Connected && !_connectionsToBeRemoved.Contains(client)) {
_connectionsToBeRemoved.Add(client);
}
}
}
if (_connectionsToBeAdded.Count > 0) {
List<IConnection> newConnections = new List<IConnection>();
lock (((ICollection)connections).SyncRoot) {
foreach (IConnection client in _connectionsToBeAdded) {
if (!connections.Contains(client)) {
connections.Add(client);
newConnections.Add(client);
}
}
}
foreach (IConnection client in newConnections) {
CurrentConnection = client;
CurrentSession = client.Session;
OnConnect(client);
}
}
if (_connectionsToBeRemoved.Count > 0) {
List<IConnection> lostConnections = new List<IConnection>();
lock (((ICollection)connections).SyncRoot) {
foreach (IConnection client in _connectionsToBeRemoved) {
if (connections.Contains(client)) {
connections.Remove(client);
lostConnections.Add(client);
}
}
}
foreach (IConnection client in lostConnections) {
CurrentConnection = client;
CurrentSession = client.Session;
OnDisconnect(client);
}
foreach (IConnection client in lostConnections) {
client.Close();
}
}
}
connectionWorker_DoneSignal.Set();
}
public void PingConnections()
{
lock (((ICollection)connections).SyncRoot) {
foreach (IConnection c in connections) {
try {
#if LOG_PP
logger.log("Sending ping to: " + c.IP.ToString());
#endif
c.Send (new Frame (Frame.OpCodeType.Ping));
} catch (Exception) {
}
}
}
}
public abstract void OnData(Frame frame);
public abstract void OnConnect(IConnection client);
public abstract void OnDisconnect(IConnection client);
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Reflection;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// A common base class for code shared between an interpreted (old) script block and a compiled (new) script block.
/// </summary>
internal abstract class ScriptCommandProcessorBase : CommandProcessorBase
{
protected ScriptCommandProcessorBase(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
: base(new ScriptInfo(string.Empty, scriptBlock, context))
{
this._dontUseScopeCommandOrigin = false;
this._fromScriptFile = false;
CommonInitialization(scriptBlock, context, useLocalScope, origin, sessionState);
}
protected ScriptCommandProcessorBase(IScriptCommandInfo commandInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState)
: base((CommandInfo)commandInfo)
{
Diagnostics.Assert(commandInfo != null, "commandInfo cannot be null");
Diagnostics.Assert(commandInfo.ScriptBlock != null, "scriptblock cannot be null");
this._fromScriptFile = (this.CommandInfo is ExternalScriptInfo || this.CommandInfo is ScriptInfo);
this._dontUseScopeCommandOrigin = true;
CommonInitialization(commandInfo.ScriptBlock, context, useLocalScope, CommandOrigin.Internal, sessionState);
}
/// <summary>
/// When executing a scriptblock, the command origin needs to be set for the current scope.
/// If this true, then the scope origin will be set to the command origin. If it's false,
/// then the scope origin will be set to Internal. This allows public functions to call
/// private functions but still see $MyInvocation.CommandOrigin as $true.
/// </summary>
protected bool _dontUseScopeCommandOrigin;
/// <summary>
/// If true, then an exit exception will be rethrown to instead of caught and processed...
/// </summary>
protected bool _rethrowExitException;
/// <summary>
/// This indicates whether exit is called during the execution of
/// script block.
/// </summary>
/// <remarks>
/// Exit command can be executed in any of begin/process/end blocks.
///
/// If exit is called in one block (for example, begin), any subsequent
/// blocks (for example, process and end) should not be executed.
/// </remarks>
protected bool _exitWasCalled;
protected ScriptBlock _scriptBlock;
private ScriptParameterBinderController _scriptParameterBinderController;
internal ScriptParameterBinderController ScriptParameterBinderController
{
get
{
if (_scriptParameterBinderController == null)
{
// Set up the hashtable that will be used to hold all of the bound parameters...
_scriptParameterBinderController =
new ScriptParameterBinderController(((IScriptCommandInfo)CommandInfo).ScriptBlock,
Command.MyInvocation, Context, Command, CommandScope);
_scriptParameterBinderController.CommandLineParameters.UpdateInvocationInfo(this.Command.MyInvocation);
this.Command.MyInvocation.UnboundArguments = _scriptParameterBinderController.DollarArgs;
}
return _scriptParameterBinderController;
}
}
/// <summary>
/// Helper function for setting up command object and commandRuntime object
/// for script command processor.
/// </summary>
protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
{
Diagnostics.Assert(context != null, "execution context cannot be null");
Diagnostics.Assert(context.Engine != null, "context.engine cannot be null");
this.CommandSessionState = sessionState;
this._context = context;
this._rethrowExitException = this.Context.ScriptCommandProcessorShouldRethrowExit;
this._context.ScriptCommandProcessorShouldRethrowExit = false;
ScriptCommand scriptCommand = new ScriptCommand { CommandInfo = this.CommandInfo };
this.Command = scriptCommand;
// WinBlue: 219115
// Set the command origin for the new ScriptCommand object since we're not
// going through command discovery here where it's usually set.
this.Command.CommandOriginInternal = origin;
this.Command.commandRuntime = this.commandRuntime = new MshCommandRuntime(this.Context, this.CommandInfo, scriptCommand);
this.CommandScope = useLocalScope
? CommandSessionState.NewScope(this.FromScriptFile)
: CommandSessionState.CurrentScope;
this.UseLocalScope = useLocalScope;
_scriptBlock = scriptBlock;
// If the script has been dotted, throw an error if it's from a different language mode.
// Unless it was a script loaded through -File, in which case the danger of dotting other
// language modes (getting internal functions in the user's state) isn't a danger
if ((!this.UseLocalScope) && (!this._rethrowExitException))
{
ValidateCompatibleLanguageMode(_scriptBlock, context.LanguageMode, Command.MyInvocation);
}
}
/// <summary>
/// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
/// and if yes, then returns the help target to display.
/// </summary>
/// <param name="helpTarget">Help target to request.</param>
/// <param name="helpCategory">Help category to request.</param>
/// <returns><see langword="true"/> if user requested help; <see langword="false"/> otherwise.</returns>
internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
{
if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null)
{
foreach (CommandParameterInternal parameter in this.arguments)
{
Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
if (parameter.IsDashQuestion())
{
Dictionary<Ast, Token[]> scriptBlockTokenCache = new Dictionary<Ast, Token[]>();
string unused;
HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo,
dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused);
if (helpInfo == null)
{
break;
}
helpTarget = helpInfo.Name;
helpCategory = helpInfo.HelpCategory;
return true;
}
}
}
return base.IsHelpRequested(out helpTarget, out helpCategory);
}
}
/// <summary>
/// This class implements a command processor for script related commands.
/// </summary>
/// <remarks>
/// 1. Usage scenarios
///
/// ScriptCommandProcessor is used for four kinds of commands.
///
/// a. Functions and filters
///
/// For example,
///
/// function foo($a) {$a}
/// foo "my text"
///
/// Second command is an example of a function invocation.
///
/// In this case, a FunctionInfo object is provided while constructing
/// command processor.
///
/// b. Script File
///
/// For example,
///
/// . .\my.ps1
///
/// In this case, a ExternalScriptInfo or ScriptInfo object is provided
/// while constructing command processor.
///
/// c. ScriptBlock
///
/// For example,
///
/// . {$a = 5}
///
/// In this case, a ScriptBlock object is provided while constructing command
/// processor.
///
/// d. Script Text
///
/// This is used internally for directly running a text stream of script.
///
/// 2. Design
///
/// a. Script block
///
/// No matter how a script command processor is created, core piece of information
/// is always a ScriptBlock object, which can come from either a FunctionInfo object,
/// a ScriptInfo object, or directly parsed from script text.
///
/// b. Script scope
///
/// A script block can be executed either in current scope or in a new scope.
///
/// New scope created should be a scope supporting $script: in case the command
/// processor is created from a script file.
///
/// c. Begin/Process/End blocks
///
/// Each script block can have one block of script for begin/process/end. These map
/// to BeginProcessing, ProcessingRecord, and EndProcessing of cmdlet api.
///
/// d. ExitException handling
///
/// If the command processor is created based on a script file, its exit exception
/// handling is different in the sense that it indicates an exitcode instead of killing
/// current powershell session.
/// </remarks>
internal sealed class DlrScriptCommandProcessor : ScriptCommandProcessorBase
{
private readonly ArrayList _input = new ArrayList();
private readonly object _dollarUnderbar = AutomationNull.Value;
private new ScriptBlock _scriptBlock;
private MutableTuple _localsTuple;
private bool _runOptimizedCode;
private bool _argsBound;
private FunctionContext _functionContext;
internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState, object dollarUnderbar)
: base(scriptBlock, context, useNewScope, origin, sessionState)
{
Init();
_dollarUnderbar = dollarUnderbar;
}
internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState)
: base(scriptBlock, context, useNewScope, origin, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(functionInfo, context, useNewScope, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(scriptInfo, context, useNewScope, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(scriptInfo, context, useNewScope, sessionState)
{
Init();
}
private void Init()
{
_scriptBlock = base._scriptBlock;
_obsoleteAttribute = _scriptBlock.ObsoleteAttribute;
_runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode <= 0 && UseLocalScope);
_localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode);
if (UseLocalScope)
{
Diagnostics.Assert(CommandScope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set.");
CommandScope.LocalsTuple = _localsTuple;
}
}
/// <summary>
/// Get the ObsoleteAttribute of the current command.
/// </summary>
internal override ObsoleteAttribute ObsoleteAttribute
{
get { return _obsoleteAttribute; }
}
private ObsoleteAttribute _obsoleteAttribute;
internal override void Prepare(IDictionary psDefaultParameterValues)
{
_localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, this.Command.MyInvocation, _context);
_scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, _context);
_functionContext = new FunctionContext
{
_executionContext = _context,
_outputPipe = commandRuntime.OutputPipe,
_localsTuple = _localsTuple,
_scriptBlock = _scriptBlock,
_file = _scriptBlock.File,
_debuggerHidden = _scriptBlock.DebuggerHidden,
_debuggerStepThrough = _scriptBlock.DebuggerStepThrough,
_sequencePoints = _scriptBlock.SequencePoints,
};
}
/// <summary>
/// Execute BeginProcessing part of command. It sets up the overall scope
/// object for this command and runs the begin clause of the script block if
/// it isn't empty.
/// </summary>
/// <exception cref="PipelineStoppedException">
/// a terminating error occurred, or the pipeline was otherwise stopped
/// </exception>
internal override void DoBegin()
{
if (!RanBeginAlready)
{
RanBeginAlready = true;
ScriptBlock.LogScriptBlockStart(_scriptBlock, Context.CurrentRunspace.InstanceId);
// Even if there is no begin, we need to set up the execution scope for this
// script...
SetCurrentScopeToExecutionScope();
CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = this;
if (_scriptBlock.HasBeginBlock)
{
RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock,
AutomationNull.Value, _input);
}
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
RestorePreviousScope();
}
}
}
internal override void ProcessRecord()
{
if (_exitWasCalled)
{
return;
}
if (!this.RanBeginAlready)
{
RanBeginAlready = true;
if (_scriptBlock.HasBeginBlock)
{
RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, AutomationNull.Value, _input);
}
}
if (_scriptBlock.HasProcessBlock)
{
if (!IsPipelineInputExpected())
{
RunClause(_runOptimizedCode ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, null, _input);
}
else
{
DoProcessRecordWithInput();
}
}
else if (IsPipelineInputExpected())
{
// accumulate the input when working in "synchronous" mode
Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started
if (this.CommandRuntime.InputPipe.ExternalReader == null)
{
while (Read())
{
// accumulate all of the objects and execute at the end.
_input.Add(Command.CurrentPipelineObject);
}
}
}
}
internal override void Complete()
{
try
{
if (_exitWasCalled)
{
return;
}
// process any items that may still be in the input pipeline
if (_scriptBlock.HasProcessBlock && IsPipelineInputExpected())
{
DoProcessRecordWithInput();
}
if (_scriptBlock.HasEndBlock)
{
var endBlock = _runOptimizedCode ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock;
if (this.CommandRuntime.InputPipe.ExternalReader == null)
{
if (IsPipelineInputExpected())
{
// read any items that may still be in the input pipe
while (Read())
{
_input.Add(Command.CurrentPipelineObject);
}
}
// run with accumulated input
RunClause(endBlock, AutomationNull.Value, _input);
}
else
{
// run with asynchronously updated $input enumerator
RunClause(endBlock, AutomationNull.Value, this.CommandRuntime.InputPipe.ExternalReader.GetReadEnumerator());
}
}
}
finally
{
ScriptBlock.LogScriptBlockEnd(_scriptBlock, Context.CurrentRunspace.InstanceId);
}
}
private void DoProcessRecordWithInput()
{
// block for input and execute "process" block for all input objects
Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started
var processBlock = _runOptimizedCode ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock;
while (Read())
{
_input.Add(Command.CurrentPipelineObject);
this.Command.MyInvocation.PipelineIterationInfo[this.Command.MyInvocation.PipelinePosition]++;
RunClause(processBlock, Command.CurrentPipelineObject, _input);
// now clear input for next iteration; also makes it clear for the end clause.
_input.Clear();
}
}
private void RunClause(Action<FunctionContext> clause, object dollarUnderbar, object inputToProcess)
{
ExecutionContext.CheckStackDepth();
Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe;
// If the script block has a different language mode than the current,
// change the language mode.
PSLanguageMode? oldLanguageMode = null;
PSLanguageMode? newLanguageMode = null;
if ((_scriptBlock.LanguageMode.HasValue) &&
(_scriptBlock.LanguageMode != Context.LanguageMode))
{
oldLanguageMode = Context.LanguageMode;
newLanguageMode = _scriptBlock.LanguageMode;
}
try
{
var oldScopeOrigin = this.Context.EngineSessionState.CurrentScope.ScopeOrigin;
try
{
this.Context.EngineSessionState.CurrentScope.ScopeOrigin =
this._dontUseScopeCommandOrigin ? CommandOrigin.Internal : this.Command.CommandOrigin;
// Set the language mode. We do this before EnterScope(), so that the language
// mode is appropriately applied for evaluation parameter defaults.
if (newLanguageMode.HasValue)
{
Context.LanguageMode = newLanguageMode.Value;
}
bool? oldLangModeTransitionStatus = null;
try
{
// If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place.
if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && newLanguageMode == PSLanguageMode.FullLanguage)
{
oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding;
Context.LanguageModeTransitionInParameterBinding = true;
}
EnterScope();
}
finally
{
if (oldLangModeTransitionStatus.HasValue)
{
// Revert the transition state to old value after doing the parameter binding
Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value;
}
}
if (commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
{
Context.RedirectErrorPipe(commandRuntime.OutputPipe);
}
else if (commandRuntime.ErrorOutputPipe.IsRedirected)
{
Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe);
}
if (dollarUnderbar != AutomationNull.Value)
{
_localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context);
}
else if (_dollarUnderbar != AutomationNull.Value)
{
_localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, _dollarUnderbar, _context);
}
if (inputToProcess != AutomationNull.Value)
{
if (inputToProcess == null)
{
inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
}
else
{
IList list = inputToProcess as IList;
inputToProcess = (list != null)
? list.GetEnumerator()
: LanguagePrimitives.GetEnumerator(inputToProcess);
}
_localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, _context);
}
clause(_functionContext);
}
catch (TargetInvocationException tie)
{
// DynamicInvoke wraps exceptions, unwrap them here.
throw tie.InnerException;
}
finally
{
this.Context.RestoreErrorPipe(oldErrorOutputPipe);
if (oldLanguageMode.HasValue)
{
Context.LanguageMode = oldLanguageMode.Value;
}
Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin;
}
}
catch (ExitException ee)
{
if (!this.FromScriptFile || _rethrowExitException)
{
throw;
}
this._exitWasCalled = true;
int exitCode = (int)ee.Argument;
this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);
if (exitCode != 0)
this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
}
catch (FlowControlException)
{
throw;
}
catch (RuntimeException e)
{
ManageScriptException(e); // always throws
// This quiets the compiler which wants to see a return value
// in all codepaths.
throw;
}
catch (Exception e)
{
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(e);
}
}
private void EnterScope()
{
if (!_argsBound)
{
_argsBound = true;
// Parameter binder may need to write warning messages for obsolete parameters
using (commandRuntime.AllowThisCommandToWrite(false))
{
this.ScriptParameterBinderController.BindCommandLineParameters(arguments);
}
_localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters,
this.ScriptParameterBinderController.CommandLineParameters.GetValueToBindToPSBoundParameters(), _context);
}
}
protected override void OnSetCurrentScope()
{
// When dotting a script, push the locals of automatic variables to
// the 'DottedScopes' of the current scope.
if (!UseLocalScope)
{
CommandSessionState.CurrentScope.DottedScopes.Push(_localsTuple);
}
}
protected override void OnRestorePreviousScope()
{
// When dotting a script, pop the locals of automatic variables from
// the 'DottedScopes' of the current scope.
if (!UseLocalScope)
{
CommandSessionState.CurrentScope.DottedScopes.Pop();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using Internal.Runtime.Augments;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Hooks for System.Private.Interop.dll code to access internal functionality in System.Private.CoreLib.dll.
///
/// Methods added to InteropExtensions should also be added to the System.Private.CoreLib.InteropServices contract
/// in order to be accessible from System.Private.Interop.dll.
/// </summary>
[CLSCompliant(false)]
public static class InteropExtensions
{
// Converts a managed DateTime to native OLE datetime
// Used by MCG marshalling code
public static double ToNativeOleDate(DateTime dateTime)
{
return dateTime.ToOADate();
}
// Converts native OLE datetime to managed DateTime
// Used by MCG marshalling code
public static DateTime FromNativeOleDate(double nativeOleDate)
{
return new DateTime(DateTime.DoubleDateToTicks(nativeOleDate));
}
// Used by MCG's SafeHandle marshalling code to initialize a handle
public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
{
safeHandle.InitializeHandle(win32Handle);
}
// Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs
public unsafe static void PinObjectAndCall(Object obj, Action<IntPtr> del)
{
fixed (IntPtr* pEEType = &obj.m_pEEType)
{
del((IntPtr)pEEType);
}
}
public static void CopyToManaged(IntPtr source, Array destination, int startIndex, int length)
{
Array.CopyToManaged(source, destination, startIndex, length);
}
public static void CopyToNative(Array array, int startIndex, IntPtr destination, int length)
{
Array.CopyToNative(array, startIndex, destination, length);
}
public static int GetElementSize(this Array array)
{
return array.EETypePtr.ComponentSize;
}
public static unsafe IntPtr GetAddrOfPinnedArrayFromEETypeField(this Array array)
{
fixed (IntPtr* pEEType = &array.m_pEEType)
{
return (IntPtr)Array.GetAddrOfPinnedArrayFromEETypeField(pEEType);
}
}
public static bool IsBlittable(this RuntimeTypeHandle handle)
{
//
// @todo: B#754744 This is used as the Project N equivalent of MethodTable::IsBlittable(). The current implementation is rather... approximate.
//
return handle.ToEETypePtr().IsPrimitive ||
!handle.ToEETypePtr().HasPointers;
}
internal static bool MightBeBlittable(this EETypePtr eeType)
{
//
// @todo: B#754744 This is used as the Project N equivalent of MethodTable::IsBlittable(). The current implementation is rather... approximate. This
// version will err in the direction of declaring things blittable. This is used for the pinned GCHandle validation code where false positives
// are the lesser evil (on the grounds that for V1, at least, app developers will almost always be testing IL versions of their apps and will notice
// any failures on that platform.)
//
return eeType.IsPrimitive ||
!eeType.HasPointers;
}
public static bool IsElementTypeBlittable(this Array array)
{
return array.IsElementTypeBlittable;
}
public static bool IsGenericType(this RuntimeTypeHandle handle)
{
EETypePtr eeType = handle.ToEETypePtr();
return eeType.IsGeneric || eeType.IsGenericTypeDefinition;
}
public static TKey FindEquivalentKeyUnsafe<TKey, TValue>(
this ConditionalWeakTable<TKey, TValue> table,
TKey key,
out TValue value
)
where TKey : class
where TValue : class
{
return table.FindEquivalentKeyUnsafe(key, out value);
}
public static System.Collections.Generic.ICollection<TValue> GetValues<TKey, TValue>(
this ConditionalWeakTable<TKey, TValue> table
)
where TKey : class
where TValue : class
{
return table.Values;
}
public static System.Collections.Generic.ICollection<TKey> GetKeys<TKey, TValue>(
this ConditionalWeakTable<TKey, TValue> table
)
where TKey : class
where TValue : class
{
return table.Keys;
}
public static void Clear<TKey, TValue>(
this ConditionalWeakTable<TKey, TValue> table)
where TKey : class
where TValue : class
{
table.Clear();
}
//TODO:Remove Delegate.GetNativeFunctionPointer
public static IntPtr GetNativeFunctionPointer(this Delegate del)
{
return del.GetNativeFunctionPointer();
}
public static IntPtr GetFunctionPointer(this Delegate del, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
bool dummyIsOpenInstanceFunction;
return del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out dummyIsOpenInstanceFunction);
}
//
// Returns the raw function pointer for a open static delegate - if the function has a jump stub
// it returns the jump target. Therefore the function pointer returned
// by two delegates may NOT be unique
//
public static IntPtr GetRawFunctionPointerForOpenStaticDelegate(this Delegate del)
{
//If it is not open static then return IntPtr.Zero
if (!del.IsOpenStatic)
return IntPtr.Zero;
bool dummyIsOpenInstanceFunction;
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
IntPtr funcPtr = del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out dummyIsOpenInstanceFunction);
// if the function pointer points to a jump stub return the target
return RuntimeImports.RhGetJmpStubCodeTarget(funcPtr);
}
public static IntPtr GetRawValue(this RuntimeTypeHandle handle)
{
return handle.RawValue;
}
/// <summary>
/// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path
/// </summary>
public static bool IsOfType(this Object obj, RuntimeTypeHandle handle)
{
RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr);
return handle.Equals(objType);
}
public static bool IsNull(this RuntimeTypeHandle handle)
{
return handle.IsNull;
}
public static Type GetTypeFromHandle(IntPtr typeHandle)
{
return Type.GetTypeFromHandle(new RuntimeTypeHandle(new EETypePtr(typeHandle)));
}
public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle);
}
public static int GetValueTypeSize(this RuntimeTypeHandle handle)
{
return (int)handle.ToEETypePtr().ValueTypeSize;
}
public static bool IsValueType(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsValueType;
}
public static bool IsEnum(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsEnum;
}
public static bool IsInterface(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsInterface;
}
public static bool AreTypesAssignable(RuntimeTypeHandle sourceType, RuntimeTypeHandle targetType)
{
return RuntimeImports.AreTypesAssignable(sourceType.ToEETypePtr(), targetType.ToEETypePtr());
}
public static unsafe void Memcpy(IntPtr destination, IntPtr source, int bytesToCopy)
{
Buffer.Memmove((byte*)destination, (byte*)source, (uint)bytesToCopy);
}
public static bool RuntimeRegisterGcCalloutForGCStart(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.StartCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForGCEnd(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.EndCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForAfterMarkPhase(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.AfterMarkPhase, pCalloutMethod);
}
public static bool RuntimeRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
return RuntimeImports.RhRegisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
RuntimeImports.RhUnregisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
/// <summary>
/// The type of a RefCounted handle
/// A ref-counted handle is a handle that acts as strong if the callback returns true, and acts as
/// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW
/// </summary>
internal const int RefCountedHandleType = 5;
public static IntPtr RuntimeHandleAllocRefCounted(Object value)
{
return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType);
}
public static void RuntimeHandleSet(IntPtr handle, Object value)
{
RuntimeImports.RhHandleSet(handle, value);
}
public static void RuntimeHandleFree(IntPtr handle)
{
RuntimeImports.RhHandleFree(handle);
}
public static IntPtr RuntimeHandleAllocDependent(object primary, object secondary)
{
return RuntimeImports.RhHandleAllocDependent(primary, secondary);
}
public static bool RuntimeIsPromoted(object obj)
{
return RuntimeImports.RhIsPromoted(obj);
}
public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary)
{
RuntimeImports.RhHandleSetDependentSecondary(handle, secondary);
}
public static T UncheckedCast<T>(object obj) where T : class
{
return RuntimeHelpers.UncheckedCast<T>(obj);
}
public static bool IsArray(RuntimeTypeHandle type)
{
return type.ToEETypePtr().IsArray;
}
public static RuntimeTypeHandle GetArrayElementType(RuntimeTypeHandle arrayType)
{
return new RuntimeTypeHandle(arrayType.ToEETypePtr().ArrayElementType);
}
public static RuntimeTypeHandle GetTypeHandle(this object target)
{
return new RuntimeTypeHandle(target.EETypePtr);
}
public static bool IsInstanceOf(object obj, RuntimeTypeHandle typeHandle)
{
return (null != RuntimeImports.IsInstanceOf(obj, typeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfClass(object obj, RuntimeTypeHandle classTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfClass(obj, classTypeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfInterface(object obj, RuntimeTypeHandle interfaceTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfInterface(obj, interfaceTypeHandle.ToEETypePtr()));
}
public static bool GuidEquals(ref Guid left, ref Guid right)
{
return left.Equals(ref right);
}
public static bool ComparerEquals<T>(T left, T right)
{
return EqualOnlyComparer<T>.Equals(left, right);
}
public static object RuntimeNewObject(RuntimeTypeHandle typeHnd)
{
return RuntimeImports.RhNewObject(typeHnd.ToEETypePtr());
}
public static unsafe void UnsafeCopyTo(this System.Text.StringBuilder stringBuilder, char* destination)
{
stringBuilder.UnsafeCopyTo(destination);
}
public static unsafe void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char* newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char[] newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out int len)
{
return stringBuilder.GetBuffer(out len);
}
public static IntPtr RuntimeHandleAllocVariable(Object value, uint type)
{
return RuntimeImports.RhHandleAllocVariable(value, type);
}
public static uint RuntimeHandleGetVariableType(IntPtr handle)
{
return RuntimeImports.RhHandleGetVariableType(handle);
}
public static void RuntimeHandleSetVariableType(IntPtr handle, uint type)
{
RuntimeImports.RhHandleSetVariableType(handle, type);
}
public static uint RuntimeHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType)
{
return RuntimeImports.RhHandleCompareExchangeVariableType(handle, oldType, newType);
}
public static void SetExceptionErrorCode(Exception exception, int hr)
{
exception.SetErrorCode(hr);
}
public static void SetExceptionMessage(Exception exception, string message)
{
exception.SetMessage(message);
}
public static Exception CreateDataMisalignedException(string message)
{
return new DataMisalignedException(message);
}
public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen)
{
return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen);
}
public enum VariableHandleType
{
WeakShort = 0x00000100,
WeakLong = 0x00000200,
Strong = 0x00000400,
Pinned = 0x00000800,
}
public static void AddExceptionDataForRestrictedErrorInfo(Exception ex, string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject)
{
ex.AddExceptionDataForRestrictedErrorInfo(restrictedError, restrictedErrorReference, restrictedCapabilitySid, restrictedErrorObject);
}
public static bool TryGetRestrictedErrorObject(Exception ex, out object restrictedErrorObject)
{
return ex.TryGetRestrictedErrorObject(out restrictedErrorObject);
}
public static bool TryGetRestrictedErrorDetails(Exception ex, out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid)
{
return ex.TryGetRestrictedErrorDetails(out restrictedError, out restrictedErrorReference, out restrictedCapabilitySid);
}
public static TypeInitializationException CreateTypeInitializationException(string message)
{
return new TypeInitializationException(message);
}
public unsafe static IntPtr GetObjectID(object obj)
{
fixed (void* p = &obj.m_pEEType)
{
return (IntPtr)p;
}
}
public static bool RhpETWShouldWalkCom()
{
return RuntimeImports.RhpETWShouldWalkCom();
}
public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags)
{
RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags);
}
public static bool SupportsReflection(this Type type)
{
return RuntimeAugments.Callbacks.SupportsReflection(type);
}
public static void SuppressReentrantWaits()
{
System.Threading.LowLevelThread.SuppressReentrantWaits();
}
public static void RestoreReentrantWaits()
{
System.Threading.LowLevelThread.RestoreReentrantWaits();
}
public static IntPtr MemAlloc(UIntPtr sizeInBytes)
{
return Interop.MemAlloc(sizeInBytes);
}
public static void MemFree(IntPtr allocatedMemory)
{
Interop.MemFree(allocatedMemory);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Data;
using POESKillTree.Localization;
using POESKillTree.ViewModels;
namespace POESKillTree.Utils.Converter
{
[ValueConversion(typeof (string), typeof (string))]
//list view sorter here
public class GroupStringConverter : IValueConverter, IComparer
{
public Dictionary<string, AttributeGroup> AttributeGroups = new Dictionary<string, AttributeGroup>();
private List<string[]> CustomGroups = new List<string[]>();
private static readonly string Keystone = L10n.Message("Keystone");
private static readonly string Weapon = L10n.Message("Weapon");
private static readonly string Charges = L10n.Message("Charges");
private static readonly string Minion = L10n.Message("Minion");
private static readonly string Trap = L10n.Message("Trap");
private static readonly string Totem = L10n.Message("Totem");
private static readonly string Curse = L10n.Message("Curse");
private static readonly string Aura = L10n.Message("Aura");
private static readonly string CriticalStrike = L10n.Message("Critical Strike");
private static readonly string Shield = L10n.Message("Shield");
private static readonly string Block = L10n.Message("Block");
private static readonly string General = L10n.Message("General");
private static readonly string Defense = L10n.Message("Defense");
private static readonly string Spell = L10n.Message("Spell");
private static readonly string Flasks = L10n.Message("Flasks");
private static readonly string CoreAttributes = L10n.Message("Core Attributes");
private static readonly string MiscLabel = L10n.Message("Everything Else");
private static readonly string DecimalRegex = "\\d+(\\.\\d*)?";
private static readonly List<string[]> DefaultGroups = new List<string[]>
{
new[] {"Share Endurance, Frenzy and Power Charges with nearby party members", Keystone},
new[] {"Critical Strike Chance with Claws", CriticalStrike},
new[] {"with Claws", Weapon},
new[] {"Endurance Charge", Charges},
new[] {"Frenzy Charge", Charges},
new[] {"Power Charge", Charges},
new[] {"Chance to Dodge", Keystone},
new[] {"Spell Damage when on Low Life", Keystone},
new[] {"Cold Damage Converted to Fire Damage", Keystone},
new[] {"Lightning Damage Converted to Fire Damage", Keystone},
new[] {"Physical Damage Converted to Fire Damage", Keystone},
new[] {"Deal no Non-Fire Damage", Keystone},
new[] {"All bonuses from an equipped Shield apply to your Minions instead of you", Keystone},
new[] {"additional totem", Keystone},
new[] {"Cannot be Stunned", Keystone},
new[] {"Cannot Evade enemy Attacks", Keystone},
new[] {"Spend Energy Shield before Mana for Skill Costs", Keystone},
new[] {"Energy Shield protects Mana instead of Life", Keystone},
new[] {"Converts all Evasion Rating to Armour. Dexterity provides no bonus to Evasion Rating", Keystone},
new[] {"Doubles chance to Evade Projectile Attacks", Keystone},
new[] {"Enemies you hit with Elemental Damage temporarily get", Keystone},
new[] {"Life Leech applies instantly", Keystone},
new[] {"Life Leech is Applied to Energy Shield instead", Keystone},
new[] {"Life Regeneration is applied to Energy Shield instead", Keystone},
new[] {"No Critical Strike Multiplier", Keystone},
new[] {"Immune to Chaos Damage", Keystone},
new[] {"Minions explode when reduced to low life", Keystone},
new[] {"Never deal Critical Strikes", Keystone},
new[] {"Projectile Attacks deal up to", Keystone},
new[] {"Removes all mana", Keystone},
new[] {"Share Endurance", Keystone},
new[] {"The increase to Physical Damage from Strength applies to Projectile Attacks as well as Melee Attacks", Keystone},
new[] {"Damage is taken from Mana before Life", Keystone},
new[] {"You can't deal Damage with your Skills yourself", Keystone},
new[] {"Your hits can't be Evaded", Keystone},
new[] {"less chance to Evade Melee Attacks", Keystone},
new[] {"more chance to Evade Projectile Attacks", Keystone},
new[] {"Maximum number of Spectres", Minion},
new[] {"Maximum number of Zombies", Minion},
new[] {"Maximum number of Skeletons", Minion},
new[] {"Minions deal", Minion},
new[] {"Minions have", Minion},
new[] {"Minions Leech", Minion},
new[] {"Minions Regenerate", Minion},
new[] {"Mine Damage", Trap},
new[] {"Trap Damage", Trap},
new[] {"Trap Duration", Trap},
new[] {"Trap Trigger Radius", Trap},
new[] {"Mine Duration", Trap},
new[] {"Mine Laying Speed", Trap},
new[] {"Trap Throwing Speed", Trap},
new[] {"Can set up to", Trap},
new[] {"Can have up to", Trap},
new[] {"Detonating Mines is Instant", Trap},
new[] {"Mine Damage Penetrates", Trap},
new[] {"Mines cannot be Damaged", Trap},
new[] {"Mine Detonation", Trap},
new[] {"Trap Damage Penetrates", Trap},
new[] {"Traps cannot be Damaged", Trap},
new[] {"throwing Traps", Trap},
new[] {"Totem Duration", Totem},
new[] {"Casting Speed for Summoning Totems", Totem},
new[] {"Totem Life", Totem},
new[] {"Totem Damage", Totem},
new[] {"Attacks used by Totems", Totem},
new[] {"Spells Cast by Totems", Totem},
new[] {"Totems gain", Totem},
new[] {"Totems have", Totem},
new[] {"Totem Placement", Totem},
new[] {"Radius of Curse", Curse},
new[] {"Curse Duration", Curse},
new[] {"Effect of your Curses", Curse},
new[] {"Radius of Curses", Curse},
new[] {"Cast Speed for Curses", Curse},
new[] {"Enemies can have 1 additional Curse", Curse},
new[] {"Mana Reserved", Aura},
new[] {"Aura", Aura},
new[] {"Auras", Aura},
new[] {"Weapon Critical Strike Chance", CriticalStrike},
new[] {"increased Critical Strike Chance", CriticalStrike},
new[] {"to Critical Strike Multiplier", CriticalStrike},
new[] {"Global Critical Strike", CriticalStrike},
new[] {"Critical Strikes with Daggers Poison the enemy", CriticalStrike},
new[] {"Knocks Back enemies if you get a Critical Strike", CriticalStrike},
new[] {"to Melee Critical Strike Multiplier", CriticalStrike},
new[] {"increased Melee Critical Strike Chance", CriticalStrike},
new[] {"Elemental Resistances while holding a Shield", Shield},
new[] {"Chance to Block Spells with Shields", Block},
new[] {"Armour from equipped Shield", Shield},
new[] {"additional Block Chance while Dual Wielding or Holding a shield", Block},
new[] {"Chance to Block with Shields", Block},
new[] {"Block and Stun Recovery", Block},
new[] {"Energy Shield from equipped Shield", Shield},
new[] {"Block Recovery", Block},
new[] {"Defences from equipped Shield", Shield},
new[] {"Damage Penetrates", General}, //needs to be here to pull into the correct tab.
new[] {"reduced Extra Damage from Critical Strikes", Defense},
new[] {"Armour", Defense},
new[] {"Fortify", Defense},
new[] {"all Elemental Resistances", Defense},
new[] {"Chaos Resistance", Defense},
new[] {"Evasion Rating", Defense},
new[] {"Cold Resistance", Defense},
new[] {"Lightning Resistance", Defense},
new[] {"maximum Mana", Defense},
new[] {"maximum Energy Shield", Defense},
new[] {"Fire Resistance", Defense},
new[] {"maximum Life", Defense},
new[] {"Light Radius", Defense},
new[] {"Evasion Rating and Armour", Defense},
new[] {"Energy Shield Recharge", Defense},
new[] {"Life Regenerated", Defense},
new[] {"Melee Physical Damage taken reflected to Attacker", Defense},
new[] {"Avoid Elemental Status Ailments", Defense},
new[] {"Damage taken Gained as Mana when Hit", Defense},
new[] {"Avoid being Chilled", Defense},
new[] {"Avoid being Frozen", Defense},
new[] {"Avoid being Ignited", Defense},
new[] {"Avoid being Shocked", Defense},
new[] {"Avoid being Stunned", Defense},
new[] {"increased Stun Recovery", Defense},
new[] {"Mana Regeneration Rate", Defense},
new[] {"maximum Mana", Defense},
new[] {"Armour", Defense},
new[] {"Avoid interruption from Stuns while Casting", Defense},
new[] {"Movement Speed", Defense},
new[] {"Enemies Cannot Leech Life From You", Defense},
new[] {"Enemies Cannot Leech Mana From You", Defense},
new[] {"Ignore all Movement Penalties", Defense},
new[] {"Physical Damage Reduction", Defense},
new[] {"Poison on Hit", General},
new[] {"Hits that Stun Enemies have Culling Strike", General},
new[] {"increased Damage against Frozen, Shocked or Ignited Enemies", General},
new[] {"Shock Duration on enemies", General},
new[] {"Radius of Area Skills", General},
new[] {"chance to Ignite", General},
new[] {"chance to Shock", General},
new[] {"Mana Gained on Kill", General},
new[] {"Life gained on General", General},
new[] {"Burning Damage", General},
new[] {"Projectile Damage", General},
new[] {"Knock enemies Back on hit", General},
new[] {"chance to Freeze", General},
new[] {"Projectile Speed", General},
new[] {"Projectiles Piercing", General},
new[] {"Ignite Duration on enemies", General},
new[] {"Knockback Distance", General},
new[] {"Mana Cost of Skills", General},
new[] {"Chill Duration on enemies", General},
new[] {"Freeze Duration on enemies", General},
new[] {"Damage over Time", General},
new[] {"Chaos Damage", General},
new[] {"Status Ailments", General},
new[] {"increased Damage against Enemies", General},
new[] {"Enemies Become Chilled as they Unfreeze", General},
new[] {"Skill Effect Duration", General},
new[] {"Life Gained on Kill", General},
new[] {"Area Damage", General},
new[] {"Stun Threshold", General},
new[] {"Stun Duration", General},
new[] {"increased Damage against Enemies on Low Life", General},
new[] {"chance to gain Onslaught", General},
new[] {"Accuracy Rating", Weapon},
new[] {"gained for each enemy hit by your Attacks", Weapon},
new[] {"Melee Weapon and Unarmed range", Weapon},
new[] {"chance to cause Bleeding", Weapon},
new[] {"Wand Physical Damage", Weapon},
new[] {"Attack Speed", Weapon},
new[] {"Melee Damage", Weapon},
new[] {"Block Chance With Staves", Block},
new[] {"Attack Damage", Weapon},
new[] {"with Daggers", Weapon},
new[] {"Arrow Speed", Weapon},
new[] {"Cast Speed while Dual Wielding", Weapon},
new[] {"Physical Damage with Staves", Weapon},
new[] {"with Axes", Weapon},
new[] {"Physical Weapon Damage while Dual Wielding", Weapon},
new[] {"with One Handed Melee Weapons", Weapon},
new[] {"with Two Handed Melee Weapons", Weapon},
new[] {"with Maces", Weapon},
new[] {"with Bows", Weapon},
new[] {"Melee Physical Damage", Weapon},
new[] {"with Swords", Weapon},
new[] {"with Wands", Weapon},
new[] {"Cold Damage with Weapons", Weapon},
new[] {"Fire Damage with Weapons", Weapon},
new[] {"Lightning Damage with Weapons", Weapon},
new[] {"Elemental Damage with Weapons", Weapon},
new[] {"Physical Damage with Wands", Weapon},
new[] {"Damage with Wands", Weapon},
new[] {"Damage with Weapons", Weapon},
new[] {"Spell Damage", Spell},
new[] {"Elemental Damage with Spells", Spell},
new[] {"enemy chance to Block Sword Attacks", Block},
new[] {"additional Block Chance while Dual Wielding", Block},
new[] {"mana gained when you Block", Block},
new[] {"Leeched", General},
new[] {"increased Physical Damage", General},
new[] {"Elemental Damage", General},
new[] {"Jewel Socket", General},
new[] {"Cast Speed", Spell},
new[] {"Cold Damage", General},
new[] {"Fire Damage", General},
new[] {"Lightning Damage", General},
new[] {"Damage while Leeching", General},
new[] {"Damage with Poison", General},
new[] {"Flask", Flasks},
new[] {"Flasks", Flasks},
new[] {"Strength", CoreAttributes},
new[] {"Intelligence", CoreAttributes},
new[] {"Dexterity", CoreAttributes},
};
public GroupStringConverter()
{
CustomGroups = new List<string[]>();
foreach (var group in DefaultGroups)
{
if (!AttributeGroups.ContainsKey(group[1]))
{
AttributeGroups.Add(group[1], new AttributeGroup(group[1]));
}
}
foreach (var group in CustomGroups)
{
if (!AttributeGroups.ContainsKey(group[1]))
{
AttributeGroups.Add(group[1], new AttributeGroup("Custom: "+group[1]));
}
}
AttributeGroups.Add(MiscLabel, new AttributeGroup(MiscLabel));
}
public List<string[]> CopyCustomGroups()
{
List<string[]> deepcopy = new List<string[]>();
foreach (var gp in CustomGroups)
{
deepcopy.Add((string[])gp.Clone());
}
return deepcopy;
}
public void ResetGroups(List<string[]> newgroups)
{
CustomGroups = new List<string[]>();
foreach (var gp in newgroups)
{
CustomGroups.Add((string[])gp.Clone());
}
AttributeGroups = new Dictionary<string, AttributeGroup>();
foreach (var group in DefaultGroups)
{
if (!AttributeGroups.ContainsKey(group[1]))
{
AttributeGroups.Add(group[1], new AttributeGroup(group[1]));
}
}
foreach (var group in CustomGroups)
{
if (!AttributeGroups.ContainsKey(group[1]))
{
AttributeGroups.Add(group[1], new AttributeGroup("Custom: " + group[1]));
}
}
AttributeGroups.Add(MiscLabel, new AttributeGroup(MiscLabel));
}
public void AddGroup(string groupname, string[] attributes)
{
if (!AttributeGroups.ContainsKey(groupname))
{
AttributeGroups.Add(groupname, new AttributeGroup("Custom: "+groupname));
}
foreach (string attr in attributes)
{
AddAttributeToGroup(attr, groupname);
}
}
private void AddAttributeToGroup(string attribute, string groupname)
{
//Remove it from any existing custom groups first
RemoveFromGroup(new string[] { attribute });
CustomGroups.Insert(0, new string[] { attribute, groupname });
}
public void RemoveFromGroup(string[] attributes)
{
List<string[]> linesToRemove = new List<string[]>();
foreach (string attr in attributes)
{
foreach (var gp in CustomGroups)
{
if (new NumberLessStringComparer().Compare(attr.ToLower(), gp[0].ToLower()) == 0)
{
linesToRemove.Add(gp);
}
}
}
foreach (string[] line in linesToRemove)
{
CustomGroups.Remove(line);
}
}
public void DeleteGroup(string groupname)
{
List<string[]> linesToRemove = new List<string[]>();
foreach (var gp in CustomGroups)
{
if (groupname.ToLower().Equals(gp[1].ToLower()))
{
linesToRemove.Add(gp);
}
}
foreach (string[] line in linesToRemove)
{
CustomGroups.Remove(line);
}
AttributeGroups.Remove(groupname);
}
public void UpdateGroupNames(List<POESKillTree.ViewModels.Attribute> attrlist)
{
Dictionary<string, float> groupTotals = new Dictionary<string, float>();
Dictionary<string, float> groupDeltas = new Dictionary<string, float>();
foreach (var gp in CustomGroups)
{
//only sum for the groups that need it
if (!gp[1].Contains("#"))
continue;
foreach (POESKillTree.ViewModels.Attribute attr in attrlist)
{
if (new NumberLessStringComparer().Compare(attr.Text.ToLower(), gp[0].ToLower()) == 0)
{
Match matchResult = Regex.Match(attr.Text, DecimalRegex);
if (matchResult.Success)
{
if (!groupTotals.ContainsKey(gp[1]))
{
groupTotals.Add(gp[1], 0);
groupDeltas.Add(gp[1], 0);
}
groupTotals[gp[1]] += (float)Decimal.Parse(matchResult.Value);
if (attr.Deltas.Length > 0)
groupDeltas[gp[1]] += attr.Deltas[0];
}
}
}
}
string deltaString;
foreach (string key in groupTotals.Keys)
{
if (AttributeGroups.ContainsKey(key))
{
if (groupDeltas[key] == 0)
deltaString = "";
else if (groupDeltas[key] > 0)
deltaString = " +" + groupDeltas[key].ToString();
else
deltaString = " " + groupDeltas[key].ToString();
AttributeGroups[key].GroupName = "Custom: "+key.Replace("#", groupTotals[key].ToString())+deltaString;
}
}
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value.ToString());
}
public int Compare(object a, object b)
{
string attr1 = ((POESKillTree.ViewModels.Attribute)a).ToString();
string attr2 = ((POESKillTree.ViewModels.Attribute)b).ToString();
//find the group names and types that the attributes belong in
//2 = misc group, 1 = default group, 0 = custom group
int group1 = 2;
int group2 = 2;
string attrgroup1 = MiscLabel;
string attrgroup2 = MiscLabel;
foreach (var gp in CustomGroups)
{
if (new NumberLessStringComparer().Compare(attr1.ToLower(), gp[0].ToLower()) == 0)
{
attrgroup1 = gp[1];
group1 = 0;
break;
}
}
if (group1 == 2) {
foreach (var gp in DefaultGroups)
{
if (attr1.ToLower().Contains(gp[0].ToLower()))
{
attrgroup1 = gp[1];
group1 = 1;
break;
}
}
}
foreach (var gp in CustomGroups)
{
if (new NumberLessStringComparer().Compare(attr2.ToLower(), gp[0].ToLower()) == 0)
{
attrgroup2 = gp[1];
group2 = 0;
break;
}
}
if (group2 == 2)
{
foreach (var gp in DefaultGroups)
{
if (attr2.ToLower().Contains(gp[0].ToLower()))
{
attrgroup2 = gp[1];
group2 = 1;
break;
}
}
}
//primary: if group types are different, sort by group type - custom first, then defaults, then misc
if (group1 != group2)
{
return group1 - group2;
}
//secondary: if groups are different, sort by group names, alphabetically, excluding numbers
if (!attrgroup1.Equals(attrgroup2))
{
attrgroup1 = Regex.Replace(attrgroup1, DecimalRegex, "#");
attrgroup2 = Regex.Replace(attrgroup2, DecimalRegex, "#");
return attrgroup1.CompareTo(attrgroup2);
}
//tertiary: if in the same group, sort by attribute string, alphabetically, excluding numbers
attr1 = Regex.Replace(attr1, DecimalRegex, "#");
attr2 = Regex.Replace(attr2, DecimalRegex, "#");
return attr1.CompareTo(attr2);
}
public AttributeGroup Convert(string s)
{
foreach (var gp in CustomGroups)
{
if (new NumberLessStringComparer().Compare(s.ToLower(), gp[0].ToLower()) == 0)
{
return AttributeGroups[gp[1]];
}
}
foreach (var gp in DefaultGroups)
{
if (s.ToLower().Contains(gp[0].ToLower()))
{
return AttributeGroups[gp[1]];
}
}
return AttributeGroups[MiscLabel];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2003
//
// File: MediaPlayerState.cs
//
//------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics;
using System.ComponentModel;
using MS.Internal;
using MS.Internal.PresentationCore; // SecurityHelper
using MS.Win32;
using System.IO.Packaging;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Windows.Navigation;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.AccessControl;//for semaphore access permissions
using System.Net;
using Microsoft.Win32;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using UnsafeNativeMethods=MS.Win32.PresentationCore.UnsafeNativeMethods;
//
// Disable the warnings that C# emmits when it finds pragmas it does not recognize, this is to
// get rid of false positive PreSharp warning
//
#pragma warning disable 1634, 1691
namespace System.Windows.Media
{
#region MediaPlayerState
/// <summary>
/// MediaPlayerState
/// Holds all of the local state that is required for playing media. This is
/// separated out into a separate class because MediaPlayer needs to be
/// Animatable, but then that means it needs to be Freezable. However, media
/// state cannot really be frozan (media piplines progress according to time
/// and are very expensive), so instead, we make the "Frozen" object copy the
/// state object around. Doing this will also help in the remote case where
/// we need to handle MediaPlayer quite differently on the channel in the
/// remote and local cases.
/// </summary>
internal class MediaPlayerState
{
#region Constructors and Finalizers
/// <summary>
/// Constructor
/// </summary>
internal
MediaPlayerState(
MediaPlayer mediaPlayer
)
{
_dispatcher = mediaPlayer.Dispatcher;
Init();
CreateMedia(mediaPlayer);
//
// We need to know about new frames when they are sent so that we can
// capture the image data in the synchronous case.
//
_mediaEventsHelper.NewFrame += new EventHandler(OnNewFrame);
//
// Opened is actually fired when the media is prerolled.
//
_mediaEventsHelper.MediaPrerolled += new EventHandler(OnMediaOpened);
}
//
/// <summary>
/// Initialize local variables to their default state. After a close we want to restore this too, same as
/// after construction.
/// </summary>
private
void
Init()
{
_volume = DEFAULT_VOLUME;
_balance = DEFAULT_BALANCE;
_speedRatio = 1.0;
_paused = false;
_muted = false;
_sourceUri = null;
_scrubbingEnabled = false;
}
/// <summary>
/// Finalizer to remove the event handler from AppDomain.ProcessExit
/// </summary>
/// <SecurityNote>
/// Critical: Helper.ProcessExitHandler is SecurityCritical as it accesses native
/// resources
/// TreatAsSafe: This doesn't actually call ProcessExitHandler, just detaches it
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
~MediaPlayerState()
{
if (_helper != null)
{
AppDomain.CurrentDomain.ProcessExit -= _helper.ProcessExitHandler;
}
}
#endregion
#region Public Methods
/// <summary>
/// Internal IsBuffering
/// </summary>
/// <SecurityNote>
/// Critical: This calls into unmanaged code and also acceses _nativemedia
/// TreatAsSafe: This information about whether buffering is on is safe to expose
/// </SecurityNote>
internal bool IsBuffering
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
bool isBuffering = false;
HRESULT.Check(MILMedia.IsBuffering(_nativeMedia, ref isBuffering));
return isBuffering;
}
}
/// <summary>
/// Internal CanPause
/// </summary>
/// <SecurityNote>
/// Critical: This is critical because it acceses _nativemedia and calls into unmanaged code
/// TreatAsSafe: This is safe to expose since giving out information about
/// whether media can be paused is safe
/// </SecurityNote>
internal bool CanPause
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
bool canPause = false;
HRESULT.Check(MILMedia.CanPause(_nativeMedia, ref canPause));
return canPause;
}
}
/// <summary>
/// Internal DownloadProgress
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning download progress is safe
/// </SecurityNote>
internal double DownloadProgress
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
double downloadProgress = 0;
HRESULT.Check(MILMedia.GetDownloadProgress(_nativeMedia, ref downloadProgress));
return downloadProgress;
}
}
/// <summary>
/// Internal BufferingProgress
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning buffering progress is safe
/// </SecurityNote>
internal double BufferingProgress
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
double bufferingProgress = 0;
HRESULT.Check(MILMedia.GetBufferingProgress(_nativeMedia, ref bufferingProgress));
return bufferingProgress;
}
}
/// <summary>
/// Returns the Height
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning natural video height is safe
/// </SecurityNote>
internal Int32 NaturalVideoHeight
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
UInt32 height = 0;
HRESULT.Check(MILMedia.GetNaturalHeight(_nativeMedia, ref height));
return (Int32)height;
}
}
/// <summary>
/// Returns the Width
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning natural video width is safe
/// </SecurityNote>
internal Int32 NaturalVideoWidth
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
UInt32 width = 0;
HRESULT.Check(MILMedia.GetNaturalWidth(_nativeMedia, ref width));
return (Int32)width;
}
}
/// <summary>
/// If media has audio content
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning whether media has audio is safe
/// </SecurityNote>
internal bool HasAudio
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
bool hasAudio = true;
HRESULT.Check(MILMedia.HasAudio(_nativeMedia, ref hasAudio));
return hasAudio;
}
}
/// <summary>
/// If the media has video content
/// </summary>
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning whether media has video is safe
/// </SecurityNote>
internal bool HasVideo
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
bool hasVideo = false;
HRESULT.Check(MILMedia.HasVideo(_nativeMedia, ref hasVideo));
return hasVideo;
}
}
/// <summary>
/// Location of the media to play. Open opens the media, this property
/// allows the source that is currently playing to be retrieved.
/// </summary>
internal Uri Source
{
get
{
VerifyAPI();
return _sourceUri;
}
}
/// <summary>
/// Internal Get Volume
/// </summary>
/// <SecurityNote>
/// Critical: This is critical because it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning volume ratio is safe and so also is setting it
/// </SecurityNote>
internal double Volume
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
return _volume;
}
[SecurityCritical, SecurityTreatAsSafe]
set
{
VerifyAPI();
if (Double.IsNaN(value))
{
throw new ArgumentException(SR.Get(SRID.ParameterValueCannotBeNaN), "value");
}
if (DoubleUtil.GreaterThanOrClose(value, 1))
{
value = 1;
}
else if (DoubleUtil.LessThanOrClose(value, 0))
{
value = 0;
}
// We only want to set the volume if the current cached volume is not the same
// No need to do extra work.
if (!DoubleUtil.AreClose(_volume, value))
{
if (!_muted)
{
int hr = MILMedia.SetVolume(_nativeMedia, value);
HRESULT.Check(hr);
// value is changing
_volume = value;
}
else
{
// If we are muted, cache the volume
_volume = value;
}
}
}
}
/// <summary>
/// Internal Get Balance
/// </summary>
/// <SecurityNote>
/// Critical: This is accesses the native media.
/// TreatAsSafe: This is safe because the act of adjusting the balance is a safe one.
/// </SecurityNote>
internal double Balance
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
return _balance;
}
[SecurityCritical, SecurityTreatAsSafe]
set
{
VerifyAPI();
if (Double.IsNaN(value))
{
throw new ArgumentException(SR.Get(SRID.ParameterValueCannotBeNaN), "value");
}
if (DoubleUtil.GreaterThanOrClose(value, 1))
{
value = 1;
}
else if (DoubleUtil.LessThanOrClose(value, -1))
{
value = -1;
}
// We only want to set the balance if the current cached balance
// is not the same. No need to do extra work.
if (!DoubleUtil.AreClose(_balance, value))
{
int hr = MILMedia.SetBalance(_nativeMedia, value);
HRESULT.Check(hr);
// value is changing
_balance = value;
}
}
}
/// <summary>
/// Whether or not scrubbing is enabled
/// </summary>
/// <SecurityNote>
/// Critical: This accesses the native media.
/// TreatAsSafe: This is safe because it's safe to adjust whether or not scrubbing is enabled
/// </SecurityNote>
internal bool ScrubbingEnabled
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
return _scrubbingEnabled;
}
[SecurityCritical, SecurityTreatAsSafe]
set
{
VerifyAPI();
if (value != _scrubbingEnabled)
{
HRESULT.Check(MILMedia.SetIsScrubbingEnabled(_nativeMedia, value));
_scrubbingEnabled = value;
}
}
}
/// <summary>
/// Internal Get Mute
/// </summary>
internal bool IsMuted
{
get
{
VerifyAPI();
return _muted;
}
set
{
VerifyAPI();
// we need to store the volume since this.Volume will change the cached value
double volume = _volume;
if (value && !_muted)
{
// Going from Unmuted -> Muted
// Set the volume to 0
this.Volume = 0;
_muted = true;
// make sure cached volume is previous value
_volume = volume;
}
else if (!value && _muted)
{
// Going from Muted -> Unmuted
_muted = false;
// set cached volume to 0 since this. Volume will only change volume
// if cached volume and new volume differ
_volume = 0;
// set volume to old cached value, which will also update our current cached value
this.Volume = volume;
}
}
}
/// <SecurityNote>
/// Critical: This is critical it calls into unmanged code and accesses _nativeMedia
/// TreatAsSafe: This is safe because the critical resource is not exposed and
/// returning natural duration is safe
/// </SecurityNote>
internal Duration NaturalDuration
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
VerifyAPI();
long mediaLength = 0;
HRESULT.Check(MILMedia.GetMediaLength(_nativeMedia, ref mediaLength));
if (mediaLength == 0)
{
return Duration.Automatic;
}
else
{
return new Duration(TimeSpan.FromTicks(mediaLength));
}
}
}
/// <summary>
/// Seek to specified position
/// </summary>
internal TimeSpan Position
{
set
{
VerifyAPI();
VerifyNotControlledByClock();
SetPosition(value);
}
get
{
VerifyAPI();
return GetPosition();
}
}
/// <summary>
/// The current speed. This cannot be changed if a clock is controlling this player
/// </summary>
internal double SpeedRatio
{
get
{
VerifyAPI();
return _speedRatio;
}
set
{
VerifyAPI();
VerifyNotControlledByClock();
if (value < 0)
{
value = 0; // we clamp negative values to 0
}
SetSpeedRatio(value);
}
}
/// <summary>
/// The dispatcher, this is actually derived from the media player
/// on construction.
/// </summary>
internal Dispatcher Dispatcher
{
get
{
return _dispatcher;
}
}
#endregion
#region EventHandlers
/// <summary>
/// Raised when there is an error opening or playing media
/// </summary>
internal event EventHandler<ExceptionEventArgs> MediaFailed
{
add
{
VerifyAPI();
_mediaEventsHelper.MediaFailed += value;
}
remove
{
VerifyAPI();
_mediaEventsHelper.MediaFailed -= value;
}
}
/// <summary>
/// Raised when the media has been opened.
/// </summary>
internal event EventHandler MediaOpened
{
add
{
VerifyAPI();
_mediaOpenedHelper.AddEvent(value);
}
remove
{
VerifyAPI();
_mediaOpenedHelper.RemoveEvent(value);
}
}
/// <summary>
/// Raised when the media has finished.
/// </summary>
internal event EventHandler MediaEnded
{
add
{
VerifyAPI();
_mediaEventsHelper.MediaEnded += value;
}
remove
{
VerifyAPI();
_mediaEventsHelper.MediaEnded -= value;
}
}
/// <summary>
/// Raised when media begins buffering.
/// </summary>
internal event EventHandler BufferingStarted
{
add
{
VerifyAPI();
_mediaEventsHelper.BufferingStarted += value;
}
remove
{
VerifyAPI();
_mediaEventsHelper.BufferingStarted -= value;
}
}
/// <summary>
/// Raised when media finishes buffering.
/// </summary>
internal event EventHandler BufferingEnded
{
add
{
VerifyAPI();
_mediaEventsHelper.BufferingEnded += value;
}
remove
{
VerifyAPI();
_mediaEventsHelper.BufferingEnded -= value;
}
}
/// <summary>
/// Raised when a script command embedded in the media is encountered.
/// </summary>
internal event EventHandler<MediaScriptCommandEventArgs> ScriptCommand
{
add
{
VerifyAPI();
_mediaEventsHelper.ScriptCommand += value;
}
remove
{
VerifyAPI();
_mediaEventsHelper.ScriptCommand -= value;
}
}
/// <summary>
/// Raised when a new frame in the media is encountered, we only
/// send one new frame per AddRefOnChannel in synchronous mode only.
/// </summary>
internal event EventHandler NewFrame
{
add
{
VerifyAPI();
_newFrameHelper.AddEvent(value);
}
remove
{
VerifyAPI();
_newFrameHelper.RemoveEvent(value);
}
}
#endregion
#region Clock dependent properties and methods
/// <summary>
/// The clock driving this instance of media
/// </summary>
internal MediaClock Clock
{
get
{
VerifyAPI();
return _mediaClock;
}
}
internal
void
SetClock(
MediaClock clock,
MediaPlayer player
)
{
VerifyAPI();
MediaClock oldClock = _mediaClock;
MediaClock newClock = clock;
// Avoid infinite loops
if (oldClock != newClock)
{
_mediaClock = newClock;
// Disassociate the old clock
if (oldClock != null)
{
oldClock.Player = null;
}
// Associate the new clock;
if (newClock != null)
{
newClock.Player = player;
}
// According to the spec, setting the Clock to null
// should set the Source to null
if (newClock == null)
{
Open(null);
}
}
}
/// <summary>
/// Open the media, at this point the underlying native resources are
/// created. The media player cannot be controlled when it isn't opened.
/// </summary>
internal
void
Open(
Uri source
)
{
VerifyAPI();
VerifyNotControlledByClock();
SetSource(source);
// Workaround for bug 107397: Resuing one instance of MediaElement and
// calling play() wont result in seek to zero, Media Freezes. Ensure
// we set Media to play from the beginning.
SetPosition(TimeSpan.Zero);
}
/// <summary>
/// Begin playback. This operation is not allowed if a clock is
/// controlling this player
/// </summary>
internal void Play()
{
VerifyAPI();
VerifyNotControlledByClock();
_paused = false;
PrivateSpeedRatio = SpeedRatio;
}
/// <summary>
/// Halt playback at current position. This operation is not allowed if
/// a clock is controlling this player
/// </summary>
internal void Pause()
{
VerifyAPI();
VerifyNotControlledByClock();
_paused = true;
PrivateSpeedRatio = 0;
}
/// <summary>
/// Halt playback and seek to the beginning of media. This operation is
/// not allowed if a clock is controlling this player
/// </summary>
internal void Stop()
{
VerifyAPI();
VerifyNotControlledByClock();
Pause();
Position = TimeSpan.FromTicks(0);
}
/// <summary>
/// Closes the underlying media. This de-allocates all of the native resources in
/// the media. The mediaplayer can be opened again by calling the Open method.
/// </summary>
/// <SecurityNote>
/// Critical: This calls into unmanaged code and also acceses _nativemedia.
/// TreatAsSafe: Intrinsically safe to close media.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal
void
Close()
{
VerifyAPI();
VerifyNotControlledByClock();
HRESULT.Check(MILMedia.Close(_nativeMedia));
//
// Once we successfully close, we don't have a clock anymore.
// Assign the property so that the clock is disconnected from the
// player as well as the player from the clock.
//
SetClock(null, null);
Init();
}
/// <summary>
/// Sends a command to play the given media.
/// </summary>
/// <SecurityNote>
/// Critical: This calls into unmanaged code and also acceses _nativemedia.
/// TreatAsSafe: Media Command merely binds resource to native player.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal
void
SendCommandMedia(
DUCE.Channel channel,
DUCE.ResourceHandle handle,
bool notifyUceDirectly
)
{
SendMediaPlayerCommand(
channel,
handle,
notifyUceDirectly
);
//
// Independently, tell the native media that we need to update the UI, the
// reason we do this directly through the player is that effects can immediately
// remove the channel on us and hence media might not get a chance to see
// the media player resource.
//
if (!notifyUceDirectly)
{
NeedUIFrameUpdate();
}
}
/// <summary>
/// Sends a request to the media player to reserve a UI frame for notification.
/// </summary>
/// <SecurityNote>
/// Critical: This calls into unmanaged code and also acceses _nativemedia.
/// TreatAsSafe: Asking for a frame update is inherently safe.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private
void
NeedUIFrameUpdate()
{
VerifyAPI();
HRESULT.Check(MILMedia.NeedUIFrameUpdate(_nativeMedia));
}
#endregion
#region Private Methods
/// <summary>
/// Create the unmanaged media resources
/// </summary>
/// <SecurityNote>
/// Critical - calls unmanaged code, access pointer parameters. It instantiates
/// windows media player
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void CreateMedia(MediaPlayer mediaPlayer)
{
CheckMediaDisabledFlags();
SafeMILHandle unmanagedProxy = null;
MediaEventsHelper.CreateMediaEventsHelper(mediaPlayer, out _mediaEventsHelper, out unmanagedProxy);
try
{
using (FactoryMaker myFactory = new FactoryMaker())
{
HRESULT.Check(UnsafeNativeMethods.MILFactory2.CreateMediaPlayer(
myFactory.FactoryPtr,
unmanagedProxy,
SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.AllAudio, MediaPermissionVideo.AllVideo, MediaPermissionImage.NoImage),
out _nativeMedia
));
}
}
catch
{
if (_nativeMedia != null && !_nativeMedia.IsInvalid)
{
_nativeMedia.Close();
}
throw;
}
_helper = new Helper(_nativeMedia);
AppDomain.CurrentDomain.ProcessExit += _helper.ProcessExitHandler;
}
/// <summary>
/// Open Media
/// </summary>
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia), access local file system
/// and also stores the path to base directory in a local variable. It also asserts
/// to allow FileIO to local directory. It calls GetBaseDirectory, that returns sensitive information.
/// TreatAsSafe: This path is sent to the unmanaged layer to be opened. Also it demands
/// fileio for absolute paths and web permissions for files on a server. It only lets you access
/// files in current directory and does not expose the location of current directory
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
private void OpenMedia(Uri source)
{
string toOpen = null;
if (source != null && source.IsAbsoluteUri && source.Scheme == PackUriHelper.UriSchemePack)
{
try
{
source = BaseUriHelper.ConvertPackUriToAbsoluteExternallyVisibleUri(source);
}
catch (InvalidOperationException)
{
source = null;
_mediaEventsHelper.RaiseMediaFailed(new System.NotSupportedException(SR.Get(SRID.Media_PackURIsAreNotSupported, null)));
}
}
// Setting a null source effectively disconects the MediaElement.
if (source != null)
{
// keep whether we asserted permissions or not
bool elevated = false;
// get the base directory of the application; never expose this
Uri appBase = SecurityHelper.GetBaseDirectory(AppDomain.CurrentDomain);
// this extracts the URI to open
Uri uriToOpen = ResolveUri(source, appBase);
// access is allowed in the following cases (only 1 & 2 require elevation):
// 1) to any HTTPS media if app is NOT coming from HTTPS
// 2) to URI in the current directory of the fusion cache
// 3) to site of origin media
if (SecurityHelper.AreStringTypesEqual(uriToOpen.Scheme, Uri.UriSchemeHttps))
{
// target is HTTPS. Then, elevate ONLY if we are NOT coming from HTTPS (=XDomain HTTPS app to HTTPS media disallowed)
Uri appDeploymentUri = SecurityHelper.ExtractUriForClickOnceDeployedApp();
if (!SecurityHelper.AreStringTypesEqual(appDeploymentUri.Scheme, Uri.UriSchemeHttps))
{
new WebPermission(NetworkAccess.Connect, BindUriHelper.UriToString(uriToOpen)).Assert();
elevated = true;
}
}
else
{
// elevate to allow access to media in the app's directory in the fusion cache.
new FileIOPermission(FileIOPermissionAccess.Read, appBase.LocalPath).Assert();// BlessedAssert
elevated = true;
}
// demand permissions. if demands succeds, it means we are in one of the cases above.
try
{
toOpen = DemandPermissions(uriToOpen);
}
finally
{
if (elevated)
{
CodeAccessPermission.RevertAssert();
}
}
}
else
{
toOpen = null;
}
// We pass in exact same URI for which we demanded permissions so that we can be sure
// there is no discrepancy between the two.
HRESULT.Check(MILMedia.Open(_nativeMedia, toOpen));
}
/// <SecurityNote>
/// Critical: This code elevates to read registry
/// TreatAsSafe: Detecting whether media is disabled is a safe operation
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
private void CheckMediaDisabledFlags()
{
if (SafeSecurityHelper.IsFeatureDisabled(SafeSecurityHelper.KeyToRead.MediaAudioOrVideoDisable))
{
// in case the registry key is '1' then demand
//Demand media permission here for Video or Audio
// Issue: 1232606 need to fix once clr has the media permissions
SecurityHelper.DemandMediaPermission(MediaPermissionAudio.AllAudio,
MediaPermissionVideo.AllVideo,
MediaPermissionImage.NoImage);
}
}
/// <SecurityNote>
/// Critical: This code returns the base directory of the app as a URI
/// IT constructs a Uri based on relative and absolute URI
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private Uri ResolveUri(Uri uri, Uri appBase)
{
if (uri.IsAbsoluteUri)
{
return uri;
}
else
{
return new Uri(appBase, uri);
}
}
// returns the exact string on which we demanded permissions
/// <SecurityNote>
/// Critical: This code is used to safeguard against various forms of attacks
/// to restrict access to loose file passed as relative path in the application
/// base direcory
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private string DemandPermissions(Uri absoluteUri)
{
Debug.Assert(absoluteUri.IsAbsoluteUri);
string toOpen = BindUriHelper.UriToString(absoluteUri);
int targetZone = SecurityHelper.MapUrlToZoneWrapper(absoluteUri);
if (targetZone == NativeMethods.URLZONE_LOCAL_MACHINE)
{
// go here only for files and not for UNC
if (absoluteUri.IsFile)
{
// Please note this pattern is unique and NEEDS TO EXIST , it prevents
// access to any folder but the one where the app is running from.
// PLEASE DO NOT REMOVE THIS DEMAND AND THE ASSERT IN THE CALLING CODE
toOpen = absoluteUri.LocalPath;
(new FileIOPermission(FileIOPermissionAccess.Read, toOpen)).Demand();
}
}
else //Any other zone
{
// UNC path pointing to a file (We filter for `http://intranet)
if (absoluteUri.IsFile && absoluteUri.IsUnc)
{
// perform checks for UNC content
SecurityHelper.EnforceUncContentAccessRules(absoluteUri);
// In this case we first check to see if the consumer has media permissions for
// safe media (Site of Origin + Cross domain).
if (!SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.SafeAudio,
MediaPermissionVideo.SafeVideo,
MediaPermissionImage.NoImage))
{
// if he does not then we demand web permission to allow access only to site of origin
(new FileIOPermission(FileIOPermissionAccess.Read, toOpen)).Demand();
}
}
else // Any other path
{
// In this case we first check to see if the consumer has media permissions for
// safe media (Site of Origin + Cross domain).
if (absoluteUri.Scheme != Uri.UriSchemeHttps)
{
//accessing non https content from an https app is disallowed
SecurityHelper.BlockCrossDomainForHttpsApps(absoluteUri);
if (!SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.SafeAudio,
MediaPermissionVideo.SafeVideo,
MediaPermissionImage.NoImage))
{
// if he does not then we demand web permission to allow access only to site of origin
(new WebPermission(NetworkAccess.Connect, toOpen)).Demand();
}
}
else// This is the case where target content is HTTPS
{
(new WebPermission(NetworkAccess.Connect, toOpen)).Demand();
}
}
}
return toOpen;
}
/// <summary>
/// Seek to specified position (in 100 nanosecond ticks)
/// </summary>
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia)
/// TreatAsSafe - critical resource isn't modified or handed out
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal void SetPosition(TimeSpan value)
{
VerifyAPI();
HRESULT.Check(MILMedia.SetPosition(_nativeMedia, value.Ticks));
}
/// <summary>
/// get the current position (in 100 nanosecond ticks)
/// </summary>
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia)
/// TreatAsSafe - critical resource isn't modified or handed out
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private TimeSpan GetPosition()
{
VerifyAPI();
long position = 0;
HRESULT.Check(MILMedia.GetPosition(_nativeMedia, ref position));
return TimeSpan.FromTicks(position);
}
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia)
/// TreatAsSafe - critical resource isn't modified or handed out
/// </SecurityNote>
private double PrivateSpeedRatio
{
[SecurityCritical, SecurityTreatAsSafe]
set
{
VerifyAPI();
if (Double.IsNaN(value))
{
throw new ArgumentException(SR.Get(SRID.ParameterValueCannotBeNaN), "value");
}
HRESULT.Check(MILMedia.SetRate(_nativeMedia, value));
}
}
//
// Set the current speed.
//
internal void SetSpeedRatio(double value)
{
_speedRatio = value;
//
// We don't change the speed if we are paused, unless we are in
// clock mode, which overrides paused mode.
//
if (!_paused || _mediaClock != null)
{
PrivateSpeedRatio = _speedRatio;
}
}
/// <summary>
/// Sets the source of the media (and opens it), without checking whether
/// we are under clock control. This is called by the clock.
/// </summary>
internal
void
SetSource(
Uri source
)
{
if (source != _sourceUri)
{
OpenMedia(source);
//
// Only assign the source uri if the OpenMedia succeeds.
//
_sourceUri = source;
}
}
/// <summary>
/// Verifies this object is in an accessible state, and that we
/// are being called from the correct thread. This method should
/// be the first thing called from any internal method.
/// </summary>
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia)
/// TreatAsSafe - critical resource isn't modified or handed out
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void VerifyAPI()
{
//
// We create _nativeMedia in the constructor, so it should always
// be initialized.
//
Debug.Assert(_nativeMedia != null && !_nativeMedia.IsInvalid);
//
// We only allow calls to any media object on the UI thread.
//
_dispatcher.VerifyAccess();
if (_nativeMedia == null || _nativeMedia.IsInvalid)
{
throw new System.NotSupportedException(SR.Get(SRID.Image_BadVersion));
}
}
/// <summary>
/// Verifies that this player is not currently controlled by a clock. Some actions are
/// invalid while we are under clock control.
/// </summary>
private
void
VerifyNotControlledByClock()
{
if (Clock != null)
{
throw new InvalidOperationException(SR.Get(SRID.Media_NotAllowedWhileTimingEngineInControl));
}
}
/// <summary>
/// SendMediaPlayerCommand
/// </summary> SecurityNote
/// <SecurityNote>
/// Critical - access critical resource (_nativeMedia)
/// TreatAsSafe - critical resource is treated like any other image.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private
void
SendMediaPlayerCommand(
DUCE.Channel channel,
DUCE.ResourceHandle handle,
bool notifyUceDirectly
)
{
//
// This is an interrop call, but, it does not set a last error being a COM call. So, suppress the
// presharp warning about losing last error.
//
#pragma warning disable 6523
//
// AddRef to ensure the media player stays alive during transport, even if the
// MediaPlayer goes away. The slave video resource takes ownership of this AddRef.
// Note there is still a gray danger zone here -- if the channel command is lost
// this reference won't be cleaned up.
//
//
UnsafeNativeMethods.MILUnknown.AddRef(_nativeMedia);
channel.SendCommandMedia(
handle,
_nativeMedia,
notifyUceDirectly
);
#pragma warning restore 6523
}
#endregion
#region Event Handlers
/// <summary>
/// When a new frame is received, we need to check if it is remote and then acquire the new frame
/// from the composition synchronously before passing the NewFrame event up to the
/// Media player.
/// </summary>
private
void
OnNewFrame(
object sender,
EventArgs args
)
{
_newFrameHelper.InvokeEvents(sender, args);
}
/// <summary>
/// Fired when the media is opened, we can't open our capture resources until the media is opened
/// because we won't know the size of the media.
/// </summary>
private
void
OnMediaOpened(
object sender,
EventArgs args
)
{
_mediaOpenedHelper.InvokeEvents(sender, args);
}
#endregion
#region Data Members
/// <summary>
/// Current volume (ranges from 0 to 1)
/// </summary>
private double _volume;
/// <summary>
/// Current balance (ranges from -1 (left) to 1 (right) )
/// </summary>
private double _balance;
/// <summary>
/// Current state of mute
/// </summary>
private bool _muted;
/// <summary>
/// Whether or not scrubbin is enabled
/// </summary>
private bool _scrubbingEnabled;
/// <summary>
/// Unamanaged Media object
/// </summary>
/// <SecurityNote>
/// Critical - this is a pointer to an unmanaged object that methods are called directly on
/// </SecurityNote>
[SecurityCritical]
private SafeMediaHandle _nativeMedia;
private MediaEventsHelper _mediaEventsHelper;
/// <summary>
/// Default volume
/// </summary>
private const double DEFAULT_VOLUME = 0.5;
/// <summary>
/// Default balance
/// </summary>
private const double DEFAULT_BALANCE = 0;
private double _speedRatio;
private bool _paused;
private Uri _sourceUri;
private MediaClock _mediaClock = null;
private Dispatcher _dispatcher = null;
private UniqueEventHelper _newFrameHelper = new UniqueEventHelper();
private UniqueEventHelper _mediaOpenedHelper = new UniqueEventHelper();
private const float _defaultDevicePixelsPerInch = 96.0F;
private Helper _helper;
/// <summary>
/// A separate class is needed to register for the ProcessExit event
/// because MediaPlayerState holds a strong reference to _nativeMedia.
/// If a MediaPlayerState method was registered for the ProcessExit
/// event then MediaPlayerState would not be garbage collected until
/// ProcessExit time.
/// </summary>
private class Helper
{
/// <SecurityNote>
/// Critical - this is a weak reference to a pointer to an unmanaged object
/// on which methods are called directly
/// </SecurityNote>
[SecurityCritical]
private WeakReference _nativeMedia;
/// <SecurityNote>
/// Accesses weak reference to pointer
/// </SecurityNote>
[SecurityCritical]
internal
Helper(
SafeMediaHandle nativeMedia
)
{
_nativeMedia = new WeakReference(nativeMedia);
}
/// <SecurityNote>
/// Accesses weak reference to pointer, calls unmanaged code
/// </SecurityNote>
[SecurityCritical]
internal
void
ProcessExitHandler(
object sender,
EventArgs args
)
{
SafeMediaHandle nativeMedia = (SafeMediaHandle)_nativeMedia.Target;
if (nativeMedia != null)
{
MILMedia.ProcessExitHandler(nativeMedia);
}
}
};
#endregion
}
#endregion
};
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IdReader.cs">
// Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in
// the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Spritely.ReadModel
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using static System.FormattableString;
/// <summary>
/// Class capable of reading Id properties from objects.
/// </summary>
public static class IdReader
{
private static readonly ConcurrentDictionary<Type, IdDefinition> idDefinitions = new ConcurrentDictionary<Type, IdDefinition>();
/// <summary>
/// Read the value from an Id member of the specified model instance.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <param name="model">The model.</param>
/// <returns>The value of the Id member.</returns>
public static object ReadValue<TModel>(TModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var idDefinition = idDefinitions.GetOrAdd(typeof(TModel), new IdDefinition(typeof(TModel)));
return idDefinition.ReadValue(model);
}
/// <summary>
/// Reads the name of the Id member.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <returns>The name of the Id member.</returns>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "This type safe method is preferred to its non-type safe equivalent.")]
public static string ReadName<TModel>()
{
var idDefinition = idDefinitions.GetOrAdd(typeof(TModel), new IdDefinition(typeof(TModel)));
return idDefinition.Name;
}
/// <summary>
/// Reads the type of the Id member.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <returns>The type of the Id member.</returns>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "There is an overload that doesn't require a generic parameter.")]
public static Type ReadType<TModel>()
{
var idDefinition = idDefinitions.GetOrAdd(typeof(TModel), new IdDefinition(typeof(TModel)));
return idDefinition.Type;
}
/// <summary>
/// Reads the type of the Id member from the given model type.
/// </summary>
/// <param name="modelType">Type of the model.</param>
/// <returns>The type of the Id member.</returns>
public static Type ReadType(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException(nameof(modelType));
}
var idDefinition = idDefinitions.GetOrAdd(modelType, new IdDefinition(modelType));
return idDefinition.Type;
}
/// <summary>
/// Sets the identifier member used during reads of a particular model type.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <param name="idMember">The identifier member.</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "This type safe method is preferred to its non-type safe equivalent.")]
public static void SetIdMember<TModel>(string idMember)
{
if (string.IsNullOrWhiteSpace(idMember))
{
throw new ArgumentNullException(nameof(idMember));
}
var idDefinition = idDefinitions.GetOrAdd(typeof(TModel), new IdDefinition(typeof(TModel)));
idDefinition.Names = new[] { idMember };
}
internal class IdDefinition
{
private static readonly object Lock = new object();
private ICollection<string> names = new[] { "Id", "id", "_id" };
private Func<object, object> readValue;
private string name;
private Type idType;
private readonly Type modelType;
public IdDefinition(Type modelType)
{
this.modelType = modelType;
}
public ICollection<string> Names
{
get { return names; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
lock (Lock)
{
names = value;
ReadValue = null;
Type = null;
}
}
}
public Func<object, object> ReadValue
{
get
{
if (readValue == null)
{
Initialize();
}
return readValue;
}
private set { readValue = value; }
}
public string Name
{
get
{
if (name == null)
{
Initialize();
}
return name;
}
private set { name = value; }
}
public Type Type
{
get
{
if (idType == null)
{
Initialize();
}
return idType;
}
private set { idType = value; }
}
private void Initialize()
{
var allMembers =
modelType.GetMembers(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
var elegibleMembers =
allMembers.Where(
m => m.MemberType == MemberTypes.Field || (m.MemberType == MemberTypes.Property && ((PropertyInfo)m).CanRead));
lock (Lock)
{
var matchingMembers = elegibleMembers.Where(m => Names.Contains(m.Name));
var idMember = Names.SelectMany(idName => matchingMembers.Where(m => m.Name == idName)).FirstOrDefault();
if (idMember == null)
{
throw new ArgumentException(
Invariant(
$"{modelType.Name} does not have an Id property or it is not readable (set only). Add a property or field named [{Names}] or if your object has a different name call IdReader.SetIdMember<{modelType.Name}>(\"YourIdProperty\")"));
}
if (idMember.MemberType == MemberTypes.Field)
{
var idField = (FieldInfo)idMember;
ReadValue = model =>
{
var id = idField.GetValue(model);
return id;
};
Name = idField.Name;
Type = idField.FieldType;
}
else
{
var idProperty = (PropertyInfo)idMember;
ReadValue = model =>
{
var id = idProperty.GetMethod.Invoke(model, new object[] { });
return id;
};
Name = idProperty.Name;
Type = idProperty.GetMethod.ReturnType;
}
}
}
}
}
}
| |
namespace EyeInTheSky.Commands
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using Castle.Core.Logging;
using EyeInTheSky.Extensions;
using EyeInTheSky.Model;
using EyeInTheSky.Model.Interfaces;
using EyeInTheSky.Model.StalkNodes;
using EyeInTheSky.Model.StalkNodes.BaseNodes;
using EyeInTheSky.Services;
using EyeInTheSky.Services.Email.Interfaces;
using EyeInTheSky.Services.Interfaces;
using Stwalkerster.Bot.CommandLib.Attributes;
using Stwalkerster.Bot.CommandLib.Commands.CommandUtilities;
using Stwalkerster.Bot.CommandLib.Commands.CommandUtilities.Response;
using Stwalkerster.Bot.CommandLib.Exceptions;
using Stwalkerster.Bot.CommandLib.Services.Interfaces;
using Stwalkerster.IrcClient.Interfaces;
using Stwalkerster.IrcClient.Model.Interfaces;
using CLFlag = Stwalkerster.Bot.CommandLib.Model.Flag;
[CommandInvocation("stalk")]
[CommandFlag(AccessFlags.User)]
public class StalkCommand : CommandBase
{
private readonly IChannelConfiguration channelConfiguration;
private readonly IAppConfiguration config;
private readonly INotificationTemplates templates;
private readonly IEmailHelper emailHelper;
private readonly IXmlCacheService xmlCacheService;
private readonly IBotUserConfiguration botUserConfiguration;
private readonly ISubscriptionHelper subscriptionHelper;
private readonly IIrcClient wikimediaClient;
private readonly IEmailTemplateFormatter emailTemplateFormatter;
private readonly IStalkNodeFactory stalkNodeFactory;
public StalkCommand(
string commandSource,
IUser user,
IList<string> arguments,
ILogger logger,
IFlagService flagService,
IConfigurationProvider configurationProvider,
IIrcClient client,
IChannelConfiguration channelConfiguration,
IStalkNodeFactory stalkNodeFactory,
IAppConfiguration config,
INotificationTemplates templates,
IEmailHelper emailHelper,
IXmlCacheService xmlCacheService,
IBotUserConfiguration botUserConfiguration,
ISubscriptionHelper subscriptionHelper,
IIrcClient wikimediaClient,
IEmailTemplateFormatter emailTemplateFormatter
) : base(
commandSource,
user,
arguments,
logger,
flagService,
configurationProvider,
client)
{
this.channelConfiguration = channelConfiguration;
this.config = config;
this.templates = templates;
this.emailHelper = emailHelper;
this.xmlCacheService = xmlCacheService;
this.botUserConfiguration = botUserConfiguration;
this.subscriptionHelper = subscriptionHelper;
this.wikimediaClient = wikimediaClient;
this.emailTemplateFormatter = emailTemplateFormatter;
this.stalkNodeFactory = stalkNodeFactory;
}
protected override IEnumerable<CommandResponse> OnPreRun(out bool abort)
{
abort = false;
if (!this.CommandSource.StartsWith("#"))
{
throw new CommandErrorException("This command must be executed in-channel!");
}
return null;
}
[SubcommandInvocation("unsubscribe")]
[RequiredArguments(1)]
[Help("<Identifier>", "Unsubscribes from email notifications for this stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> UnsubscribeMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
var ircChannel = this.channelConfiguration[this.CommandSource];
if (!ircChannel.Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var accountKey = string.Format("$a:{0}", this.User.Account);
var botUser = this.botUserConfiguration[accountKey];
if (botUser == null)
{
yield return new CommandResponse
{
Message = "You must be a registered user to use this command."
};
yield break;
}
var stalk = ircChannel.Stalks[stalkName];
SubscriptionSource subscriptionSource;
var result = this.subscriptionHelper.UnsubscribeStalk(botUser.Mask, ircChannel, stalk, out subscriptionSource);
this.channelConfiguration.Save();
if (result)
{
yield return new CommandResponse
{
Message = string.Format("Unsubscribed from notifications for stalk {0}", stalkName)
};
}
else
{
yield return new CommandResponse
{
Message = string.Format("You are not subscribed to notifications for stalk {0}", stalkName)
};
}
}
[SubcommandInvocation("subscribe")]
[RequiredArguments(1)]
[Help("<Identifier>", "Subscribes to email notifications for this stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> SubscribeMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
var ircChannel = this.channelConfiguration[this.CommandSource];
if (!ircChannel.Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var accountKey = string.Format("$a:{0}", this.User.Account);
var botUser = this.botUserConfiguration[accountKey];
if (botUser == null)
{
yield return new CommandResponse
{
Message = "You must be a registered user with a confirmed email address to use this command."
};
yield break;
}
if (!botUser.EmailAddressConfirmed)
{
yield return new CommandResponse
{
Message = "You must have a confirmed email address to use this command."
};
yield break;
}
var stalk = ircChannel.Stalks[stalkName];
SubscriptionSource subscriptionSource;
var result = this.subscriptionHelper.SubscribeStalk(botUser.Mask, ircChannel, stalk, out subscriptionSource);
this.channelConfiguration.Save();
if (result)
{
yield return new CommandResponse
{
Message = string.Format("Subscribed to notifications for stalk {0}", stalkName)
};
}
else
{
var message = string.Format("You are already subscribed to notifications for stalk {0}", stalkName);
if (subscriptionSource == SubscriptionSource.Channel)
{
message = string.Format(
"You are already subscribed to notifications for {1}, including stalk {0}", stalkName,
ircChannel.Identifier);
}
yield return new CommandResponse
{
Message = message
};
}
}
[SubcommandInvocation("report")]
[Help("", "Sends a report on the status of all stalks via email")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> ReportMode()
{
var accountKey = string.Format("$a:{0}", this.User.Account);
var botUser = this.botUserConfiguration[accountKey];
if (botUser == null)
{
yield return new CommandResponse
{
Message = "You must be a registered user with a confirmed email address to use this command."
};
yield break;
}
if (!botUser.EmailAddressConfirmed)
{
yield return new CommandResponse
{
Message = "You must have a confirmed email address to use this command."
};
yield break;
}
var stalks = this.channelConfiguration[this.CommandSource].Stalks.Values;
var disabled = stalks.Where(x => !x.IsEnabled);
var expired = stalks.Where(x => x.ExpiryTime != null && x.ExpiryTime < DateTime.UtcNow);
var active = stalks.Where(x => x.IsActive());
var body = string.Format(
this.templates.EmailStalkReport,
this.emailTemplateFormatter.FormatStalkListForEmail(active, botUser),
this.emailTemplateFormatter.FormatStalkListForEmail(disabled, botUser),
this.emailTemplateFormatter.FormatStalkListForEmail(expired, botUser),
this.CommandSource
);
this.emailHelper.SendEmail(
body,
string.Format(this.templates.EmailStalkReportSubject, this.CommandSource),
null,
botUser,
null);
yield return new CommandResponse
{
Message = "Stalk report sent via email"
};
}
[SubcommandInvocation("or")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help("<Identifier> <user|page|summary|xml> <Match...>",
"Sets the stalk configuration of the specified stalk to the logical OR of the current configuration, and a specified user, page, or edit summary; or XML tree (advanced).")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> OrMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var newStalkType = tokenList.PopFromFront();
var stalk = this.channelConfiguration[this.CommandSource].Stalks[stalkName];
var newTarget = string.Join(" ", tokenList);
var newNode = this.CreateNode(newStalkType, newTarget);
if (stalk.SearchTree.GetType() == typeof(OrNode))
{
((OrNode) stalk.SearchTree).ChildNodes.Add(newNode);
}
else
{
var newroot = new OrNode
{
ChildNodes = new List<IStalkNode>
{
stalk.SearchTree,
newNode
}
};
stalk.SearchTree = newroot;
}
yield return new CommandResponse
{
Message = string.Format(
"Set {0} for stalk {1} with CSL value: {2}",
newStalkType,
stalkName,
stalk.SearchTree)
};
this.channelConfiguration.Save();
}
[SubcommandInvocation("and")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help("<Identifier> <user|page|summary|xml> <Match...>",
"Sets the stalk configuration of the specified stalk to the logical AND of the current configuration, and a specified user, page, or edit summary; or XML tree (advanced).")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> AndMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var newStalkType = tokenList.PopFromFront();
var stalk = this.channelConfiguration[this.CommandSource].Stalks[stalkName];
var newTarget = string.Join(" ", tokenList);
var newNode = this.CreateNode(newStalkType, newTarget);
if (stalk.SearchTree.GetType() == typeof(AndNode))
{
((AndNode) stalk.SearchTree).ChildNodes.Add(newNode);
}
else
{
var newroot = new AndNode
{
ChildNodes = new List<IStalkNode>
{
stalk.SearchTree,
newNode
}
};
stalk.SearchTree = newroot;
}
yield return new CommandResponse
{
Message = string.Format(
"Set {0} for stalk {1} with CSL value: {2}",
newStalkType,
stalkName,
stalk.SearchTree)
};
this.channelConfiguration.Save();
}
[SubcommandInvocation("enabled")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help("<Identifier> <true|false>", "Marks a stalk as enabled or disabled")]
// ReSharper disable once UnusedMember.Global
// ReSharper disable once MemberCanBePrivate.Global
protected IEnumerable<CommandResponse> EnabledMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
bool enabled;
var possibleBoolean = tokenList.PopFromFront();
if (!BooleanParser.TryParse(possibleBoolean, out enabled))
{
throw new CommandErrorException(
string.Format(
"{0} is not a value of boolean I recognise. Try 'true', 'false' or ERR_FILE_NOT_FOUND.",
possibleBoolean));
}
yield return new CommandResponse
{
Message = string.Format("Set enabled attribute on stalk {0} to {1}", stalkName, enabled)
};
this.channelConfiguration[this.CommandSource].Stalks[stalkName].IsEnabled = enabled;
this.channelConfiguration.Save();
}
[SubcommandInvocation("enable")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(1)]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> EnableAlias()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
this.Arguments.Clear();
this.Arguments.Add(stalkName);
this.Arguments.Add("true");
return this.EnabledMode();
}
[SubcommandInvocation("disable")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(1)]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> DisableAlias()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
this.Arguments.Clear();
this.Arguments.Add(stalkName);
this.Arguments.Add("false");
return this.EnabledMode();
}
[SubcommandInvocation("expiry")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help(new[]{"<Identifier> <Expiry Date>","<Identifier> <Duration>", "<Identifier> never"},
"Sets the expiry date/time of the specified stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> ExpiryMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var date = string.Join(" ", tokenList);
DateTime expiryTime;
TimeSpan expiryDuration;
if (date == "never" || date == "infinite" || date == "infinity")
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].ExpiryTime = null;
yield return new CommandResponse
{
Message = string.Format("Removed expiry from stalk {0}", stalkName)
};
}
else if (DateTime.TryParse(date, out expiryTime))
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].ExpiryTime = expiryTime;
yield return new CommandResponse
{
Message = string.Format(
"Set expiry attribute on stalk {0} to {1}",
stalkName,
expiryTime.ToString(this.config.DateFormat))
};
}
else if (TimeSpan.TryParse(date, out expiryDuration))
{
expiryTime = DateTime.UtcNow + expiryDuration;
this.channelConfiguration[this.CommandSource].Stalks[stalkName].ExpiryTime = expiryTime;
yield return new CommandResponse
{
Message = string.Format(
"Set expiry attribute on stalk {0} to {1}",
stalkName,
expiryTime.ToString(this.config.DateFormat))
};
}
else
{
throw new CommandErrorException(string.Format(
"Unable to parse date from '{0}'. If you mean to remove the expiry date, please specify \"never\".",
date));
}
this.channelConfiguration.Save();
}
[SubcommandInvocation("dynamicexpiry")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help(new[]{"<Identifier> <Interval>", "<Identifier> never"},
"Sets the dynamic expiry duration of the specified stalk. ")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> DynamicExpiryMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var date = string.Join(" ", tokenList);
TimeSpan expiryDuration;
if (date == "never" || date == "infinite" || date == "infinity")
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].DynamicExpiry = null;
yield return new CommandResponse
{
Message = string.Format("Removed dynamic expiry duration from stalk {0}", stalkName)
};
}
else if (TimeSpan.TryParse(date, out expiryDuration))
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].DynamicExpiry = expiryDuration;
yield return new CommandResponse
{
Message = string.Format(
"Set dynamic expiry attribute on stalk {0} to {1}",
stalkName,
expiryDuration.ToString(this.config.TimeSpanFormat))
};
}
else
{
throw new CommandErrorException(string.Format(
"Unable to parse time span from '{0}'. If you mean to remove the dynamic expiry duration, please specify \"never\".",
date));
}
this.channelConfiguration.Save();
}
[SubcommandInvocation("description"), SubcommandInvocation("desc")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(1)]
[Help("<Identifier> <Description...>", "Sets the description of the specified stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> DescriptionMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var descr = string.Join(" ", tokenList);
if (string.IsNullOrWhiteSpace(descr))
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].Description = null;
yield return new CommandResponse
{
Message = string.Format("Cleared description attribute on stalk {0}", stalkName)
};
}
else
{
this.channelConfiguration[this.CommandSource].Stalks[stalkName].Description = descr;
yield return new CommandResponse
{
Message = string.Format("Set description attribute on stalk {0} to {1}", stalkName, descr)
};
}
this.channelConfiguration.Save();
}
[SubcommandInvocation("list")]
[CommandFlag(CLFlag.Standard)]
[Help("", "Lists all active stalks")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> ListMode()
{
var activeStalks = this.channelConfiguration[this.CommandSource]
.Stalks.Values.Where(x => x.IsActive())
.ToList();
if (!activeStalks.Any())
{
yield return new CommandResponse
{
Message = "There are no active stalks.",
Type = CommandResponseType.Notice,
Destination = CommandResponseDestination.PrivateMessage
};
yield break;
}
yield return new CommandResponse
{
Message = "Active stalk list:",
Type = CommandResponseType.Notice,
Destination = CommandResponseDestination.PrivateMessage
};
foreach (var stalk in activeStalks)
{
var message = string.Format(
"Identifier: {0}, Last modified: {1}, Type: Complex {2}",
stalk.Identifier,
stalk.LastUpdateTime.GetValueOrDefault().ToString(this.config.DateFormat),
stalk.SearchTree);
yield return new CommandResponse
{
Message = message,
Type = CommandResponseType.Notice,
Destination = CommandResponseDestination.PrivateMessage
};
}
yield return new CommandResponse
{
Message = "End of stalk list.",
Type = CommandResponseType.Notice,
Destination = CommandResponseDestination.PrivateMessage
};
this.channelConfiguration.Save();
}
[SubcommandInvocation("set")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(2)]
[Help(
"<Identifier> <user|page|summary|xml> <Match...>",
"Sets the stalk configuration of the specified stalk to specified user, page, or edit summary. Alternatively, manually specify an XML tree (advanced).")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> SetMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var newStalkType = tokenList.PopFromFront();
var stalk = this.channelConfiguration[this.CommandSource].Stalks[stalkName];
var newTarget = string.Join(" ", tokenList);
var newroot = this.CreateNode(newStalkType, newTarget);
stalk.SearchTree = newroot;
yield return new CommandResponse
{
Message = string.Format("Set {0} for stalk {1} with CSL value: {2}", newStalkType, stalkName, newroot)
};
this.channelConfiguration.Save();
}
[SubcommandInvocation("delete"), SubcommandInvocation("del")]
[RequiredArguments(1)]
[CommandFlag(AccessFlags.Configuration)]
[Help("<identifier>", "Deletes a stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> DeleteMode()
{
var stalkName = this.Arguments.First();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
this.channelConfiguration[this.CommandSource].Stalks.Remove(stalkName);
ChannelConfiguration.IndividualMatchDuration.RemoveLabelled(this.CommandSource, stalkName);
yield return new CommandResponse
{
Message = string.Format("Deleted stalk {0}", stalkName)
};
this.channelConfiguration.Save();
}
[SubcommandInvocation("export")]
[CommandFlag(CLFlag.Standard)]
[RequiredArguments(1)]
[Help("<identifier>", "Retrieves the XML search tree of a specific stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> ExportMode()
{
var stalkName = this.Arguments.First();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var searchTree = this.channelConfiguration[this.CommandSource].Stalks[stalkName].SearchTree;
yield return new CommandResponse
{
Message = string.Format(
"{0}: {1}",
stalkName,
this.stalkNodeFactory.ToXml(new XmlDocument(), searchTree).OuterXml
)
};
}
[SubcommandInvocation("refresh")]
[CommandFlag(AccessFlags.Configuration)]
[RequiredArguments(1)]
[Help("<identifier>", "Refreshes the stalk tree if any external node providers are used.")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> RefreshMode()
{
var stalkName = this.Arguments.First();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
// bounce through XML, as this is guaranteed to be a refresh.
var originalTree = this.channelConfiguration[this.CommandSource].Stalks[stalkName].SearchTree;
var xmlTree = this.stalkNodeFactory.ToXml(new XmlDocument(), originalTree);
var newTree = this.stalkNodeFactory.NewFromXmlFragment(xmlTree);
yield return new CommandResponse
{
Message = string.Format(
"{0}: {1}",
stalkName,
newTree
)
};
}
[RequiredArguments(1)]
[SubcommandInvocation("add"), SubcommandInvocation("create")]
[CommandFlag(AccessFlags.Configuration)]
[Help("<identifier>", "Adds a new unconfigured stalk")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> AddMode()
{
var tokenList = this.Arguments;
var stalkName = tokenList.First();
var stalk = new ComplexStalk(stalkName)
{Channel = this.CommandSource, WatchChannel = this.config.WikimediaChannel};
this.channelConfiguration[this.CommandSource].Stalks.Add(stalk.Identifier, stalk);
yield return new CommandResponse
{
Message = string.Format("Added disabled stalk {0} with CSL value: {1}", stalkName, stalk.SearchTree)
};
this.channelConfiguration.Save();
}
[RequiredArguments(3)]
[SubcommandInvocation("clone")]
[CommandFlag(AccessFlags.Configuration)]
[Help("<source channel> <source identifier> <target identifier>", "Clones an existing stalk from a different channel")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> CloneMode()
{
var tokenList = this.Arguments;
var sourceChannel = tokenList[0];
var sourceIdentifier = tokenList[1];
var targetIdentifier = tokenList[2];
var sourceChannelConfig = this.channelConfiguration.ContainsKey(sourceChannel)
? this.channelConfiguration[sourceChannel]
: null;
if (sourceChannelConfig == null)
{
throw new CommandErrorException(string.Format("The channel {0} does not exist in configuration", sourceChannel));
}
var sourceStalk = sourceChannelConfig.Stalks.ContainsKey(sourceIdentifier)
? sourceChannelConfig.Stalks[sourceIdentifier]
: null;
if (sourceStalk == null)
{
throw new CommandErrorException(string.Format("The channel {0} does not exist in configuration", sourceChannel));
}
if (this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(targetIdentifier))
{
throw new CommandErrorException(string.Format("The identifier {0} already exists in this channel!",
targetIdentifier));
}
var tree = sourceStalk.SearchTree;
// bounce it via XML to ensure its a) different objects and b) saves properly
tree = this.stalkNodeFactory.NewFromXmlFragment(this.stalkNodeFactory.ToXml(new XmlDocument(), tree));
var newStalk = new ComplexStalk(targetIdentifier)
{
Channel = this.CommandSource,
Description = string.Format("{0}; based on stalk {1} from {2}", sourceStalk.Description, sourceIdentifier, sourceChannel),
ExpiryTime = sourceStalk.ExpiryTime,
IsEnabled = sourceStalk.IsEnabled,
SearchTree = tree,
WatchChannel = sourceStalk.WatchChannel,
DynamicExpiry = sourceStalk.DynamicExpiry,
LastTriggerTime = sourceStalk.LastTriggerTime
};
this.channelConfiguration[this.CommandSource].Stalks.Add(newStalk.Identifier, newStalk);
this.channelConfiguration.Save();
yield return new CommandResponse
{
Message = string.Format("Created new {1} stalk {0}{2} with CSL {3}",
newStalk.Identifier,
newStalk.IsEnabled ? "enabled" : "disabled",
newStalk.ExpiryTime.HasValue
? newStalk.ExpiryTime < DateTime.UtcNow
? string.Format(" (expired {0:%d}d {0:%h}h {0:%m}m ago)", newStalk.ExpiryTime.Value - DateTime.UtcNow)
: string.Format(" (expiring in {0:%d}d {0:%h}h {0:%m}m)", newStalk.ExpiryTime.Value - DateTime.UtcNow)
: string.Empty,
tree
)
};
}
[RequiredArguments(2)]
[SubcommandInvocation("watchchannel")]
[CommandFlag(AccessFlags.Configuration)]
[Help("<identifier> <channel>", "Changes the monitored feed to a different wiki")]
// ReSharper disable once UnusedMember.Global
protected IEnumerable<CommandResponse> WatchChannelMode()
{
var tokenList = (List<string>) this.Arguments;
var stalkName = tokenList.PopFromFront();
if (!this.channelConfiguration[this.CommandSource].Stalks.ContainsKey(stalkName))
{
throw new CommandErrorException(string.Format("Can't find the stalk '{0}'!", stalkName));
}
var stalk = this.channelConfiguration[this.CommandSource].Stalks[stalkName];
var oldWatchChannel = stalk.WatchChannel;
stalk.WatchChannel = tokenList.PopFromFront();
if (!this.wikimediaClient.Channels.ContainsKey(stalk.WatchChannel))
{
this.wikimediaClient.JoinChannel(stalk.WatchChannel);
}
var remainingStalksOnChannel = this.channelConfiguration.Items.Select(x => x.Stalks)
.Aggregate(
new List<IStalk>(),
(agg, cur) =>
{
agg.AddRange(cur.Values.Where(x => x.WatchChannel == oldWatchChannel));
return agg;
});
if (remainingStalksOnChannel.Count == 0)
{
this.wikimediaClient.PartChannel(oldWatchChannel, "Nothing left to watch here");
}
Debugger.Break();
yield return new CommandResponse
{
Message = string.Format("Set watch channel for stalk {0} to {1}", stalkName, stalk.WatchChannel)
};
this.channelConfiguration.Save();
}
protected IStalkNode CreateNode(string type, string stalkTarget)
{
IStalkNode newNode;
var escapedTarget = Regex.Escape(stalkTarget);
switch (type)
{
case "user":
var usn = new UserStalkNode();
usn.SetMatchExpression(escapedTarget);
newNode = usn;
break;
case "page":
var psn = new PageStalkNode();
psn.SetMatchExpression(escapedTarget);
newNode = psn;
break;
case "summary":
var ssn = new SummaryStalkNode();
ssn.SetMatchExpression(escapedTarget);
newNode = ssn;
break;
case "xml":
try
{
var xml = this.xmlCacheService.RetrieveXml(this.User);
if (xml == null)
{
throw new CommandErrorException("No cached XML. Please use the xml command first.");
}
newNode = this.stalkNodeFactory.NewFromXmlFragment(xml);
}
catch (XmlException ex)
{
throw new CommandErrorException(ex.Message, ex);
}
break;
default:
throw new CommandErrorException("Unknown stalk type!");
}
return newNode;
}
}
}
| |
// 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: XMLParser and Tree builder internal to BCL
**
**
===========================================================*/
namespace System
{
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Security;
using System.Globalization;
using System.IO;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
internal enum ConfigEvents
{
StartDocument = 0,
StartDTD = StartDocument + 1,
EndDTD = StartDTD + 1,
StartDTDSubset = EndDTD + 1,
EndDTDSubset = StartDTDSubset + 1,
EndProlog = EndDTDSubset + 1,
StartEntity = EndProlog + 1,
EndEntity = StartEntity + 1,
EndDocument = EndEntity + 1,
DataAvailable = EndDocument + 1,
LastEvent = DataAvailable
}
[Serializable]
internal enum ConfigNodeType
{
Element = 1,
Attribute = Element + 1,
Pi = Attribute + 1,
XmlDecl = Pi + 1,
DocType = XmlDecl + 1,
DTDAttribute = DocType + 1,
EntityDecl = DTDAttribute + 1,
ElementDecl = EntityDecl + 1,
AttlistDecl = ElementDecl + 1,
Notation = AttlistDecl + 1,
Group = Notation + 1,
IncludeSect = Group + 1,
PCData = IncludeSect + 1,
CData = PCData + 1,
IgnoreSect = CData + 1,
Comment = IgnoreSect + 1,
EntityRef = Comment + 1,
Whitespace = EntityRef + 1,
Name = Whitespace + 1,
NMToken = Name + 1,
String = NMToken + 1,
Peref = String + 1,
Model = Peref + 1,
ATTDef = Model + 1,
ATTType = ATTDef + 1,
ATTPresence = ATTType + 1,
DTDSubset = ATTPresence + 1,
LastNodeType = DTDSubset + 1
}
[Serializable]
internal enum ConfigNodeSubType
{
Version = (int)ConfigNodeType.LastNodeType,
Encoding = Version + 1,
Standalone = Encoding + 1,
NS = Standalone + 1,
XMLSpace = NS + 1,
XMLLang = XMLSpace + 1,
System = XMLLang + 1,
Public = System + 1,
NData = Public + 1,
AtCData = NData + 1,
AtId = AtCData + 1,
AtIdref = AtId + 1,
AtIdrefs = AtIdref + 1,
AtEntity = AtIdrefs + 1,
AtEntities = AtEntity + 1,
AtNmToken = AtEntities + 1,
AtNmTokens = AtNmToken + 1,
AtNotation = AtNmTokens + 1,
AtRequired = AtNotation + 1,
AtImplied = AtRequired + 1,
AtFixed = AtImplied + 1,
PentityDecl = AtFixed + 1,
Empty = PentityDecl + 1,
Any = Empty + 1,
Mixed = Any + 1,
Sequence = Mixed + 1,
Choice = Sequence + 1,
Star = Choice + 1,
Plus = Star + 1,
Questionmark = Plus + 1,
LastSubNodeType = Questionmark + 1
}
internal abstract class BaseConfigHandler
{
// These delegates must be at the very start of the object
// This is necessary because unmanaged code takes a dependency on this layout
// Any changes made to this must be reflected in ConfigHelper.h in ConfigFactory class
protected Delegate[] eventCallbacks;
public BaseConfigHandler()
{
InitializeCallbacks();
}
private void InitializeCallbacks()
{
if (eventCallbacks == null)
{
eventCallbacks = new Delegate[6];
eventCallbacks[0] = new NotifyEventCallback(this.NotifyEvent);
eventCallbacks[1] = new BeginChildrenCallback(this.BeginChildren);
eventCallbacks[2] = new EndChildrenCallback(this.EndChildren);
eventCallbacks[3] = new ErrorCallback(this.Error);
eventCallbacks[4] = new CreateNodeCallback(this.CreateNode);
eventCallbacks[5] = new CreateAttributeCallback(this.CreateAttribute);
}
}
private delegate void NotifyEventCallback(ConfigEvents nEvent);
public abstract void NotifyEvent(ConfigEvents nEvent);
private delegate void BeginChildrenCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
public abstract void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
private delegate void EndChildrenCallback(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
public abstract void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
private delegate void ErrorCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
private delegate void CreateNodeCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
private delegate void CreateAttributeCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void RunParser(String fileName);
}
// Class used to build a DOM like tree of parsed XML
internal class ConfigTreeParser : BaseConfigHandler
{
ConfigNode rootNode = null;
ConfigNode currentNode = null;
String fileName = null;
int attributeEntry;
String key = null;
String [] treeRootPath = null; // element to start tree
bool parsing = false;
int depth = 0;
int pathDepth = 0;
int searchDepth = 0;
bool bNoSearchPath = false;
// Track state for error message formatting
String lastProcessed = null;
bool lastProcessedEndElement;
// NOTE: This parser takes a path eg. /configuration/system.runtime.remoting
// and will return a node which matches this.
internal ConfigNode Parse(String fileName, String configPath)
{
return Parse(fileName, configPath, false);
}
internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
this.fileName = fileName;
if (configPath[0] == '/'){
treeRootPath = configPath.Substring(1).Split('/');
pathDepth = treeRootPath.Length - 1;
bNoSearchPath = false;
}
else{
treeRootPath = new String[1];
treeRootPath[0] = configPath;
bNoSearchPath = true;
}
if (!skipSecurityStuff) {
(new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath(fileName))).Demand();
}
#pragma warning disable 618
(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
#pragma warning restore 618
try
{
RunParser(fileName);
}
catch(FileNotFoundException) {
throw; // Pass these through unadulterated.
}
catch(DirectoryNotFoundException) {
throw; // Pass these through unadulterated.
}
catch(UnauthorizedAccessException) {
throw;
}
catch(FileLoadException) {
throw;
}
catch(Exception inner) {
String message = GetInvalidSyntaxMessage();
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
throw new Exception(message, inner);
}
return rootNode;
}
public override void NotifyEvent(ConfigEvents nEvent)
{
BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n");
}
public override void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
//Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (!parsing &&
(!bNoSearchPath
&& depth == (searchDepth + 1)
&& String.Compare(text, treeRootPath[searchDepth], StringComparison.Ordinal) == 0))
{
searchDepth++;
}
}
public override void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
lastProcessed = text;
lastProcessedEndElement = true;
if (parsing)
{
//Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty);
if (currentNode == rootNode)
{
// End of section of tree which is parsed
parsing = false;
}
currentNode = currentNode.Parent;
}
else if (nType == ConfigNodeType.Element){
if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], StringComparison.Ordinal) == 0)
{
searchDepth--;
depth--;
}
else
depth--;
}
}
public override void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0);
}
public override void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (nType == ConfigNodeType.Element)
{
// New Node
lastProcessed = text;
lastProcessedEndElement = false;
if (parsing
|| (bNoSearchPath &&
String.Compare(text, treeRootPath[0], StringComparison.OrdinalIgnoreCase) == 0)
|| (depth == searchDepth && searchDepth == pathDepth &&
String.Compare(text, treeRootPath[pathDepth], StringComparison.OrdinalIgnoreCase) == 0 ))
{
parsing = true;
ConfigNode parentNode = currentNode;
currentNode = new ConfigNode(text, parentNode);
if (rootNode == null)
rootNode = currentNode;
else
parentNode.AddChild(currentNode);
}
else
depth++;
}
else if (nType == ConfigNodeType.PCData)
{
// Data node
if (currentNode != null)
{
currentNode.Value = text;
}
}
}
public override void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (parsing)
{
// if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the
// attribute name is encountered
if (nType == ConfigNodeType.Attribute)
{
attributeEntry = currentNode.AddAttribute(text, "");
key = text;
}
else if (nType == ConfigNodeType.PCData)
{
currentNode.ReplaceAttribute(attributeEntry, key, text);
}
else
{
String message = GetInvalidSyntaxMessage();
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
throw new Exception(message);
}
}
}
#if _DEBUG
[System.Diagnostics.Conditional("_LOGGING")]
private void Trace(String name,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength, int fEmpty)
{
BCLDebug.Trace("REMOTE","Node "+name);
BCLDebug.Trace("REMOTE","text "+text);
BCLDebug.Trace("REMOTE","textLength "+textLength);
BCLDebug.Trace("REMOTE","size "+size);
BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString());
BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString());
BCLDebug.Trace("REMOTE","terminal "+terminal);
BCLDebug.Trace("REMOTE","prefixLength "+prefixLength);
BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n");
}
#endif
private String GetInvalidSyntaxMessage()
{
String lastProcessedTag = null;
if (lastProcessed != null)
lastProcessedTag = (lastProcessedEndElement ? "</" : "<") + lastProcessed + ">";
return Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile", fileName, lastProcessedTag);
}
}
// Node in Tree produced by ConfigTreeParser
internal class ConfigNode
{
String m_name = null;
String m_value = null;
ConfigNode m_parent = null;
List<ConfigNode> m_children = new List<ConfigNode>(5);
List<DictionaryEntry> m_attributes = new List<DictionaryEntry>(5);
internal ConfigNode(String name, ConfigNode parent)
{
m_name = name;
m_parent = parent;
}
internal String Name
{
get {return m_name;}
}
internal String Value
{
get {return m_value;}
set {m_value = value;}
}
internal ConfigNode Parent
{
get {return m_parent;}
}
internal List<ConfigNode> Children
{
get {return m_children;}
}
internal List<DictionaryEntry> Attributes
{
get {return m_attributes;}
}
internal void AddChild(ConfigNode child)
{
child.m_parent = this;
m_children.Add(child);
}
internal int AddAttribute(String key, String value)
{
m_attributes.Add(new DictionaryEntry(key, value));
return m_attributes.Count-1;
}
internal void ReplaceAttribute(int index, String key, String value)
{
m_attributes[index] = new DictionaryEntry(key, value);
}
#if _DEBUG
[System.Diagnostics.Conditional("_LOGGING")]
internal void Trace()
{
BCLDebug.Trace("REMOTE","************ConfigNode************");
BCLDebug.Trace("REMOTE","Name = "+m_name);
if (m_value != null)
BCLDebug.Trace("REMOTE","Value = "+m_value);
if (m_parent != null)
BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name);
for (int i=0; i<m_attributes.Count; i++)
{
DictionaryEntry de = (DictionaryEntry)m_attributes[i];
BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value);
}
for (int i=0; i<m_children.Count; i++)
{
((ConfigNode)m_children[i]).Trace();
}
}
#endif
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
/// <summary>
/// A selection that uses indices instead of features.
/// </summary>
public class IndexSelection : Changeable, IIndexSelection
{
#region Fields
private readonly IFeatureLayer _layer;
private readonly List<ShapeRange> _shapes;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="IndexSelection"/> class.
/// </summary>
/// <param name="layer">Layer the selected items belong to.</param>
public IndexSelection(IFeatureLayer layer)
{
_layer = layer;
_shapes = layer.DataSet.ShapeIndices;
SelectionMode = SelectionMode.IntersectsExtent;
SelectionState = true;
}
#endregion
#region Properties
/// <inheritdoc />
public int Count
{
get
{
return _layer.DrawnStates?.Count(_ => _.Selected == SelectionState) ?? 0;
}
}
/// <summary>
/// Gets the envelope of this collection.
/// </summary>
public Envelope Envelope
{
get
{
if (!_layer.DrawnStatesNeeded) return new Envelope();
Extent ext = new Extent();
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected == SelectionState)
{
ext.ExpandToInclude(_shapes[shp].Extent);
}
}
return ext.ToEnvelope();
}
}
/// <inheritdoc />
public bool IsReadOnly => false;
/// <summary>
/// Gets or sets the handler to use for progress messages during selection.
/// </summary>
public IProgressHandler ProgressHandler { get; set; }
/// <summary>
/// Gets or sets the region category. Setting this to a specific category will only allow selection by
/// region to affect the features that are within the specified category.
/// </summary>
public IFeatureCategory RegionCategory { get; set; }
/// <summary>
/// Gets or sets the selection mode. The selection mode controls how envelopes are treated when working with geometries.
/// </summary>
public SelectionMode SelectionMode { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this should work as "Selected" indices (true) or
/// "UnSelected" indices (false).
/// </summary>
public bool SelectionState { get; set; }
#endregion
#region Methods
/// <inheritdoc />
public void Add(int index)
{
if (index < 0 || index >= _layer.DrawnStates.Length) return;
if (_layer.DrawnStates[index].Selected == SelectionState) return;
_layer.DrawnStates[index].Selected = SelectionState;
OnChanged();
}
/// <summary>
/// Adds all of the specified index values to the selection
/// </summary>
/// <param name="indices">The indices to add</param>
public void AddRange(IEnumerable<int> indices)
{
foreach (int index in indices)
{
// CGX
if (_layer.DrawnStates.Length > index)
_layer.DrawnStates[index].Selected = SelectionState;
}
OnChanged();
}
/// <summary>
/// This uses extent checking (rather than full polygon intersection checking). It will add
/// any members that are either contained by or intersect with the specified region
/// depending on the SelectionMode property. The order of operation is the region
/// acting on the feature, so Contains, for instance, would work with points.
/// </summary>
/// <param name="region">The region that contains the features that get added.</param>
/// <param name="affectedArea">The affected area of this addition</param>
/// <returns>True if any item was actually added to the collection</returns>
public bool AddRegion(Envelope region, out Envelope affectedArea)
{
Action<FastDrawnState> addToSelection = state => state.Selected = SelectionState;
return DoAction(addToSelection, region, out affectedArea);
}
/// <inheritdoc />
public void AddRow(Dictionary<string, object> values)
{
// Don't worry about the index in this case.
_layer.DataSet.AddRow(values);
}
/// <inheritdoc />
public void AddRow(IDataRow values)
{
// Don't worry about the index in this case.
_layer.DataSet.AddRow(values);
}
/// <inheritdoc />
public void Clear()
{
foreach (FastDrawnState state in _layer.DrawnStates)
{
state.Selected = !SelectionState;
}
OnChanged();
}
/// <inheritdoc />
public bool Contains(int index)
{
return _layer.DrawnStates[index].Selected == SelectionState;
}
/// <inheritdoc />
public void CopyTo(int[] array, int arrayIndex)
{
int index = arrayIndex;
foreach (int i in this)
{
array[index] = i;
index++;
}
}
/// <inheritdoc />
public void Edit(int index, Dictionary<string, object> values)
{
int sourceIndex = GetSourceIndex(index);
_layer.DataSet.Edit(sourceIndex, values);
}
/// <inheritdoc />
public void Edit(int index, IDataRow values)
{
int sourceIndex = GetSourceIndex(index);
_layer.DataSet.Edit(sourceIndex, values);
}
/// <inheritdoc />
public IDataTable GetAttributes(int startIndex, int numRows)
{
return GetAttributes(startIndex, numRows, _layer.DataSet.GetColumns().Select(d => d.ColumnName));
}
/// <inheritdoc />
public IDataTable GetAttributes(int startIndex, int numRows, IEnumerable<string> fieldNames)
{
var c = new AttributeCache(_layer.DataSet, numRows);
var fn = new HashSet<string>(fieldNames);
var result = new DS_DataTable();
foreach (DataColumn col in _layer.DataSet.GetColumns())
{
if (fn.Contains(col.ColumnName))
{
result.Columns.Add(col);
}
}
int i = 0;
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int fid = 0; fid < drawnStates.Length; fid++)
{
if (drawnStates[fid].Selected)
{
i++;
if (i < startIndex) continue;
IDataRow dr = result.NewRow();
Dictionary<string, object> vals = c.RetrieveElement(fid);
foreach (KeyValuePair<string, object> pair in vals)
{
if (fn.Contains(pair.Key)) dr[pair.Key] = pair.Value;
}
result.Rows.Add(dr);
if (i > startIndex + numRows) break;
}
}
return result;
}
/// <inheritdoc />
public DataColumn GetColumn(string name)
{
return _layer.DataSet.GetColumn(name);
}
/// <inheritdoc />
public DataColumn[] GetColumns()
{
{
return _layer.DataSet.GetColumns();
}
}
/// <inheritdoc />
public int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize)
{
int numSelected = Count;
int[] counts = new int[expressions.Length];
bool requiresRun = false;
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie]))
{
counts[ie] = numSelected;
}
else
{
requiresRun = true;
}
}
if (!requiresRun) return counts;
AttributePager ap = new AttributePager(_layer.DataSet, 100000);
int numinTable = 0;
DataTable result = new DataTable();
result.Columns.AddRange(_layer.DataSet.GetColumns());
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected)
{
result.Rows.Add(ap.Row(shp).ItemArray);
numinTable++;
if (numinTable > 100000)
{
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie])) continue;
counts[ie] += result.Select(expressions[ie]).Length;
}
result.Clear();
}
}
}
for (int ie = 0; ie < expressions.Length; ie++)
{
if (string.IsNullOrEmpty(expressions[ie])) continue;
counts[ie] += result.Select(expressions[ie]).Length;
}
result.Clear();
return counts;
}
/// <inheritdoc />
public IEnumerator<int> GetEnumerator()
{
return new IndexSelectionEnumerator(_layer.DrawnStates, SelectionState);
}
/// <summary>
/// Inverts the selection based on the current SelectionMode
/// </summary>
/// <param name="region">The geographic region to reverse the selected state</param>
/// <param name="affectedArea">The affected area to invert</param>
/// <returns>True, if the selection was changed.</returns>
public bool InvertSelection(Envelope region, out Envelope affectedArea)
{
Action<FastDrawnState> invertSelection = state => state.Selected = !state.Selected;
return DoAction(invertSelection, region, out affectedArea);
}
/// <inheritdoc />
public int NumRows()
{
return Count;
}
/// <inheritdoc />
public bool Remove(int index)
{
if (index < 0 || index >= _layer.DrawnStates.Length) return false;
if (_layer.DrawnStates[index].Selected != SelectionState) return false;
_layer.DrawnStates[index].Selected = !SelectionState;
OnChanged();
return true;
}
/// <summary>
/// Attempts to remove all the members from the collection. If
/// one of the specified indices is outside the range of possible
/// values, this returns false, even if others were successfully removed.
/// This will also return false if none of the states were changed.
/// </summary>
/// <param name="indices">The indices to remove</param>
/// <returns>True if the selection was changed.</returns>
public bool RemoveRange(IEnumerable<int> indices)
{
bool problem = false;
bool changed = false;
FastDrawnState[] drawnStates = _layer.DrawnStates;
foreach (int index in indices)
{
if (index < 0 || index > drawnStates.Length)
{
problem = true;
}
else
{
if (drawnStates[index].Selected != !SelectionState) changed = true;
drawnStates[index].Selected = !SelectionState;
}
}
return !problem && changed;
}
/// <summary>
/// Tests each member currently in the selected features based on
/// the SelectionMode. If it passes, it will remove the feature from
/// the selection.
/// </summary>
/// <param name="region">The geographic region to remove</param>
/// <param name="affectedArea">A geographic area that was affected by this change.</param>
/// <returns>Boolean, true if the collection was changed</returns>
public bool RemoveRegion(Envelope region, out Envelope affectedArea)
{
Action<FastDrawnState> removeFromSelection = state => state.Selected = !SelectionState;
return DoAction(removeFromSelection, region, out affectedArea);
}
/// <inheritdoc />
public void SetAttributes(int startIndex, IDataTable values)
{
FastDrawnState[] drawnStates = _layer.DrawnStates;
int sind = -1;
for (int fid = 0; fid < drawnStates.Length; fid++)
{
if (drawnStates[fid].Selected)
{
sind++;
if (sind > startIndex + values.Rows.Count)
{
break;
}
if (sind >= startIndex)
{
_layer.DataSet.Edit(fid, values.Rows[sind]);
}
}
}
}
/// <summary>
/// Exports the members of this collection as a list of IFeature.
/// </summary>
/// <returns>A List of IFeature</returns>
public List<IFeature> ToFeatureList()
{
List<IFeature> result = new List<IFeature>();
FastDrawnState[] drawnStates = _layer.DrawnStates;
for (int shp = 0; shp < drawnStates.Length; shp++)
{
if (drawnStates[shp].Selected == SelectionState)
{
result.Add(_layer.DataSet.GetFeature(shp));
}
}
return result;
}
/// <summary>
/// Returns a new featureset based on the features in this collection.
/// </summary>
/// <returns>An in memory featureset that has not yet been saved to a file in any way.</returns>
public FeatureSet ToFeatureSet()
{
return new FeatureSet(ToFeatureList())
{
Projection = _layer.DataSet.Projection
};
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Runs the given action for all the shapes that are affected by the current SelectionMode and the given region.
/// </summary>
/// <param name="action">Action that is run on the affected shapes.</param>
/// <param name="region">Region that is used to determine the affected shapes.</param>
/// <param name="affectedArea">Area that results from the affected shapes.</param>
/// <returns>True, if at least one shape was affected.</returns>
private bool DoAction(Action<FastDrawnState> action, Envelope region, out Envelope affectedArea)
{
bool somethingChanged = false;
SuspendChanges();
Extent affected = new Extent();
IPolygon reg = region.ToPolygon();
ShapeRange env = new ShapeRange(region);
for (int shp = 0; shp < _layer.DrawnStates.Length; shp++)
{
// CGX
if (!_layer.DrawnStates[shp].Visible) continue;
if (RegionCategory != null && _layer.DrawnStates[shp].Category != RegionCategory) continue;
bool doAction = false;
ShapeRange shape = _shapes[shp];
switch (SelectionMode)
{
case SelectionMode.Intersects:
// Prevent geometry creation (which is slow) and use ShapeRange instead
doAction = env.Intersects(shape);
break;
case SelectionMode.IntersectsExtent:
doAction = shape.Extent.Intersects(region);
break;
case SelectionMode.ContainsExtent:
doAction = shape.Extent.Within(region);
break;
case SelectionMode.Disjoint:
if (!shape.Extent.Intersects(region))
{
doAction = true;
}
else
{
IGeometry g = _layer.DataSet.GetFeature(shp).Geometry;
doAction = reg.Disjoint(g);
}
break;
}
if (shape.Extent.Intersects(region))
{
IGeometry geom = _layer.DataSet.GetFeature(shp).Geometry;
switch (SelectionMode)
{
case SelectionMode.Contains:
doAction = shape.Extent.Within(region) || reg.Contains(geom);
break;
case SelectionMode.CoveredBy:
doAction = reg.CoveredBy(geom);
break;
case SelectionMode.Covers:
doAction = reg.Covers(geom);
break;
case SelectionMode.Overlaps:
doAction = reg.Overlaps(geom);
break;
case SelectionMode.Touches:
doAction = reg.Touches(geom);
break;
case SelectionMode.Within:
doAction = reg.Within(geom);
break;
}
}
if (doAction)
{
action(_layer.DrawnStates[shp]);
affected.ExpandToInclude(shape.Extent);
somethingChanged = true;
OnChanged();
}
}
ResumeChanges();
affectedArea = affected.ToEnvelope();
return somethingChanged;
}
private int GetSourceIndex(int selectedIndex)
{
// For instance, the 0 index member of the selection might in fact
// be the 10th member of the featureset. But we want to edit the 10th member
// and not the 0 member.
int count = 0;
foreach (int i in this)
{
if (count == selectedIndex) return i;
count++;
}
throw new IndexOutOfRangeException("Index requested was: " + selectedIndex + " but the selection only has " + count + " members");
}
#endregion
#region Classes
/// <summary>
/// This class cycles through the members
/// </summary>
private class IndexSelectionEnumerator : IEnumerator<int>
{
#region Fields
private readonly bool _selectionState;
private readonly FastDrawnState[] _states;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="IndexSelectionEnumerator"/> class.
/// </summary>
/// <param name="states">The states.</param>
/// <param name="selectionState">The selection state.</param>
public IndexSelectionEnumerator(FastDrawnState[] states, bool selectionState)
{
_states = states;
_selectionState = selectionState;
Current = -1;
}
#endregion
#region Properties
/// <inheritdoc />
public int Current { get; private set; }
object IEnumerator.Current => Current;
#endregion
#region Methods
/// <inheritdoc />
public void Dispose()
{
}
/// <inheritdoc />
public bool MoveNext()
{
do
{
Current++;
}
while (Current < _states.Length && _states[Current].Selected != _selectionState);
return Current != _states.Length;
}
/// <inheritdoc />
public void Reset()
{
Current = -1;
}
#endregion
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.Modularity;
namespace Prism.Wpf.Tests.Modularity
{
[TestClass]
public class ModuleCatalogFixture
{
[TestMethod]
public void CanCreateCatalogFromList()
{
var moduleInfo = new ModuleInfo("MockModule", "type");
List<ModuleInfo> moduleInfos = new List<ModuleInfo> { moduleInfo };
var moduleCatalog = new ModuleCatalog(moduleInfos);
Assert.AreEqual(1, moduleCatalog.Modules.Count());
Assert.AreEqual(moduleInfo, moduleCatalog.Modules.ElementAt(0));
}
[TestMethod]
public void CanGetDependenciesForModule()
{
// A <- B
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependentModules = moduleCatalog.GetDependentModules(moduleInfoB);
Assert.AreEqual(1, dependentModules.Count());
Assert.AreEqual(moduleInfoA, dependentModules.ElementAt(0));
}
[TestMethod]
public void CanCompleteListWithTheirDependencies()
{
// A <- B <- C
var moduleInfoA = CreateModuleInfo("A");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
var moduleInfoOrphan = CreateModuleInfo("X", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
, moduleInfoOrphan
};
var moduleCatalog = new ModuleCatalog(moduleInfos);
IEnumerable<ModuleInfo> dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleInfoC });
Assert.AreEqual(3, dependantModules.Count());
Assert.IsTrue(dependantModules.Contains(moduleInfoA));
Assert.IsTrue(dependantModules.Contains(moduleInfoB));
Assert.IsTrue(dependantModules.Contains(moduleInfoC));
}
[TestMethod]
[ExpectedException(typeof(CyclicDependencyFoundException))]
public void ShouldThrowOnCyclicDependency()
{
// A <- B <- C <- A
var moduleInfoA = CreateModuleInfo("A", "C");
var moduleInfoB = CreateModuleInfo("B", "A");
var moduleInfoC = CreateModuleInfo("C", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
, moduleInfoB
, moduleInfoC
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(DuplicateModuleException))]
public void ShouldThrowOnDuplicateModule()
{
var moduleInfoA1 = CreateModuleInfo("A");
var moduleInfoA2 = CreateModuleInfo("A");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA1
, moduleInfoA2
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
[ExpectedException(typeof(ModularityException))]
public void ShouldThrowOnMissingDependency()
{
var moduleInfoA = CreateModuleInfo("A", "B");
List<ModuleInfo> moduleInfos = new List<ModuleInfo>
{
moduleInfoA
};
new ModuleCatalog(moduleInfos).Validate();
}
[TestMethod]
public void CanAddModules()
{
var catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule));
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
}
[TestMethod]
public void CanAddGroups()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo = new ModuleInfo();
ModuleInfoGroup group = new ModuleInfoGroup { moduleInfo };
catalog.Items.Add(group);
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreSame(moduleInfo, catalog.Modules.ElementAt(0));
}
[TestMethod]
public void ShouldAggregateGroupsAndLooseModuleInfos()
{
var catalog = new ModuleCatalog();
ModuleInfo moduleInfo1 = new ModuleInfo();
ModuleInfo moduleInfo2 = new ModuleInfo();
ModuleInfo moduleInfo3 = new ModuleInfo();
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo1 });
catalog.Items.Add(new ModuleInfoGroup() { moduleInfo2 });
catalog.AddModule(moduleInfo3);
Assert.AreEqual(3, catalog.Modules.Count());
Assert.IsTrue(catalog.Modules.Contains(moduleInfo1));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo2));
Assert.IsTrue(catalog.Modules.Contains(moduleInfo3));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CompleteListWithDependenciesThrowsWithNull()
{
var catalog = new ModuleCatalog();
catalog.CompleteListWithDependencies(null);
}
[TestMethod]
public void LooseModuleIfDependentOnModuleInGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ModuleInGroupDependsOnModuleInOtherGroupThrows()
{
var catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
catalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB", "ModuleA") });
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldRevalidateWhenAddingNewModuleIfValidated()
{
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleA") });
testableCatalog.Validate();
testableCatalog.Items.Add(new ModuleInfoGroup() { CreateModuleInfo("ModuleB") });
Assert.IsTrue(testableCatalog.ValidateCalled);
}
[TestMethod]
public void ModuleInGroupCanDependOnModuleInSameGroup()
{
var catalog = new ModuleCatalog();
var moduleA = CreateModuleInfo("ModuleA");
var moduleB = CreateModuleInfo("ModuleB", "ModuleA");
catalog.Items.Add(new ModuleInfoGroup()
{
moduleA,
moduleB
});
var moduleBDependencies = catalog.GetDependentModules(moduleB);
Assert.AreEqual(1, moduleBDependencies.Count());
Assert.AreEqual(moduleA, moduleBDependencies.First());
}
[TestMethod]
public void StartupModuleDependentOnAnOnDemandModuleThrows()
{
var catalog = new ModuleCatalog();
var moduleOnDemand = CreateModuleInfo("ModuleA");
moduleOnDemand.InitializationMode = InitializationMode.OnDemand;
catalog.AddModule(moduleOnDemand);
catalog.AddModule(CreateModuleInfo("ModuleB", "ModuleA"));
try
{
catalog.Validate();
}
catch (Exception ex)
{
Assert.IsInstanceOfType(ex, typeof(ModularityException));
Assert.AreEqual("ModuleB", ((ModularityException)ex).ModuleName);
return;
}
Assert.Fail("Exception not thrown.");
}
[TestMethod]
public void ShouldReturnInCorrectRetrieveOrderWhenCompletingListWithDependencies()
{
// A <- B <- C <- D, C <- X
var moduleA = CreateModuleInfo("A");
var moduleB = CreateModuleInfo("B", "A");
var moduleC = CreateModuleInfo("C", "B");
var moduleD = CreateModuleInfo("D", "C");
var moduleX = CreateModuleInfo("X", "C");
var moduleCatalog = new ModuleCatalog();
// Add the modules in random order
moduleCatalog.AddModule(moduleB);
moduleCatalog.AddModule(moduleA);
moduleCatalog.AddModule(moduleD);
moduleCatalog.AddModule(moduleX);
moduleCatalog.AddModule(moduleC);
var dependantModules = moduleCatalog.CompleteListWithDependencies(new[] { moduleD, moduleX }).ToList();
Assert.AreEqual(5, dependantModules.Count);
Assert.IsTrue(dependantModules.IndexOf(moduleA) < dependantModules.IndexOf(moduleB));
Assert.IsTrue(dependantModules.IndexOf(moduleB) < dependantModules.IndexOf(moduleC));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleD));
Assert.IsTrue(dependantModules.IndexOf(moduleC) < dependantModules.IndexOf(moduleX));
}
[TestMethod]
public void CanLoadCatalogFromXaml()
{
Stream stream =
Assembly.GetExecutingAssembly().GetManifestResourceStream(
"Prism.Wpf.Tests.Modularity.ModuleCatalogXaml.SimpleModuleCatalog.xaml");
var catalog = ModuleCatalog.CreateFromXaml(stream);
Assert.IsNotNull(catalog);
Assert.AreEqual(4, catalog.Modules.Count());
}
[TestMethod]
public void ShouldLoadAndValidateOnInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.IsTrue(testableCatalog.LoadCalled);
Assert.IsTrue(testableCatalog.ValidateCalled);
Assert.IsTrue(testableCatalog.LoadCalledFirst);
}
[TestMethod]
public void ShouldNotLoadAgainIfInitializedCalledMoreThanOnce()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldNotLoadAgainDuringInitialize()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
Assert.IsFalse(testableCatalog.LoadCalled);
Assert.IsFalse(testableCatalog.ValidateCalled);
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Initialize();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void ShouldAllowLoadToBeInvokedTwice()
{
var catalog = new TestableModuleCatalog();
var testableCatalog = new TestableModuleCatalog();
testableCatalog.Load();
Assert.AreEqual<int>(1, testableCatalog.LoadCalledCount);
testableCatalog.Load();
Assert.AreEqual<int>(2, testableCatalog.LoadCalledCount);
}
[TestMethod]
public void CanAddModule1()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule2()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule("Module", "ModuleType", "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("Module", catalog.Modules.First().ModuleName);
Assert.AreEqual("ModuleType", catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule3()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), InitializationMode.OnDemand, "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.OnDemand, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddModule4()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(MockModule), "DependsOn1", "DependsOn2");
Assert.AreEqual(1, catalog.Modules.Count());
Assert.AreEqual("MockModule", catalog.Modules.First().ModuleName);
Assert.AreEqual(typeof(MockModule).AssemblyQualifiedName, catalog.Modules.First().ModuleType);
Assert.AreEqual(InitializationMode.WhenAvailable, catalog.Modules.First().InitializationMode);
Assert.AreEqual(2, catalog.Modules.First().DependsOn.Count);
Assert.AreEqual("DependsOn1", catalog.Modules.First().DependsOn[0]);
Assert.AreEqual("DependsOn2", catalog.Modules.First().DependsOn[1]);
}
[TestMethod]
public void CanAddGroup()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.Items.Add(new ModuleInfoGroup());
catalog.AddGroup(InitializationMode.OnDemand, "Ref1",
new ModuleInfo("M1", "T1"),
new ModuleInfo("M2", "T2", "M1"));
Assert.AreEqual(2, catalog.Modules.Count());
var module1 = catalog.Modules.First();
var module2 = catalog.Modules.Skip(1).First();
Assert.AreEqual("M1", module1.ModuleName);
Assert.AreEqual("T1", module1.ModuleType);
Assert.AreEqual("Ref1", module1.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module1.InitializationMode);
Assert.AreEqual("M2", module2.ModuleName);
Assert.AreEqual("T2", module2.ModuleType);
Assert.AreEqual("Ref1", module2.Ref);
Assert.AreEqual(InitializationMode.OnDemand, module2.InitializationMode);
}
private class TestableModuleCatalog : ModuleCatalog
{
public bool ValidateCalled { get; set; }
public bool LoadCalledFirst { get; set; }
public bool LoadCalled
{
get { return LoadCalledCount > 0; }
}
public int LoadCalledCount { get; set; }
public override void Validate()
{
ValidateCalled = true;
Validated = true;
}
protected override void InnerLoad()
{
if (ValidateCalled == false && !LoadCalled)
LoadCalledFirst = true;
LoadCalledCount++;
}
}
private static ModuleInfo CreateModuleInfo(string name, params string[] dependsOn)
{
ModuleInfo moduleInfo = new ModuleInfo(name, name);
moduleInfo.DependsOn.AddRange(dependsOn);
return moduleInfo;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OmniSharp.Eventing;
using OmniSharp.Http.Middleware;
using OmniSharp.Mef;
using OmniSharp.Models;
using OmniSharp.Models.FindSymbols;
using OmniSharp.Models.GotoDefinition;
using OmniSharp.Models.UpdateBuffer;
using OmniSharp.Models.WorkspaceInformation;
using OmniSharp.Services;
using OmniSharp.Utilities;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Http.Tests
{
public class EndpointMiddlewareFacts : AbstractTestFixture
{
public EndpointMiddlewareFacts(ITestOutputHelper output)
: base(output)
{
}
[OmniSharpHandler(OmniSharpEndpoints.GotoDefinition, LanguageNames.CSharp)]
public class GotoDefinitionService : IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<GotoDefinitionResponse> Handle(GotoDefinitionRequest request)
{
return Task.FromResult<GotoDefinitionResponse>(null);
}
}
[OmniSharpHandler(OmniSharpEndpoints.FindSymbols, LanguageNames.CSharp)]
public class FindSymbolsService : IRequestHandler<FindSymbolsRequest, QuickFixResponse>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<QuickFixResponse> Handle(FindSymbolsRequest request)
{
return Task.FromResult<QuickFixResponse>(null);
}
}
[OmniSharpHandler(OmniSharpEndpoints.UpdateBuffer, LanguageNames.CSharp)]
public class UpdateBufferService : IRequestHandler<UpdateBufferRequest, object>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<object> Handle(UpdateBufferRequest request)
{
return Task.FromResult<object>(null);
}
}
class Response { }
[Export(typeof(IProjectSystem))]
class FakeProjectSystem : IProjectSystem
{
public string Key { get; } = "Fake";
public string Language { get; } = LanguageNames.CSharp;
public IEnumerable<string> Extensions { get; } = new[] { ".cs" };
public bool EnabledByDefault { get; } = true;
public bool Initialized { get; } = true;
public Task WaitForIdleAsync() => throw new NotImplementedException();
public Task<object> GetWorkspaceModelAsync(WorkspaceInformationRequest request)
{
throw new NotImplementedException();
}
public Task<object> GetProjectModelAsync(string path)
{
throw new NotImplementedException();
}
public void Initalize(IConfiguration configuration) { }
}
private class PlugInHost : DisposableObject
{
private readonly IServiceProvider _serviceProvider;
public CompositionHost CompositionHost { get; }
public PlugInHost(IServiceProvider serviceProvider, CompositionHost compositionHost)
{
this._serviceProvider = serviceProvider;
this.CompositionHost = compositionHost;
}
protected override void DisposeCore(bool disposing)
{
(this._serviceProvider as IDisposable)?.Dispose();
this.CompositionHost.Dispose();
}
}
protected Assembly GetAssembly<T>()
{
return typeof(T).GetTypeInfo().Assembly;
}
private PlugInHost CreatePlugInHost(params Assembly[] assemblies)
{
var serviceProvider = TestServiceProvider.Create(this.TestOutput, new OmniSharpEnvironment());
var compositionHost = new CompositionHostBuilder(serviceProvider)
.WithAssemblies(assemblies)
.Build(workingDirectory: null);
return new PlugInHost(serviceProvider, compositionHost);
}
[Fact]
public async Task Passes_through_for_invalid_path()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(GetAssembly<EndpointMiddlewareFacts>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/notvalid");
await Assert.ThrowsAsync<NotImplementedException>(() => middleware.Invoke(context));
}
}
[Fact]
public async Task Does_not_throw_for_valid_path()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/gotodefinition");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new GotoDefinitionRequest
{
FileName = "bar.cs",
Line = 2,
Column = 14,
Timeout = 60000
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_services()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/gotodefinition");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new GotoDefinitionRequest
{
FileName = "bar.cs",
Line = 2,
Column = 14,
Timeout = 60000
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_all_services_with_delegate()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/findsymbols");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new FindSymbolsRequest
{
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_specific_service_with_delegate()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly,
typeof(OmniSharpEndpointMetadata).GetTypeInfo().Assembly))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/findsymbols");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new FindSymbolsRequest
{
Language = LanguageNames.CSharp
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
public Func<ThrowRequest, Task<ThrowResponse>> ThrowDelegate = (request) =>
{
return Task.FromResult<ThrowResponse>(null);
};
[OmniSharpEndpoint("/throw", typeof(ThrowRequest), typeof(ThrowResponse))]
public class ThrowRequest : IRequest { }
public class ThrowResponse { }
[Fact]
public async Task Should_throw_if_type_is_not_mergeable()
{
RequestDelegate _next = async (ctx) => await Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(GetAssembly<EndpointMiddlewareFacts>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/throw");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new ThrowRequest())
)
);
await Assert.ThrowsAsync<NotSupportedException>(async () => await middleware.Invoke(context));
}
}
}
}
| |
// 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: This is the value class representing a Unicode character
** Char methods until we create this functionality.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible
, IComparable<Char>, IEquatable<Char>
{
//
// Member Variables
//
internal char m_value;
//
// Public Constants
//
// The maximum character value.
public const char MaxValue = (char) 0xFFFF;
// The minimum character value.
public const char MinValue = (char) 0x00;
// Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space.
private readonly static byte[] categoryForLatin1 = {
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027
(byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F
(byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
(byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
};
// Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
private static bool IsLatin1(char ch) {
return (ch <= '\x00ff');
}
// Return true for all characters below or equal U+007f, which is ASCII.
private static bool IsAscii(char ch) {
return (ch <= '\x007f');
}
// Return the Unicode category for Unicode character <= 0x00ff.
private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
return (UnicodeCategory)(categoryForLatin1[(int)ch]);
}
//
// Private Constants
//
//
// Overriden Instance Methods
//
// Calculate a hashcode for a 2 byte Unicode character.
public override int GetHashCode() {
return (int)m_value | ((int)m_value << 16);
}
// Used for comparing two boxed Char objects.
//
public override bool Equals(Object obj) {
if (!(obj is Char)) {
return false;
}
return (m_value==((Char)obj).m_value);
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Char obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Char, this method throws an ArgumentException.
//
[Pure]
public int CompareTo(Object value) {
if (value==null) {
return 1;
}
if (!(value is Char)) {
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeChar"));
}
return (m_value-((Char)value).m_value);
}
[Pure]
public int CompareTo(Char value) {
return (m_value-value);
}
// Overrides System.Object.ToString.
[Pure]
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
[Pure]
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
//
// Formatting Methods
//
/*===================================ToString===================================
**This static methods takes a character and returns the String representation of it.
==============================================================================*/
// Provides a string representation of a character.
[Pure]
public static String ToString(char c) {
Contract.Ensures(Contract.Result<String>() != null);
return new String(c, 1);
}
public static char Parse(String s) {
if (s==null) {
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
if (s.Length!=1) {
throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar"));
}
return s[0];
}
public static bool TryParse(String s, out Char result) {
result = '\0';
if (s == null) {
return false;
}
if (s.Length != 1) {
return false;
}
result = s[0];
return true;
}
//
// Static Methods
//
/*=================================ISDIGIT======================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a digit. **
==============================================================================*/
// Determines whether a character is a digit.
[Pure]
public static bool IsDigit(char c) {
if (IsLatin1(c)) {
return (c >= '0' && c <= '9');
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber);
}
/*=================================CheckLetter=====================================
** Check if the specified UnicodeCategory belongs to the letter categories.
==============================================================================*/
internal static bool CheckLetter(UnicodeCategory uc) {
switch(uc) {
case (UnicodeCategory.UppercaseLetter):
case (UnicodeCategory.LowercaseLetter):
case (UnicodeCategory.TitlecaseLetter):
case (UnicodeCategory.ModifierLetter):
case (UnicodeCategory.OtherLetter):
return (true);
}
return (false);
}
/*=================================ISLETTER=====================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a letter. **
==============================================================================*/
// Determines whether a character is a letter.
[Pure]
public static bool IsLetter(char c) {
if (IsLatin1(c)) {
if (IsAscii(c)) {
c |=(char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c)));
}
private static bool IsWhiteSpaceLatin1(char c) {
// There are characters which belong to UnicodeCategory.Control but are considered as white spaces.
// We use code point comparisons for these characters here as a temporary fix.
// U+0009 = <control> HORIZONTAL TAB
// U+000a = <control> LINE FEED
// U+000b = <control> VERTICAL TAB
// U+000c = <contorl> FORM FEED
// U+000d = <control> CARRIAGE RETURN
// U+0085 = <control> NEXT LINE
// U+00a0 = NO-BREAK SPACE
if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') {
return (true);
}
return (false);
}
/*===============================ISWHITESPACE===================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a whitespace character. **
==============================================================================*/
// Determines whether a character is whitespace.
[Pure]
public static bool IsWhiteSpace(char c) {
if (IsLatin1(c)) {
return (IsWhiteSpaceLatin1(c));
}
return CharUnicodeInfo.IsWhiteSpace(c);
}
/*===================================IsUpper====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an uppercase character.
==============================================================================*/
// Determines whether a character is upper-case.
[Pure]
public static bool IsUpper(char c) {
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
/*===================================IsLower====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an lowercase character.
==============================================================================*/
// Determines whether a character is lower-case.
[Pure]
public static bool IsLower(char c) {
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
internal static bool CheckPunctuation(UnicodeCategory uc)
{
switch (uc) {
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
return (true);
}
return (false);
}
/*================================IsPunctuation=================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an punctuation mark
==============================================================================*/
// Determines whether a character is a punctuation mark.
[Pure]
public static bool IsPunctuation(char c){
if (IsLatin1(c)) {
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c)));
}
/*=================================CheckLetterOrDigit=====================================
** Check if the specified UnicodeCategory belongs to the letter or digit categories.
==============================================================================*/
internal static bool CheckLetterOrDigit(UnicodeCategory uc) {
switch (uc) {
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.DecimalDigitNumber:
return (true);
}
return (false);
}
// Determines whether a character is a letter or a digit.
[Pure]
public static bool IsLetterOrDigit(char c) {
if (IsLatin1(c)) {
return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c)));
}
return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c)));
}
/*===================================ToUpper====================================
**
==============================================================================*/
// Converts a character to upper-case for the specified culture.
// <;<;Not fully implemented>;>;
public static char ToUpper(char c, CultureInfo culture) {
if (culture==null)
throw new ArgumentNullException("culture");
Contract.EndContractBlock();
return culture.TextInfo.ToUpper(c);
}
/*=================================TOUPPER======================================
**A wrapper for Char.toUpperCase. Converts character c to its **
**uppercase equivalent. If c is already an uppercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to upper-case for the default culture.
//
public static char ToUpper(char c) {
return ToUpper(c, CultureInfo.CurrentCulture);
}
// Converts a character to upper-case for invariant culture.
public static char ToUpperInvariant(char c) {
return ToUpper(c, CultureInfo.InvariantCulture);
}
/*===================================ToLower====================================
**
==============================================================================*/
// Converts a character to lower-case for the specified culture.
// <;<;Not fully implemented>;>;
public static char ToLower(char c, CultureInfo culture) {
if (culture==null)
throw new ArgumentNullException("culture");
Contract.EndContractBlock();
return culture.TextInfo.ToLower(c);
}
/*=================================TOLOWER======================================
**A wrapper for Char.toLowerCase. Converts character c to its **
**lowercase equivalent. If c is already a lowercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to lower-case for the default culture.
public static char ToLower(char c) {
return ToLower(c, CultureInfo.CurrentCulture);
}
// Converts a character to lower-case for invariant culture.
public static char ToLowerInvariant(char c) {
return ToLower(c, CultureInfo.InvariantCulture);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode() {
return TypeCode.Char;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Boolean"));
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Single"));
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double"));
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Decimal"));
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
public static bool IsControl(char c)
{
if (IsLatin1(c)) {
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control);
}
public static bool IsControl(String s, int index) {
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
}
public static bool IsDigit(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
return (c >= '0' && c <= '9');
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
}
public static bool IsLetter(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
if (IsAscii(c)) {
c |=(char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
public static bool IsLetterOrDigit(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
}
return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index));
}
public static bool IsLower(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
}
/*=================================CheckNumber=====================================
** Check if the specified UnicodeCategory belongs to the number categories.
==============================================================================*/
internal static bool CheckNumber(UnicodeCategory uc) {
switch (uc) {
case (UnicodeCategory.DecimalDigitNumber):
case (UnicodeCategory.LetterNumber):
case (UnicodeCategory.OtherNumber):
return (true);
}
return (false);
}
public static bool IsNumber(char c)
{
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsNumber(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
////////////////////////////////////////////////////////////////////////
//
// IsPunctuation
//
// Determines if the given character is a punctuation character.
//
////////////////////////////////////////////////////////////////////////
public static bool IsPunctuation (String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
/*================================= CheckSeparator ============================
** Check if the specified UnicodeCategory belongs to the seprator categories.
==============================================================================*/
internal static bool CheckSeparator(UnicodeCategory uc)
{
switch (uc) {
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
return (true);
}
return (false);
}
private static bool IsSeparatorLatin1(char c) {
// U+00a0 = NO-BREAK SPACE
// There is no LineSeparator or ParagraphSeparator in Latin 1 range.
return (c == '\x0020' || c == '\x00a0');
}
public static bool IsSeparator(char c)
{
if (IsLatin1(c)) {
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsSeparator(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
[Pure]
public static bool IsSurrogate(char c)
{
return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END);
}
[Pure]
public static bool IsSurrogate(String s, int index)
{
if (s==null) {
throw new ArgumentNullException("s");
}
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsSurrogate(s[index]));
}
/*================================= CheckSymbol ============================
** Check if the specified UnicodeCategory belongs to the symbol categories.
==============================================================================*/
internal static bool CheckSymbol(UnicodeCategory uc) {
switch (uc) {
case (UnicodeCategory.MathSymbol):
case (UnicodeCategory.CurrencySymbol):
case (UnicodeCategory.ModifierSymbol):
case (UnicodeCategory.OtherSymbol):
return (true);
}
return (false);
}
public static bool IsSymbol(char c)
{
if (IsLatin1(c)) {
return (CheckSymbol(GetLatin1UnicodeCategory(c)));
}
return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c)));
}
public static bool IsSymbol(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (IsLatin1(s[index])) {
return (CheckSymbol(GetLatin1UnicodeCategory(s[index])));
}
return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
public static bool IsUpper(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c)) {
if (IsAscii(c)) {
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
}
public static bool IsWhiteSpace(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (IsLatin1(s[index])) {
return IsWhiteSpaceLatin1(s[index]);
}
return CharUnicodeInfo.IsWhiteSpace(s, index);
}
public static UnicodeCategory GetUnicodeCategory(char c)
{
if (IsLatin1(c)) {
return (GetLatin1UnicodeCategory(c));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(c);
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (IsLatin1(s[index])) {
return (GetLatin1UnicodeCategory(s[index]));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(s, index);
}
public static double GetNumericValue(char c)
{
return CharUnicodeInfo.GetNumericValue(c);
}
public static double GetNumericValue(String s, int index)
{
if (s==null)
throw new ArgumentNullException("s");
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return CharUnicodeInfo.GetNumericValue(s, index);
}
/*================================= IsHighSurrogate ============================
** Check if a char is a high surrogate.
==============================================================================*/
[Pure]
public static bool IsHighSurrogate(char c) {
return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END));
}
[Pure]
public static bool IsHighSurrogate(String s, int index) {
if (s == null) {
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsHighSurrogate(s[index]));
}
/*================================= IsLowSurrogate ============================
** Check if a char is a low surrogate.
==============================================================================*/
[Pure]
public static bool IsLowSurrogate(char c) {
return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END));
}
[Pure]
public static bool IsLowSurrogate(String s, int index) {
if (s == null) {
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsLowSurrogate(s[index]));
}
/*================================= IsSurrogatePair ============================
** Check if the string specified by the index starts with a surrogate pair.
==============================================================================*/
[Pure]
public static bool IsSurrogatePair(String s, int index) {
if (s == null) {
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (index + 1 < s.Length) {
return (IsSurrogatePair(s[index], s[index+1]));
}
return (false);
}
[Pure]
public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) {
return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) &&
(lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END));
}
internal const int UNICODE_PLANE00_END = 0x00ffff;
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
// The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode.
// Plane 16 contains 0x100000 ~ 0x10ffff.
internal const int UNICODE_PLANE16_END = 0x10ffff;
internal const int HIGH_SURROGATE_START = 0x00d800;
internal const int LOW_SURROGATE_END = 0x00dfff;
/*================================= ConvertFromUtf32 ============================
** Convert an UTF32 value into a surrogate pair.
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String ConvertFromUtf32(int utf32)
{
// For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
// are considered as irregular code unit sequence, but they are not illegal.
if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) {
throw new ArgumentOutOfRangeException("utf32", Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32"));
}
Contract.EndContractBlock();
if (utf32 < UNICODE_PLANE01_START) {
// This is a BMP character.
return (Char.ToString((char)utf32));
}
unsafe
{
// This is a supplementary character. Convert it to a surrogate pair in UTF-16.
utf32 -= UNICODE_PLANE01_START;
uint surrogate = 0; // allocate 2 chars worth of stack space
char* address = (char*)&surrogate;
address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START);
address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START);
return new string(address, 0, 2);
}
}
/*=============================ConvertToUtf32===================================
** Convert a surrogate pair to UTF32 value
==============================================================================*/
public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) {
if (!IsHighSurrogate(highSurrogate)) {
throw new ArgumentOutOfRangeException("highSurrogate", Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
}
if (!IsLowSurrogate(lowSurrogate)) {
throw new ArgumentOutOfRangeException("lowSurrogate", Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
}
Contract.EndContractBlock();
return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START);
}
/*=============================ConvertToUtf32===================================
** Convert a character or a surrogate pair starting at index of the specified string
** to UTF32 value.
** The char pointed by index should be a surrogate pair or a BMP character.
** This method throws if a high-surrogate is not followed by a low surrogate.
** This method throws if a low surrogate is seen without preceding a high-surrogate.
==============================================================================*/
public static int ConvertToUtf32(String s, int index) {
if (s == null) {
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
// Check if the character at index is a high surrogate.
int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x7ff) {
// Found a surrogate char.
if (temp1 <= 0x3ff) {
// Found a high surrogate.
if (index < s.Length - 1) {
int temp2 = (int)s[index+1] - CharUnicodeInfo.LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff) {
// Found a low surrogate.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
} else {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), "s");
}
} else {
// Found a high surrogate at the end of the string.
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), "s");
}
} else {
// Find a low surrogate at the character pointed by index.
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), "s");
}
}
// Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
return ((int)s[index]);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Network.Version2017_03_01.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Internal;
using Microsoft.Azure.Management.Internal.Network;
using Microsoft.Azure.Management.Internal.Network.Version2017_03_01;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Network security rule.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class SecurityRule : SubResource
{
/// <summary>
/// Initializes a new instance of the SecurityRule class.
/// </summary>
public SecurityRule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SecurityRule class.
/// </summary>
/// <param name="protocol">Network protocol this rule applies to.
/// Possible values are 'Tcp', 'Udp', and '*'. Possible values include:
/// 'Tcp', 'Udp', '*'</param>
/// <param name="sourceAddressPrefix">The CIDR or source IP range.
/// Asterix '*' can also be used to match all source IPs. Default tags
/// such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can
/// also be used. If this is an ingress rule, specifies where network
/// traffic originates from. </param>
/// <param name="destinationAddressPrefix">The destination address
/// prefix. CIDR or source IP range. Asterix '*' can also be used to
/// match all source IPs. Default tags such as 'VirtualNetwork',
/// 'AzureLoadBalancer' and 'Internet' can also be used.</param>
/// <param name="access">The network traffic is allowed or denied.
/// Possible values are: 'Allow' and 'Deny'. Possible values include:
/// 'Allow', 'Deny'</param>
/// <param name="direction">The direction of the rule. The direction
/// specifies if rule will be evaluated on incoming or outcoming
/// traffic. Possible values are: 'Inbound' and 'Outbound'. Possible
/// values include: 'Inbound', 'Outbound'</param>
/// <param name="id">Resource ID.</param>
/// <param name="description">A description for this rule. Restricted
/// to 140 chars.</param>
/// <param name="sourcePortRange">The source port or range. Integer or
/// range between 0 and 65535. Asterix '*' can also be used to match
/// all ports.</param>
/// <param name="destinationPortRange">The destination port or range.
/// Integer or range between 0 and 65535. Asterix '*' can also be used
/// to match all ports.</param>
/// <param name="priority">The priority of the rule. The value can be
/// between 100 and 4096. The priority number must be unique for each
/// rule in the collection. The lower the priority number, the higher
/// the priority of the rule.</param>
/// <param name="provisioningState">The provisioning state of the
/// public IP resource. Possible values are: 'Updating', 'Deleting',
/// and 'Failed'.</param>
/// <param name="name">The name of the resource that is unique within a
/// resource group. This name can be used to access the
/// resource.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
public SecurityRule(string protocol, string sourceAddressPrefix, string destinationAddressPrefix, string access, string direction, string id = default(string), string description = default(string), string sourcePortRange = default(string), string destinationPortRange = default(string), int? priority = default(int?), string provisioningState = default(string), string name = default(string), string etag = default(string))
: base(id)
{
Description = description;
Protocol = protocol;
SourcePortRange = sourcePortRange;
DestinationPortRange = destinationPortRange;
SourceAddressPrefix = sourceAddressPrefix;
DestinationAddressPrefix = destinationAddressPrefix;
Access = access;
Priority = priority;
Direction = direction;
ProvisioningState = provisioningState;
Name = name;
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a description for this rule. Restricted to 140 chars.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets network protocol this rule applies to. Possible values
/// are 'Tcp', 'Udp', and '*'. Possible values include: 'Tcp', 'Udp',
/// '*'
/// </summary>
[JsonProperty(PropertyName = "properties.protocol")]
public string Protocol { get; set; }
/// <summary>
/// Gets or sets the source port or range. Integer or range between 0
/// and 65535. Asterix '*' can also be used to match all ports.
/// </summary>
[JsonProperty(PropertyName = "properties.sourcePortRange")]
public string SourcePortRange { get; set; }
/// <summary>
/// Gets or sets the destination port or range. Integer or range
/// between 0 and 65535. Asterix '*' can also be used to match all
/// ports.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationPortRange")]
public string DestinationPortRange { get; set; }
/// <summary>
/// Gets or sets the CIDR or source IP range. Asterix '*' can also be
/// used to match all source IPs. Default tags such as
/// 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be
/// used. If this is an ingress rule, specifies where network traffic
/// originates from.
/// </summary>
[JsonProperty(PropertyName = "properties.sourceAddressPrefix")]
public string SourceAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the destination address prefix. CIDR or source IP
/// range. Asterix '*' can also be used to match all source IPs.
/// Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
/// 'Internet' can also be used.
/// </summary>
[JsonProperty(PropertyName = "properties.destinationAddressPrefix")]
public string DestinationAddressPrefix { get; set; }
/// <summary>
/// Gets or sets the network traffic is allowed or denied. Possible
/// values are: 'Allow' and 'Deny'. Possible values include: 'Allow',
/// 'Deny'
/// </summary>
[JsonProperty(PropertyName = "properties.access")]
public string Access { get; set; }
/// <summary>
/// Gets or sets the priority of the rule. The value can be between 100
/// and 4096. The priority number must be unique for each rule in the
/// collection. The lower the priority number, the higher the priority
/// of the rule.
/// </summary>
[JsonProperty(PropertyName = "properties.priority")]
public int? Priority { get; set; }
/// <summary>
/// Gets or sets the direction of the rule. The direction specifies if
/// rule will be evaluated on incoming or outcoming traffic. Possible
/// values are: 'Inbound' and 'Outbound'. Possible values include:
/// 'Inbound', 'Outbound'
/// </summary>
[JsonProperty(PropertyName = "properties.direction")]
public string Direction { get; set; }
/// <summary>
/// Gets or sets the provisioning state of the public IP resource.
/// Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; set; }
/// <summary>
/// Gets or sets the name of the resource that is unique within a
/// resource group. This name can be used to access the resource.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets a unique read-only string that changes whenever the
/// resource is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Protocol == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Protocol");
}
if (SourceAddressPrefix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SourceAddressPrefix");
}
if (DestinationAddressPrefix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "DestinationAddressPrefix");
}
if (Access == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Access");
}
if (Direction == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Direction");
}
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using UIKit;
namespace ArcGISRuntime.Samples.ListTransformations
{
[Register("SpatialRelationships")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Spatial relationships",
category: "Geometry",
description: "Determine spatial relationships between two geometries.",
instructions: "Select one of the three graphics. The tree view will list the relationships the selected graphic has to the other graphic geometries.",
tags: new[] { "geometries", "relationship", "spatial analysis" })]
public class SpatialRelationships : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UITextView _resultTextView;
private UIStackView _stackView;
// References to the graphics and graphics overlay.
private GraphicsOverlay _graphicsOverlay;
private Graphic _polygonGraphic;
private Graphic _polylineGraphic;
private Graphic _pointGraphic;
public SpatialRelationships()
{
Title = "Spatial relationships";
}
private async void Initialize()
{
// Configure the basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISTopographic);
// Create the graphics overlay.
_graphicsOverlay = new GraphicsOverlay();
// Add the overlay to the MapView.
_myMapView.GraphicsOverlays.Add(_graphicsOverlay);
// Update the selection color.
_myMapView.SelectionProperties.Color = Color.Yellow;
// Create the point collection that defines the polygon.
PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
{
new MapPoint(-5991501.677830, 5599295.131468),
new MapPoint(-6928550.398185, 2087936.739807),
new MapPoint(-3149463.800709, 1840803.011362),
new MapPoint(-1563689.043184, 3714900.452072),
new MapPoint(-3180355.516764, 5619889.608838)
};
// Create the polygon.
Polygon polygonGeometry = new Polygon(polygonPoints);
// Define the symbology of the polygon.
SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Green, 2);
SimpleFillSymbol polygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, polygonOutlineSymbol);
// Create the polygon graphic and add it to the graphics overlay.
_polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
_graphicsOverlay.Graphics.Add(_polygonGraphic);
// Create the point collection that defines the polyline.
PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator)
{
new MapPoint(-4354240.726880, -609939.795721),
new MapPoint(-3427489.245210, 2139422.933233),
new MapPoint(-2109442.693501, 4301843.057130),
new MapPoint(-1810822.771630, 7205664.366363)
};
// Create the polyline.
Polyline polylineGeometry = new Polyline(polylinePoints);
// Create the polyline graphic and add it to the graphics overlay.
_polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 4));
_graphicsOverlay.Graphics.Add(_polylineGraphic);
// Create the point geometry that defines the point graphic.
MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);
// Define the symbology for the point.
SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 10);
// Create the point graphic and add it to the graphics overlay.
_pointGraphic = new Graphic(pointGeometry, locationMarker);
_graphicsOverlay.Graphics.Add(_pointGraphic);
try
{
// Set the viewpoint to center on the point.
await _myMapView.SetViewpointAsync(new Viewpoint(pointGeometry, 200000000));
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
}
}
private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
// Identify the tapped graphics.
IdentifyGraphicsOverlayResult result = null;
try
{
result = await _myMapView.IdentifyGraphicsOverlayAsync(_graphicsOverlay, e.Position, 5, false);
}
catch (Exception ex)
{
new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
}
// Return if there are no results.
if (result == null || result.Graphics.Count < 1)
{
return;
}
// Get the smallest identified graphic.
Graphic identifiedGraphic = result.Graphics.OrderBy(graphic => GeometryEngine.Area(graphic.Geometry)).First();
// Clear any existing selection, then select the tapped graphic.
_graphicsOverlay.ClearSelection();
identifiedGraphic.IsSelected = true;
// Get the selected graphic's geometry.
Geometry selectedGeometry = identifiedGraphic.Geometry;
// Perform the calculation and show the results.
_resultTextView.Text = GetOutputText(selectedGeometry);
}
private string GetOutputText(Geometry selectedGeometry)
{
string output = "";
// Get the relationships.
List<SpatialRelationship> polygonRelationships = GetSpatialRelationships(selectedGeometry, _polygonGraphic.Geometry);
List<SpatialRelationship> polylineRelationships = GetSpatialRelationships(selectedGeometry, _polylineGraphic.Geometry);
List<SpatialRelationship> pointRelationships = GetSpatialRelationships(selectedGeometry, _pointGraphic.Geometry);
// Add the point relationships to the output.
if (selectedGeometry.GeometryType != GeometryType.Point)
{
output += "Point:\n";
foreach (SpatialRelationship relationship in pointRelationships)
{
output += $"\t{relationship}\n";
}
}
// Add the polygon relationships to the output.
if (selectedGeometry.GeometryType != GeometryType.Polygon)
{
output += "Polygon:\n";
foreach (SpatialRelationship relationship in polygonRelationships)
{
output += $"\t{relationship}\n";
}
}
// Add the polyline relationships to the output.
if (selectedGeometry.GeometryType != GeometryType.Polyline)
{
output += "Polyline:\n";
foreach (SpatialRelationship relationship in polylineRelationships)
{
output += $"\t{relationship}\n";
}
}
return output;
}
/// <summary>
/// Returns a list of spatial relationships between two geometries.
/// </summary>
/// <param name="a">The 'a' in "a contains b".</param>
/// <param name="b">The 'b' in "a contains b".</param>
/// <returns>A list of spatial relationships that are true for a and b.</returns>
private static List<SpatialRelationship> GetSpatialRelationships(Geometry a, Geometry b)
{
List<SpatialRelationship> relationships = new List<SpatialRelationship>();
if (GeometryEngine.Crosses(a, b))
{
relationships.Add(SpatialRelationship.Crosses);
}
if (GeometryEngine.Contains(a, b))
{
relationships.Add(SpatialRelationship.Contains);
}
if (GeometryEngine.Disjoint(a, b))
{
relationships.Add(SpatialRelationship.Disjoint);
}
if (GeometryEngine.Intersects(a, b))
{
relationships.Add(SpatialRelationship.Intersects);
}
if (GeometryEngine.Overlaps(a, b))
{
relationships.Add(SpatialRelationship.Overlaps);
}
if (GeometryEngine.Touches(a, b))
{
relationships.Add(SpatialRelationship.Touches);
}
if (GeometryEngine.Within(a, b))
{
relationships.Add(SpatialRelationship.Within);
}
return relationships;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor };
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_resultTextView = new UITextView
{
TextColor = ApplicationTheme.ForegroundColor,
Text = "Tap a shape to see its relationship with the others.",
Editable = false,
ScrollEnabled = false,
};
_stackView = new UIStackView(new UIView[] { _myMapView, _resultTextView });
_stackView.Distribution = UIStackViewDistribution.FillEqually;
_stackView.TranslatesAutoresizingMaskIntoConstraints = false;
_stackView.Axis = UILayoutConstraintAxis.Vertical;
// Add the views.
View.AddSubview(_stackView);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_stackView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_stackView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_stackView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_stackView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
});
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
// Landscape
_stackView.Axis = UILayoutConstraintAxis.Horizontal;
}
else
{
// Portrait
_stackView.Axis = UILayoutConstraintAxis.Vertical;
}
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_myMapView.GeoViewTapped += MyMapView_GeoViewTapped;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_myMapView.GeoViewTapped -= MyMapView_GeoViewTapped;
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AccessApproval.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAccessApprovalServiceClientTest
{
[xunit::FactAttribute]
public void GetApprovalRequestRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest response = client.GetApprovalRequest(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetApprovalRequestRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApprovalRequest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest responseCallSettings = await client.GetApprovalRequestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ApprovalRequest responseCancellationToken = await client.GetApprovalRequestAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetApprovalRequest()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest response = client.GetApprovalRequest(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetApprovalRequestAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApprovalRequest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest responseCallSettings = await client.GetApprovalRequestAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ApprovalRequest responseCancellationToken = await client.GetApprovalRequestAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetApprovalRequestResourceNames()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest response = client.GetApprovalRequest(request.ApprovalRequestName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetApprovalRequestResourceNamesAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetApprovalRequestMessage request = new GetApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetApprovalRequestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApprovalRequest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest responseCallSettings = await client.GetApprovalRequestAsync(request.ApprovalRequestName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ApprovalRequest responseCancellationToken = await client.GetApprovalRequestAsync(request.ApprovalRequestName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ApproveApprovalRequestRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
ExpireTime = new wkt::Timestamp(),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.ApproveApprovalRequest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest response = client.ApproveApprovalRequest(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ApproveApprovalRequestRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
ExpireTime = new wkt::Timestamp(),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.ApproveApprovalRequestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApprovalRequest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest responseCallSettings = await client.ApproveApprovalRequestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ApprovalRequest responseCancellationToken = await client.ApproveApprovalRequestAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DismissApprovalRequestRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DismissApprovalRequestMessage request = new DismissApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.DismissApprovalRequest(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest response = client.DismissApprovalRequest(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DismissApprovalRequestRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DismissApprovalRequestMessage request = new DismissApprovalRequestMessage
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
};
ApprovalRequest expectedResponse = new ApprovalRequest
{
ApprovalRequestName = ApprovalRequestName.FromProjectApprovalRequest("[PROJECT]", "[APPROVAL_REQUEST]"),
RequestedResourceName = "requested_resource_name3898f866",
RequestedReason = new AccessReason(),
RequestedLocations = new AccessLocations(),
RequestTime = new wkt::Timestamp(),
RequestedExpiration = new wkt::Timestamp(),
Approve = new ApproveDecision(),
Dismiss = new DismissDecision(),
RequestedResourceProperties = new ResourceProperties(),
};
mockGrpcClient.Setup(x => x.DismissApprovalRequestAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApprovalRequest>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
ApprovalRequest responseCallSettings = await client.DismissApprovalRequestAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ApprovalRequest responseCancellationToken = await client.DismissApprovalRequestAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAccessApprovalSettingsRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings response = client.GetAccessApprovalSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAccessApprovalSettingsRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessApprovalSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings responseCallSettings = await client.GetAccessApprovalSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessApprovalSettings responseCancellationToken = await client.GetAccessApprovalSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAccessApprovalSettings()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings response = client.GetAccessApprovalSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAccessApprovalSettingsAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessApprovalSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings responseCallSettings = await client.GetAccessApprovalSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessApprovalSettings responseCancellationToken = await client.GetAccessApprovalSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAccessApprovalSettingsResourceNames()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings response = client.GetAccessApprovalSettings(request.AccessApprovalSettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAccessApprovalSettingsResourceNamesAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.GetAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessApprovalSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings responseCallSettings = await client.GetAccessApprovalSettingsAsync(request.AccessApprovalSettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessApprovalSettings responseCancellationToken = await client.GetAccessApprovalSettingsAsync(request.AccessApprovalSettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAccessApprovalSettingsRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new wkt::FieldMask(),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.UpdateAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings response = client.UpdateAccessApprovalSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAccessApprovalSettingsRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new wkt::FieldMask(),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.UpdateAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessApprovalSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings responseCallSettings = await client.UpdateAccessApprovalSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessApprovalSettings responseCancellationToken = await client.UpdateAccessApprovalSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAccessApprovalSettings()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new wkt::FieldMask(),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.UpdateAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings response = client.UpdateAccessApprovalSettings(request.Settings, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAccessApprovalSettingsAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new wkt::FieldMask(),
};
AccessApprovalSettings expectedResponse = new AccessApprovalSettings
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
NotificationEmails =
{
"notification_emails936d0793",
},
EnrolledServices =
{
new EnrolledService(),
},
EnrolledAncestor = true,
};
mockGrpcClient.Setup(x => x.UpdateAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AccessApprovalSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
AccessApprovalSettings responseCallSettings = await client.UpdateAccessApprovalSettingsAsync(request.Settings, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AccessApprovalSettings responseCancellationToken = await client.UpdateAccessApprovalSettingsAsync(request.Settings, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAccessApprovalSettingsRequestObject()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAccessApprovalSettings(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAccessApprovalSettingsRequestObjectAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAccessApprovalSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAccessApprovalSettingsAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAccessApprovalSettings()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAccessApprovalSettings(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAccessApprovalSettingsAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAccessApprovalSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAccessApprovalSettingsAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAccessApprovalSettingsResourceNames()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAccessApprovalSettings(request.AccessApprovalSettingsName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAccessApprovalSettingsResourceNamesAsync()
{
moq::Mock<AccessApproval.AccessApprovalClient> mockGrpcClient = new moq::Mock<AccessApproval.AccessApprovalClient>(moq::MockBehavior.Strict);
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage
{
AccessApprovalSettingsName = AccessApprovalSettingsName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAccessApprovalSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AccessApprovalServiceClient client = new AccessApprovalServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAccessApprovalSettingsAsync(request.AccessApprovalSettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAccessApprovalSettingsAsync(request.AccessApprovalSettingsName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class TransactionTest
{
[CheckConnStrSetupFact]
public static void TestMain()
{
new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString).StartTest();
}
private sealed class TransactionTestWorker
{
private readonly string _tempTableName1;
private readonly string _tempTableName2;
private string _connectionString;
public TransactionTestWorker(string connectionString)
{
_connectionString = connectionString;
_tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
_tempTableName2 = _tempTableName1 + "_2";
}
public void StartTest()
{
try
{
PrepareTables();
CommitTransactionTest();
ResetTables();
RollbackTransactionTest();
ResetTables();
ScopedTransactionTest();
ResetTables();
ExceptionTest();
ResetTables();
ReadUncommitedIsolationLevel_ShouldReturnUncommitedData();
ResetTables();
ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction();
ResetTables();
}
finally
{
//make sure to clean up
DropTempTables();
}
}
private void PrepareTables()
{
using (var conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", _tempTableName1), conn);
command.ExecuteNonQuery();
command.CommandText = "create table " + _tempTableName2 + "(col1 int, col2 varchar(32))";
command.ExecuteNonQuery();
}
}
private void DropTempTables()
{
using (var conn = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(
string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", _tempTableName1, _tempTableName2), conn);
conn.Open();
command.ExecuteNonQuery();
}
}
public void ResetTables()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", _tempTableName1, _tempTableName2), connection))
{
command.ExecuteNonQuery();
}
}
}
private void CommitTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Commit();
using (SqlDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read()) { count++; }
Assert.True(count == 1, "Error: incorrect number of rows in table after update.");
Assert.Equal(count, 1);
}
}
}
private void RollbackTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Rollback();
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 0);
}
connection.Close();
}
}
private void ScopedTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction("transName");
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Save("saveName");
//insert another one
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );";
command2.ExecuteNonQuery();
}
tx.Rollback("saveName");
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 1);
}
tx.Rollback();
connection.Close();
}
}
private void ExceptionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
AssertException<InvalidOperationException>(() =>
{
SqlCommand command = new SqlCommand("sql", connection);
command.ExecuteNonQuery();
}, executeCommandWithoutTransactionMessage);
AssertException<InvalidOperationException>(() =>
{
SqlConnection con1 = new SqlConnection(_connectionString);
con1.Open();
SqlCommand command = new SqlCommand("sql", con1);
command.Transaction = tx;
command.ExecuteNonQuery();
}, transactionConflictErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction(null);
}, parallelTransactionErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction("");
}, parallelTransactionErrorMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback("");
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save("");
}, invalidSaveStateMessage);
}
}
public static void AssertException<T>(Action action, string expectedErrorMessage) where T : Exception
{
var exception = Assert.Throws<T>(action);
Assert.Equal(exception.Message, expectedErrorMessage);
}
private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted);
command2.Transaction = tx2;
using (SqlDataReader reader = command2.ExecuteReader())
{
int count = 0;
while (reader.Read()) count++;
Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommitted which should return uncommitted data.");
}
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
command2.Transaction = tx2;
AssertException<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Data.ProviderBase
{
internal class DbMetaDataFactory
{
private DataSet _metaDataCollectionsDataSet;
private string _normalizedServerVersion;
private string _serverVersionString;
// well known column names
private const string _collectionName = "CollectionName";
private const string _populationMechanism = "PopulationMechanism";
private const string _populationString = "PopulationString";
private const string _maximumVersion = "MaximumVersion";
private const string _minimumVersion = "MinimumVersion";
private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized";
private const string _dataSourceProductVersion = "DataSourceProductVersion";
private const string _restrictionDefault = "RestrictionDefault";
private const string _restrictionNumber = "RestrictionNumber";
private const string _numberOfRestrictions = "NumberOfRestrictions";
private const string _restrictionName = "RestrictionName";
private const string _parameterName = "ParameterName";
// population mechanisms
private const string _dataTable = "DataTable";
private const string _sqlCommand = "SQLCommand";
private const string _prepareCollection = "PrepareCollection";
public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion)
{
ADP.CheckArgumentNull(xmlStream, nameof(xmlStream));
ADP.CheckArgumentNull(serverVersion, nameof(serverVersion));
ADP.CheckArgumentNull(normalizedServerVersion, nameof(normalizedServerVersion));
LoadDataSetFromXml(xmlStream);
_serverVersionString = serverVersion;
_normalizedServerVersion = normalizedServerVersion;
}
protected DataSet CollectionDataSet => _metaDataCollectionsDataSet;
protected string ServerVersion => _serverVersionString;
protected string ServerVersionNormalized => _normalizedServerVersion;
protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames)
{
DataTable destinationTable;
DataColumn[] filteredSourceColumns;
DataColumnCollection destinationColumns;
DataRow newRow;
DataTable sourceTable = _metaDataCollectionsDataSet.Tables[collectionName];
if ((sourceTable == null) || (collectionName != sourceTable.TableName))
{
throw ADP.DataTableDoesNotExist(collectionName);
}
destinationTable = new DataTable(collectionName)
{
Locale = CultureInfo.InvariantCulture
};
destinationColumns = destinationTable.Columns;
filteredSourceColumns = FilterColumns(sourceTable, hiddenColumnNames, destinationColumns);
foreach (DataRow row in sourceTable.Rows)
{
if (SupportedByCurrentVersion(row) == true)
{
newRow = destinationTable.NewRow();
for (int i = 0; i < destinationColumns.Count; i++)
{
newRow[destinationColumns[i]] = row[filteredSourceColumns[i], DataRowVersion.Current];
}
destinationTable.Rows.Add(newRow);
newRow.AcceptChanges();
}
}
return destinationTable;
}
public void Dispose() => Dispose(true);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_normalizedServerVersion = null;
_serverVersionString = null;
_metaDataCollectionsDataSet.Dispose();
}
}
private DataTable ExecuteCommand(DataRow requestedCollectionRow, string[] restrictions, DbConnection connection)
{
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString];
DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName];
DataTable resultTable = null;
DbCommand command = null;
DataTable schemaTable = null;
Debug.Assert(requestedCollectionRow != null);
string sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string;
int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current];
string collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
if ((restrictions != null) && (restrictions.Length > numberOfRestrictions))
{
throw ADP.TooManyRestrictions(collectionName);
}
command = connection.CreateCommand();
command.CommandText = sqlCommand;
command.CommandTimeout = Math.Max(command.CommandTimeout, 180);
for (int i = 0; i < numberOfRestrictions; i++)
{
DbParameter restrictionParameter = command.CreateParameter();
if ((restrictions != null) && (restrictions.Length > i) && (restrictions[i] != null))
{
restrictionParameter.Value = restrictions[i];
}
else
{
// This is where we have to assign null to the value of the parameter.
restrictionParameter.Value = DBNull.Value;
}
restrictionParameter.ParameterName = GetParameterName(collectionName, i + 1);
restrictionParameter.Direction = ParameterDirection.Input;
command.Parameters.Add(restrictionParameter);
}
DbDataReader reader = null;
try
{
try
{
reader = command.ExecuteReader();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.QueryFailed(collectionName, e);
}
// Build a DataTable from the reader
resultTable = new DataTable(collectionName)
{
Locale = CultureInfo.InvariantCulture
};
schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"] as Type);
}
object[] values = new object[resultTable.Columns.Count];
while (reader.Read())
{
reader.GetValues(values);
resultTable.Rows.Add(values);
}
}
finally
{
if (reader != null)
{
reader.Dispose();
reader = null;
}
}
return resultTable;
}
private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns)
{
int columnCount = 0;
foreach (DataColumn sourceColumn in sourceTable.Columns)
{
if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
{
columnCount++;
}
}
if (columnCount == 0)
{
throw ADP.NoColumns();
}
int currentColumn = 0;
DataColumn[] filteredSourceColumns = new DataColumn[columnCount];
foreach (DataColumn sourceColumn in sourceTable.Columns)
{
if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
{
DataColumn newDestinationColumn = new DataColumn(sourceColumn.ColumnName, sourceColumn.DataType);
destinationColumns.Add(newDestinationColumn);
filteredSourceColumns[currentColumn] = sourceColumn;
currentColumn++;
}
}
return filteredSourceColumns;
}
internal DataRow FindMetaDataCollectionRow(string collectionName)
{
bool versionFailure;
bool haveExactMatch;
bool haveMultipleInexactMatches;
string candidateCollectionName;
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
if (metaDataCollectionsTable == null)
{
throw ADP.InvalidXml();
}
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType))
{
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
DataRow requestedCollectionRow = null;
string exactCollectionName = null;
// find the requested collection
versionFailure = false;
haveExactMatch = false;
haveMultipleInexactMatches = false;
foreach (DataRow row in metaDataCollectionsTable.Rows)
{
candidateCollectionName = row[collectionNameColumn, DataRowVersion.Current] as string;
if (string.IsNullOrEmpty(candidateCollectionName))
{
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName))
{
if (SupportedByCurrentVersion(row) == false)
{
versionFailure = true;
}
else
{
if (collectionName == candidateCollectionName)
{
if (haveExactMatch == true)
{
throw ADP.CollectionNameIsNotUnique(collectionName);
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
haveExactMatch = true;
}
else
{
// have an inexact match - ok only if it is the only one
if (exactCollectionName != null)
{
// can't fail here becasue we may still find an exact match
haveMultipleInexactMatches = true;
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
}
}
}
}
if (requestedCollectionRow == null)
{
if (versionFailure == false)
{
throw ADP.UndefinedCollection(collectionName);
}
else
{
throw ADP.UnsupportedVersion(collectionName);
}
}
if ((haveExactMatch == false) && (haveMultipleInexactMatches == true))
{
throw ADP.AmbigousCollectionName(collectionName);
}
return requestedCollectionRow;
}
private void FixUpVersion(DataTable dataSourceInfoTable)
{
Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation);
DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion];
DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized];
if ((versionColumn == null) || (normalizedVersionColumn == null))
{
throw ADP.MissingDataSourceInformationColumn();
}
if (dataSourceInfoTable.Rows.Count != 1)
{
throw ADP.IncorrectNumberOfDataSourceInformationRows();
}
DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0];
dataSourceInfoRow[versionColumn] = _serverVersionString;
dataSourceInfoRow[normalizedVersionColumn] = _normalizedServerVersion;
dataSourceInfoRow.AcceptChanges();
}
private string GetParameterName(string neededCollectionName, int neededRestrictionNumber)
{
DataTable restrictionsTable = null;
DataColumnCollection restrictionColumns = null;
DataColumn collectionName = null;
DataColumn parameterName = null;
DataColumn restrictionName = null;
DataColumn restrictionNumber = null;
string result = null;
restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
if (restrictionsTable != null)
{
restrictionColumns = restrictionsTable.Columns;
if (restrictionColumns != null)
{
collectionName = restrictionColumns[_collectionName];
parameterName = restrictionColumns[_parameterName];
restrictionName = restrictionColumns[_restrictionName];
restrictionNumber = restrictionColumns[_restrictionNumber];
}
}
if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null))
{
throw ADP.MissingRestrictionColumn();
}
foreach (DataRow restriction in restrictionsTable.Rows)
{
if (((string)restriction[collectionName] == neededCollectionName) &&
((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
(SupportedByCurrentVersion(restriction)))
{
result = (string)restriction[parameterName];
break;
}
}
if (result == null)
{
throw ADP.MissingRestrictionRow();
}
return result;
}
public virtual DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions)
{
Debug.Assert(_metaDataCollectionsDataSet != null);
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
DataRow requestedCollectionRow = null;
DataTable requestedSchema = null;
string[] hiddenColumns;
string exactCollectionName = null;
requestedCollectionRow = FindMetaDataCollectionRow(collectionName);
exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
if (ADP.IsEmptyArray(restrictions) == false)
{
for (int i = 0; i < restrictions.Length; i++)
{
if ((restrictions[i] != null) && (restrictions[i].Length > 4096))
{
// use a non-specific error because no new beta 2 error messages are allowed
// TODO: will add a more descriptive error in RTM
throw ADP.NotSupported();
}
}
}
string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string;
switch (populationMechanism)
{
case _dataTable:
if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections)
{
hiddenColumns = new string[2];
hiddenColumns[0] = _populationMechanism;
hiddenColumns[1] = _populationString;
}
else
{
hiddenColumns = null;
}
// none of the datatable collections support restrictions
if (ADP.IsEmptyArray(restrictions) == false)
{
throw ADP.TooManyRestrictions(exactCollectionName);
}
requestedSchema = CloneAndFilterCollection(exactCollectionName, hiddenColumns);
// TODO: Consider an alternate method that doesn't involve special casing -- perhaps _prepareCollection
// for the data source infomation table we need to fix up the version columns at run time
// since the version is determined at run time
if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation)
{
FixUpVersion(requestedSchema);
}
break;
case _sqlCommand:
requestedSchema = ExecuteCommand(requestedCollectionRow, restrictions, connection);
break;
case _prepareCollection:
requestedSchema = PrepareCollection(exactCollectionName, restrictions, connection);
break;
default:
throw ADP.UndefinedPopulationMechanism(populationMechanism);
}
return requestedSchema;
}
private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames)
{
bool result = true;
string sourceColumnName = sourceColumn.ColumnName;
switch (sourceColumnName)
{
case _minimumVersion:
case _maximumVersion:
result = false;
break;
default:
if (hiddenColumnNames == null)
{
break;
}
for (int i = 0; i < hiddenColumnNames.Length; i++)
{
if (hiddenColumnNames[i] == sourceColumnName)
{
result = false;
break;
}
}
break;
}
return result;
}
private void LoadDataSetFromXml(Stream XmlStream)
{
_metaDataCollectionsDataSet = new DataSet();
_metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
_metaDataCollectionsDataSet.ReadXml(XmlStream);
}
protected virtual DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection)
{
throw ADP.NotSupported();
}
private bool SupportedByCurrentVersion(DataRow requestedCollectionRow)
{
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
DataColumn versionColumn;
object version;
// check the minimum version first
versionColumn = tableColumns[_minimumVersion];
if (versionColumn != null)
{
version = requestedCollectionRow[versionColumn];
if (version != null)
{
if (version != DBNull.Value)
{
if (0 > string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
}
}
// if the minmum version was ok what about the maximum version
if (result == true)
{
versionColumn = tableColumns[_maximumVersion];
if (versionColumn != null)
{
version = requestedCollectionRow[versionColumn];
if (version != null)
{
if (version != DBNull.Value)
{
if (0 < string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
}
}
}
return result;
}
}
}
| |
//
// Copyright 2014, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using Android.Provider;
using NUnit.Framework;
using Xamarin.Contacts;
namespace Xamarin.Mobile.Tests.Tests
{
[TestFixture]
class ContentQueryTranslatorTests
{
[Test]
public void FirstSingleClause()
{
Queryable.First (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1));
}
[Test]
public void FirstOrDefaultSingleClause()
{
Queryable.FirstOrDefault (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1));
}
[Test]
public void SingleOrDefaultSingleClause()
{
Queryable.SingleOrDefault (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2));
}
[Test]
public void SingleSingleClause()
{
Queryable.Single (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2));
}
[Test]
public void WhereSingleClause()
{
Queryable.Where (c => c.DisplayName == "Display Name").ToArray();
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
[Test]
public void CountSingleClause()
{
Queryable.Count (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.True);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
[Test]
public void AnySingleClause()
{
Queryable.Any (c => c.DisplayName == "Display Name");
AssertSingularWithSingleClause();
Assert.That (Translator.IsAny, Is.True);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
public void AssertSingularWithSingleClause()
{
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
Assert.That (Translator.QueryString, Is.EqualTo ("(display_name = ?)"));
Assert.That (Translator.Projections, Is.Null.Or.Empty, "Projections were present");
Assert.That (Translator.ClauseParameters, Contains.Item ("Display Name"));
Assert.That (Translator.ReturnType, Is.Null.Or.EqualTo (typeof (Contact)));
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Contacts.ContentUri));
}
[Test]
public void FirstTwoClausesSameTableSameMimetype()
{
Queryable.First (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1));
}
[Test]
public void FirstOrDefaultTwoClausesSameTableSameMimetype()
{
Queryable.FirstOrDefault (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1));
}
[Test]
public void SingleTwoClausesSameTableSameMimetype()
{
Queryable.Single (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType ();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2));
}
[Test]
public void SingleOrDefaultTwoClausesSameTableSameMimetype()
{
Queryable.SingleOrDefault (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2));
}
[Test]
public void WhereSingleTwoClausesSameTableSameMimeType()
{
Queryable.Where (c => c.FirstName == "Foo" && c.LastName == "Bar").ToArray();
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
[Test]
public void CountSingleTwoClausesSameTableSameMimeType()
{
Queryable.Count (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.True);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
[Test]
public void AnySingleTwoClausesSameTableSameMimeType()
{
Queryable.Any (c => c.FirstName == "Foo" && c.LastName == "Bar");
AssertSingularWithTwoClausesFromSameTableAndMimeType();
Assert.That (Translator.IsAny, Is.True);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
}
public void AssertSingularWithTwoClausesFromSameTableAndMimeType()
{
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
Assert.That (Translator.QueryString, Is.EqualTo (
String.Format ("(({0} = ?) AND (({1} = ?) AND ({2} = ?)))",
ContactsContract.DataColumns.Mimetype,
ContactsContract.CommonDataKinds.StructuredName.GivenName,
ContactsContract.CommonDataKinds.StructuredName.FamilyName)));
Assert.That (Translator.Projections, Is.Null.Or.Empty, "Projections were present");
Assert.That (Translator.ClauseParameters[0], Is.EqualTo (ContactsContract.CommonDataKinds.StructuredName.ContentItemType));
Assert.That (Translator.ClauseParameters[1], Is.EqualTo ("Foo"));
Assert.That (Translator.ClauseParameters[2], Is.EqualTo ("Bar"));
Assert.That (Translator.ReturnType, Is.Null.Or.EqualTo (typeof (Contact)));
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Data.ContentUri));
Assert.That (Translator.SortString, Is.Null.Or.Empty);
}
[Test]
public void WhereTwoClausesSameTableDifferentMimeType()
{
Queryable.Where (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar").ToArray();
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1), "Take was not -1");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
[Category ("Any"), Category ("TwoClausesSameTableDifferentMimeType")]
public void AnyTwoClausesSameTableDifferentMimeType()
{
Queryable.Any (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.True);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1), "Take was not -1");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
[Category ("Count"), Category ("TwoClausesSameTableDifferentMimeType")]
public void CountTwoClausesSameTableDifferentMimeType()
{
Queryable.Count (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.True);
Assert.That (Translator.Take, Is.EqualTo (-1), "Take was not -1");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
public void FirstTwoClausesSameTableDifferentMimeType()
{
Queryable.First (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1), "Take was not 1");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
public void FirstOrDefaultTwoClausesSameTableDifferentMimeType()
{
Queryable.FirstOrDefault (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (1), "Take was not 1");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
public void SingleTwoClausesSameTableDifferentMimetype()
{
Queryable.Single (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2), "Take was not 2");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
[Test]
public void SingleOrDefaultTwoClausesSameTableDifferentMimetype()
{
Queryable.SingleOrDefault (c => c.FirstName == "Foo" && c.DisplayName == "Foo Bar");
AssertWhereWithTwoClausesFromSameTableDifferentMimeType ();
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (2), "Take was not 2");
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
}
public void AssertWhereWithTwoClausesFromSameTableDifferentMimeType()
{
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.Skip, Is.EqualTo (-1), "Skip was not -1");
Assert.That (Translator.QueryString, Is.EqualTo (
String.Format ("(({0} = ?) AND (({1} = ?)))",
ContactsContract.DataColumns.Mimetype,
ContactsContract.CommonDataKinds.StructuredName.GivenName)));
Assert.That (Translator.Projections, Is.Null.Or.Empty, "Projections were present");
Assert.That (Translator.ClauseParameters[0], Is.EqualTo (ContactsContract.CommonDataKinds.StructuredName.ContentItemType));
Assert.That (Translator.ClauseParameters[1], Is.EqualTo ("Foo"));
Assert.That (Translator.ClauseParameters.Length, Is.EqualTo (2));
Assert.That (Translator.ReturnType, Is.Null.Or.EqualTo (typeof (Contact)));
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Data.ContentUri));
Assert.That (Translator.SortString, Is.Null.Or.Empty);
}
[Test]
public void WhereWithOrClauseFromSameTableDifferentMimeType()
{
Queryable.Where (c => c.FirstName == "Foo" || c.DisplayName == "Foo Bar").ToArray();
AssertFallback();
}
[Test]
public void WhereFallback()
{
Queryable.Where (c => c.Organizations.Any()).ToArray();
AssertFallback();
}
[Test]
public void FirstFallback()
{
Queryable.First (c => c.Organizations.Any());
AssertFallback();
}
[Test]
public void FirstOrDefaultFallback()
{
Queryable.FirstOrDefault (c => c.Organizations.Any());
AssertFallback();
}
[Test]
public void SingleFallback()
{
Queryable.Single (c => c.Organizations.Any());
AssertFallback();
}
[Test]
public void SingleOrDefaultFallback()
{
Queryable.SingleOrDefault (c => c.Organizations.Any());
AssertFallback();
}
[Test]
public void AnyFallback()
{
Queryable.Any (c => c.Organizations.Any());
AssertFallback();
}
[Test]
public void CountFallback()
{
Queryable.Count (c => c.Organizations.Any());
AssertFallback();
}
public void AssertFallback()
{
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Skip, Is.EqualTo (-1));
Assert.That (Translator.Take, Is.EqualTo (-1));
Assert.That (Translator.Projections, Is.Null.Or.Empty);
Assert.That (Translator.QueryString, Is.Null.Or.Empty);
Assert.That (Translator.SortString, Is.Null.Or.Empty);
Assert.That (Translator.ReturnType, Is.Null);
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Contacts.ContentUri));
Assert.That (Translator.ClauseParameters, Is.Null.Or.Empty);
}
[Test]
public void Count()
{
Queryable.Count();
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.True);
Assert.That (Translator.Take, Is.EqualTo (-1));
Assert.That (Translator.Skip, Is.EqualTo (-1));
Assert.That (Translator.QueryString, Is.Null.Or.Empty);
Assert.That (Translator.ClauseParameters, Is.Null.Or.Empty);
Assert.That (Translator.Projections, Is.Null.Or.Empty);
Assert.That (Translator.SortString, Is.Null.Or.Empty);
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Contacts.ContentUri));
Assert.That (Translator.ReturnType, Is.Null);
}
[Test]
public void Any()
{
Queryable.Any();
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.IsAny, Is.True);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
Assert.That (Translator.Skip, Is.EqualTo (-1));
Assert.That (Translator.QueryString, Is.Null);
Assert.That (Translator.ClauseParameters, Is.Null.Or.Empty);
Assert.That (Translator.Projections, Is.Null.Or.Empty);
Assert.That (Translator.SortString, Is.Null.Or.Empty);
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Contacts.ContentUri));
Assert.That (Translator.ReturnType, Is.Null);
}
[Test]
public void Skip()
{
Queryable.Skip (5).ToArray();
Translator.Translate (Queryable.LastExpression);
Assert.That (Translator.IsAny, Is.False);
Assert.That (Translator.IsCount, Is.False);
Assert.That (Translator.Take, Is.EqualTo (-1));
Assert.That (Translator.Skip, Is.EqualTo (5));
Assert.That (Translator.QueryString, Is.Null);
Assert.That (Translator.ClauseParameters, Is.Null.Or.Empty);
Assert.That (Translator.Projections, Is.Null.Or.Empty);
Assert.That (Translator.SortString, Is.Null.Or.Empty);
Assert.That (Translator.Table, Is.EqualTo (ContactsContract.Contacts.ContentUri));
Assert.That (Translator.ReturnType, Is.Null);
}
private MockQueryable<Contact> Queryable
{
get { return this.queryable; }
}
private ContentQueryTranslator Translator
{
get { return this.translator; }
}
private MockQueryable<Contact> queryable;
private ContentQueryTranslator translator;
[SetUp]
public void Setup()
{
this.queryable = new MockQueryable<Contact>();
this.translator = new ContentQueryTranslator (this.queryable.Provider, new ContactTableFinder { UseRawContacts = false });
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MIMDashboard.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
namespace Svg
{
[SvgElement("radialGradient")]
public sealed class SvgRadialGradientServer : SvgGradientServer
{
[SvgAttribute("cx")]
public SvgUnit CenterX
{
get
{
return this.Attributes.GetAttribute<SvgUnit>("cx");
}
set
{
this.Attributes["cx"] = value;
}
}
[SvgAttribute("cy")]
public SvgUnit CenterY
{
get
{
return this.Attributes.GetAttribute<SvgUnit>("cy");
}
set
{
this.Attributes["cy"] = value;
}
}
[SvgAttribute("r")]
public SvgUnit Radius
{
get
{
return this.Attributes.GetAttribute<SvgUnit>("r");
}
set
{
this.Attributes["r"] = value;
}
}
[SvgAttribute("fx")]
public SvgUnit FocalX
{
get
{
var value = this.Attributes.GetAttribute<SvgUnit>("fx");
if (value.IsEmpty || value.IsNone)
{
value = this.CenterX;
}
return value;
}
set
{
this.Attributes["fx"] = value;
}
}
[SvgAttribute("fy")]
public SvgUnit FocalY
{
get
{
var value = this.Attributes.GetAttribute<SvgUnit>("fy");
if (value.IsEmpty || value.IsNone)
{
value = this.CenterY;
}
return value;
}
set
{
this.Attributes["fy"] = value;
}
}
public SvgRadialGradientServer()
{
CenterX = new SvgUnit(SvgUnitType.Percentage, 50F);
CenterY = new SvgUnit(SvgUnitType.Percentage, 50F);
Radius = new SvgUnit(SvgUnitType.Percentage, 50F);
}
private object _lockObj = new Object();
private SvgUnit NormalizeUnit(SvgUnit orig)
{
return (orig.Type == SvgUnitType.Percentage && this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox ?
new SvgUnit(SvgUnitType.User, orig.Value / 100) :
orig);
}
public override Brush GetBrush(SvgVisualElement renderingElement, ISvgRenderer renderer, float opacity, bool forStroke = false)
{
LoadStops(renderingElement);
try
{
if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.SetBoundable(renderingElement);
// Calculate the path and transform it appropriately
var center = new PointF(NormalizeUnit(CenterX).ToDeviceValue(renderer, UnitRenderingType.Horizontal, this),
NormalizeUnit(CenterY).ToDeviceValue(renderer, UnitRenderingType.Vertical, this));
var focals = new PointF[] {new PointF(NormalizeUnit(FocalX).ToDeviceValue(renderer, UnitRenderingType.Horizontal, this),
NormalizeUnit(FocalY).ToDeviceValue(renderer, UnitRenderingType.Vertical, this)) };
var specifiedRadius = NormalizeUnit(Radius).ToDeviceValue(renderer, UnitRenderingType.Other, this);
var path = new GraphicsPath();
path.AddEllipse(
center.X - specifiedRadius, center.Y - specifiedRadius,
specifiedRadius * 2, specifiedRadius * 2
);
using (var transform = EffectiveGradientTransform)
{
var bounds = renderer.GetBoundable().Bounds;
transform.Translate(bounds.X, bounds.Y, MatrixOrder.Prepend);
if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox)
{
transform.Scale(bounds.Width, bounds.Height, MatrixOrder.Prepend);
}
path.Transform(transform);
transform.TransformPoints(focals);
}
// Calculate any required scaling
var scaleBounds = RectangleF.Inflate(renderingElement.Bounds, renderingElement.StrokeWidth, renderingElement.StrokeWidth);
var scale = CalcScale(scaleBounds, path);
// Not ideal, but this makes sure that the rest of the shape gets properly filled or drawn
if (scale > 1.0f && SpreadMethod == SvgGradientSpreadMethod.Pad)
{
var stop = Stops.Last();
var origColor = stop.GetColor(renderingElement);
var renderColor = System.Drawing.Color.FromArgb((int)Math.Round(opacity * stop.Opacity * 255), origColor);
var origClip = renderer.GetClip();
try
{
using (var solidBrush = new SolidBrush(renderColor))
{
var newClip = origClip.Clone();
newClip.Exclude(path);
renderer.SetClip(newClip);
var renderPath = (GraphicsPath)renderingElement.Path(renderer);
if (forStroke)
{
using (var pen = new Pen(solidBrush, renderingElement.StrokeWidth.ToDeviceValue(renderer, UnitRenderingType.Other, renderingElement)))
{
renderer.DrawPath(pen, renderPath);
}
}
else
{
renderer.FillPath(solidBrush, renderPath);
}
}
}
finally
{
renderer.SetClip(origClip);
}
}
// Get the color blend and any tweak to the scaling
var blend = CalculateColorBlend(renderer, opacity, scale, out scale);
// Transform the path based on the scaling
var gradBounds = path.GetBounds();
var transCenter = new PointF(gradBounds.Left + gradBounds.Width / 2, gradBounds.Top + gradBounds.Height / 2);
using (var scaleMat = new Matrix())
{
scaleMat.Translate(-1 * transCenter.X, -1 * transCenter.Y, MatrixOrder.Append);
scaleMat.Scale(scale, scale, MatrixOrder.Append);
scaleMat.Translate(transCenter.X, transCenter.Y, MatrixOrder.Append);
path.Transform(scaleMat);
}
// calculate the brush
var brush = new PathGradientBrush(path);
brush.CenterPoint = focals[0];
brush.InterpolationColors = blend;
return brush;
}
finally
{
if (this.GradientUnits == SvgCoordinateUnits.ObjectBoundingBox) renderer.PopBoundable();
}
}
/// <summary>
/// Determine how much (approximately) the path must be scaled to contain the rectangle
/// </summary>
/// <param name="bounds">Bounds that the path must contain</param>
/// <param name="path">Path of the gradient</param>
/// <param name="graphics">Not used</param>
/// <returns>Scale factor</returns>
/// <remarks>
/// This method continually transforms the rectangle (fewer points) until it is contained by the path
/// and returns the result of the search. The scale factor is set to a constant 95%
/// </remarks>
private float CalcScale(RectangleF bounds, GraphicsPath path, Graphics graphics = null)
{
var points = new PointF[] {
new PointF(bounds.Left, bounds.Top),
new PointF(bounds.Right, bounds.Top),
new PointF(bounds.Right, bounds.Bottom),
new PointF(bounds.Left, bounds.Bottom)
};
var pathBounds = path.GetBounds();
var pathCenter = new PointF(pathBounds.X + pathBounds.Width / 2, pathBounds.Y + pathBounds.Height / 2);
using (var transform = new Matrix())
{
transform.Translate(-1 * pathCenter.X, -1 * pathCenter.Y, MatrixOrder.Append);
transform.Scale(.95f, .95f, MatrixOrder.Append);
transform.Translate(pathCenter.X, pathCenter.Y, MatrixOrder.Append);
while (!(path.IsVisible(points[0]) && path.IsVisible(points[1]) &&
path.IsVisible(points[2]) && path.IsVisible(points[3])))
{
var previousPoints = new PointF[]
{
new PointF(points[0].X, points[0].Y),
new PointF(points[1].X, points[1].Y),
new PointF(points[2].X, points[2].Y),
new PointF(points[3].X, points[3].Y)
};
transform.TransformPoints(points);
if (Enumerable.SequenceEqual(previousPoints, points))
{
break;
}
}
}
return bounds.Height / (points[2].Y - points[1].Y);
}
//New plan:
// scale the outer rectangle to always encompass ellipse
// cut the ellipse in half (either vertical or horizontal)
// determine the region on each side of the ellipse
private static IEnumerable<GraphicsPath> GetDifference(RectangleF subject, GraphicsPath clip)
{
var clipFlat = (GraphicsPath)clip.Clone();
clipFlat.Flatten();
var clipBounds = clipFlat.GetBounds();
var bounds = RectangleF.Union(subject, clipBounds);
bounds.Inflate(bounds.Width * .3f, bounds.Height * 0.3f);
var clipMidPoint = new PointF((clipBounds.Left + clipBounds.Right) / 2, (clipBounds.Top + clipBounds.Bottom) / 2);
var leftPoints = new List<PointF>();
var rightPoints = new List<PointF>();
foreach (var pt in clipFlat.PathPoints)
{
if (pt.X <= clipMidPoint.X)
{
leftPoints.Add(pt);
}
else
{
rightPoints.Add(pt);
}
}
leftPoints.Sort((p, q) => p.Y.CompareTo(q.Y));
rightPoints.Sort((p, q) => p.Y.CompareTo(q.Y));
var point = new PointF((leftPoints.Last().X + rightPoints.Last().X) / 2,
(leftPoints.Last().Y + rightPoints.Last().Y) / 2);
leftPoints.Add(point);
rightPoints.Add(point);
point = new PointF(point.X, bounds.Bottom);
leftPoints.Add(point);
rightPoints.Add(point);
leftPoints.Add(new PointF(bounds.Left, bounds.Bottom));
leftPoints.Add(new PointF(bounds.Left, bounds.Top));
rightPoints.Add(new PointF(bounds.Right, bounds.Bottom));
rightPoints.Add(new PointF(bounds.Right, bounds.Top));
point = new PointF((leftPoints.First().X + rightPoints.First().X) / 2, bounds.Top);
leftPoints.Add(point);
rightPoints.Add(point);
point = new PointF(point.X, (leftPoints.First().Y + rightPoints.First().Y) / 2);
leftPoints.Add(point);
rightPoints.Add(point);
var path = new GraphicsPath(FillMode.Winding);
path.AddPolygon(leftPoints.ToArray());
yield return path;
path.Reset();
path.AddPolygon(rightPoints.ToArray());
yield return path;
}
private static GraphicsPath CreateGraphicsPath(PointF origin, PointF centerPoint, float effectiveRadius)
{
var path = new GraphicsPath();
path.AddEllipse(
origin.X + centerPoint.X - effectiveRadius,
origin.Y + centerPoint.Y - effectiveRadius,
effectiveRadius * 2,
effectiveRadius * 2
);
return path;
}
private ColorBlend CalculateColorBlend(ISvgRenderer renderer, float opacity, float scale, out float outScale)
{
var colorBlend = GetColorBlend(renderer, opacity, true);
float newScale;
List<float> pos;
List<Color> colors;
outScale = scale;
if (scale > 1)
{
switch (this.SpreadMethod)
{
case SvgGradientSpreadMethod.Reflect:
newScale = (float)Math.Ceiling(scale);
pos = (from p in colorBlend.Positions select 1 + (p - 1) / newScale).ToList();
colors = colorBlend.Colors.ToList();
for (var i = 1; i < newScale; i++)
{
if (i % 2 == 1)
{
for (int j = 1; j < colorBlend.Positions.Length; j++)
{
pos.Insert(0, (newScale - i - 1) / newScale + 1 - colorBlend.Positions[j]);
colors.Insert(0, colorBlend.Colors[j]);
}
}
else
{
for (int j = 0; j < colorBlend.Positions.Length - 1; j++)
{
pos.Insert(j, (newScale - i - 1) / newScale + colorBlend.Positions[j]);
colors.Insert(j, colorBlend.Colors[j]);
}
}
}
colorBlend.Positions = pos.ToArray();
colorBlend.Colors = colors.ToArray();
outScale = newScale;
break;
case SvgGradientSpreadMethod.Repeat:
newScale = (float)Math.Ceiling(scale);
pos = (from p in colorBlend.Positions select p / newScale).ToList();
colors = colorBlend.Colors.ToList();
for (var i = 1; i < newScale; i++)
{
pos.AddRange(from p in colorBlend.Positions select (i + (p <= 0 ? 0.001f : p)) / newScale);
colors.AddRange(colorBlend.Colors);
}
colorBlend.Positions = pos.ToArray();
colorBlend.Colors = colors.ToArray();
outScale = newScale;
break;
default:
outScale = 1.0f;
//for (var i = 0; i < colorBlend.Positions.Length - 1; i++)
//{
// colorBlend.Positions[i] = 1 - (1 - colorBlend.Positions[i]) / scale;
//}
//colorBlend.Positions = new[] { 0F }.Concat(colorBlend.Positions).ToArray();
//colorBlend.Colors = new[] { colorBlend.Colors.First() }.Concat(colorBlend.Colors).ToArray();
break;
}
}
return colorBlend;
}
public override SvgElement DeepCopy()
{
return DeepCopy<SvgRadialGradientServer>();
}
public override SvgElement DeepCopy<T>()
{
var newObj = base.DeepCopy<T>() as SvgRadialGradientServer;
newObj.CenterX = this.CenterX;
newObj.CenterY = this.CenterY;
newObj.Radius = this.Radius;
newObj.FocalX = this.FocalX;
newObj.FocalY = this.FocalY;
return newObj;
}
}
}
| |
#define THE_SYMBOL
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using QUnit;
namespace CoreLib.TestScript.Reflection {
[TestFixture]
public class AttributeTests {
class A1Attribute : Attribute {
public int V { get; private set; }
public A1Attribute(int v) { V = v; }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class A2Attribute : Attribute {
public int V { get; private set; }
public A2Attribute(int v) { V = v; }
}
class A3Attribute : Attribute {
public int V { get; private set; }
public A3Attribute(int v) { V = v; }
}
class A4Attribute : Attribute {
public int V { get; private set; }
public A4Attribute(int v) { V = v; }
}
[AttributeUsage(AttributeTargets.All, Inherited = false)]
class A5Attribute : Attribute {}
class A6Attribute : Attribute {
public bool B { get; private set; }
public byte Y { get; private set; }
public char C { get; private set; }
public double D { get; private set; }
public float F { get; private set; }
public int I { get; private set; }
public long L { get; private set; }
public short H { get; private set; }
public E1 E { get; private set; }
public string S { get; private set; }
public object O { get; private set; }
public Type T { get; private set; }
public A6Attribute(bool b, byte y, char c, double d, float f, int i, long l, short h, E1 e, string s, object o, Type t) {
B = b;
Y = y;
C = c;
D = d;
F = f;
I = i;
L = l;
H = h;
E = e;
S = s;
O = o;
T = t;
}
}
class A7Attribute : Attribute {
public int[] I { get; private set; }
public string[] S { get; private set; }
public A7Attribute(int[] i, string[] s) {
I = i;
S = s;
}
}
class A8Attribute : Attribute {
public E2 E { get; private set; }
public A8Attribute(E2 e) {
E = e;
}
}
class A9Attribute : Attribute {
public int P1 { get; set; }
public int P2 { [InlineCode("{this}.$$XX$$")] get; [InlineCode("{this}.$$XX$$ = {value}")] set; }
[IntrinsicProperty] public int P3 { get; set; }
[NonScriptable] public int P4 { get; set; }
public int F1 { get; set; }
[NonScriptable] public int F2 { get; set; }
}
[NonScriptable]
class A10Attribute : Attribute {}
class A11Attribute : Attribute {
[PreserveName] public int i;
[ScriptName("")]
public A11Attribute() {}
[ScriptName("named")]
public A11Attribute(int i) {
this.i = i;
}
[InlineCode("{{ i: {i} }}")]
public A11Attribute(int i, string _) {}
}
[Conditional("THE_SYMBOL")]
class A12Attribute : Attribute {}
[Conditional("THE_SYMBOL"), Conditional("OTHER_SYMBOL")]
class A13Attribute : Attribute {}
[Conditional("OTHER_SYMBOL")]
class A14Attribute : Attribute {}
class C1 {}
[A1(1), A2(2)]
class C2 {}
[A1(1), A2(2)]
interface I1 {}
[A1(1), A2(2)]
enum E1 { V1 = 1, V2 = 2 }
[NamedValues]
enum E2 { V1, V2 }
[A3(3)]
class C3 : C2 {}
[A4(4)]
class C4 : C3 {}
[A1(5)]
class C5 : C2 {}
[A2(6)]
class C6 : C2 {}
[A5]
class C7 {}
class C8 : C7 {}
[A1(7), A2(8), A2(9), A3(10)]
class C9 {}
[A1(11)]
class C10<T1, T2> {}
[A1(12)]
class I2<T1, T2> {}
[A6(true, 43, '\x44', 45.5, 46.5f, 47, 48, 49, E1.V1, "Test_string", null, typeof(string))]
class C11 {}
[A7(new[] { 42, 17, 31 }, new[] { "X", "Y2", "Z3" })]
class C12 {}
[A8(E2.V2)]
class C13 {}
[A9(P1 = 42)]
class C14 {}
[A9(P2 = 18)]
class C15 {}
[A9(P3 = 43)]
class C16 {}
[A9(F1 = 13)]
class C18 {}
[A10, A1(12)]
class C19 {}
[A11(42)]
class C20 {}
[A11(18, "X")]
class C21 {}
[A12, A13, A14]
class C22 {
[A12, A13, A14] public void M() {}
}
[Test]
public void CanGetCustomTypeAttributesForTypeWithNoAttributes() {
var arr = typeof(C1).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 0, "Should have no attributes");
}
[Test]
public void CanGetCustomTypeAttributesForClassWithAttributes() {
var arr = typeof(C2).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 2, "Should have two attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute, "A2 should exist");
var a1 = (A1Attribute)(arr[0] is A1Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a1.V, 1);
var a2 = (A2Attribute)(arr[0] is A2Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a2.V, 2);
}
[Test]
public void NonScriptableAttributesAreNotIncluded() {
var arr = typeof(C19).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 1, "Should have one attribute");
Assert.IsTrue(arr[0] is A1Attribute, "A1 should exist");
}
[Test]
public void CanGetCustomTypeAttributesForInterfaceWithAttributes() {
var arr = typeof(I1).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 2, "Should have two attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute, "A2 should exist");
var a1 = (A1Attribute)(arr[0] is A1Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a1.V, 1);
var a2 = (A2Attribute)(arr[0] is A2Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a2.V, 2);
}
[Test]
public void CanGetCustomTypeAttributesForEnumWithAttributes() {
var arr = typeof(E1).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 2, "Should have two attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute, "A2 should exist");
var a1 = (A1Attribute)(arr[0] is A1Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a1.V, 1);
var a2 = (A2Attribute)(arr[0] is A2Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a2.V, 2);
}
[Test]
public void InheritedFlagToGetCustomAttributesWorks() {
var arr = typeof(C3).GetCustomAttributes(false);
Assert.AreEqual(arr.Length, 1, "Should have one non-inherited attribute");
Assert.IsTrue(arr[0] is A3Attribute);
arr = typeof(C3).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 3, "Should have three inherited attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute || arr[2] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute || arr[2] is A2Attribute, "A2 should exist");
Assert.IsTrue(arr[0] is A3Attribute || arr[1] is A3Attribute || arr[2] is A3Attribute, "A3 should exist");
}
[Test]
public void DeepInheritanceWorks() {
var arr = typeof(C4).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 4, "Should have 4 attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute || arr[2] is A1Attribute || arr[3] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute || arr[2] is A2Attribute || arr[3] is A2Attribute, "A2 should exist");
Assert.IsTrue(arr[0] is A3Attribute || arr[1] is A3Attribute || arr[2] is A3Attribute || arr[3] is A3Attribute, "A3 should exist");
Assert.IsTrue(arr[0] is A4Attribute || arr[1] is A4Attribute || arr[2] is A4Attribute || arr[3] is A4Attribute, "A4 should exist");
}
[Test]
public void OverridingSingleUseAttributeReplacesTheAttributeOnTheBaseClass() {
var arr = typeof(C5).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 2, "Should have 2 attributes");
Assert.IsTrue(arr[0] is A1Attribute || arr[1] is A1Attribute, "A1 should exist");
Assert.IsTrue(arr[0] is A2Attribute || arr[1] is A2Attribute, "A2 should exist");
var a1 = (A1Attribute)(arr[0] is A1Attribute ? arr[0] : arr[1]);
Assert.AreEqual(a1.V, 5);
}
[Test]
public void ApplyingNewInstanceOfMultipleUseAttributeAddsTheAttribute() {
var arr = typeof(C6).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 3, "Should have 2 attributes");
Assert.AreEqual(1, arr.Filter(a => a is A1Attribute).Length, "Should have one A1");
Assert.AreEqual(2, arr.Filter(a => a is A2Attribute).Length, "Should have two A2");
var a2 = (A2Attribute[])arr.Filter(a => a is A2Attribute);
Assert.IsTrue(a2[0].V == 2 || a2[1].V == 2);
Assert.IsTrue(a2[0].V == 6 || a2[1].V == 6);
}
[Test]
public void NonInheritedAttributeIsNotInherited() {
var arr = typeof(C8).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 0, "Should not have any attributes");
}
[Test]
public void GetCustomAttributesTypeFilterWorks() {
var arr = typeof(C9).GetCustomAttributes(typeof(A2Attribute), true);
Assert.AreEqual(arr.Length, 2, "Should have 2 A2 attributes");
Assert.IsTrue(arr[0] is A2Attribute && arr[1] is A2Attribute, "Should only return A2 attributes");
Assert.IsTrue(((A2Attribute)arr[0]).V == 8 || ((A2Attribute)arr[0]).V == 9, "Attribute members should be correct");
Assert.IsTrue(((A2Attribute)arr[1]).V == 8 || ((A2Attribute)arr[1]).V == 9, "Attribute members should be correct");
}
[Test]
public void GetCustomAttributesWorksForOpenGenericClass() {
var arr = typeof(C10<,>).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 1, "Should have one attribute");
Assert.IsTrue(arr[0] is A1Attribute, "Should be A1");
}
[Test]
public void GetCustomAttributesWorksForConstructedGenericClass() {
var arr = typeof(C10<int,string>).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 1, "Should have one attribute");
Assert.IsTrue(arr[0] is A1Attribute, "Should be A1");
}
[Test]
public void GetCustomAttributesWorksForOpenGenericInterface() {
var arr = typeof(I2<,>).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 1, "Should have one attribute");
Assert.IsTrue(arr[0] is A1Attribute, "Should be A1");
}
[Test]
public void GetCustomAttributesWorksForConstructedGenericInterface() {
var arr = typeof(I2<int,string>).GetCustomAttributes(true);
Assert.AreEqual(arr.Length, 1, "Should have one attribute");
Assert.IsTrue(arr[0] is A1Attribute, "Should be A1");
}
[Test]
public void AllSupportedScalarTypesCanBeUsedAsAttributeArguments() {
var a6 = (A6Attribute)typeof(C11).GetCustomAttributes(false)[0];
Assert.AreEqual(a6.B, true, "B");
Assert.AreEqual(a6.Y, 43, "Y");
Assert.AreEqual((int)a6.C, 0x44, "C");
Assert.AreEqual(a6.D, 45.5, "D");
Assert.AreEqual(a6.F, 46.5, "F");
Assert.AreEqual(a6.I, 47, "I");
Assert.AreEqual(a6.L, 48, "L");
Assert.AreEqual(a6.H, 49, "H");
Assert.AreEqual(a6.E, E1.V1, "E");
Assert.AreEqual(a6.S, "Test_string", "S");
Assert.AreEqual(a6.O, null, "O");
Assert.AreEqual(a6.T, typeof(string), "T");
}
[Test]
public void ArraysCanBeUsedAsAttributeArguments() {
var a7 = (A7Attribute)typeof(C12).GetCustomAttributes(false)[0];
Assert.AreEqual(a7.I, new[] { 42, 17, 31 }, "I");
Assert.AreEqual(a7.S, new[] { "X", "Y2", "Z3" }, "S");
}
[Test]
public void NamedValuesEnumCanBeUsedAsAttributeArgument() {
var a8 = (A8Attribute)typeof(C13).GetCustomAttributes(false)[0];
Assert.AreEqual(a8.E, "v2", "E");
}
[Test]
public void PropertiesWithSetMethodsImplementedAsNormalMethodsCanBeSetInAttributeDeclaration() {
var a = (A9Attribute)typeof(C14).GetCustomAttributes(false)[0];
Assert.AreEqual(a.P1, 42);
}
[Test]
public void PropertiesWithSetMethodsImplementedAsInlineCodeCanBeSetInAttributeDeclaration() {
var a = (A9Attribute)typeof(C15).GetCustomAttributes(false)[0];
Assert.AreEqual(a.P2, 18);
}
[Test]
public void PropertiesImplementedAsFieldsCanBeAssignedInAttributeDeclaration() {
var a = (A9Attribute)typeof(C16).GetCustomAttributes(false)[0];
Assert.AreEqual(a.P3, 43);
}
[Test]
public void FieldsCanBeAssignedInAttributeDeclaration() {
var a = (A9Attribute)typeof(C18).GetCustomAttributes(false)[0];
Assert.AreEqual(a.F1, 13);
}
[Test]
public void CreatingAttributeWithNamedConstructorWorks() {
var a = (A11Attribute)typeof(C20).GetCustomAttributes(false)[0];
Assert.AreEqual(a.i, 42);
}
[Test]
public void CreatingAttributeWithInlineCodeConstructorWorks() {
dynamic a = typeof(C21).GetCustomAttributes(false)[0];
Assert.AreEqual(a.i, 18);
}
[Test]
public void ConditionalAttributesWhoseSymbolsAreNotDefinedAreRemoved() {
Assert.AreEqual(typeof(C22).GetCustomAttributes(typeof(A12Attribute), false).Length, 1, "A12");
Assert.AreEqual(typeof(C22).GetCustomAttributes(typeof(A13Attribute), false).Length, 1, "A13");
Assert.AreEqual(typeof(C22).GetCustomAttributes(typeof(A14Attribute), false).Length, 0, "A14");
Assert.AreEqual(typeof(C22).GetMethod("M").GetCustomAttributes(typeof(A12Attribute), false).Length, 1, "A12");
Assert.AreEqual(typeof(C22).GetMethod("M").GetCustomAttributes(typeof(A13Attribute), false).Length, 1, "A13");
Assert.AreEqual(typeof(C22).GetMethod("M").GetCustomAttributes(typeof(A14Attribute), false).Length, 0, "A14");
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F10_City (editable child object).<br/>
/// This is a generated base class of <see cref="F10_City"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="F11_CityRoadObjects"/> of type <see cref="F11_CityRoadColl"/> (1:M relation to <see cref="F12_CityRoad"/>)<br/>
/// This class is an item of <see cref="F09_CityColl"/> collection.
/// </remarks>
[Serializable]
public partial class F10_City : BusinessBase<F10_City>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int parent_Region_ID = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID");
/// <summary>
/// Gets the Cities ID.
/// </summary>
/// <value>The Cities ID.</value>
public int City_ID
{
get { return GetProperty(City_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="City_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name");
/// <summary>
/// Gets or sets the Cities Name.
/// </summary>
/// <value>The Cities Name.</value>
public string City_Name
{
get { return GetProperty(City_NameProperty); }
set { SetProperty(City_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F11_City_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F11_City_Child> F11_City_SingleObjectProperty = RegisterProperty<F11_City_Child>(p => p.F11_City_SingleObject, "F11 City Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F11 City Single Object ("parent load" child property).
/// </summary>
/// <value>The F11 City Single Object.</value>
public F11_City_Child F11_City_SingleObject
{
get { return GetProperty(F11_City_SingleObjectProperty); }
private set { LoadProperty(F11_City_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F11_City_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F11_City_ReChild> F11_City_ASingleObjectProperty = RegisterProperty<F11_City_ReChild>(p => p.F11_City_ASingleObject, "F11 City ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F11 City ASingle Object ("parent load" child property).
/// </summary>
/// <value>The F11 City ASingle Object.</value>
public F11_City_ReChild F11_City_ASingleObject
{
get { return GetProperty(F11_City_ASingleObjectProperty); }
private set { LoadProperty(F11_City_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F11_CityRoadObjects"/> property.
/// </summary>
public static readonly PropertyInfo<F11_CityRoadColl> F11_CityRoadObjectsProperty = RegisterProperty<F11_CityRoadColl>(p => p.F11_CityRoadObjects, "F11 CityRoad Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the F11 City Road Objects ("parent load" child property).
/// </summary>
/// <value>The F11 City Road Objects.</value>
public F11_CityRoadColl F11_CityRoadObjects
{
get { return GetProperty(F11_CityRoadObjectsProperty); }
private set { LoadProperty(F11_CityRoadObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F10_City"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F10_City"/> object.</returns>
internal static F10_City NewF10_City()
{
return DataPortal.CreateChild<F10_City>();
}
/// <summary>
/// Factory method. Loads a <see cref="F10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F10_City"/> object.</returns>
internal static F10_City GetF10_City(SafeDataReader dr)
{
F10_City obj = new F10_City();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(F11_CityRoadObjectsProperty, F11_CityRoadColl.NewF11_CityRoadColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F10_City"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F10_City()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F10_City"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(F11_City_SingleObjectProperty, DataPortal.CreateChild<F11_City_Child>());
LoadProperty(F11_City_ASingleObjectProperty, DataPortal.CreateChild<F11_City_ReChild>());
LoadProperty(F11_CityRoadObjectsProperty, DataPortal.CreateChild<F11_CityRoadColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F10_City"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_IDProperty, dr.GetInt32("City_ID"));
LoadProperty(City_NameProperty, dr.GetString("City_Name"));
// parent properties
parent_Region_ID = dr.GetInt32("Parent_Region_ID");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="F11_City_Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F11_City_Child child)
{
LoadProperty(F11_City_SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="F11_City_ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F11_City_ReChild child)
{
LoadProperty(F11_City_ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="F10_City"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F08_Region parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddF10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Region_ID", parent.Region_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(City_IDProperty, (int) cmd.Parameters["@City_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F10_City"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateF10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Name", ReadProperty(City_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="F10_City"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteF10_City", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID", ReadProperty(City_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(F11_City_SingleObjectProperty, DataPortal.CreateChild<F11_City_Child>());
LoadProperty(F11_City_ASingleObjectProperty, DataPortal.CreateChild<F11_City_ReChild>());
LoadProperty(F11_CityRoadObjectsProperty, DataPortal.CreateChild<F11_CityRoadColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/* Copyright (C) 2014 Newcastle University
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
using System;
using System.Collections.Generic;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Support.V7.Widget;
using Bootleg.API;
using Android.Support.V4.Widget;
using System.Threading;
using System.Threading.Tasks;
using Square.Picasso;
using Bootleg.Droid.UI;
using Android.Content;
using static Android.Support.V7.Widget.GridLayoutManager;
using Android.App;
using Bootleg.API.Model;
namespace Bootleg.Droid
{
public class EventListFragment : Android.Support.V4.App.Fragment,IImagePausable
{
public event Action<Shoot> OnConnect;
public event Action<Shoot> OnSub;
public event Action<Shoot> OnReview;
public event Action OnStartNew;
bool loadedalready = false;
List<Shoot> events = new List<Shoot>();
public EventListFragment()
{
events = new List<Shoot>();
}
public EventListFragment(EventAdapter.EventViewType ev)
{
events = new List<Shoot>();
this.eventviewtype = ev;
}
public override void OnPause()
{
try
{
cancel.Cancel();
}
catch{
}
base.OnPause();
}
Shoot parent;
//EventAdapter.EventViewType viewtype;
public void LoadEvents(List<Shoot> events, Shoot parent, EventAdapter.EventViewType ev)
{
this.events = events;
this.parent = parent;
this.eventviewtype = ev;
if (listAdapter == null)
listAdapter = new EventAdapter(Activity);
listAdapter.UpdateData(events,ev);
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
EventAdapter listAdapter;
public void SetFilter(string q)
{
listAdapter.SetFilter(q);
}
public void ClearFilter()
{
listAdapter.FlushFilter();
}
CancellationTokenSource cancel = new CancellationTokenSource();
public delegate Task EventUpdateDelegate(CancellationToken cancel);
private EventUpdateDelegate updater;
private string propertyname;
private EventAdapter.EventViewType eventviewtype;
private CancellationToken canceller;
public void SetEvents(string propertyname,EventUpdateDelegate updater,CancellationToken cancel, EventAdapter.EventViewType viewtype)
{
this.updater = updater;
this.propertyname = propertyname;
this.eventviewtype = viewtype;
this.canceller = cancel;
this.eventviewtype = viewtype;
}
public async Task RefreshMe(bool manually)
{
try
{
if (!string.IsNullOrEmpty(propertyname))
{
if (listAdapter == null)
listAdapter = new EventAdapter(Activity);
listAdapter.FlushFilter();
events = Bootlegger.BootleggerClient.GetType().GetProperty(propertyname).GetValue(Bootlegger.BootleggerClient) as List<Shoot>;
//events = data;
listAdapter.UpdateData(events, eventviewtype);
//run loader on initial set:
Loading = true;
if (manually)
{
if ((Context.ApplicationContext as BootleggerApp).IsReallyConnected)
{
try
{
await updater(canceller);
}
catch (TaskCanceledException)
{
//do nothing...
}
catch (Exception e)
{
OnError?.Invoke(e);
}
}
events = Bootlegger.BootleggerClient.GetType().GetProperty(propertyname).GetValue(Bootlegger.BootleggerClient) as List<Shoot>;
listAdapter.UpdateData(events, eventviewtype);
}
//listAdapter.UpdateData(events, eventviewtype);
Loading = false;
// Whitelabel - if there is only 1 event:
if (eventviewtype == EventAdapter.EventViewType.FEATURED && WhiteLabelConfig.ALLOW_SINGLE_SHOOT)
{
if (events.Count == 1 && Bootlegger.BootleggerClient.CurrentUser != null)
{
var diag = new Android.Support.V7.App.AlertDialog.Builder(Context)
.SetTitle(Resource.String.single_shoot_title)
.SetMessage(Resource.String.single_shoot_msg)
.SetPositiveButton(Resource.String.continuebtn, (o, e) =>
{
var ev = events[0];
OnConnect((string.IsNullOrEmpty(ev.group)) ? ev : ev.events[0]);
})
.SetNegativeButton(Android.Resource.String.Cancel, (o, e) =>
{
})
.Show();
}
}
}
}
catch (Exception e)
{
if (Activity != null)
{
//failed to refresh for some reason
OnError?.Invoke(e);
}
}
}
public event Action<Exception> OnError;
private bool Loading
{
set
{
if (value)
{
try
{
try
{
//View.FindViewById<View>(Resource.Id.empty).Visibility = ViewStates.Gone;
//View.FindViewById<View>(Resource.Id.makenew).Visibility = ViewStates.Gone;
//View.FindViewById<View>(Resource.Id.swiperefresh).Visibility = ViewStates.Gone;
}
catch (Exception)
{
}
View.FindViewById<ProgressBar>(Resource.Id.loading).Visibility = ViewStates.Visible;
}
catch { }
}
else
{
try {
View.FindViewById<ProgressBar>(Resource.Id.loading).Visibility = ViewStates.Gone;
//View.FindViewById<View>(Resource.Id.swiperefresh).Visibility = ViewStates.Visible;
}
catch
{
}
}
}
}
async void Events_Refresh(object sender, EventArgs e)
{
try
{
try
{
await updater(canceller);
}
catch (TaskCanceledException)
{
//do nothing...
}
catch (Exception ex)
{
OnError?.Invoke(ex);
}
if (parent==null)
{
LoadEvents(Bootlegger.BootleggerClient.GetType().GetProperty(propertyname).GetValue(Bootlegger.BootleggerClient) as List<Shoot>,null, eventviewtype);
}
else
{
LoadEvents((Bootlegger.BootleggerClient.GetType().GetProperty(propertyname).GetValue(Bootlegger.BootleggerClient) as List<Shoot>).Find(ec=> ec.group == parent.group ).events, parent, eventviewtype);
}
}
catch (Exception ex)
{
try {
LoginFuncs.ShowError(Activity, ex);
}
catch
{
//failed if fragment destroyed
}
}
finally
{
theview.FindViewById<SwipeRefreshLayout>(Resource.Id.swiperefresh).Refreshing = false;
}
}
View theview;
RecyclerView listview;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.EventList, container, false);
listview = view.FindViewById<RecyclerView>(Resource.Id.eventsView);
if (Context.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
{
listview.LayoutParameters.Height = LayoutParams.WrapContent;
}
theview = view;
listAdapter = new EventAdapter(container.Context);
listAdapter.UpdateData(events, eventviewtype);
listAdapter.Capture += ListAdapter_Capture;
listAdapter.Edit += ListAdapter_Edit;
listAdapter.Share += ListAdapter_Share;
listAdapter.ShowMore += ListAdapter_ShowMore;
listAdapter.MakeShoot += ListAdapter_MakeShoot;
listAdapter.OnEnterCode += ListAdapter_OnEnterCode;
listAdapter.HasStableIds = true;
// use a linear layout manager
if (eventviewtype == EventAdapter.EventViewType.FEATURED)
{
var lm = new LinearLayoutManager(Context, (int)Orientation.Horizontal, false);
listview.SetLayoutManager(lm);
view.FindViewById<SwipeRefreshLayout>(Resource.Id.swiperefresh).Enabled = false;
listview.SetPadding(Utils.dp2px(Context, 30), 0, Utils.dp2px(Context, 30), 0);
listview.NestedScrollingEnabled = true;
}
else
{
var mLayoutManager = new GridLayoutManager(container.Context, Activity.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape ? 2 : 1);
mLayoutManager.SetSpanSizeLookup(new MySpanSizeLookup(Activity,listAdapter));
listview.SetLayoutManager(mLayoutManager);
}
if (eventviewtype == EventAdapter.EventViewType.NEARBY_SINGLE)
{
//do nothing?
var lm = new LinearLayoutManager(Context, (int)Orientation.Horizontal, false);
listview.SetLayoutManager(lm);
view.FindViewById<SwipeRefreshLayout>(Resource.Id.swiperefresh).Enabled = false;
}
listview.SetAdapter(listAdapter);
listview.AddOnScrollListener(new PausableScrollListener(Context,listAdapter));
view.FindViewById<SwipeRefreshLayout>(Resource.Id.swiperefresh).Refresh += Events_Refresh;
view.FindViewById<View>(Resource.Id.swiperefresh).Visibility = ViewStates.Visible;
return view;
}
private void ListAdapter_OnEnterCode(string obj)
{
OnEnterCode?.Invoke(obj);
}
private class MySpanSizeLookup : SpanSizeLookup
{
EventAdapter adapter;
Activity activity;
public MySpanSizeLookup(Activity activity, EventAdapter adapter)
{
this.adapter = adapter;
this.activity = activity;
}
public override int GetSpanSize(int position)
{
//if (adapter)
//return activity.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape ? 1 : 2;
if (adapter.GetItemViewType(position) == (int)EventAdapter.TileType.EVENT)
return 1;
else
return activity.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape ? 2 : 1;
//return ((adapter.GetItemViewType(position) == (int)EventAdapter.TileType.ENTERCODE) || (adapter.GetItemViewType(position) == (int)EventAdapter.TileType.EMPTY) || (adapter.GetItemViewType(position) == (int)EventAdapter.TileType.NEWSHOOT)) ? 2 : 1;
}
}
private void ListAdapter_Share(Shoot obj)
{
Intent sharingIntent = new Intent(Intent.ActionSend);
sharingIntent.SetType("text/plain");
sharingIntent.PutExtra(Intent.ExtraSubject, obj.name);
sharingIntent.PutExtra(Intent.ExtraText, Bootlegger.BootleggerClient.server + "/s/" + obj.offlinecode);
//StartActivity(Intent.CreateChooser(sharingIntent, Resources.GetString(Resource.String.sharevia)));
}
private void ListAdapter_MakeShoot()
{
OnStartNew?.Invoke();
}
public override void OnStart()
{
base.OnStart();
}
public event Action OnShowMore;
public event Action<string> OnEnterCode;
private void ListAdapter_ShowMore()
{
OnShowMore?.Invoke();
}
private void ListAdapter_Edit(object sender, Shoot e)
{
OnReview?.Invoke(e);
}
public async override void OnResume()
{
base.OnResume();
if (!loadedalready)
{
await RefreshMe(false);
loadedalready = true;
await RefreshMe(true);
}
else
{
await RefreshMe(false);
}
}
private void ListAdapter_Capture(object sender, Shoot e)
{
if (e.group != null)
{
OnSub?.Invoke(e);
}
else
{
OnConnect?.Invoke(e);
}
}
public void Pause()
{
Picasso.With(Context).PauseTag(listAdapter);
}
public void Resume()
{
Picasso.With(Context).ResumeTag(listAdapter);
}
}
}
| |
using System;
using System.Collections.Generic;
public class GuidEquals1
{
public static int Main()
{
GuidEquals1 ac = new GuidEquals1();
TestLibrary.TestFramework.BeginTestCase("GuidEquals1");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Guid g1;
Guid g2;
int a;
short b;
short c;
byte[] d;
bool compare;
TestLibrary.TestFramework.BeginScenario("PosTest1: Guid.Equals(object) always equals");
try
{
d = new byte[8];
for(int i=0;i<d.Length; i++) d[i] = TestLibrary.Generator.GetByte(-55);
a = TestLibrary.Generator.GetInt32(-55);
b = TestLibrary.Generator.GetInt16(-55);
c = TestLibrary.Generator.GetInt16(-55);
g1 = new Guid(a, b, c, d);
// equals
g2 = new Guid(a, b, c, d);
compare = g1.Equals((object)g2);
if (!compare)
{
TestLibrary.TestFramework.LogError("000", "Guid1: " + g1);
TestLibrary.TestFramework.LogError("001", "Guid2: " + g2);
TestLibrary.TestFramework.LogError("002", "Compare failed");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Guid g;
byte[] b;
bool compare;
object obj;
TestLibrary.TestFramework.BeginScenario("PosTest2: Guid.Equals(object) object is null");
try
{
b = new byte[16];
for(int i=0;i<b.Length; i++) b[i] = TestLibrary.Generator.GetByte(-55);
g = new Guid(b);
obj = null;
compare = g.Equals(obj);
if (compare)
{
TestLibrary.TestFramework.LogError("004", "Compare succeed unexpectedly");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Guid g1;
Guid g2;
int a;
short b;
short c;
byte[] d;
bool compare;
TestLibrary.TestFramework.BeginScenario("PosTest3: Guid.Equals(object) always less than");
try
{
for (int i=0; i<11; i++)
{
d = new byte[8];
for(int j=0;j<d.Length; j++) d[j] = (byte)(Math.Abs(TestLibrary.Generator.GetByte(-55) - 1) + 1);
a = Math.Abs(TestLibrary.Generator.GetInt32(-55) - 1) + 1;
b = (short)(Math.Abs(TestLibrary.Generator.GetInt16(-55) - 1) + 1);
c = (short)(Math.Abs(TestLibrary.Generator.GetInt16(-55) - 1) + 1);
g1 = new Guid(a, b, c, d);
// less than
switch (i)
{
case 0:
g2 = new Guid(a-1, b, c, d);
break;
case 1:
g2 = new Guid(a, (short)(b-1), c, d);
break;
case 2:
g2 = new Guid(a, b, (short)(c-1), d);
break;
default:
d[i-3] = (byte)(d[i-3] - 1);
g2 = new Guid(a, b, c, d);
break;
}
compare = g1.Equals((object)g2);
if (compare)
{
TestLibrary.TestFramework.LogError("006", "Guid1: " + g1);
TestLibrary.TestFramework.LogError("007", "Guid2: " + g2);
TestLibrary.TestFramework.LogError("008", "Compare succeed unexpectedly");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Guid g1;
Guid g2;
int a;
short b;
short c;
byte[] d;
bool compare;
TestLibrary.TestFramework.BeginScenario("PosTest4: Guid.Equals(object) always greater than");
try
{
for (int i=0; i<11; i++)
{
d = new byte[8];
for(int j=0;j<d.Length; j++) d[j] = (byte)(Math.Abs(TestLibrary.Generator.GetByte(-55) - 1));
a = Math.Abs(TestLibrary.Generator.GetInt32(-55) - 1);
b = (short)(Math.Abs(TestLibrary.Generator.GetInt16(-55) - 1));
c = (short)(Math.Abs(TestLibrary.Generator.GetInt16(-55) - 1));
g1 = new Guid(a, b, c, d);
// less than
switch (i)
{
case 0:
g2 = new Guid(a+1, b, c, d);
break;
case 1:
g2 = new Guid(a, (short)(b+1), c, d);
break;
case 2:
g2 = new Guid(a, b, (short)(c+1), d);
break;
default:
d[i-3] = (byte)(d[i-3] + 1);
g2 = new Guid(a, b, c, d);
break;
}
compare = g1.Equals((object)g2);
if (compare)
{
TestLibrary.TestFramework.LogError("010", "Guid1: " + g1);
TestLibrary.TestFramework.LogError("011", "Guid2: " + g2);
TestLibrary.TestFramework.LogError("012", "Compare succeed unexpectedly");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
Guid g;
byte[] b;
bool compare;
TestLibrary.TestFramework.BeginScenario("PosTest5: Guid.Equals(object) object is not a Guid");
try
{
b = new byte[16];
for(int i=0;i<b.Length; i++) b[i] = TestLibrary.Generator.GetByte(-55);
g = new Guid(b);
compare = g.Equals((object)this);
if (compare)
{
TestLibrary.TestFramework.LogError("014", "Compare succeed unexpectedly");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
using System.Drawing;
using System.Windows.Forms;
namespace ToolStripCustomizer.ColorTables
{
sealed class Office2007ColorTable : PresetColorTable
{
public Office2007ColorTable()
: base("Office 2007 Azure")
{
}
public override Color ButtonSelectedBorder
{
get
{
return Color.FromArgb(255, 255, 189, 105);
}
}
public override Color ButtonCheckedGradientBegin
{
get
{
return Color.FromArgb(255, 255, 207, 146);
}
}
public override Color ButtonCheckedGradientMiddle
{
get
{
return Color.FromArgb(255, 255, 189, 105);
}
}
public override Color ButtonCheckedGradientEnd
{
get
{
return Color.FromArgb(255, 255, 175, 73);
}
}
public override Color ButtonSelectedGradientBegin
{
get
{
return Color.FromArgb(255, 255, 245, 204);
}
}
public override Color ButtonSelectedGradientMiddle
{
get
{
return Color.FromArgb(255, 255, 230, 162);
}
}
public override Color ButtonSelectedGradientEnd
{
get
{
return Color.FromArgb(255, 255, 218, 117);
}
}
public override Color ButtonPressedGradientBegin
{
get
{
return Color.FromArgb(255, 252, 151, 61);
}
}
public override Color ButtonPressedGradientMiddle
{
get
{
return Color.FromArgb(255, 255, 171, 63);
}
}
public override Color ButtonPressedGradientEnd
{
get
{
return Color.FromArgb(255, 255, 184, 94);
}
}
public override Color CheckBackground
{
get
{
return Color.FromArgb(255, 255, 215, 166);
}
}
public override Color CheckSelectedBackground
{
get
{
return Color.FromArgb(255, 255, 215, 166);
}
}
public override Color CheckPressedBackground
{
get
{
return Color.FromArgb(255, 253, 170, 96);
}
}
public override Color GripDark
{
get
{
return Color.FromArgb(255, 111, 157, 217);
}
}
public override Color GripLight
{
get
{
return Color.FromArgb(255, 255, 255, 255);
}
}
public override Color ImageMarginGradientBegin
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color ImageMarginGradientMiddle
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color ImageMarginGradientEnd
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color ImageMarginRevealedGradientBegin
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color ImageMarginRevealedGradientMiddle
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color ImageMarginRevealedGradientEnd
{
get
{
return Color.FromArgb(255, 233, 238, 238);
}
}
public override Color MenuStripGradientBegin
{
get
{
return Color.FromArgb(255, 191, 219, 255);
}
}
public override Color MenuStripGradientEnd
{
get
{
return Color.FromArgb(255, 191, 219, 255);
}
}
public override Color MenuItemSelected
{
get
{
return Color.FromArgb(255, 255, 231, 162);
}
}
public override Color MenuItemBorder
{
get
{
return Color.FromArgb(255, 255, 189, 105);
}
}
public override Color MenuBorder
{
get
{
return Color.FromArgb(255, 101, 147, 207);
}
}
public override Color MenuItemSelectedGradientBegin
{
get
{
return Color.FromArgb(255, 255, 245, 204);
}
}
public override Color MenuItemSelectedGradientEnd
{
get
{
return Color.FromArgb(255, 255, 218, 117);
}
}
public override Color MenuItemPressedGradientBegin
{
get
{
return Color.FromArgb(255, 226, 239, 255);
}
}
public override Color MenuItemPressedGradientMiddle
{
get
{
return Color.FromArgb(255, 190, 215, 247);
}
}
public override Color MenuItemPressedGradientEnd
{
get
{
return Color.FromArgb(255, 153, 191, 240);
}
}
public override Color RaftingContainerGradientBegin
{
get
{
return Color.FromArgb(255, 255, 255, 255);
}
}
public override Color RaftingContainerGradientEnd
{
get
{
return Color.FromArgb(255, 255, 255, 255);
}
}
public override Color SeparatorDark
{
get
{
return Color.FromArgb(255, 157, 201, 255);
}
}
public override Color SeparatorLight
{
get
{
return Color.FromArgb(255, 255, 255, 255);
}
}
public override Color StatusStripGradientBegin
{
get
{
return Color.FromArgb(255, 227, 239, 255);
}
}
public override Color StatusStripGradientEnd
{
get
{
return Color.FromArgb(255, 177, 211, 255);
}
}
public override Color ToolStripBorder
{
get
{
return Color.FromArgb(255, 111, 157, 217);
}
}
public override Color ToolStripDropDownBackground
{
get
{
return Color.FromArgb(255, 246, 246, 246);
}
}
public override Color ToolStripGradientBegin
{
get
{
return Color.FromArgb(255, 227, 239, 255);
}
}
public override Color ToolStripGradientMiddle
{
get
{
return Color.FromArgb(255, 218, 234, 255);
}
}
public override Color ToolStripGradientEnd
{
get
{
return Color.FromArgb(255, 177, 211, 255);
}
}
public override Color ToolStripContentPanelGradientBegin
{
get
{
return Color.FromArgb(255, 215, 232, 255);
}
}
public override Color ToolStripContentPanelGradientEnd
{
get
{
return Color.FromArgb(255, 111, 157, 217);
}
}
public override Color ToolStripPanelGradientBegin
{
get
{
return Color.FromArgb(255, 191, 219, 255);
}
}
public override Color ToolStripPanelGradientEnd
{
get
{
return Color.FromArgb(255, 191, 219, 255);
}
}
public override Color OverflowButtonGradientBegin
{
get
{
return Color.FromArgb(255, 215, 232, 255);
}
}
public override Color OverflowButtonGradientMiddle
{
get
{
return Color.FromArgb(255, 167, 204, 251);
}
}
public override Color OverflowButtonGradientEnd
{
get
{
return Color.FromArgb(255, 111, 157, 217);
}
}
}
}
| |
using Signum.Engine.Migrations;
using Signum.Entities.Authorization;
using Signum.Entities.Dynamic;
using System.IO;
namespace Signum.Engine.Dynamic;
public static class DynamicSqlMigrationLogic
{
[AutoExpressionField]
public static bool IsApplied(this DynamicRenameEntity r) =>
As.Expression(() => Database.Query<DynamicSqlMigrationEntity>().Any(m => m.CreationDate > r.CreationDate));
public static StringBuilder? CurrentLog = null;
public static string? LastLog;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<DynamicRenameEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.CreationDate,
e.ReplacementKey,
e.OldName,
e.NewName,
IsApplied = e.IsApplied(),
});
sb.Include<DynamicSqlMigrationEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.CreationDate,
e.CreatedBy,
e.ExecutionDate,
e.ExecutedBy,
e.Comment,
});
new Graph<DynamicSqlMigrationEntity>.Construct(DynamicSqlMigrationOperation.Create)
{
Construct = args =>
{
if (DynamicLogic.CodeGenError!= null)
throw new InvalidOperationException(DynamicSqlMigrationMessage.PreventingGenerationNewScriptBecauseOfErrorsInDynamicCodeFixErrorsAndRestartServer.NiceToString());
var old = Replacements.AutoReplacement;
var lastRenames = Database.Query<DynamicRenameEntity>()
.Where(a => !a.IsApplied())
.OrderBy(a => a.CreationDate)
.ToList();
try
{
if (Replacements.AutoReplacement == null)
Replacements.AutoReplacement = ctx =>
{
var currentName =
ctx.ReplacementKey.StartsWith(Replacements.KeyEnumsForTable("")) ? AutoReplacementEnums(ctx):
ctx.ReplacementKey.StartsWith(PropertyRouteLogic.PropertiesFor.FormatWith("")) ? DynamicAutoReplacementsProperties(ctx, lastRenames) :
ctx.ReplacementKey.StartsWith(Replacements.KeyColumnsForTable("")) ? DynamicAutoReplacementsColumns(ctx, lastRenames) :
ctx.ReplacementKey == Replacements.KeyTables ? DynamicAutoReplacementsSimple(ctx, lastRenames, Replacements.KeyTables) :
ctx.ReplacementKey == typeof(OperationSymbol).Name ? DynamicAutoReplacementsOperations(ctx, lastRenames) :
ctx.ReplacementKey == QueryLogic.QueriesKey ? DynamicAutoReplacementsSimple(ctx, lastRenames, DynamicTypeLogic.TypeNameKey) :
DynamicAutoReplacementsSimple(ctx, lastRenames, ctx.ReplacementKey);
if (currentName != null)
return new Replacements.Selection(ctx.OldValue, currentName);
return new Replacements.Selection(ctx.OldValue, null);
};
var script = Schema.Current.SynchronizationScript(interactive: false, replaceDatabaseName: SqlMigrationRunner.DatabaseNameReplacement);
return new DynamicSqlMigrationEntity
{
CreationDate = Clock.Now,
CreatedBy = UserEntity.Current.ToLite(),
Script = script?.ToString() ?? "",
};
}
finally
{
Replacements.AutoReplacement = old;
}
}
}.Register();
new Graph<DynamicSqlMigrationEntity>.Execute(DynamicSqlMigrationOperation.Save)
{
CanExecute = a=> a.ExecutionDate == null ? null : DynamicSqlMigrationMessage.TheMigrationIsAlreadyExecuted.NiceToString(),
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) => { }
}.Register();
new Graph<DynamicSqlMigrationEntity>.Execute(DynamicSqlMigrationOperation.Execute)
{
CanExecute = a => a.ExecutionDate == null ? null : DynamicSqlMigrationMessage.TheMigrationIsAlreadyExecuted.NiceToString(),
Execute = (e, _) => {
if (CurrentLog != null)
throw new InvalidOperationException("There is already a migration running");
e.ExecutionDate = Clock.Now;
e.ExecutedBy = UserEntity.Current.ToLite();
var oldOut = Console.Out;
try
{
CurrentLog = new StringBuilder();
LastLog = null;
Console.SetOut(new SynchronizedStringWriter(CurrentLog!));
string title = e.CreationDate + (e.Comment.HasText() ? " ({0})".FormatWith(e.Comment) : null);
using (var tr = Transaction.ForceNew(System.Data.IsolationLevel.Unspecified))
{
SqlPreCommandExtensions.ExecuteScript(title, e.Script);
tr.Commit();
}
}
catch(ExecuteSqlScriptException ex)
{
ex.InnerException!.PreserveStackTrace();
throw ex.InnerException!;
}
finally
{
LastLog = CurrentLog?.ToString();
CurrentLog = null;
Console.SetOut(oldOut);
}
}
}.Register();
new Graph<DynamicSqlMigrationEntity>.Delete(DynamicSqlMigrationOperation.Delete)
{
CanDelete = a => a.ExecutionDate == null ? null : DynamicSqlMigrationMessage.TheMigrationIsAlreadyExecuted.NiceToString(),
Delete = (e, _) => { e.Delete(); }
}.Register();
}
}
public static void AddDynamicRename(string replacementKey, string oldName, string newName)
{
new DynamicRenameEntity { ReplacementKey = replacementKey, OldName = oldName, NewName = newName }.Save();
}
private static string AutoReplacementEnums(Replacements.AutoReplacementContext ctx)
{
StringDistance sd = new StringDistance();
return ctx.NewValues!.MinBy(nv => sd.LevenshteinDistance(nv, ctx.OldValue))!;
}
public static string? DynamicAutoReplacementsSimple(Replacements.AutoReplacementContext ctx, List<DynamicRenameEntity> lastRenames, string replacementKey)
{
var list = lastRenames.Where(a => a.ReplacementKey == replacementKey).ToList();
var currentName = ctx.OldValue;
foreach (var r in list)
{
if (r.OldName == currentName)
currentName = r.NewName;
}
if (ctx.NewValues!.Contains(currentName))
return currentName;
return null;
}
public static string? DynamicAutoReplacementsOperations(Replacements.AutoReplacementContext ctx, List<DynamicRenameEntity> lastRenames)
{
var typeReplacements = lastRenames.Where(a => a.ReplacementKey == DynamicTypeLogic.TypeNameKey).ToList();
var typeName = ctx.OldValue.TryBefore("Operation.");
if (typeName == null)
return null;
foreach (var r in typeReplacements)
{
if (r.OldName == typeName)
typeName = r.NewName;
}
var newName = typeName + "Operation." + ctx.OldValue.After("Operation.");
if (ctx.NewValues!.Contains(newName))
return newName;
return null;
}
public static string? DynamicAutoReplacementsProperties(Replacements.AutoReplacementContext ctx, List<DynamicRenameEntity> lastRenames)
{
var prefix = ctx.ReplacementKey.Before(":");
var tableNames = GetAllRenames(ctx.ReplacementKey.After(":"), DynamicTypeLogic.TypeNameKey, lastRenames);
var allKeys = tableNames.Select(tn => prefix + ":" + tn).And(DynamicTypeLogic.UnknownPropertyKey).ToList();
var list = lastRenames.Where(a => allKeys.Contains(a.ReplacementKey)).ToList();
var currentName = ctx.OldValue;
foreach (var r in list)
{
if (currentName.Split('.').Contains(r.OldName))
currentName = currentName.Split('.').Select(p => p == r.OldName ? r.NewName : p).ToString(".");
}
if (ctx.NewValues!.Contains(currentName))
return currentName;
return null;
}
public static string? DynamicAutoReplacementsColumns(Replacements.AutoReplacementContext ctx, List<DynamicRenameEntity> lastRenames)
{
var prefix = ctx.ReplacementKey.Before(":");
var tableNames = GetAllRenames(ctx.ReplacementKey.After(":"), Replacements.KeyTables, lastRenames);
var allKeys = tableNames.Select(tn => prefix + ":" + tn).And(DynamicTypeLogic.UnknownColumnKey).ToList();
var list = lastRenames.Where(a => allKeys.Contains(a.ReplacementKey)).ToList();
var currentName = ctx.OldValue;
foreach (var r in list)
{
if (currentName.Split('_').Contains(r.OldName))
currentName = currentName.Split('_').Select(p => p == r.OldName ? r.NewName : p).ToString("_");
}
if (ctx.NewValues!.Contains(currentName))
return currentName;
return null;
}
private static List<string> GetAllRenames(string lastName, string replacementKey, List<DynamicRenameEntity> lastRenames)
{
var currentTypeName = lastName;
var typeRenames = lastRenames.Where(a => a.ReplacementKey == replacementKey);
List<string> allTypeNames = new List<string> { currentTypeName };
foreach (var item in typeRenames.Reverse())
{
if (item.NewName == currentTypeName)
{
currentTypeName = item.OldName;
allTypeNames.Add(currentTypeName);
}
}
return allTypeNames;
}
public static string? GetLog()
{
var ll = LastLog;
var sb = CurrentLog;
if (ll != null)
return ll;
if (sb != null)
{
lock (sb)
return sb.ToString();
}
return null;
}
internal class SynchronizedStringWriter : TextWriter
{
private StringBuilder stringBuilder;
public SynchronizedStringWriter(StringBuilder currentLog)
{
this.stringBuilder = currentLog;
}
public override Encoding Encoding => Encoding.Unicode;
public override void Write(char value)
{
lock (stringBuilder)
base.Write(value);
}
public override void WriteLine()
{
lock (stringBuilder)
base.WriteLine();
}
public override void Write(string? value)
{
lock (stringBuilder)
base.Write(value);
}
}
}
| |
using Orleans.CodeGenerator.SyntaxGeneration;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using static Orleans.CodeGenerator.InvokableGenerator;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Orleans.CodeGenerator
{
internal static class SerializerGenerator
{
private const string BaseTypeSerializerFieldName = "_baseTypeSerializer";
private const string ActivatorFieldName = "_activator";
private const string SerializeMethodName = "Serialize";
private const string DeserializeMethodName = "Deserialize";
private const string WriteFieldMethodName = "WriteField";
private const string ReadValueMethodName = "ReadValue";
private const string CodecFieldTypeFieldName = "_codecFieldType";
public static ClassDeclarationSyntax GenerateSerializer(LibraryTypes libraryTypes, ISerializableTypeDescription type)
{
var simpleClassName = GetSimpleClassName(type);
var members = new List<ISerializableMember>();
foreach (var member in type.Members)
{
if (member is ISerializableMember serializable)
{
members.Add(serializable);
}
else if (member is IFieldDescription or IPropertyDescription)
{
members.Add(new SerializableMember(libraryTypes, type, member, members.Count));
}
else if (member is MethodParameterFieldDescription methodParameter)
{
members.Add(new SerializableMethodMember(methodParameter));
}
}
var fieldDescriptions = GetFieldDescriptions(type, members, libraryTypes);
var fieldDeclarations = GetFieldDeclarations(fieldDescriptions);
var ctor = GenerateConstructor(libraryTypes, simpleClassName, fieldDescriptions);
var accessibility = type.Accessibility switch
{
Accessibility.Public => SyntaxKind.PublicKeyword,
_ => SyntaxKind.InternalKeyword,
};
var classDeclaration = ClassDeclaration(simpleClassName)
.AddBaseListTypes(SimpleBaseType(libraryTypes.FieldCodec_1.ToTypeSyntax(type.TypeSyntax)))
.AddModifiers(Token(accessibility), Token(SyntaxKind.SealedKeyword))
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetGeneratedCodeAttributeSyntax())))
.AddMembers(fieldDeclarations)
.AddMembers(ctor);
if (type.IsEnumType)
{
var writeMethod = GenerateEnumWriteMethod(type, libraryTypes);
var readMethod = GenerateEnumReadMethod(type, libraryTypes);
classDeclaration = classDeclaration.AddMembers(writeMethod, readMethod);
}
else
{
var serializeMethod = GenerateSerializeMethod(type, fieldDescriptions, members, libraryTypes);
var deserializeMethod = GenerateDeserializeMethod(type, fieldDescriptions, members, libraryTypes);
var writeFieldMethod = GenerateCompoundTypeWriteFieldMethod(type, libraryTypes);
var readValueMethod = GenerateCompoundTypeReadValueMethod(type, fieldDescriptions, libraryTypes);
classDeclaration = classDeclaration.AddMembers(serializeMethod, deserializeMethod, writeFieldMethod, readValueMethod);
var serializerInterface = type.IsValueType ? libraryTypes.ValueSerializer : libraryTypes.BaseCodec_1;
classDeclaration = classDeclaration.AddBaseListTypes(SimpleBaseType(serializerInterface.ToTypeSyntax(type.TypeSyntax)));
}
if (type.IsGenericType)
{
classDeclaration = SyntaxFactoryUtility.AddGenericTypeParameters(classDeclaration, type.TypeParameters);
}
return classDeclaration;
}
public static string GetSimpleClassName(ISerializableTypeDescription serializableType) => GetSimpleClassName(serializableType.Name);
public static string GetSimpleClassName(string name) => $"Codec_{name}";
public static string GetGeneratedNamespaceName(ITypeSymbol type) => type.GetNamespaceAndNesting() switch
{
{ Length: > 0 } ns => $"{CodeGenerator.CodeGeneratorName}.{ns}",
_ => CodeGenerator.CodeGeneratorName
};
private static MemberDeclarationSyntax[] GetFieldDeclarations(List<GeneratedFieldDescription> fieldDescriptions)
{
return fieldDescriptions.Select(GetFieldDeclaration).ToArray();
static MemberDeclarationSyntax GetFieldDeclaration(GeneratedFieldDescription description)
{
switch (description)
{
case TypeFieldDescription type:
return FieldDeclaration(
VariableDeclaration(
type.FieldType,
SingletonSeparatedList(VariableDeclarator(type.FieldName)
.WithInitializer(EqualsValueClause(TypeOfExpression(type.UnderlyingTypeSyntax))))))
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword));
case CodecFieldTypeFieldDescription type:
return FieldDeclaration(
VariableDeclaration(
type.FieldType,
SingletonSeparatedList(VariableDeclarator(type.FieldName)
.WithInitializer(EqualsValueClause(TypeOfExpression(type.CodecFieldType))))))
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword));
case SetterFieldDescription setter:
{
var fieldSetterVariable = VariableDeclarator(setter.FieldName);
return
FieldDeclaration(VariableDeclaration(setter.FieldType).AddVariables(fieldSetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword));
}
case GetterFieldDescription getter:
{
var fieldGetterVariable = VariableDeclarator(getter.FieldName);
return
FieldDeclaration(VariableDeclaration(getter.FieldType).AddVariables(fieldGetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword));
}
default:
return FieldDeclaration(VariableDeclaration(description.FieldType, SingletonSeparatedList(VariableDeclarator(description.FieldName))))
.AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword));
}
}
}
private static ConstructorDeclarationSyntax GenerateConstructor(LibraryTypes libraryTypes, string simpleClassName, List<GeneratedFieldDescription> fieldDescriptions)
{
var injected = fieldDescriptions.Where(f => f.IsInjected).ToList();
var parameters = new List<ParameterSyntax>(injected.Select(f => Parameter(f.FieldName.ToIdentifier()).WithType(f.FieldType)));
const string CodecProviderParameterName = "codecProvider";
parameters.Add(Parameter(Identifier(CodecProviderParameterName)).WithType(libraryTypes.ICodecProvider.ToTypeSyntax()));
var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor");
IEnumerable<StatementSyntax> GetStatements()
{
foreach (var field in fieldDescriptions)
{
switch (field)
{
case GetterFieldDescription getter:
yield return getter.InitializationSyntax;
break;
case SetterFieldDescription setter:
yield return setter.InitializationSyntax;
break;
case GeneratedFieldDescription _ when field.IsInjected:
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ThisExpression().Member(field.FieldName.ToIdentifierName()),
Unwrapped(field.FieldName.ToIdentifierName())));
break;
case CodecFieldDescription codec when !field.IsInjected:
{
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ThisExpression().Member(field.FieldName.ToIdentifierName()),
GetService(field.FieldType)));
}
break;
}
}
}
return ConstructorDeclaration(simpleClassName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.ToArray())
.AddBodyStatements(GetStatements().ToArray());
static ExpressionSyntax Unwrapped(ExpressionSyntax expr)
{
return InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName("UnwrapService")),
ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(expr) })));
}
static ExpressionSyntax GetService(TypeSyntax type)
{
return InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), GenericName(Identifier("GetService"), TypeArgumentList(SingletonSeparatedList(type)))),
ArgumentList(SeparatedList(new[] { Argument(ThisExpression()), Argument(IdentifierName(CodecProviderParameterName)) })));
}
}
private static List<GeneratedFieldDescription> GetFieldDescriptions(
ISerializableTypeDescription serializableTypeDescription,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var fields = new List<GeneratedFieldDescription>();
fields.AddRange(serializableTypeDescription.Members
.Distinct(MemberDescriptionTypeComparer.Default)
.Select(member => GetTypeDescription(member)));
fields.Add(new CodecFieldTypeFieldDescription(libraryTypes.Type.ToTypeSyntax(), CodecFieldTypeFieldName, serializableTypeDescription.TypeSyntax));
if (serializableTypeDescription.HasComplexBaseType)
{
fields.Add(new BaseCodecFieldDescription(libraryTypes.BaseCodec_1.ToTypeSyntax(serializableTypeDescription.BaseTypeSyntax), BaseTypeSerializerFieldName));
}
if (serializableTypeDescription.UseActivator)
{
fields.Add(new ActivatorFieldDescription(libraryTypes.IActivator_1.ToTypeSyntax(serializableTypeDescription.TypeSyntax), ActivatorFieldName));
}
// Add a codec field for any field in the target which does not have a static codec.
fields.AddRange(serializableTypeDescription.Members
.Distinct(MemberDescriptionTypeComparer.Default)
.Where(t => !libraryTypes.StaticCodecs.Any(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, t.Type)))
.Select(member => GetCodecDescription(member)));
foreach (var member in members)
{
if (member.GetGetterFieldDescription() is { } getterFieldDescription)
{
fields.Add(getterFieldDescription);
}
if (member.GetSetterFieldDescription() is { } setterFieldDescription)
{
fields.Add(setterFieldDescription);
}
}
for (var hookIndex = 0; hookIndex < serializableTypeDescription.SerializationHooks.Count; ++hookIndex)
{
var hookType = serializableTypeDescription.SerializationHooks[hookIndex];
fields.Add(new SerializationHookFieldDescription(hookType.ToTypeSyntax(), $"_hook{hookIndex}"));
}
return fields;
CodecFieldDescription GetCodecDescription(IMemberDescription member)
{
TypeSyntax codecType = null;
if (member.Type.HasAttribute(libraryTypes.GenerateSerializerAttribute)
&& (!SymbolEqualityComparer.Default.Equals(member.Type.ContainingAssembly, libraryTypes.Compilation.Assembly) || member.Type.ContainingAssembly.HasAttribute(libraryTypes.TypeManifestProviderAttribute)))
{
// Use the concrete generated type and avoid expensive interface dispatch
if (member.Type is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsGenericType)
{
// Construct the full generic type name
var ns = ParseName(GetGeneratedNamespaceName(member.Type));
var name = GenericName(Identifier(GetSimpleClassName(member.Type.Name)), TypeArgumentList(SeparatedList(namedTypeSymbol.TypeArguments.Select(arg => member.GetTypeSyntax(arg)))));
codecType = QualifiedName(ns, name);
}
else
{
var simpleName = $"{GetGeneratedNamespaceName(member.Type)}.{GetSimpleClassName(member.Type.Name)}";
codecType = ParseTypeName(simpleName);
}
}
else if (libraryTypes.WellKnownCodecs.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, member.Type)) is WellKnownCodecDescription codec)
{
// The codec is not a static codec and is also not a generic codec.
codecType = codec.CodecType.ToTypeSyntax();
}
else if (member.Type is INamedTypeSymbol named && libraryTypes.WellKnownCodecs.Find(c => member.Type is INamedTypeSymbol named && named.ConstructedFrom is ISymbol unboundFieldType && SymbolEqualityComparer.Default.Equals(c.UnderlyingType, unboundFieldType)) is WellKnownCodecDescription genericCodec)
{
// Construct the generic codec type using the field's type arguments.
codecType = genericCodec.CodecType.Construct(named.TypeArguments.ToArray()).ToTypeSyntax();
}
else
{
// Use the IFieldCodec<TField> interface
codecType = libraryTypes.FieldCodec_1.ToTypeSyntax(member.TypeSyntax);
}
var fieldName = '_' + ToLowerCamelCase(member.TypeNameIdentifier) + "Codec";
return new CodecFieldDescription(codecType, fieldName, member.Type);
}
TypeFieldDescription GetTypeDescription(IMemberDescription member)
{
var fieldName = '_' + ToLowerCamelCase(member.TypeNameIdentifier) + "Type";
return new TypeFieldDescription(libraryTypes.Type.ToTypeSyntax(), fieldName, member.TypeSyntax, member.Type);
}
static string ToLowerCamelCase(string input) => char.IsLower(input, 0) ? input : char.ToLowerInvariant(input[0]) + input.Substring(1);
}
private static MemberDeclarationSyntax GenerateSerializeMethod(
ISerializableTypeDescription type,
List<GeneratedFieldDescription> serializerFields,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword));
var writerParam = "writer".ToIdentifierName();
var instanceParam = "instance".ToIdentifierName();
var body = new List<StatementSyntax>();
if (type.HasComplexBaseType)
{
body.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(BaseTypeSerializerFieldName.ToIdentifierName()).Member(SerializeMethodName),
ArgumentList(SeparatedList(new[] { Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(instanceParam) })))));
body.Add(ExpressionStatement(InvocationExpression(writerParam.Member("WriteEndBase"), ArgumentList())));
}
body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnSerializing"));
// Order members according to their FieldId, since fields must be serialized in order and FieldIds are serialized as deltas.
var previousFieldIdVar = "previousFieldId".ToIdentifierName();
if (type.OmitDefaultMemberValues && members.Count > 0)
{
// C#: uint previousFieldId = 0;
body.Add(LocalDeclarationStatement(
VariableDeclaration(
PredefinedType(Token(SyntaxKind.UIntKeyword)),
SingletonSeparatedList(VariableDeclarator(previousFieldIdVar.Identifier)
.WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))))))));
}
uint previousFieldId = 0;
foreach (var member in members.OrderBy(m => m.Member.FieldId))
{
var description = member.Member;
ExpressionSyntax fieldIdDeltaExpr;
if (type.OmitDefaultMemberValues)
{
// C#: <fieldId> - previousFieldId
fieldIdDeltaExpr = BinaryExpression(SyntaxKind.SubtractExpression, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(description.FieldId)), previousFieldIdVar);
}
else
{
var fieldIdDelta = description.FieldId - previousFieldId;
previousFieldId = description.FieldId;
fieldIdDeltaExpr = LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(fieldIdDelta));
}
// Codecs can either be static classes or injected into the constructor.
// Either way, the member signatures are the same.
var memberType = description.Type;
var staticCodec = libraryTypes.StaticCodecs.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, memberType));
ExpressionSyntax codecExpression;
if (staticCodec != null && libraryTypes.Compilation.IsSymbolAccessibleWithin(staticCodec.CodecType, libraryTypes.Compilation.Assembly))
{
codecExpression = staticCodec.CodecType.ToNameSyntax();
}
else
{
var instanceCodec = serializerFields.OfType<CodecFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType));
codecExpression = ThisExpression().Member(instanceCodec.FieldName);
}
var expectedType = serializerFields.OfType<TypeFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType));
var writeFieldExpr = ExpressionStatement(
InvocationExpression(
codecExpression.Member("WriteField"),
ArgumentList(
SeparatedList(
new[]
{
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldIdDeltaExpr),
Argument(expectedType.FieldName.ToIdentifierName()),
Argument(member.GetGetter(instanceParam))
}))));
if (!type.OmitDefaultMemberValues)
{
body.Add(writeFieldExpr);
}
else
{
ExpressionSyntax condition = member.IsValueType switch
{
true => BinaryExpression(SyntaxKind.NotEqualsExpression, member.GetGetter(instanceParam), LiteralExpression(SyntaxKind.DefaultLiteralExpression)),
false => IsPatternExpression(member.GetGetter(instanceParam), TypePattern(libraryTypes.Object.ToTypeSyntax()))
};
body.Add(IfStatement(
condition,
Block(
writeFieldExpr,
ExpressionStatement(AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, previousFieldIdVar, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(description.FieldId)))))));
}
}
body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnSerialized"));
var parameters = new[]
{
Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter("instance".ToIdentifier()).WithType(type.TypeSyntax)
};
if (type.IsValueType)
{
parameters[1] = parameters[1].WithModifiers(TokenList(Token(SyntaxKind.RefKeyword)));
}
return MethodDeclaration(returnType, SerializeMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddTypeParameterListParameters(TypeParameter("TBufferWriter"))
.AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax())))
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static MemberDeclarationSyntax GenerateDeserializeMethod(
ISerializableTypeDescription type,
List<GeneratedFieldDescription> serializerFields,
List<ISerializableMember> members,
LibraryTypes libraryTypes)
{
var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword));
var readerParam = "reader".ToIdentifierName();
var instanceParam = "instance".ToIdentifierName();
var idVar = "id".ToIdentifierName();
var headerVar = "header".ToIdentifierName();
var readHeaderLocalFunc = "ReadHeader".ToIdentifierName();
var readHeaderEndLocalFunc = "ReadHeaderExpectingEndBaseOrEndObject".ToIdentifierName();
var body = new List<StatementSyntax>
{
// C#: int id = 0;
LocalDeclarationStatement(
VariableDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
SingletonSeparatedList(VariableDeclarator(idVar.Identifier)
.WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))))))),
// C#: Field header = default;
LocalDeclarationStatement(
VariableDeclaration(
libraryTypes.Field.ToTypeSyntax(),
SingletonSeparatedList(VariableDeclarator(headerVar.Identifier)
.WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.DefaultLiteralExpression))))))
};
if (type.HasComplexBaseType)
{
// C#: this.baseTypeSerializer.Deserialize(ref reader, instance);
body.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(BaseTypeSerializerFieldName.ToIdentifierName()).Member(DeserializeMethodName),
ArgumentList(SeparatedList(new[]
{
Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(instanceParam)
})))));
}
body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnDeserializing"));
body.Add(WhileStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression), Block(GetDeserializerLoopBody())));
body.AddRange(AddSerializationCallbacks(type, instanceParam, "OnDeserialized"));
var genericParam = ParseTypeName("TReaderInput");
var parameters = new[]
{
Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(genericParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter(instanceParam.Identifier).WithType(type.TypeSyntax)
};
if (type.IsValueType)
{
parameters[1] = parameters[1].WithModifiers(TokenList(Token(SyntaxKind.RefKeyword)));
}
return MethodDeclaration(returnType, DeserializeMethodName)
.AddTypeParameterListParameters(TypeParameter("TReaderInput"))
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
// Create the loop body.
List<StatementSyntax> GetDeserializerLoopBody()
{
var loopBody = new List<StatementSyntax>();
var codecs = serializerFields.OfType<ICodecDescription>()
.Concat(libraryTypes.StaticCodecs)
.ToList();
var orderedMembers = members.OrderBy(m => m.Member.FieldId).ToList();
var lastMember = orderedMembers.LastOrDefault();
// C#: id = OrleansGeneratedCodeHelper.ReadHeader(ref reader, ref header, id);
{
var readHeaderMethodName = orderedMembers.Count == 0 ? "ReadHeaderExpectingEndBaseOrEndObject" : "ReadHeader";
var readFieldHeader =
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(idVar.Identifier),
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName(readHeaderMethodName)),
ArgumentList(SeparatedList(new[]
{
Argument(readerParam).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(headerVar).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(idVar)
})))));
loopBody.Add(readFieldHeader);
}
foreach (var member in orderedMembers)
{
var description = member.Member;
// C#: instance.<member> = <codec>.ReadValue(ref reader, header);
// Codecs can either be static classes or injected into the constructor.
// Either way, the member signatures are the same.
var codec = codecs.First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, description.Type));
var memberType = description.Type;
var staticCodec = libraryTypes.StaticCodecs.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, memberType));
ExpressionSyntax codecExpression;
if (staticCodec != null)
{
codecExpression = staticCodec.CodecType.ToNameSyntax();
}
else
{
var instanceCodec = serializerFields.OfType<CodecFieldDescription>().First(f => SymbolEqualityComparer.Default.Equals(f.UnderlyingType, memberType));
codecExpression = ThisExpression().Member(instanceCodec.FieldName);
}
ExpressionSyntax readValueExpression = InvocationExpression(
codecExpression.Member("ReadValue"),
ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(headerVar) })));
if (!codec.UnderlyingType.Equals(member.TypeSyntax))
{
// If the member type type differs from the codec type (eg because the member is an array), cast the result.
readValueExpression = CastExpression(description.TypeSyntax, readValueExpression);
}
var memberAssignment = ExpressionStatement(member.GetSetter(instanceParam, readValueExpression));
var readHeaderMethodName = ReferenceEquals(member, lastMember) ? "ReadHeaderExpectingEndBaseOrEndObject" : "ReadHeader";
var readFieldHeader =
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName(idVar.Identifier),
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("OrleansGeneratedCodeHelper"), IdentifierName(readHeaderMethodName)),
ArgumentList(SeparatedList(new[]
{
Argument(readerParam).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(headerVar).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(idVar)
})))));
var ifBody = Block(List(new StatementSyntax[] { memberAssignment, readFieldHeader }));
// C#: if (id == <fieldId>) { ... }
var ifStatement = IfStatement(BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(idVar.Identifier), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)description.FieldId))),
ifBody);
loopBody.Add(ifStatement);
}
// C#: if (id == -1) { break; }
loopBody.Add(IfStatement(BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(idVar.Identifier), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(-1))),
Block(List(new StatementSyntax[] { BreakStatement() }))));
// Consume any unknown fields
// C#: reader.ConsumeUnknownField(header);
var consumeUnknown = ExpressionStatement(InvocationExpression(readerParam.Member("ConsumeUnknownField"),
ArgumentList(SeparatedList(new[] { Argument(headerVar) }))));
loopBody.Add(consumeUnknown);
return loopBody;
}
}
private static IEnumerable<StatementSyntax> AddSerializationCallbacks(ISerializableTypeDescription type, IdentifierNameSyntax instanceParam, string callbackMethodName)
{
for (var hookIndex = 0; hookIndex < type.SerializationHooks.Count; ++hookIndex)
{
var hookType = type.SerializationHooks[hookIndex];
var member = hookType.GetAllMembers<IMethodSymbol>(callbackMethodName, Accessibility.Public).FirstOrDefault();
if (member is null || member.Parameters.Length != 1)
{
continue;
}
var argument = Argument(instanceParam);
if (member.Parameters[0].RefKind == RefKind.Ref)
{
argument = argument.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword));
}
yield return ExpressionStatement(InvocationExpression(
ThisExpression().Member($"_hook{hookIndex}").Member(callbackMethodName),
ArgumentList(SeparatedList(new[] { argument }))));
}
}
private static MemberDeclarationSyntax GenerateCompoundTypeWriteFieldMethod(
ISerializableTypeDescription type,
LibraryTypes libraryTypes)
{
var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword));
var writerParam = "writer".ToIdentifierName();
var fieldIdDeltaParam = "fieldIdDelta".ToIdentifierName();
var expectedTypeParam = "expectedType".ToIdentifierName();
var valueParam = "value".ToIdentifierName();
var valueTypeField = "valueType".ToIdentifierName();
var innerBody = new List<StatementSyntax>();
if (type.IsValueType)
{
// C#: ReferenceCodec.MarkValueField(reader.Session);
innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(writerParam.Member("Session")))))));
}
else
{
if (type.TrackReferences)
{
// C#: if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; }
innerBody.Add(
IfStatement(
InvocationExpression(
IdentifierName("ReferenceCodec").Member("TryWriteReferenceField"),
ArgumentList(SeparatedList(new[]
{
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldIdDeltaParam),
Argument(expectedTypeParam),
Argument(valueParam)
}))),
Block(ReturnStatement()))
);
}
else
{
// C#: if (value is null) { ReferenceCodec.WriteNullReference(ref writer, fieldIdDelta, expectedType); return; }
innerBody.Add(
IfStatement(
IsPatternExpression(valueParam, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))),
Block(
ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("WriteNullReference"),
ArgumentList(SeparatedList(new[]
{
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldIdDeltaParam),
Argument(expectedTypeParam)
})))),
ReturnStatement()))
);
// C#: ReferenceCodec.MarkValueField(reader.Session);
innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(writerParam.Member("Session")))))));
}
}
// Generate the most appropriate expression to get the field type.
ExpressionSyntax valueTypeInitializer = type.IsValueType switch {
true => IdentifierName(CodecFieldTypeFieldName),
false => ConditionalAccessExpression(valueParam, InvocationExpression(MemberBindingExpression(IdentifierName("GetType"))))
};
ExpressionSyntax valueTypeExpression = type.IsSealedType switch
{
true => IdentifierName(CodecFieldTypeFieldName),
false => valueTypeField
};
// C#: writer.WriteStartObject(fieldIdDelta, expectedType, fieldType);
innerBody.Add(
ExpressionStatement(InvocationExpression(writerParam.Member("WriteStartObject"),
ArgumentList(SeparatedList(new[]{
Argument(fieldIdDeltaParam),
Argument(expectedTypeParam),
Argument(valueTypeExpression)
})))
));
// C#: this.Serialize(ref writer, [ref] value);
var valueParamArgument = type.IsValueType switch
{
true => Argument(valueParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
false => Argument(valueParam)
};
innerBody.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(SerializeMethodName),
ArgumentList(
SeparatedList(
new[]
{
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
valueParamArgument
})))));
// C#: writer.WriteEndObject();
innerBody.Add(ExpressionStatement(InvocationExpression(writerParam.Member("WriteEndObject"))));
List<StatementSyntax> body;
if (type.IsSealedType)
{
body = innerBody;
}
else
{
// For types which are not sealed/value types, add some extra logic to support sub-types:
body = new List<StatementSyntax>
{
// C#: var fieldType = value?.GetType();
LocalDeclarationStatement(
VariableDeclaration(
libraryTypes.Type.ToTypeSyntax(),
SingletonSeparatedList(VariableDeclarator(valueTypeField.Identifier)
.WithInitializer(EqualsValueClause(valueTypeInitializer))))),
// C#: if (fieldType is null || fieldType == typeof(TField)) { <inner body> }
// C#: else { OrleansGeneratedCodeHelper.SerializeUnexpectedType(ref writer, fieldIdDelta, expectedType, value); }
IfStatement(
BinaryExpression(SyntaxKind.LogicalOrExpression,
IsPatternExpression(valueTypeField, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))),
BinaryExpression(SyntaxKind.EqualsExpression, valueTypeField, IdentifierName(CodecFieldTypeFieldName))),
Block(innerBody),
ElseClause(Block(new StatementSyntax[]
{
ExpressionStatement(
InvocationExpression(
IdentifierName("OrleansGeneratedCodeHelper").Member("SerializeUnexpectedType"),
ArgumentList(
SeparatedList(new [] {
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldIdDeltaParam),
Argument(expectedTypeParam),
Argument(valueParam)
}))))
})))
};
}
var parameters = new[]
{
Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter("fieldIdDelta".ToIdentifier()).WithType(libraryTypes.UInt32.ToTypeSyntax()),
Parameter("expectedType".ToIdentifier()).WithType(libraryTypes.Type.ToTypeSyntax()),
Parameter("value".ToIdentifier()).WithType(type.TypeSyntax)
};
return MethodDeclaration(returnType, WriteFieldMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddTypeParameterListParameters(TypeParameter("TBufferWriter"))
.AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax())))
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static MemberDeclarationSyntax GenerateCompoundTypeReadValueMethod(
ISerializableTypeDescription type,
List<GeneratedFieldDescription> serializerFields,
LibraryTypes libraryTypes)
{
var readerParam = "reader".ToIdentifierName();
var fieldParam = "field".ToIdentifierName();
var resultVar = "result".ToIdentifierName();
var readerInputTypeParam = ParseTypeName("TReaderInput");
var body = new List<StatementSyntax>();
var innerBody = new List<StatementSyntax>();
if (!type.IsValueType)
{
// C#: if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<TField, TReaderInput>(ref reader, field); }
body.Add(
IfStatement(
BinaryExpression(SyntaxKind.EqualsExpression, fieldParam.Member("WireType"), libraryTypes.WireType.ToTypeSyntax().Member("Reference")),
Block(ReturnStatement(InvocationExpression(
IdentifierName("ReferenceCodec").Member("ReadReference", new[] { type.TypeSyntax, readerInputTypeParam }),
ArgumentList(SeparatedList(new[]
{
Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldParam),
}))))))
);
}
ExpressionSyntax createValueExpression = type.UseActivator switch
{
true => InvocationExpression(serializerFields.OfType<ActivatorFieldDescription>().Single().FieldName.ToIdentifierName().Member("Create")),
false => type.GetObjectCreationExpression(libraryTypes)
};
// C#: TField result = _activator.Create();
// or C#: TField result = new TField();
innerBody.Add(LocalDeclarationStatement(
VariableDeclaration(
type.TypeSyntax,
SingletonSeparatedList(VariableDeclarator(resultVar.Identifier)
.WithInitializer(EqualsValueClause(createValueExpression))))));
if (type.TrackReferences)
{
// C#: ReferenceCodec.RecordObject(reader.Session, result);
innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("RecordObject"), ArgumentList(SeparatedList(new[] { Argument(readerParam.Member("Session")), Argument(resultVar) })))));
}
else
{
// C#: ReferenceCodec.MarkValueField(reader.Session);
innerBody.Add(ExpressionStatement(InvocationExpression(IdentifierName("ReferenceCodec").Member("MarkValueField"), ArgumentList(SingletonSeparatedList(Argument(readerParam.Member("Session")))))));
}
// C#: this.Deserializer(ref reader, [ref] result);
var resultArgument = type.IsValueType switch
{
true => Argument(resultVar).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
false => Argument(resultVar)
};
innerBody.Add(
ExpressionStatement(
InvocationExpression(
ThisExpression().Member(DeserializeMethodName),
ArgumentList(
SeparatedList(
new[]
{
Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
resultArgument
})))));
innerBody.Add(ReturnStatement(resultVar));
if (type.IsSealedType)
{
body.AddRange(innerBody);
}
else
{
// C#: var fieldType = field.FieldType;
var valueTypeField = "valueType".ToIdentifierName();
body.Add(
LocalDeclarationStatement(
VariableDeclaration(
libraryTypes.Type.ToTypeSyntax(),
SingletonSeparatedList(VariableDeclarator(valueTypeField.Identifier)
.WithInitializer(EqualsValueClause(fieldParam.Member("FieldType")))))));
body.Add(
IfStatement(
BinaryExpression(SyntaxKind.LogicalOrExpression,
IsPatternExpression(valueTypeField, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression))),
BinaryExpression(SyntaxKind.EqualsExpression, valueTypeField, IdentifierName(CodecFieldTypeFieldName))),
Block(innerBody)));
body.Add(ReturnStatement(
InvocationExpression(
IdentifierName("OrleansGeneratedCodeHelper").Member("DeserializeUnexpectedType", new[] { readerInputTypeParam, type.TypeSyntax }),
ArgumentList(
SeparatedList(new[] {
Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldParam)
})))));
}
var parameters = new[]
{
Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(readerInputTypeParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter(fieldParam.Identifier).WithType(libraryTypes.Field.ToTypeSyntax())
};
return MethodDeclaration(type.TypeSyntax, ReadValueMethodName)
.AddTypeParameterListParameters(TypeParameter("TReaderInput"))
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static MemberDeclarationSyntax GenerateEnumWriteMethod(
ISerializableTypeDescription type,
LibraryTypes libraryTypes)
{
var returnType = PredefinedType(Token(SyntaxKind.VoidKeyword));
var writerParam = "writer".ToIdentifierName();
var fieldIdDeltaParam = "fieldIdDelta".ToIdentifierName();
var expectedTypeParam = "expectedType".ToIdentifierName();
var valueParam = "value".ToIdentifierName();
var body = new List<StatementSyntax>();
// Codecs can either be static classes or injected into the constructor.
// Either way, the member signatures are the same.
var staticCodec = libraryTypes.StaticCodecs.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, type.BaseType));
var codecExpression = staticCodec.CodecType.ToNameSyntax();
body.Add(
ExpressionStatement(
InvocationExpression(
codecExpression.Member("WriteField"),
ArgumentList(
SeparatedList(
new[]
{
Argument(writerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)),
Argument(fieldIdDeltaParam),
Argument(expectedTypeParam),
Argument(CastExpression(type.BaseTypeSyntax, valueParam)),
Argument(TypeOfExpression(type.TypeSyntax))
})))));
var parameters = new[]
{
Parameter("writer".ToIdentifier()).WithType(libraryTypes.Writer.ToTypeSyntax()).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter("fieldIdDelta".ToIdentifier()).WithType(libraryTypes.UInt32.ToTypeSyntax()),
Parameter("expectedType".ToIdentifier()).WithType(libraryTypes.Type.ToTypeSyntax()),
Parameter("value".ToIdentifier()).WithType(type.TypeSyntax)
};
return MethodDeclaration(returnType, WriteFieldMethodName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddTypeParameterListParameters(TypeParameter("TBufferWriter"))
.AddConstraintClauses(TypeParameterConstraintClause("TBufferWriter").AddConstraints(TypeConstraint(libraryTypes.IBufferWriter.Construct(libraryTypes.Byte).ToTypeSyntax())))
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
private static MemberDeclarationSyntax GenerateEnumReadMethod(
ISerializableTypeDescription type,
LibraryTypes libraryTypes)
{
var readerParam = "reader".ToIdentifierName();
var fieldParam = "field".ToIdentifierName();
var staticCodec = libraryTypes.StaticCodecs.Find(c => SymbolEqualityComparer.Default.Equals(c.UnderlyingType, type.BaseType));
ExpressionSyntax codecExpression = staticCodec.CodecType.ToNameSyntax();
ExpressionSyntax readValueExpression = InvocationExpression(
codecExpression.Member("ReadValue"),
ArgumentList(SeparatedList(new[] { Argument(readerParam).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), Argument(fieldParam) })));
readValueExpression = CastExpression(type.TypeSyntax, readValueExpression);
var body = new List<StatementSyntax>
{
ReturnStatement(readValueExpression)
};
var genericParam = ParseTypeName("TReaderInput");
var parameters = new[]
{
Parameter(readerParam.Identifier).WithType(libraryTypes.Reader.ToTypeSyntax(genericParam)).WithModifiers(TokenList(Token(SyntaxKind.RefKeyword))),
Parameter(fieldParam.Identifier).WithType(libraryTypes.Field.ToTypeSyntax())
};
return MethodDeclaration(type.TypeSyntax, ReadValueMethodName)
.AddTypeParameterListParameters(TypeParameter("TReaderInput"))
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters)
.AddAttributeLists(AttributeList(SingletonSeparatedList(CodeGenerator.GetMethodImplAttributeSyntax())))
.AddBodyStatements(body.ToArray());
}
internal abstract class GeneratedFieldDescription
{
protected GeneratedFieldDescription(TypeSyntax fieldType, string fieldName)
{
FieldType = fieldType;
FieldName = fieldName;
}
public TypeSyntax FieldType { get; }
public string FieldName { get; }
public abstract bool IsInjected { get; }
}
internal class BaseCodecFieldDescription : GeneratedFieldDescription
{
public BaseCodecFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName)
{
}
public override bool IsInjected => true;
}
internal class ActivatorFieldDescription : GeneratedFieldDescription
{
public ActivatorFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName)
{
}
public override bool IsInjected => true;
}
internal class CodecFieldDescription : GeneratedFieldDescription, ICodecDescription
{
public CodecFieldDescription(TypeSyntax fieldType, string fieldName, ITypeSymbol underlyingType) : base(fieldType, fieldName)
{
UnderlyingType = underlyingType;
}
public ITypeSymbol UnderlyingType { get; }
public override bool IsInjected => false;
}
internal class TypeFieldDescription : GeneratedFieldDescription
{
public TypeFieldDescription(TypeSyntax fieldType, string fieldName, TypeSyntax underlyingTypeSyntax, ITypeSymbol underlyingType) : base(fieldType, fieldName)
{
UnderlyingType = underlyingType;
UnderlyingTypeSyntax = underlyingTypeSyntax;
}
public TypeSyntax UnderlyingTypeSyntax { get; }
public ITypeSymbol UnderlyingType { get; }
public override bool IsInjected => false;
}
internal class CodecFieldTypeFieldDescription : GeneratedFieldDescription
{
public CodecFieldTypeFieldDescription(TypeSyntax fieldType, string fieldName, TypeSyntax codecFieldType) : base(fieldType, fieldName)
{
CodecFieldType = codecFieldType;
}
public TypeSyntax CodecFieldType { get; }
public override bool IsInjected => false;
}
internal class SetterFieldDescription : GeneratedFieldDescription
{
public SetterFieldDescription(TypeSyntax fieldType, string fieldName, StatementSyntax initializationSyntax) : base(fieldType, fieldName)
{
InitializationSyntax = initializationSyntax;
}
public override bool IsInjected => false;
public StatementSyntax InitializationSyntax { get; }
}
internal class GetterFieldDescription : GeneratedFieldDescription
{
public GetterFieldDescription(TypeSyntax fieldType, string fieldName, StatementSyntax initializationSyntax) : base(fieldType, fieldName)
{
InitializationSyntax = initializationSyntax;
}
public override bool IsInjected => false;
public StatementSyntax InitializationSyntax { get; }
}
internal class SerializationHookFieldDescription : GeneratedFieldDescription
{
public SerializationHookFieldDescription(TypeSyntax fieldType, string fieldName) : base(fieldType, fieldName)
{
}
public override bool IsInjected => true;
}
internal interface ISerializableMember
{
bool IsShallowCopyable { get; }
bool IsValueType { get; }
IMemberDescription Member { get; }
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
TypeSyntax TypeSyntax { get; }
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if necessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
ExpressionSyntax GetGetter(ExpressionSyntax instance);
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value);
GetterFieldDescription GetGetterFieldDescription();
SetterFieldDescription GetSetterFieldDescription();
}
/// <summary>
/// Represents a serializable member (field/property) of a type.
/// </summary>
internal class SerializableMethodMember : ISerializableMember
{
private readonly MethodParameterFieldDescription _member;
public SerializableMethodMember(MethodParameterFieldDescription member)
{
_member = member;
}
public IMemberDescription Member => _member;
private LibraryTypes LibraryTypes => _member.Method.ContainingInterface.CodeGenerator.LibraryTypes;
public bool IsShallowCopyable => LibraryTypes.IsShallowCopyable(_member.Parameter.Type) || _member.Parameter.HasAnyAttribute(LibraryTypes.ImmutableAttributes);
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
public TypeSyntax TypeSyntax => _member.TypeSyntax;
public bool IsValueType => _member.Type.IsValueType;
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if necessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
public ExpressionSyntax GetGetter(ExpressionSyntax instance) => instance.Member(_member.FieldName);
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value) => AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(_member.FieldName),
value);
public GetterFieldDescription GetGetterFieldDescription() => null;
public SetterFieldDescription GetSetterFieldDescription() => null;
}
/// <summary>
/// Represents a serializable member (field/property) of a type.
/// </summary>
internal class SerializableMember : ISerializableMember
{
private readonly SemanticModel _model;
private readonly LibraryTypes _libraryTypes;
private IPropertySymbol _property;
private readonly IMemberDescription _member;
/// <summary>
/// The ordinal assigned to this field.
/// </summary>
private readonly int _ordinal;
public SerializableMember(LibraryTypes libraryTypes, ISerializableTypeDescription type, IMemberDescription member, int ordinal)
{
_libraryTypes = libraryTypes;
_model = type.SemanticModel;
_ordinal = ordinal;
_member = member;
}
public bool IsShallowCopyable => _libraryTypes.IsShallowCopyable(_member.Type) || (Property is { } prop && prop.HasAnyAttribute(_libraryTypes.ImmutableAttributes)) || _member.Symbol.HasAnyAttribute(_libraryTypes.ImmutableAttributes);
public bool IsValueType => Type.IsValueType;
public IMemberDescription Member => _member;
/// <summary>
/// Gets the underlying <see cref="Field"/> instance.
/// </summary>
private IFieldSymbol Field => (_member as IFieldDescription)?.Field;
public ITypeSymbol Type => _member.Type;
public INamedTypeSymbol ContainingType => _member.ContainingType;
public string MemberName => Field?.Name ?? Property?.Name;
/// <summary>
/// Gets the name of the getter field.
/// </summary>
private string GetterFieldName => "getField" + _ordinal;
/// <summary>
/// Gets the name of the setter field.
/// </summary>
private string SetterFieldName => "setField" + _ordinal;
/// <summary>
/// Gets a value indicating whether or not this member represents an accessible field.
/// </summary>
private bool IsGettableField => Field is { } field && _model.IsAccessible(0, field) && !IsObsolete;
/// <summary>
/// Gets a value indicating whether or not this member represents an accessible, mutable field.
/// </summary>
private bool IsSettableField => Field is { } field && IsGettableField && !field.IsReadOnly;
/// <summary>
/// Gets a value indicating whether or not this member represents a property with an accessible, non-obsolete getter.
/// </summary>
private bool IsGettableProperty => Property?.GetMethod is { } getMethod && _model.IsAccessible(0, getMethod) && !IsObsolete;
/// <summary>
/// Gets a value indicating whether or not this member represents a property with an accessible, non-obsolete setter.
/// </summary>
private bool IsSettableProperty => Property?.SetMethod is { } setMethod && _model.IsAccessible(0, setMethod) && !setMethod.IsInitOnly && !IsObsolete;
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
public TypeSyntax TypeSyntax => Member.Type.TypeKind == TypeKind.Dynamic
? PredefinedType(Token(SyntaxKind.ObjectKeyword))
: _member.GetTypeSyntax(Member.Type);
/// <summary>
/// Gets the <see cref="Property"/> which this field is the backing property for, or
/// <see langword="null" /> if this is not the backing field of an auto-property.
/// </summary>
private IPropertySymbol Property => _property ??= _property = Member.Symbol as IPropertySymbol ?? PropertyUtility.GetMatchingProperty(Field);
/// <summary>
/// Gets a value indicating whether or not this field is obsolete.
/// </summary>
private bool IsObsolete => Member.Symbol.HasAttribute(_libraryTypes.ObsoleteAttribute) ||
Property != null && Property.HasAttribute(_libraryTypes.ObsoleteAttribute);
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if necessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
public ExpressionSyntax GetGetter(ExpressionSyntax instance)
{
// If the field is the backing field for an accessible auto-property use the property directly.
ExpressionSyntax result;
if (IsGettableProperty)
{
result = instance.Member(Property.Name);
}
else if (IsGettableField)
{
result = instance.Member(Field.Name);
}
else
{
// Retrieve the field using the generated getter.
result =
InvocationExpression(IdentifierName(GetterFieldName))
.AddArgumentListArguments(Argument(instance));
}
return result;
}
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value)
{
// If the field is the backing field for an accessible auto-property use the property directly.
if (IsSettableProperty)
{
return AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(Property.Name),
value);
}
if (IsSettableField)
{
return AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(Field.Name),
value);
}
var instanceArg = Argument(instance);
if (ContainingType != null && ContainingType.IsValueType)
{
instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword));
}
return
InvocationExpression(IdentifierName(SetterFieldName))
.AddArgumentListArguments(instanceArg, Argument(value));
}
public GetterFieldDescription GetGetterFieldDescription()
{
if (IsGettableField || IsGettableProperty) return null;
var getterType = _libraryTypes.Func_2.ToTypeSyntax(_member.GetTypeSyntax(ContainingType), TypeSyntax);
// Generate syntax to initialize the field in the constructor
var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor");
var fieldInfo = GetGetFieldInfoExpression(ContainingType, MemberName);
var accessorInvoke = CastExpression(
getterType,
InvocationExpression(fieldAccessorUtility.Member("GetGetter")).AddArgumentListArguments(Argument(fieldInfo)));
var initializationSyntax = ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(GetterFieldName), accessorInvoke));
return new GetterFieldDescription(getterType, GetterFieldName, initializationSyntax);
}
public SetterFieldDescription GetSetterFieldDescription()
{
if (IsSettableField || IsSettableProperty) return null;
TypeSyntax fieldType;
if (ContainingType != null && ContainingType.IsValueType)
{
fieldType = _libraryTypes.ValueTypeSetter_2.ToTypeSyntax(_member.GetTypeSyntax(ContainingType), TypeSyntax);
}
else
{
fieldType = _libraryTypes.Action_2.ToTypeSyntax(_member.GetTypeSyntax(ContainingType), TypeSyntax);
}
// Generate syntax to initialize the field in the constructor
var fieldAccessorUtility = AliasQualifiedName("global", IdentifierName("Orleans.Serialization")).Member("Utilities").Member("FieldAccessor");
var fieldInfo = GetGetFieldInfoExpression(ContainingType, MemberName);
var isContainedByValueType = ContainingType != null && ContainingType.IsValueType;
var accessorMethod = isContainedByValueType ? "GetValueSetter" : "GetReferenceSetter";
var accessorInvoke = CastExpression(
fieldType,
InvocationExpression(fieldAccessorUtility.Member(accessorMethod))
.AddArgumentListArguments(Argument(fieldInfo)));
var initializationSyntax = ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(SetterFieldName), accessorInvoke));
return new SetterFieldDescription(fieldType, SetterFieldName, initializationSyntax);
}
public static InvocationExpressionSyntax GetGetFieldInfoExpression(INamedTypeSymbol containingType, string fieldName)
{
var bindingFlags = SymbolSyntaxExtensions.GetBindingFlagsParenthesizedExpressionSyntax(
SyntaxKind.BitwiseOrExpression,
BindingFlags.Instance,
BindingFlags.NonPublic,
BindingFlags.Public);
return InvocationExpression(TypeOfExpression(containingType.ToTypeSyntax()).Member("GetField"))
.AddArgumentListArguments(
Argument(fieldName.GetLiteralExpression()),
Argument(bindingFlags));
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.OLE.Interop;
using System.Runtime.InteropServices;
using System.Threading;
namespace Microsoft.MIDebugEngine
{
internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback
{
// If we store the event callback in a normal IDebugEventCallback2 member, COM interop will attempt to call back to the main UI
// thread the first time that we invoke the call back. To work around this, we will instead store the event call back in the
// global interface table like we would if we implemented this code in native.
private readonly uint _cookie;
// NOTE: The GIT doesn't aggregate the free threaded marshaler, so we can't store it in an RCW
// or the CLR will just call right back to the main thread to try and marshal it.
private readonly IntPtr _pGIT;
private readonly AD7Engine _engine;
private Guid _IID_IDebugEventCallback2 = typeof(IDebugEventCallback2).GUID;
private readonly object _cacheLock = new object();
private int _cachedEventCallbackThread;
private IDebugEventCallback2 _cacheEventCallback;
public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback)
{
// Obtain the GIT from COM, and store the event callback in it
Guid CLSID_StdGlobalInterfaceTable = new Guid("00000323-0000-0000-C000-000000000046");
Guid IID_IGlobalInterfaceTable = typeof(IGlobalInterfaceTable).GUID;
const int CLSCTX_INPROC_SERVER = 0x1;
_pGIT = NativeMethods.CoCreateInstance(ref CLSID_StdGlobalInterfaceTable, IntPtr.Zero, CLSCTX_INPROC_SERVER, ref IID_IGlobalInterfaceTable);
var git = GetGlobalInterfaceTable();
git.RegisterInterfaceInGlobal(ad7Callback, ref _IID_IDebugEventCallback2, out _cookie);
Marshal.ReleaseComObject(git);
_engine = engine;
}
~EngineCallback()
{
// NOTE: This object does NOT implement the dispose pattern. The reasons are --
// 1. The underlying thing we are disposing is the SDM's IDebugEventCallback2. We are not going to get
// deterministic release of this without both implementing the dispose pattern on this object but also
// switching to use Marshal.ReleaseComObject everywhere. Marshal.ReleaseComObject is difficult to get
// right and there isn't a large need to deterministically release the SDM's event callback.
// 2. There is some risk of deadlock if we tried to implement the dispose pattern because of the trickiness
// of releasing cross-thread COM interfaces. We could avoid this by doing an async dispose, but then
// we losing the primary benefit of dispose which is the deterministic release.
if (_cookie != 0)
{
var git = GetGlobalInterfaceTable();
git.RevokeInterfaceFromGlobal(_cookie);
Marshal.ReleaseComObject(git);
}
if (_pGIT != IntPtr.Zero)
{
Marshal.Release(_pGIT);
}
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread)
{
uint attributes;
Guid riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
var callback = GetEventCallback();
EngineUtils.RequireOk(callback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes));
}
private IGlobalInterfaceTable GetGlobalInterfaceTable()
{
Debug.Assert(_pGIT != IntPtr.Zero, "GetGlobalInterfaceTable called before the m_pGIT is initialized");
// NOTE: We want to use GetUniqueObjectForIUnknown since the GIT will exist in both the STA and the MTA, and we don't want
// them to be the same rcw
return (IGlobalInterfaceTable)Marshal.GetUniqueObjectForIUnknown(_pGIT);
}
private IDebugEventCallback2 GetEventCallback()
{
Debug.Assert(_cookie != 0, "GetEventCallback called before m_cookie is initialized");
// We send esentially all events from the same thread, so lets optimize the common case
int currentThreadId = Thread.CurrentThread.ManagedThreadId;
if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId)
{
lock (_cacheLock)
{
if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId)
{
return _cacheEventCallback;
}
}
}
var git = GetGlobalInterfaceTable();
IntPtr pCallback;
git.GetInterfaceFromGlobal(_cookie, ref _IID_IDebugEventCallback2, out pCallback);
Marshal.ReleaseComObject(git);
var eventCallback = (IDebugEventCallback2)Marshal.GetObjectForIUnknown(pCallback);
Marshal.Release(pCallback);
lock (_cacheLock)
{
_cachedEventCallbackThread = currentThreadId;
_cacheEventCallback = eventCallback;
}
return eventCallback;
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread)
{
IDebugProgram2 program = _engine;
if (!_engine.ProgramCreateEventSent)
{
// Any events before programe create shouldn't include the program
program = null;
}
Send(eventObject, iidEvent, program, thread);
}
public void OnError(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Error, isAsync: true);
}
/// <summary>
/// Sends an error to the user, blocking until the user dismisses the error
/// </summary>
/// <param name="message">string to display to the user</param>
public void OnErrorImmediate(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Error, isAsync: false);
}
public void OnWarning(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Warning, isAsync: true);
}
public void OnModuleLoad(DebuggedModule debuggedModule)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event
// for the exe.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
debuggedModule.Client = ad7Module;
// The sample engine does not support binding breakpoints as modules load since the primary exe is the only module
// symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded.
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnModuleUnload(DebuggedModule debuggedModule)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Module ad7Module = (AD7Module)debuggedModule.Client;
Debug.Assert(ad7Module != null);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */);
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnOutputString(string outputString)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString);
Send(eventObject, AD7OutputDebugStringEvent.IID, null);
}
public void OnOutputMessage(string outputMessage, enum_MESSAGETYPE messageType)
{
try
{
var eventObject = new AD7MessageEvent(outputMessage, messageType, isAsync: false, severity: AD7MessageEvent.Severity.Warning);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
public void OnProcessExit(uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
try
{
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
catch (InvalidOperationException)
{
// If debugging has already stopped, this can throw
}
}
public void OnEntryPoint(DebuggedThread thread)
{
AD7EntryPointEvent eventObject = new AD7EntryPointEvent();
Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client);
}
public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client;
Debug.Assert(ad7Thread != null);
AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode);
Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread);
}
public void OnThreadStart(DebuggedThread debuggedThread)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event
// for the main thread of the application.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent();
Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client);
}
public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count];
int i = 0;
foreach (object objCurrentBreakpoint in clients)
{
boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint;
i++;
}
// An engine that supports more advanced breakpoint features such as hit counts, conditions and filters
// should notify each bound breakpoint that it has been hit and evaluate conditions here.
// The sample engine does not support these features.
AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7BreakpointEvent.IID, ad7Thread);
}
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
public void OnException(DebuggedThread thread, string name, string description, uint code)
{
AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7ExceptionEvent.IID, ad7Thread);
}
public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null)
{
AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(var, prop);
Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client);
}
public void OnStepComplete(DebuggedThread thread)
{
// Step complete is sent when a step has finished
AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent();
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread);
}
public void OnAsyncBreakComplete(DebuggedThread thread)
{
// This will get called when the engine receives the breakpoint event that is created when the user
// hits the pause button in vs.
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent();
Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread);
}
public void OnLoadComplete(DebuggedThread thread)
{
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent();
Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread);
}
public void OnProgramDestroy(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
// Engines notify the debugger about the results of a symbol serach by sending an instance
// of IDebugSymbolSearchEvent2
public void OnSymbolSearch(DebuggedModule module, string status, uint dwStatusFlags)
{
enum_MODULE_INFO_FLAGS statusFlags = (enum_MODULE_INFO_FLAGS)dwStatusFlags;
string statusString = ((statusFlags & enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED) != 0 ? "Symbols Loaded - " : "No symbols loaded") + status;
AD7Module ad7Module = new AD7Module(module, _engine.DebuggedProcess);
AD7SymbolSearchEvent eventObject = new AD7SymbolSearchEvent(ad7Module, statusString, statusFlags);
Send(eventObject, AD7SymbolSearchEvent.IID, null);
}
// Engines notify the debugger that a breakpoint has bound through the breakpoint bound event.
public void OnBreakpointBound(object objBoundBreakpoint)
{
AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint;
IDebugPendingBreakpoint2 pendingBreakpoint;
((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint);
AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint);
Send(eventObject, AD7BreakpointBoundEvent.IID, null);
}
// Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event
public void OnBreakpointError(AD7ErrorBreakpoint bperr)
{
AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr);
Send(eventObject, AD7BreakpointErrorEvent.IID, null);
}
// Engines notify the SDM that a bound breakpoint change resulted in an error
public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason);
Send(eventObject, AD7BreakpointUnboundEvent.IID, null);
}
public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2);
Send(eventObject, AD7CustomDebugEvent.IID, null);
}
private void SendMessage(string message, AD7MessageEvent.Severity severity, bool isAsync)
{
try
{
// IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine.
// The sample engine doesn't take advantage of this.
AD7MessageEvent eventObject = new AD7MessageEvent(message, enum_MESSAGETYPE.MT_MESSAGEBOX, isAsync, severity);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
private static class NativeMethods
{
[DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)]
public static extern IntPtr CoCreateInstance(
[In] ref Guid clsid,
IntPtr punkOuter,
int context,
[In] ref Guid iid);
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tests;
namespace ManualInheritanceChain
{
public class Level1 : BaseOfChain
{
public override void Test(int x)
{
if (x <= 0) throw new ArgumentException("Level 1: x must be positive");
Contract.EndContractBlock();
}
}
[ContractClass(typeof(Level2Contract))]
public abstract class Level2 : Level1
{
public override void Test(int x)
{
if (x <= 0) throw new ArgumentException("Level 2: x must be positive");
Contract.EndContractBlock();
}
public abstract void Test(string s);
[Pure]
protected abstract bool IsNonEmpty(string s);
}
[ContractClassFor(typeof(Level2))]
abstract class Level2Contract : Level2
{
public override void Test(string s)
{
if (s == null) throw new ArgumentNullException("s");
Contract.EndContractBlock();
}
protected override bool IsNonEmpty(string s)
{
Contract.Requires(s != null);
throw new NotImplementedException();
}
}
public class Level3 : Level2
{
public override void Test(int x)
{
if (x <= 0) throw new ArgumentException("Level 3: x must be positive");
Contract.EndContractBlock();
}
public override void Test(string s)
{
// test if we inherit abstract oob class contract
}
protected override bool IsNonEmpty(string s)
{
return !String.IsNullOrEmpty(s);
}
public bool TestIsNonEmpty(string s)
{
return IsNonEmpty(s);
}
}
public class Level4 : Level3
{
public override void Test(int x)
{
if (x <= 0) throw new ArgumentException("Level 4: x must be positive");
Contract.EndContractBlock();
}
public override void Test(string s)
{
if (s == null) throw new ArgumentNullException("Level 4: s");
Contract.EndContractBlock();
}
}
[TestClass]
public class TestClass : DisableAssertUI
{
[TestMethod]
public void TestBasePositive()
{
new BaseOfChain().Test(1);
}
[TestMethod]
public void TestLevel1Positive()
{
new Level1().Test(1);
}
[TestMethod]
public void TestLevel3Positive1()
{
new Level3().Test(1);
}
[TestMethod]
public void TestLevel3Positive2()
{
new Level3().Test("foo");
}
[TestMethod]
public void TestLevel3Positive3()
{
bool result = new Level3().TestIsNonEmpty("foo");
Assert.IsTrue(result);
}
[TestMethod]
public void TestLevel3Positive4()
{
bool result = new Level3().TestIsNonEmpty("");
Assert.IsFalse(result);
}
[TestMethod]
public void TestLevel4Positive1()
{
new Level4().Test(1);
}
[TestMethod]
public void TestLevel4Positive2()
{
new Level4().Test("foo");
}
[TestMethod]
public void TestBaseNegative()
{
try
{
new BaseOfChain().Test(0);
}
catch (ArgumentException a)
{
Assert.AreEqual("Precondition failed: x must be positive", a.Message);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel1Negative()
{
try
{
new Level1().Test(0);
}
catch (ArgumentException a)
{
Assert.AreEqual("Precondition failed: x must be positive", a.Message);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel3Negative1()
{
try
{
new Level3().Test(0);
}
catch (ArgumentException a)
{
Assert.AreEqual("Precondition failed: x must be positive", a.Message);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel3Negative2()
{
try
{
new Level3().Test(null);
}
catch (ArgumentException a)
{
Assert.AreEqual("Value cannot be null.\r\nParameter name: s", a.Message);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel3Negative3()
{
try {
new Level3().TestIsNonEmpty(null);
}
catch (TestRewriterMethods.PreconditionException p) {
Assert.AreEqual("s != null", p.Condition);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel4Negative1()
{
try
{
new Level4().Test(0);
}
catch (ArgumentException a)
{
Assert.AreEqual("Precondition failed: x must be positive", a.Message);
return;
}
throw new Exception();
}
[TestMethod]
public void TestLevel4Negative2()
{
try
{
new Level4().Test(null);
}
catch (ArgumentException a)
{
Assert.IsTrue(a.Message.EndsWith(": s"));
return;
}
throw new Exception();
}
}
}
| |
// 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 Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// Specifies the target CPU architecture.
/// </summary>
public enum TargetArchitecture
{
Unknown,
ARM,
ARM64,
X64,
X86,
Wasm32,
}
/// <summary>
/// Specifies the target ABI.
/// </summary>
public enum TargetOS
{
Unknown,
Windows,
Linux,
OSX,
FreeBSD,
NetBSD,
WebAssembly,
}
public enum TargetAbi
{
Unknown,
/// <summary>
/// Cross-platform console model
/// </summary>
CoreRT,
/// <summary>
/// Jit runtime ABI
/// </summary>
Jit,
/// <summary>
/// Cross-platform portable C++ codegen
/// </summary>
CppCodegen,
}
/// <summary>
/// Represents various details about the compilation target that affect
/// layout, padding, allocations, or ABI.
/// </summary>
public partial class TargetDetails
{
/// <summary>
/// Gets the target CPU architecture.
/// </summary>
public TargetArchitecture Architecture
{
get;
}
/// <summary>
/// Gets the target ABI.
/// </summary>
public TargetOS OperatingSystem
{
get;
}
public TargetAbi Abi
{
get;
}
/// <summary>
/// Gets the size of a pointer for the target of the compilation.
/// </summary>
public int PointerSize
{
get
{
switch (Architecture)
{
case TargetArchitecture.ARM64:
case TargetArchitecture.X64:
return 8;
case TargetArchitecture.ARM:
case TargetArchitecture.X86:
case TargetArchitecture.Wasm32:
return 4;
default:
throw new NotSupportedException();
}
}
}
public bool SupportsRelativePointers
{
get
{
return (Abi != TargetAbi.CppCodegen) && (Architecture != TargetArchitecture.Wasm32);
}
}
/// <summary>
/// Gets the maximum alignment to which something can be aligned
/// </summary>
public int MaximumAlignment
{
get
{
if (Architecture == TargetArchitecture.ARM)
{
// Corresponds to alignment required for __m128 (there's no __m256)
return 8;
}
else if (Architecture == TargetArchitecture.ARM64)
{
// Corresponds to alignmet required for __m256
return 16;
}
// 256-bit vector is the type with the higest alignment we support
return 32;
}
}
public LayoutInt LayoutPointerSize => new LayoutInt(PointerSize);
/// <summary>
/// Gets the default field packing size.
/// </summary>
public int DefaultPackingSize
{
get
{
// We use default packing size of 32 irrespective of the platform.
return 32;
}
}
/// <summary>
/// Gets the minimum required alignment for methods whose address is visible
/// to managed code.
/// </summary>
public int MinimumFunctionAlignment
{
get
{
// We use a minimum alignment of 4 irrespective of the platform.
// This is to prevent confusing the method address with a fat function pointer.
return 4;
}
}
/// <summary>
/// Gets the alignment that is optimal for this platform.
/// </summary>
public int OptimumFunctionAlignment
{
get
{
// Matches the choice in the C++ compiler.
// We want a number that is optimized for micro-op caches in the processor.
return 16;
}
}
public int MinimumCodeAlignment
{
get
{
switch (Architecture)
{
case TargetArchitecture.ARM:
return 2;
case TargetArchitecture.ARM64:
return 4;
default:
return 1;
}
}
}
public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi)
{
Architecture = architecture;
OperatingSystem = targetOS;
Abi = abi;
}
/// <summary>
/// Gets the dyadic logarithm of the maximum size of a primitive type
/// </summary>
public static int MaximumLog2PrimitiveSize
{
get
{
return 3;
}
}
/// <summary>
/// Gets the maximum size of a primitive type
/// </summary>
public static int MaximumPrimitiveSize
{
get
{
return 1 << MaximumLog2PrimitiveSize;
}
}
/// <summary>
/// Retrieves the size of a well known type.
/// </summary>
public LayoutInt GetWellKnownTypeSize(DefType type)
{
switch (type.Category)
{
case TypeFlags.Void:
return new LayoutInt(PointerSize);
case TypeFlags.Boolean:
return new LayoutInt(1);
case TypeFlags.Char:
return new LayoutInt(2);
case TypeFlags.Byte:
case TypeFlags.SByte:
return new LayoutInt(1);
case TypeFlags.UInt16:
case TypeFlags.Int16:
return new LayoutInt(2);
case TypeFlags.UInt32:
case TypeFlags.Int32:
return new LayoutInt(4);
case TypeFlags.UInt64:
case TypeFlags.Int64:
return new LayoutInt(8);
case TypeFlags.Single:
return new LayoutInt(4);
case TypeFlags.Double:
return new LayoutInt(8);
case TypeFlags.UIntPtr:
case TypeFlags.IntPtr:
return new LayoutInt(PointerSize);
}
// Add new well known types if necessary
throw new InvalidOperationException();
}
/// <summary>
/// Retrieves the alignment required by a well known type.
/// </summary>
public LayoutInt GetWellKnownTypeAlignment(DefType type)
{
// Size == Alignment for all platforms.
return GetWellKnownTypeSize(type);
}
/// <summary>
/// Given an alignment of the fields of a type, determine the alignment that is necessary for allocating the object on the GC heap
/// </summary>
/// <returns></returns>
public LayoutInt GetObjectAlignment(LayoutInt fieldAlignment)
{
switch (Architecture)
{
case TargetArchitecture.ARM:
// ARM supports two alignments for objects on the GC heap (4 byte and 8 byte)
if (fieldAlignment.IsIndeterminate)
return LayoutInt.Indeterminate;
if (fieldAlignment.AsInt <= 4)
return new LayoutInt(4);
else
return new LayoutInt(8);
case TargetArchitecture.X64:
case TargetArchitecture.ARM64:
return new LayoutInt(8);
case TargetArchitecture.X86:
case TargetArchitecture.Wasm32:
return new LayoutInt(4);
default:
throw new NotSupportedException();
}
}
/// <summary>
/// Returns True if compiling for Windows
/// </summary>
public bool IsWindows
{
get
{
return OperatingSystem == TargetOS.Windows;
}
}
/// <summary>
/// Maximum number of elements in a HFA type.
/// </summary>
public int MaximumHfaElementCount
{
get
{
// There is a hard limit of 4 elements on an HFA type, see
// http://blogs.msdn.com/b/vcblog/archive/2013/07/12/introducing-vector-calling-convention.aspx
Debug.Assert(Architecture == TargetArchitecture.ARM ||
Architecture == TargetArchitecture.ARM64 ||
Architecture == TargetArchitecture.X64 ||
Architecture == TargetArchitecture.X86);
return 4;
}
}
}
}
| |
namespace Cql.Core.PetaPoco
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using AsyncPoco;
using Cql.Core.Common.Types;
using Cql.Core.SqlServer;
using SortOrder = Cql.Core.Common.Types.SortOrder;
public static class PetaPocoExtensions
{
public static Task<PagedResult<T>> ExecutePagedResult<T>(this Database db, IPagingInfo paging, Sql sqlCount, Sql sqlQuery)
{
return db.PageAsync<T>(paging.PageNumber, paging.PageSize, sqlCount, sqlQuery).ToPagedResult();
}
public static Task<PagedResult<T>> ExecutePagedResult<T>(this Database db, IPagingInfo paging, Sql sql)
{
return db.PageAsync<T>(paging.PageNumber, paging.PageSize, sql).ToPagedResult();
}
public static Task<PagedResult<T>> ExecutePagedResult<T>(this Database db, IPagingInfo paging, string sql, params object[] args)
{
return db.PageAsync<T>(paging.PageNumber, paging.PageSize, sql, args).ToPagedResult();
}
public static Sql FilterByDateRange(this Sql sql, string columnName, IDateRangeFilter filter, DateRangeAdjustment rangeAdjustment = DateRangeAdjustment.None)
{
if (filter == null)
{
return sql;
}
if (filter.DateFrom.HasValue && filter.DateTo.HasValue)
{
return sql.Where($"{columnName} BETWEEN @0 AND @1", GetDateFromValue(filter.DateFrom, rangeAdjustment), GetDateToValue(filter.DateTo, rangeAdjustment));
}
if (filter.DateFrom.HasValue)
{
sql = sql.Where($"{columnName} >= @0", GetDateFromValue(filter.DateFrom, rangeAdjustment));
}
if (filter.DateTo.HasValue)
{
sql = sql.Where($"{columnName} <= @0", GetDateToValue(filter.DateTo, rangeAdjustment));
}
return sql;
}
public static Sql OrderByOptional(this Sql sql, string column, SortOrder? order)
{
return order.HasValue ? sql.OrderBy($"{column} {order}") : sql;
}
public static TQueryResult PocoQuery<TQueryResult>(this IDbConnectionCreator connectionCreator, Func<Database, TQueryResult> executeFunc)
{
using (var connection = connectionCreator.CreateDbConnection())
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
using (var db = CreateDatabase(connection))
{
try
{
return executeFunc(db);
}
catch (SqlException ex)
{
connectionCreator.RaiseExecuteErrorEvent(ex);
throw;
}
finally
{
connectionCreator.RaiseCommandsExecutedEvent();
}
}
}
}
public static async Task<TQueryResult> PocoQuery<TQueryResult>(this IDbConnectionCreator connectionCreator, Func<Database, Task<TQueryResult>> executeFunc)
{
using (var connection = connectionCreator.CreateDbConnection())
{
if (connection.State != ConnectionState.Open)
{
await connection.OpenAsync();
}
using (var db = CreateDatabase(connection))
{
try
{
return await executeFunc(db).ConfigureAwait(false);
}
catch (SqlException ex)
{
connectionCreator.RaiseExecuteErrorEvent(ex);
throw;
}
finally
{
connectionCreator.RaiseCommandsExecutedEvent();
}
}
}
}
/// <summary>
/// Updates if primaryKey is greater than 0, otherwise, inserts. SaveAsync won't work in every case,
/// but works with the 95% of cases where primary key is INT NOT NULL IDENTITY(X,X)
/// </summary>
/// <typeparam name="T">Type of object - must match table name.</typeparam>
/// <param name="db">PetaPoco database</param>
/// <param name="primaryKeyName">Name of primary key column.</param>
/// <param name="poco">Object to save.</param>
/// <param name="primaryKey">Value of primary key field</param>
/// <returns></returns>
public static Task SaveAsync<T>(this Database db, string primaryKeyName, object poco, int primaryKey)
{
if (primaryKey > 0)
{
return db.UpdateAsync(typeof(T).Name, primaryKeyName, poco);
}
return db.InsertAsync(typeof(T).Name, primaryKeyName, true, poco);
}
/// <summary>
/// Updates if primaryKey is greater than 0, otherwise, inserts. SaveAsync won't work in every case,
/// but works with the 95% of cases where primary key is INT NOT NULL IDENTITY(X,X)
/// </summary>
/// <param name="db">PetaPoco database</param>
/// <param name="tableName">Name of database table.</param>
/// <param name="primaryKeyName">Name of primary key column.</param>
/// <param name="poco">Object to save.</param>
/// <param name="primaryKey">Value of primary key field</param>
/// <returns></returns>
public static Task SaveAsync(this Database db, string tableName, string primaryKeyName, object poco, int primaryKey)
{
if (primaryKey > 0)
{
return db.UpdateAsync(tableName, primaryKeyName, poco);
}
return db.InsertAsync(tableName, primaryKeyName, true, poco);
}
/// <summary>
/// Convert the PetaPoco paging object to the CPI paging object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page"></param>
/// <returns></returns>
public static Task<PagedResult<T>> ToPagedResult<T>(this Task<Page<T>> page)
{
var tcs = new TaskCompletionSource<PagedResult<T>>();
page.ContinueWith(async t => tcs.SetResult((await t).ToPagedResult()), TaskContinuationOptions.OnlyOnRanToCompletion);
page.ContinueWith(
t =>
{
if (t.Exception != null)
{
tcs.SetException(t.Exception.InnerExceptions);
}
},
TaskContinuationOptions.OnlyOnFaulted);
page.ContinueWith(t => tcs.SetCanceled(), TaskContinuationOptions.OnlyOnCanceled);
return tcs.Task;
}
/// <summary>
/// Convert the PetaPoco paging object to the CPI paging object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page"></param>
/// <returns></returns>
public static PagedResult<T> ToPagedResult<T>(this Page<T> page)
{
return new PagedResult<T>
{
CurrentPageNumber = page.CurrentPage,
PageSize = page.ItemsPerPage,
TotalRecords = page.TotalItems,
TotalPageCount = page.TotalPages,
Results = page.Items
};
}
public static Sql WhereHasValue(this Sql sql, string columnName, bool? condition)
{
if (!condition.HasValue)
{
return sql;
}
return sql.Where(condition.Value ? $"{columnName} IS NULL" : $"{columnName} IS NOT NULL");
}
/// <summary>
/// Conditionally appends a WHERE CLAUSE statement if the <paramref name="value" /> is not <c>null</c> for each of the
/// specified <paramref name="columns"></paramref> using an "OR" statement to join the predicate conditions.
/// </summary>
/// <param name="sql">The Sql Builder instance</param>
/// <param name="columns">The column names (as they would appear in the WHERE clause)</param>
/// <param name="value">The value</param>
/// <param name="compare">One of the StringCompare options</param>
/// <returns>The original Sql Builder</returns>
public static Sql WhereOptional(this Sql sql, string[] columns, string value, StringCompare? compare)
{
if (columns == null || columns.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(columns));
}
if (string.IsNullOrWhiteSpace(value))
{
return sql;
}
var stringCompare = compare.GetValueOrDefault(StringCompare.Contains);
var firstColumn = true;
var innerSql = new Sql("WHERE (");
foreach (var column in columns)
{
if (!firstColumn)
{
innerSql.Append("OR ");
}
if (stringCompare == StringCompare.Equals)
{
innerSql.Append($"({column} = @0)", value);
}
else
{
innerSql.Append($"({column} LIKE @0)", value.WildcardSearch(stringCompare));
}
firstColumn = false;
}
innerSql.Append(")");
return sql.Append(innerSql);
}
/// <summary>
/// If value is not null, adds a where clause to the SQL.
/// </summary>
/// <param name="sql">The SQL</param>
/// <param name="column">Column name to query.</param>
/// <param name="value">Value to query.</param>
/// <returns></returns>
public static Sql WhereOptional<T>(this Sql sql, string column, T? value)
where T : struct
{
return value.HasValue ? sql.Where($"{column} = @0", value) : sql;
}
/// <summary>
/// If value is not null, adds a where clause to the SQL.
/// </summary>
/// <param name="sql">The SQL</param>
/// <param name="column">Column name to query.</param>
/// <param name="value">Value to query.</param>
/// <param name="convert">The value formation method</param>
/// <returns></returns>
public static Sql WhereOptional<T, TConverted>(this Sql sql, string column, T? value, Func<T, TConverted> convert)
where T : struct
{
return value.HasValue ? sql.Where($"{column} = @0", convert(value.Value)) : sql;
}
/// <summary>
/// If the list isn't null and there are any non-null values in the list, add them to the SQL using an IN() query.
/// </summary>
/// <param name="sql">The PetaPoco SQL.</param>
/// <param name="column">Column name to query.</param>
/// <param name="values">Values to query.</param>
/// <returns></returns>
public static Sql WhereOptional(this Sql sql, string column, IEnumerable<object> values)
{
if (values != null && values.Any(v => v != null))
{
return sql.Where($"{column} IN (@0)", values);
}
return sql;
}
/// <summary>
/// If value is not null or whitespace, adds a where clause to the SQL.
/// </summary>
/// <param name="sql">The SQL</param>
/// <param name="column">Column name to query.</param>
/// <param name="value">Value to query.</param>
/// <param name="compare">Type of comparison - converts to LIKE with %'s in the appropriate position.</param>
/// <returns></returns>
public static Sql WhereOptional(this Sql sql, string column, string value, StringCompare? compare)
{
var stringCompare = compare.GetValueOrDefault(StringCompare.Contains);
return string.IsNullOrWhiteSpace(value)
? sql
: (stringCompare == StringCompare.Equals ? sql.Where($"{column} = @0", value) : sql.Where($"{column} LIKE @0", value.WildcardSearch(stringCompare)));
}
/// <summary>
/// If the list isn't null and there are any non-null values in the list, add them to the SQL using an IN() query.
/// </summary>
/// <param name="sql">The PetaPoco SQL.</param>
/// <param name="column">Column name to query.</param>
/// <param name="values">Values to query.</param>
/// <returns></returns>
public static Sql WhereOptional(this Sql sql, string column, IEnumerable<int> values)
{
return values == null ? sql : sql.WhereOptional(column, values.Cast<object>());
}
private static Database CreateDatabase(DbConnection connection)
{
return new Database(connection);
}
private static DateTime GetDateFromValue(DateTime? dateFrom, DateRangeAdjustment rangeAdjustment)
{
var value = dateFrom.GetValueOrDefault();
return rangeAdjustment == DateRangeAdjustment.Inclusive ? new DateTime(value.Year, value.Month, value.Day, 0, 0, 0, 0, value.Kind) : value;
}
private static DateTime GetDateToValue(DateTime? dateTo, DateRangeAdjustment rangeAdjustment)
{
var value = dateTo.GetValueOrDefault();
return rangeAdjustment == DateRangeAdjustment.Inclusive ? new DateTime(value.Year, value.Month, value.Day, 23, 59, 59, 999, value.Kind) : value;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------------
//
// Description:
// This is a sub class of the abstract class for Package.
// This implementation is specific to Zip file format.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
//------------------------------------------------------
//
// Public Constructors
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException("contentType");
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straighforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Internal Constructors
//
//------------------------------------------------------
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the speficied access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return String.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
// None
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some dont. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
static private CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Members
private const int InitialPartListSize = 50;
private const int InitialPieceNameListSize = 50;
private ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private bool _shouldCloseContainerStream;
private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private FileAccess _packageFileAccess;
private FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Class
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dicitonary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extenstion should not be null");
Debug.Assert(extensionB != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extenstion should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
#region ContentTypeHelper Class
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
#region Constructor
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
#endregion Constructor
#region Internal Properties
internal static string ContentTypeFileName
{
get
{
return s_contentTypesFile;
}
}
#endregion Internal Properties
#region Internal Methods
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
#endregion Internal Methods
#region Private Methods
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_typesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0)
continue;
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
#region Default Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName);
ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_defaultTagName);
#endregion Default Tag
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
#region Override Tag
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName);
ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_overrideTagName);
#endregion Override Tag
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(s_overrideTagName);
xmlWriter.WriteAttributeString(s_partNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(s_defaultTagName);
xmlWriter.WriteAttributeString(s_extensionAttributeName, extension);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
#endregion Private Methods
#region Member Variables
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private Dictionary<string, ContentType> _defaultDictionary;
private ZipArchive _zipArchive;
private FileMode _packageFileMode;
private FileAccess _packageFileAccess;
private ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private static readonly string s_contentTypesFile = "[Content_Types].xml";
private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private static readonly int s_defaultDictionaryInitialSize = 16;
private static readonly int s_overrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private static readonly string s_typesTagName = "Types";
private static readonly string s_defaultTagName = "Default";
private static readonly string s_extensionAttributeName = "Extension";
private static readonly string s_contentTypeAttributeName = "ContentType";
private static readonly string s_overrideTagName = "Override";
private static readonly string s_partNameAttributeName = "PartName";
private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample.";
#endregion Member Variables
}
#endregion ContentTypeHelper Class
#endregion Private Class
}
}
| |
// 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.Globalization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// The pattern matcher is thread-safe. However, it maintains an internal cache of
/// information as it is used. Therefore, you should not keep it around forever and should get
/// and release the matcher appropriately once you no longer need it.
/// Also, while the pattern matcher is culture aware, it uses the culture specified in the
/// constructor.
/// </summary>
internal sealed class PatternMatcher
{
private readonly object _gate = new object();
private readonly Dictionary<string, List<TextSpan>> _stringToWordParts = new Dictionary<string, List<TextSpan>>();
private readonly Dictionary<string, List<TextSpan>> _stringToCharacterParts = new Dictionary<string, List<TextSpan>>();
private readonly Func<string, List<TextSpan>> _breakIntoWordParts = StringBreaker.BreakIntoWordParts;
private readonly Func<string, List<TextSpan>> _breakIntoCharacterParts = StringBreaker.BreakIntoCharacterParts;
private readonly Dictionary<string, string[]> _patternToParts = new Dictionary<string, string[]>();
private readonly Func<string, string[]> _breakPatternIntoParts;
// PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops
private readonly CompareInfo _compareInfo;
/// <summary>
/// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison.
/// </summary>
public PatternMatcher(bool verbatimIdentifierPrefixIsWordCharacter = false) : this(CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter)
{
}
/// <summary>
/// Construct a new PatternMatcher using the specified culture.
/// </summary>
/// <param name="culture">The culture to use for string searching and comparison.</param>
/// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param>
public PatternMatcher(CultureInfo culture, bool verbatimIdentifierPrefixIsWordCharacter)
{
_compareInfo = culture.CompareInfo;
_breakPatternIntoParts = (pattern) => BreakPatternIntoParts(pattern, verbatimIdentifierPrefixIsWordCharacter);
}
private List<TextSpan> GetCharacterParts(string pattern)
{
lock (_gate)
{
return _stringToCharacterParts.GetOrAdd(pattern, _breakIntoCharacterParts);
}
}
private List<TextSpan> GetWordParts(string word)
{
lock (_gate)
{
return _stringToWordParts.GetOrAdd(word, _breakIntoWordParts);
}
}
private string[] GetPatternParts(string pattern)
{
lock (_gate)
{
return _patternToParts.GetOrAdd(pattern, _breakPatternIntoParts);
}
}
internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate, string pattern)
{
return MatchSingleWordPattern(candidate, pattern, punctuationStripped: false);
}
private static bool ContainsUpperCaseLetter(string pattern)
{
// Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation
for (int i = 0; i < pattern.Length; i++)
{
if (char.IsUpper(pattern[i]))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a candidate string should matched given the user's pattern.
/// </summary>
/// <param name="candidate">The string to test.</param>
/// <param name="pattern">The pattern to match against, which may use things like
/// Camel-Cased patterns.</param>
/// <param name="punctuationStripped">Whether punctuation (space or asterisk) was stripped
/// from the pattern.</param>
private PatternMatch? MatchSingleWordPattern(string candidate, string pattern, bool punctuationStripped)
{
// We never match whitespace only
if (string.IsNullOrWhiteSpace(pattern) || string.IsNullOrWhiteSpace(candidate))
{
return null;
}
// The logic for pattern matching is now as follows:
//
// 1) Break the pattern passed in into pattern parts. Breaking is rather simple and a
// good way to think about it that if gives you all the individual alphanumeric chunks
// of the pattern.
//
// 2) For each part try to match the part against the candidate value.
//
// 3) Matching is as follows:
//
// a) Check if the part matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
//
// b) Check if the part is a prefix of the candidate, in a case insensitive or
// sensitive manner. If it does, return that there was a prefix match.
//
// c) If the part is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of
// some word part. That way we don't match something like 'Class' when the user
// types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
// 'a').
//
// d) If the part was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
//
// e) If the part was not entirely lowercase, then attempt a camel cased match as
// well.
//
// f) The pattern is all lower case. Is it a case insensitive substring of the candidate starting
// on a part boundary of the candidate?
//
// Only if all parts have some sort of match is the pattern considered matched.
int index = _compareInfo.IndexOf(candidate, pattern, CompareOptions.IgnoreCase);
if (index == 0)
{
if (pattern.Length == candidate.Length)
{
// a) Check if the part matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
return new PatternMatch(PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == pattern);
}
else
{
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return new PatternMatch(PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, pattern));
}
}
var isLowercase = !ContainsUpperCaseLetter(pattern);
if (isLowercase)
{
if (index > 0)
{
// c) If the part is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of some
// word part. That way we don't match something like 'Class' when the user types 'a'.
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var candidateParts = GetWordParts(candidate);
foreach (var part in candidateParts)
{
if (PartStartsWith(candidate, part, pattern, CompareOptions.IgnoreCase))
{
return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: PartStartsWith(candidate, part, pattern, CompareOptions.None));
}
}
}
}
else
{
// d) If the part was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
if (_compareInfo.IndexOf(candidate, pattern) > 0)
{
return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true);
}
}
if (!isLowercase)
{
// e) If the part was not entirely lowercase, then attempt a camel cased match as well.
var patternParts = GetCharacterParts(pattern);
if (patternParts.Count > 0)
{
var candidateParts = GetWordParts(candidate);
var camelCaseWeight = TryCamelCaseMatch(candidate, candidateParts, pattern, patternParts, CompareOptions.None);
if (camelCaseWeight.HasValue)
{
return new PatternMatch(PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight);
}
camelCaseWeight = TryCamelCaseMatch(candidate, candidateParts, pattern, patternParts, CompareOptions.IgnoreCase);
if (camelCaseWeight.HasValue)
{
return new PatternMatch(PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight);
}
}
}
if (isLowercase)
{
// f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
// We could check every character boundary start of the candidate for the pattern. However, that's
// an m * n operation in the wost case. Instead, find the first instance of the pattern
// substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
// filter the list based on a substring that starts on a capital letter and also with a lowercase one.
// (Pattern: fogbar, Candidate: quuxfogbarFogBar).
if (pattern.Length < candidate.Length)
{
var firstInstance = _compareInfo.IndexOf(candidate, pattern, CompareOptions.IgnoreCase);
if (firstInstance != -1 && char.IsUpper(candidate[firstInstance]))
{
return new PatternMatch(PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false);
}
}
}
return null;
}
private static bool ContainsSpaceOrAsterisk(string text)
{
for (int i = 0; i < text.Length; i++)
{
char ch = text[i];
if (ch == ' ' || ch == '*')
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <param name="candidate">The word being tested.</param>
/// <param name="pattern">The multiple-word query pattern.</param>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public IEnumerable<PatternMatch> MatchPattern(string candidate, string pattern)
{
PatternMatch[] matches;
var singleMatch = MatchPatternInternal(candidate, pattern, wantAllMatches: true, allMatches: out matches);
if (singleMatch.HasValue)
{
return SpecializedCollections.SingletonEnumerable(singleMatch.Value);
}
return matches;
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <remarks>
/// PERF: This is slightly faster and uses less memory than <see cref="MatchPattern(string, string)"/>
/// so, unless you need to know the full set of matches, use this version.
/// </remarks>
/// <param name="candidate">The word being tested.</param>
/// <param name="pattern">The multiple-word query pattern.</param>
/// <returns>If this was a match, the first element of the set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public PatternMatch? MatchPatternFirstOrNullable(string candidate, string pattern)
{
PatternMatch[] ignored;
return MatchPatternInternal(candidate, pattern, wantAllMatches: false, allMatches: out ignored);
}
/// <summary>
/// Internal helper for MatchPatternInternal
/// </summary>
/// <remarks>
/// PERF: Designed to minimize allocations in common cases.
/// If there's no match, then null is returned.
/// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable)
/// If there are multiple matches, and the caller wants them all, then a List is allocated.
/// </remarks>
/// <param name="candidate">The word being tested.</param>
/// <param name="pattern">The multiple-word query pattern.</param>
/// <param name="wantAllMatches">Does the caller want all matches or just the first?</param>
/// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param>
/// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns>
private PatternMatch? MatchPatternInternal(string candidate, string pattern, bool wantAllMatches, out PatternMatch[] allMatches)
{
allMatches = null;
// We never match whitespace only
if (string.IsNullOrWhiteSpace(pattern) || string.IsNullOrWhiteSpace(candidate))
{
return null;
}
// First check if the pattern matches as is. This is also useful if the pattern contains
// characters we would normally strip when splitting into parts that we also may want to
// match in the candidate. For example if the pattern is "@int" and the candidate is
// "@int", then that will show up as an exact match here.
//
// Note: if the pattern contains a space or an asterisk then we must assume that it's a
// multi-word pattern.
if (!ContainsSpaceOrAsterisk(pattern))
{
var match = MatchSingleWordPattern(candidate, pattern, punctuationStripped: false);
if (match != null)
{
return match;
}
}
var patternParts = GetPatternParts(pattern);
PatternMatch[] matches = null;
for (int i = 0; i < patternParts.Length; i++)
{
var word = patternParts[i];
// Try to match the candidate with this word
var result = MatchSingleWordPattern(candidate, word, punctuationStripped: true);
if (result == null)
{
return null;
}
if (!wantAllMatches || patternParts.Length == 1)
{
// Stop at the first word
return result;
}
if (matches == null)
{
matches = new PatternMatch[patternParts.Length];
}
matches[i] = result.Value;
}
allMatches = matches;
return null;
}
private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter)
{
return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@');
}
private static int CountParts(string pattern, bool verbatimIdentifierPrefixIsWordCharacter)
{
int count = 0;
int wordLength = 0;
for (int i = 0; i < pattern.Length; i++)
{
if (IsWordChar(pattern[i], verbatimIdentifierPrefixIsWordCharacter))
{
wordLength++;
}
else
{
if (wordLength > 0)
{
count++;
wordLength = 0;
}
}
}
if (wordLength > 0)
{
count++;
}
return count;
}
private static string[] BreakPatternIntoParts(string pattern, bool verbatimIdentifierPrefixIsWordCharacter)
{
int partCount = CountParts(pattern, verbatimIdentifierPrefixIsWordCharacter);
if (partCount == 0)
{
return SpecializedCollections.EmptyArray<string>();
}
var result = new string[partCount];
int resultIndex = 0;
int wordStart = 0;
int wordLength = 0;
for (int i = 0; i < pattern.Length; i++)
{
var ch = pattern[i];
if (IsWordChar(ch, verbatimIdentifierPrefixIsWordCharacter))
{
if (wordLength++ == 0)
{
wordStart = i;
}
}
else
{
if (wordLength > 0)
{
result[resultIndex++] = pattern.Substring(wordStart, wordLength);
wordLength = 0;
}
}
}
if (wordLength > 0)
{
result[resultIndex++] = pattern.Substring(wordStart, wordLength);
}
return result;
}
/// <summary>
/// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part?
/// </summary>
/// <param name="candidate">The candidate text</param>
/// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
/// <param name="pattern">The pattern text</param>
/// <param name="patternPart">The span within the <paramref name="pattern"/> text</param>
/// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
/// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with
/// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns>
private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions)
{
if (patternPart.Length > candidatePart.Length)
{
// Pattern part is longer than the candidate part. There can never be a match.
return false;
}
return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0;
}
/// <summary>
/// Does the given part start with the given pattern?
/// </summary>
/// <param name="candidate">The candidate text</param>
/// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
/// <param name="pattern">The pattern text</param>
/// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
/// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns>
private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions)
{
return PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions);
}
private int? TryCamelCaseMatch(string candidate, List<TextSpan> candidateParts, string pattern, List<TextSpan> patternParts, CompareOptions compareOption)
{
// Note: we may have more pattern parts than candidate parts. This is because multiple
// pattern parts may match a candidate part. For example "SiUI" against "SimpleUI".
// We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U
// and I will both match in UI.
int candidateCurrent = 0;
int patternCurrent = 0;
int? firstMatch = null;
bool? contiguous = null;
while (true)
{
// Let's consider our termination cases
if (patternCurrent == patternParts.Count)
{
Contract.Requires(firstMatch.HasValue);
Contract.Requires(contiguous.HasValue);
// We did match! We shall assign a weight to this
int weight = 0;
// Was this contiguous?
if (contiguous.Value)
{
weight += 1;
}
// Did we start at the beginning of the candidate?
if (firstMatch.Value == 0)
{
weight += 2;
}
return weight;
}
else if (candidateCurrent == candidateParts.Count)
{
// No match, since we still have more of the pattern to hit
return null;
}
var candidatePart = candidateParts[candidateCurrent];
bool gotOneMatchThisCandidate = false;
// Consider the case of matching SiUI against SimpleUIElement. The candidate parts
// will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si'
// against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to
// still keep matching pattern parts against that candidate part.
for (; patternCurrent < patternParts.Count; patternCurrent++)
{
var patternPart = patternParts[patternCurrent];
if (gotOneMatchThisCandidate)
{
// We've already gotten one pattern part match in this candidate. We will
// only continue trying to consumer pattern parts if the last part and this
// part are both upper case.
if (!char.IsUpper(pattern[patternParts[patternCurrent - 1].Start]) ||
!char.IsUpper(pattern[patternParts[patternCurrent].Start]))
{
break;
}
}
if (!PartStartsWith(candidate, candidatePart, pattern, patternPart, compareOption))
{
break;
}
gotOneMatchThisCandidate = true;
firstMatch = firstMatch ?? candidateCurrent;
// If we were contiguous, then keep that value. If we weren't, then keep that
// value. If we don't know, then set the value to 'true' as an initial match is
// obviously contiguous.
contiguous = contiguous ?? true;
candidatePart = new TextSpan(candidatePart.Start + patternPart.Length, candidatePart.Length - patternPart.Length);
}
// Check if we matched anything at all. If we didn't, then we need to unset the
// contiguous bit if we currently had it set.
// If we haven't set the bit yet, then that means we haven't matched anything so
// far, and we don't want to change that.
if (!gotOneMatchThisCandidate && contiguous.HasValue)
{
contiguous = false;
}
// Move onto the next candidate.
candidateCurrent++;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using GitVersion.Common;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using LibGit2Sharp;
namespace GitVersion.Configuration
{
public class BranchConfigurationCalculator : IBranchConfigurationCalculator
{
private const string FallbackConfigName = "Fallback";
private readonly ILog log;
private readonly IRepositoryMetadataProvider repositoryMetadataProvider;
public BranchConfigurationCalculator(ILog log, IRepositoryMetadataProvider repositoryMetadataProvider)
{
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.repositoryMetadataProvider = repositoryMetadataProvider ?? throw new ArgumentNullException(nameof(repositoryMetadataProvider));
}
/// <summary>
/// Gets the <see cref="BranchConfig"/> for the current commit.
/// </summary>
public BranchConfig GetBranchConfiguration(Branch targetBranch, Commit currentCommit, Config configuration, IList<Branch> excludedInheritBranches = null)
{
var matchingBranches = configuration.GetConfigForBranch(targetBranch.NameWithoutRemote());
if (matchingBranches == null)
{
log.Info($"No branch configuration found for branch {targetBranch.FriendlyName}, falling back to default configuration");
matchingBranches = BranchConfig.CreateDefaultBranchConfig(FallbackConfigName)
.Apply(new BranchConfig
{
Regex = "",
VersioningMode = configuration.VersioningMode,
Increment = configuration.Increment ?? IncrementStrategy.Inherit,
});
}
if (matchingBranches.Increment == IncrementStrategy.Inherit)
{
matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches);
if (matchingBranches.Name.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit)
{
// We tried, and failed to inherit, just fall back to patch
matchingBranches.Increment = IncrementStrategy.Patch;
}
}
return matchingBranches;
}
// TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases
private BranchConfig InheritBranchConfiguration(Branch targetBranch, BranchConfig branchConfiguration, Commit currentCommit, Config configuration, IList<Branch> excludedInheritBranches)
{
using (log.IndentLog("Attempting to inherit branch configuration from parent branch"))
{
var excludedBranches = new[] { targetBranch };
// Check if we are a merge commit. If so likely we are a pull request
var parentCount = currentCommit.Parents.Count();
if (parentCount == 2)
{
excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches);
}
excludedInheritBranches ??= repositoryMetadataProvider.GetExcludedInheritBranches(configuration);
// Add new excluded branches.
foreach (var excludedBranch in excludedBranches.ExcludingBranches(excludedInheritBranches))
{
excludedInheritBranches.Add(excludedBranch);
}
var branchesToEvaluate = repositoryMetadataProvider.ExcludingBranches(excludedInheritBranches).ToList();
var branchPoint = repositoryMetadataProvider
.FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray());
List<Branch> possibleParents;
if (branchPoint == BranchCommit.Empty)
{
possibleParents = repositoryMetadataProvider.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate)
// It fails to inherit Increment branch configuration if more than 1 parent;
// therefore no point to get more than 2 parents
.Take(2)
.ToList();
}
else
{
var branches = repositoryMetadataProvider.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList();
if (branches.Count > 1)
{
var currentTipBranches = repositoryMetadataProvider.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList();
possibleParents = branches.Except(currentTipBranches).ToList();
}
else
{
possibleParents = branches;
}
}
log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)));
if (possibleParents.Count == 1)
{
var branchConfig = GetBranchConfiguration(possibleParents[0], currentCommit, configuration, excludedInheritBranches);
// If we have resolved a fallback config we should not return that we have got config
if (branchConfig.Name != FallbackConfigName)
{
return new BranchConfig(branchConfiguration)
{
Increment = branchConfig.Increment,
PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion,
// If we are inheriting from develop then we should behave like develop
TracksReleaseBranches = branchConfig.TracksReleaseBranches
};
}
}
// If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config
// if develop exists and master if not
var errorMessage = possibleParents.Count == 0
? "Failed to inherit Increment branch configuration, no branches found."
: "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName));
var chosenBranch = repositoryMetadataProvider.GetChosenBranch(configuration);
if (chosenBranch == null)
{
// TODO We should call the build server to generate this exception, each build server works differently
// for fetch issues and we could give better warnings.
throw new InvalidOperationException("Could not find a 'develop' or 'master' branch, neither locally nor remotely.");
}
var branchName = chosenBranch.FriendlyName;
log.Warning(errorMessage + System.Environment.NewLine + "Falling back to " + branchName + " branch config");
// To prevent infinite loops, make sure that a new branch was chosen.
if (targetBranch.IsSameBranch(chosenBranch))
{
var developOrMasterConfig =
ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(
chosenBranch, branchConfiguration, configuration);
if (developOrMasterConfig != null)
{
return developOrMasterConfig;
}
log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead.");
return new BranchConfig(branchConfiguration)
{
Increment = IncrementStrategy.Patch
};
}
var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches);
var configIncrement = inheritingBranchConfig.Increment;
if (inheritingBranchConfig.Name.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit)
{
log.Warning("Fallback config inherits by default, dropping to patch increment");
configIncrement = IncrementStrategy.Patch;
}
return new BranchConfig(branchConfiguration)
{
Increment = configIncrement,
PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion,
// If we are inheriting from develop then we should behave like develop
TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches
};
}
}
private Branch[] CalculateWhenMultipleParents(Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches)
{
var parents = currentCommit.Parents.ToArray();
var branches = repositoryMetadataProvider.GetBranchesForCommit(parents[1]);
if (branches.Count == 1)
{
var branch = branches[0];
excludedBranches = new[]
{
currentBranch,
branch
};
currentBranch = branch;
}
else if (branches.Count > 1)
{
currentBranch = branches.FirstOrDefault(b => b.NameWithoutRemote() == "master") ?? branches.First();
}
else
{
var possibleTargetBranches = repositoryMetadataProvider.GetBranchesForCommit(parents[0]);
if (possibleTargetBranches.Count > 1)
{
currentBranch = possibleTargetBranches.FirstOrDefault(b => b.NameWithoutRemote() == "master") ?? possibleTargetBranches.First();
}
else
{
currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch;
}
}
log.Info("HEAD is merge commit, this is likely a pull request using " + currentBranch.FriendlyName + " as base");
return excludedBranches;
}
private static BranchConfig ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(Branch chosenBranch, BranchConfig branchConfiguration, Config config)
{
BranchConfig masterOrDevelopConfig = null;
var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex;
var masterBranchRegex = config.Branches[Config.MasterBranchKey].Regex;
if (Regex.IsMatch(chosenBranch.FriendlyName, developBranchRegex, RegexOptions.IgnoreCase))
{
// Normally we would not expect this to happen but for safety we add a check
if (config.Branches[Config.DevelopBranchKey].Increment !=
IncrementStrategy.Inherit)
{
masterOrDevelopConfig = new BranchConfig(branchConfiguration)
{
Increment = config.Branches[Config.DevelopBranchKey].Increment
};
}
}
else if (Regex.IsMatch(chosenBranch.FriendlyName, masterBranchRegex, RegexOptions.IgnoreCase))
{
// Normally we would not expect this to happen but for safety we add a check
if (config.Branches[Config.MasterBranchKey].Increment !=
IncrementStrategy.Inherit)
{
masterOrDevelopConfig = new BranchConfig(branchConfiguration)
{
Increment = config.Branches[Config.DevelopBranchKey].Increment
};
}
}
return masterOrDevelopConfig;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Manatee.Trello.Internal.Caching;
using Manatee.Trello.Internal.DataAccess;
using Manatee.Trello.Internal.Validation;
using Manatee.Trello.Json;
namespace Manatee.Trello.Internal.Synchronization
{
internal class CardContext : DeletableSynchronizationContext<IJsonCard>
{
private static readonly Dictionary<string, object> Parameters;
private static readonly Card.Fields MemberFields;
public static Dictionary<string, object> CurrentParameters
{
get
{
lock (Parameters)
{
if (!Parameters.Any())
GenerateParameters();
return new Dictionary<string, object>(Parameters);
}
}
}
public ReadOnlyActionCollection Actions { get; }
public AttachmentCollection Attachments { get; }
public BadgesContext BadgesContext { get; }
public CheckListCollection CheckLists { get; }
public CommentCollection Comments { get; }
public ReadOnlyCustomFieldCollection CustomFields { get; }
public CardLabelCollection Labels { get; }
public MemberCollection Members { get; }
public ReadOnlyPowerUpDataCollection PowerUpData { get; }
public CardStickerCollection Stickers { get; }
public ReadOnlyMemberCollection VotingMembers { get; }
public virtual bool HasValidId => IdRule.Instance.Validate(Data.Id, null) == null;
static CardContext()
{
Parameters = new Dictionary<string, object>();
MemberFields = Card.Fields.Badges |
Card.Fields.DateLastActivity |
Card.Fields.Description |
Card.Fields.Due |
Card.Fields.IsArchived |
Card.Fields.IsComplete |
Card.Fields.IsSubscribed |
Card.Fields.Labels |
Card.Fields.List |
Card.Fields.ManualCoverAttachment |
Card.Fields.Name |
Card.Fields.Position |
Card.Fields.ShortId |
Card.Fields.ShortUrl |
Card.Fields.Url;
Properties = new Dictionary<string, Property<IJsonCard>>
{
{
nameof(Card.Board),
new Property<IJsonCard, Board>((d, a) => d.Board?.GetFromCache<Board, IJsonBoard>(a),
(d, o) => d.Board = o?.Json)
},
{
nameof(Card.Description),
new Property<IJsonCard, string>((d, a) => d.Desc, (d, o) => d.Desc = o)
},
{
nameof(Card.DueDate),
new Property<IJsonCard, DateTime?>((d, a) => d.Due?.Decode(), (d, o) =>
{
d.Due = o?.Encode();
d.ForceDueDate = o == null;
})
},
{
nameof(Card.Id),
new Property<IJsonCard, string>((d, a) => d.Id, (d, o) => d.Id = o)
},
{
nameof(Card.IsArchived),
new Property<IJsonCard, bool?>((d, a) => d.Closed, (d, o) => d.Closed = o)
},
{
nameof(Card.IsComplete),
new Property<IJsonCard, bool?>((d, a) => d.DueComplete, (d, o) => d.DueComplete = o)
},
{
nameof(Card.IsSubscribed),
new Property<IJsonCard, bool?>((d, a) => d.Subscribed, (d, o) => d.Subscribed = o)
},
{
nameof(Card.LastActivity),
new Property<IJsonCard, DateTime?>((d, a) => d.DateLastActivity, (d, o) => d.DateLastActivity = o)
},
{
nameof(Card.List),
new Property<IJsonCard, List>((d, a) => d.List?.GetFromCache<List, IJsonList>(a),
(d, o) => d.List = o?.Json)
},
{
nameof(Card.Name),
new Property<IJsonCard, string>((d, a) => d.Name, (d, o) => d.Name = o)
},
{
nameof(Card.Position),
new Property<IJsonCard, Position>((d, a) => Position.GetPosition(d.Pos),
(d, o) => d.Pos = Position.GetJson(o))
},
{
nameof(Card.ShortId),
new Property<IJsonCard, int?>((d, a) => d.IdShort, (d, o) => d.IdShort = o)
},
{
nameof(Card.ShortUrl),
new Property<IJsonCard, string>((d, a) => d.ShortUrl, (d, o) => d.ShortUrl = o)
},
{
nameof(Card.Url),
new Property<IJsonCard, string>((d, a) => d.Url, (d, o) => d.Url = o)
},
{
nameof(IJsonCard.ValidForMerge),
new Property<IJsonCard, bool>((d, a) => d.ValidForMerge, (d, o) => d.ValidForMerge = o, true)
},
};
}
public CardContext(string id, TrelloAuthorization auth)
: base(auth)
{
Data.Id = id;
Actions = new ReadOnlyActionCollection(typeof(Card), () => Data.Id, auth);
Actions.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Actions)});
Attachments = new AttachmentCollection(() => Data.Id, auth);
Attachments.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Attachments)});
CheckLists = new CheckListCollection(() => Data.Id, auth);
CheckLists.Refreshed += (s, e) => OnMerged(new List<string> {nameof(CheckLists)});
Comments = new CommentCollection(() => Data.Id, auth);
Comments.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Comments)});
CustomFields = new ReadOnlyCustomFieldCollection(() => Data.Id, auth);
CustomFields.Refreshed += (s, e) => OnMerged(new List<string> {nameof(CustomFields)});
Labels = new CardLabelCollection(this, auth);
Labels.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Labels)});
Members = new MemberCollection(() => Data.Id, auth);
Members.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Members)});
PowerUpData = new ReadOnlyPowerUpDataCollection(EntityRequestType.Card_Read_PowerUpData, () => Data.Id, auth);
PowerUpData.Refreshed += (s, e) => OnMerged(new List<string> {nameof(PowerUpData)});
Stickers = new CardStickerCollection(() => Data.Id, auth);
Stickers.Refreshed += (s, e) => OnMerged(new List<string> {nameof(Stickers)});
VotingMembers = new ReadOnlyMemberCollection(EntityRequestType.Card_Read_MembersVoted, () => Data.Id, auth);
VotingMembers.Refreshed += (s, e) => OnMerged(new List<string> {nameof(VotingMembers)});
BadgesContext = new BadgesContext(Auth);
Data.Badges = BadgesContext.Data;
}
public static void UpdateParameters()
{
lock (Parameters)
{
Parameters.Clear();
}
}
private static void GenerateParameters()
{
lock (Parameters)
{
Parameters.Clear();
var flags = Enum.GetValues(typeof(Card.Fields)).Cast<Card.Fields>().ToList();
var availableFields = (Card.Fields)flags.Cast<int>().Sum();
var memberFields = availableFields & MemberFields & Card.DownloadedFields;
Parameters["fields"] = memberFields.GetDescription();
var parameterFields = availableFields & Card.DownloadedFields & (~MemberFields);
if (parameterFields.HasFlag(Card.Fields.Actions))
{
Parameters["actions"] = "all";
Parameters["actions_format"] = "list";
}
if (parameterFields.HasFlag(Card.Fields.Attachments))
{
Parameters["attachments"] = "true";
Parameters["attachment_fields"] = AttachmentContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Card.Fields.CustomFields))
Parameters["customFieldItems"] = "true";
if (parameterFields.HasFlag(Card.Fields.Checklists))
{
Parameters["checklists"] = "all";
Parameters["checklist_fields"] = CheckListContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Card.Fields.Comments))
{
Parameters["actions"] = "commentCard";
Parameters["actions_format"] = "list";
}
if (parameterFields.HasFlag(Card.Fields.Members))
{
Parameters["members"] = "true";
Parameters["member_fields"] = MemberContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Card.Fields.Stickers))
Parameters["stickers"] = "true";
if (parameterFields.HasFlag(Card.Fields.VotingMembers))
{
Parameters["membersVoted"] = "true";
Parameters["membersVoted_fields"] = MemberContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Card.Fields.Board))
{
Parameters["board"] = "true";
Parameters["board_fields"] = BoardContext.CurrentParameters["fields"];
}
if (parameterFields.HasFlag(Card.Fields.List))
{
Parameters["list"] = "true";
Parameters["list_fields"] = ListContext.CurrentParameters["fields"];
}
}
}
public override Endpoint GetRefreshEndpoint()
{
return EndpointFactory.Build(EntityRequestType.Card_Read_Refresh,
new Dictionary<string, object> {{"_id", Data.Id}});
}
protected override Dictionary<string, object> GetParameters()
{
return CurrentParameters;
}
protected override Endpoint GetDeleteEndpoint()
{
return EndpointFactory.Build(EntityRequestType.Card_Write_Delete,
new Dictionary<string, object> {{"_id", Data.Id}});
}
protected override async Task SubmitData(IJsonCard json, CancellationToken ct)
{
var endpoint = EndpointFactory.Build(EntityRequestType.Card_Write_Update,
new Dictionary<string, object> {{"_id", Data.Id}});
var newData = await JsonRepository.Execute(Auth, endpoint, json, ct);
Merge(newData);
}
protected override IEnumerable<string> MergeDependencies(IJsonCard json, bool overwrite)
{
var properties = BadgesContext.Merge(json.Badges, overwrite)
.Select(p => $"{nameof(Card.Badges)}.{p}")
.ToList();
if (json.Actions != null)
{
Actions.Update(json.Actions.Select(a => a.GetFromCache<Action, IJsonAction>(Auth, overwrite)));
properties.Add(nameof(Card.Actions));
}
if (json.Attachments != null)
{
Attachments.Update(json.Attachments.Select(a => a.TryGetFromCache<Attachment, IJsonAttachment>(overwrite) ?? new Attachment(a, Data.Id, Auth)));
properties.Add(nameof(Card.Attachments));
}
if (json.CheckLists != null)
{
CheckLists.Update(json.CheckLists.Select(a => a.GetFromCache<CheckList, IJsonCheckList>(Auth, overwrite)));
properties.Add(nameof(Card.CheckLists));
}
if (json.Comments != null)
{
Comments.Update(json.Comments.Select(a => a.GetFromCache<Action, IJsonAction>(Auth, overwrite)));
properties.Add(nameof(Card.Comments));
}
if (json.CustomFields != null)
{
CustomFields.Update(json.CustomFields.Select(a => a.GetFromCache<CustomField, IJsonCustomField>(Auth, overwrite, Data.Id)));
properties.Add(nameof(Card.CustomFields));
}
if (json.Labels != null)
{
Labels.Update(json.Labels.Select(a => a.GetFromCache<Label, IJsonLabel>(Auth, overwrite)));
properties.Add(nameof(Card.Labels));
}
if (json.Members != null)
{
Members.Update(json.Members.Select(a => a.GetFromCache<Member, IJsonMember>(Auth, overwrite)));
properties.Add(nameof(Card.Members));
}
if (json.PowerUpData != null)
{
PowerUpData.Update(json.PowerUpData.Select(a => a.GetFromCache<PowerUpData, IJsonPowerUpData>(Auth, overwrite)));
properties.Add(nameof(Card.PowerUpData));
}
if (json.Stickers != null)
{
Stickers.Update(json.Stickers.Select(a => a.TryGetFromCache<Sticker, IJsonSticker>(overwrite) ?? new Sticker(a, Data.Id, Auth)));
properties.Add(nameof(Card.Stickers));
}
if (json.MembersVoted != null)
{
VotingMembers.Update(json.MembersVoted.Select(a => a.GetFromCache<Member, IJsonMember>(Auth, overwrite)));
properties.Add(nameof(Card.VotingMembers));
}
return properties;
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class EquipmentService : IEquipmentService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public EquipmentService(DbAppContext context)
{
_context = context;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Equipment created</response>
public virtual IActionResult EquipmentBulkPostAsync(Equipment[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentGetAsync()
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular Equipment</remarks>
/// <param name="id">id of Equipment to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">Equipment not found</response>
public virtual IActionResult EquipmentIdAttachmentsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Equipment to delete</param>
/// <response code="200">OK</response>
/// <response code="404">Equipment not found</response>
public virtual IActionResult EquipmentIdDeletePostAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Equipment to fetch EquipmentAttachments for</param>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentIdEquipmentattachmentsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Equipment to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Equipment not found</response>
public virtual IActionResult EquipmentIdGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular Equipment</remarks>
/// <param name="id">id of Equipment to fetch History for</param>
/// <param name="offset">offset for records that are returned</param>
/// <param name="limit">limits the number of records returned.</param>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentIdHistoryGetAsync(int id, int? offset, int? limit)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the Equipment</remarks>
/// <param name="id">id of Equipment to add History for</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="201">History created</response>
public virtual IActionResult EquipmentIdHistoryPostAsync(int id, History item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Equipment to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Equipment not found</response>
public virtual IActionResult EquipmentIdPutAsync(int id, Equipment item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Equipment to fetch EquipmentViewModel for</param>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentIdViewGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">Equipment created</response>
public virtual IActionResult EquipmentPostAsync(Equipment item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
/// Recalculates seniority for the database
/// </summary>
/// <remarks>Used to calculate seniority for all database records.</remarks>
/// <param name="region">Region to recalculate</param>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentRecalcSeniorityGetAsync(int region)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
/// Searches Equipment
/// </summary>
/// <remarks>Used for the equipment search page.</remarks>
/// <param name="localareas">Local Areas (comma seperated list of id numbers)</param>
/// <param name="types">Equipment Types (comma seperated list of id numbers)</param>
/// <param name="equipmentAttachment">Searches equipmentAttachment type</param>
/// <param name="owner"></param>
/// <param name="status">Status</param>
/// <param name="hired">Hired</param>
/// <param name="notverifiedsincedate">Not Verified Since Date</param>
/// <response code="200">OK</response>
public virtual IActionResult EquipmentSearchGetAsync(string localareas, string types, string equipmentAttachment, int? owner, string status, bool? hired, DateTime? notverifiedsincedate)
{
var result = "";
return new ObjectResult(result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information
//
// KeyInfoTest.cs - Test Cases for KeyInfo
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
public class KeyInfoTest
{
private KeyInfo info;
public KeyInfoTest()
{
info = new KeyInfo();
}
[Fact]
public void EmptyKeyInfo()
{
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (info.GetXml().OuterXml));
Assert.Equal(0, info.Count);
}
[Fact]
public void KeyInfoName()
{
KeyInfoName name = new KeyInfoName();
name.Value = "Mono::";
info.AddClause(name);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>Mono::</KeyName></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
[Fact]
public void KeyInfoNode()
{
string test = "<Test>KeyInfoNode</Test>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(test);
KeyInfoNode node = new KeyInfoNode(doc.DocumentElement);
info.AddClause(node);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\">KeyInfoNode</Test></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
private static string dsaP = "rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=";
private static string dsaQ = "tf0K9rMyvUrU4cIkwbCrDRhQAJk=";
private static string dsaG = "S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=";
private static string dsaY = "LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=";
//private static string dsaJ = "9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey";
//private static string dsaSeed = "HxW3N4RHWVgqDQKuGg7iJTUTiCs=";
//private static string dsaPgenCounter = "Asw=";
// private static string xmlDSA = "<DSAKeyValue><P>" + dsaP + "</P><Q>" + dsaQ + "</Q><G>" + dsaG + "</G><Y>" + dsaY + "</Y><J>" + dsaJ + "</J><Seed>" + dsaSeed + "</Seed><PgenCounter>" + dsaPgenCounter + "</PgenCounter></DSAKeyValue>";
private static string xmlDSA = "<DSAKeyValue><P>" + dsaP + "</P><Q>" + dsaQ + "</Q><G>" + dsaG + "</G><Y>" + dsaY + "</Y></DSAKeyValue>";
[Fact]
public void DSAKeyValue()
{
using (DSA key = DSA.Create())
{
key.ImportParameters(new DSAParameters {
P = Convert.FromBase64String(dsaP),
Q = Convert.FromBase64String(dsaQ),
G = Convert.FromBase64String(dsaG),
Y = Convert.FromBase64String(dsaY),
//J = Convert.FromBase64String(dsaJ),
//Seed = Convert.FromBase64String(dsaSeed),
//Counter = BitConverter.ToUInt16(Convert.FromBase64String(dsaPgenCounter), 0)
});
DSAKeyValue dsa = new DSAKeyValue(key);
info.AddClause(dsa);
AssertCrypto.AssertXmlEquals("dsa",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" +
xmlDSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
private static string rsaModulus = "9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=";
private static string rsaExponent = "AQAB";
private static string xmlRSA = "<RSAKeyValue><Modulus>" + rsaModulus + "</Modulus><Exponent>" + rsaExponent + "</Exponent></RSAKeyValue>";
[Fact]
public void RSAKeyValue()
{
using (RSA key = RSA.Create())
{
key.ImportParameters(new RSAParameters()
{
Modulus = Convert.FromBase64String(rsaModulus),
Exponent = Convert.FromBase64String(rsaExponent)
});
RSAKeyValue rsa = new RSAKeyValue(key);
info.AddClause(rsa);
AssertCrypto.AssertXmlEquals("rsa",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" +
xmlRSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
[Fact]
public void RetrievalMethod()
{
KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod();
retrieval.Uri = "http://www.go-mono.org/";
info.AddClause(retrieval);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RetrievalMethod URI=\"http://www.go-mono.org/\" /></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
static byte[] cert = { 0x30,0x82,0x02,0x1D,0x30,0x82,0x01,0x86,0x02,0x01,0x14,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x58,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x43,0x41,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x4B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x20,0x43,0x61,0x6E,0x61,0x64,0x61,0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,0x0A,0x2B,0x06,0x01,0x04,0x01,0x2A,0x02,0x0B,0x02,0x01,0x13,0x18,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,
0x73,0x40,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x2E,0x63,0x61,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x35,0x30,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x39,0x39,0x30,0x35,0x30,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x30,0x58,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x43,0x41,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x4B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x20,0x43,0x61,0x6E,0x61,0x64,0x61,0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,
0x0A,0x2B,0x06,0x01,0x04,0x01,0x2A,0x02,0x0B,0x02,0x01,0x13,0x18,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x40,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x2E,0x63,0x61,0x30,0x81,0x9D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8B,0x00,0x30,0x81,0x87,0x02,0x81,0x81,0x00,0xCD,0x23,0xFA,0x2A,0xE1,0xED,0x98,0xF4,0xE9,0xD0,0x93,0x3E,0xD7,0x7A,0x80,0x02,0x4C,0xCC,0xC1,0x02,0xAF,0x5C,0xB6,0x1F,0x7F,0xFA,0x57,0x42,0x6F,0x30,0xD1,0x20,0xC5,0xB5,
0x21,0x07,0x40,0x2C,0xA9,0x86,0xC2,0xF3,0x64,0x84,0xAE,0x3D,0x85,0x2E,0xED,0x85,0xBD,0x54,0xB0,0x18,0x28,0xEF,0x6A,0xF8,0x1B,0xE7,0x0B,0x16,0x1F,0x93,0x25,0x4F,0xC7,0xF8,0x8E,0xC3,0xB9,0xCA,0x98,0x84,0x0E,0x55,0xD0,0x2F,0xEF,0x78,0x77,0xC5,0x72,0x28,0x5F,0x60,0xBF,0x19,0x2B,0xD1,0x72,0xA2,0xB7,0xD8,0x3F,0xE0,0x97,0x34,0x5A,0x01,0xBD,0x04,0x9C,0xC8,0x78,0x45,0xCD,0x93,0x8D,0x15,0xF2,0x76,0x10,0x11,0xAB,0xB8,0x5B,0x2E,0x9E,0x52,0xDD,0x81,0x3E,0x9C,0x64,0xC8,0x29,0x93,0x02,0x01,0x03,0x30,0x0D,0x06,
0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x32,0x1A,0x35,0xBA,0xBF,0x43,0x27,0xD6,0xB4,0xD4,0xB8,0x76,0xE5,0xE3,0x9B,0x4D,0x6C,0xC0,0x86,0xC9,0x77,0x35,0xBA,0x6B,0x16,0x2D,0x13,0x46,0x4A,0xB0,0x32,0x53,0xA1,0x5B,0x5A,0xE9,0x99,0xE2,0x0C,0x86,0x88,0x17,0x4E,0x0D,0xFE,0x82,0xAC,0x4E,0x47,0xEF,0xFB,0xFF,0x39,0xAC,0xEE,0x35,0xC8,0xFA,0x52,0x37,0x0A,0x49,0xAD,0x59,0xAD,0xE2,0x8A,0xA9,0x1C,0xC6,0x5F,0x1F,0xF8,0x6F,0x73,0x7E,0xCD,0xA0,0x31,0xE8,0x0C,0xBE,0xF5,0x4D,
0xD9,0xB2,0xAB,0x8A,0x12,0xB6,0x30,0x78,0x68,0x11,0x7C,0x0D,0xF1,0x49,0x4D,0xA3,0xFD,0xB2,0xE9,0xFF,0x1D,0xF0,0x91,0xFA,0x54,0x85,0xFF,0x33,0x90,0xE8,0xC1,0xBF,0xA4,0x9B,0xA4,0x62,0x46,0xBD,0x61,0x12,0x59,0x98,0x41,0x89 };
[Fact]
public void X509Data()
{
using (X509Certificate x509 = new X509Certificate(cert))
{
KeyInfoX509Data x509data = new KeyInfoX509Data(x509);
info.AddClause(x509data);
AssertCrypto.AssertXmlEquals("X509Data",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>",
(info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
[Fact]
public void Complex()
{
KeyInfoName name = new KeyInfoName();
name.Value = "CoreFx::";
info.AddClause(name);
using (DSA keyDSA = DSA.Create())
{
keyDSA.ImportParameters(new DSAParameters
{
P = Convert.FromBase64String(dsaP),
Q = Convert.FromBase64String(dsaQ),
G = Convert.FromBase64String(dsaG),
Y = Convert.FromBase64String(dsaY),
});
DSAKeyValue dsa = new DSAKeyValue(keyDSA);
info.AddClause(dsa);
using (RSA keyRSA = RSA.Create())
{
keyRSA.ImportParameters(new RSAParameters()
{
Modulus = Convert.FromBase64String(rsaModulus),
Exponent = Convert.FromBase64String(rsaExponent)
});
RSAKeyValue rsa = new RSAKeyValue(keyRSA);
info.AddClause(rsa);
KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod();
retrieval.Uri = "https://github.com/dotnet/corefx";
info.AddClause(retrieval);
using (X509Certificate x509 = new X509Certificate(cert))
{
KeyInfoX509Data x509data = new KeyInfoX509Data(x509);
info.AddClause(x509data);
string s = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>CoreFx::</KeyName><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><DSAKeyValue><P>rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=</P><Q>tf0K9rMyvUrU4cIkwbCrDRhQAJk=</Q><G>S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=</G><Y>LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=</Y></DSAKeyValue></KeyValue>";
s += "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>";
s += "<RetrievalMethod URI=\"https://github.com/dotnet/corefx\" />";
s += "<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\">";
s += "<X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>";
AssertCrypto.AssertXmlEquals("Complex", s, (info.GetXml().OuterXml));
Assert.Equal(5, info.Count);
}
}
}
}
[Fact]
public void ImportKeyNode()
{
string keyName = "Mono::";
string dsaP = "rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=";
string dsaQ = "tf0K9rMyvUrU4cIkwbCrDRhQAJk=";
string dsaG = "S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=";
string dsaY = "LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=";
string dsaJ = "9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey";
string dsaSeed = "HxW3N4RHWVgqDQKuGg7iJTUTiCs=";
string dsaPgenCounter = "Asw=";
string rsaModulus = "9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=";
string rsaExponent = "AQAB";
string x509cert = "MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=";
string retrievalElementUri = @"http://www.go-mono.org/";
string value = $@"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<KeyName>{keyName}</KeyName>
<KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<DSAKeyValue>
<P>{dsaP}</P>
<Q>{dsaQ}</Q>
<G>{dsaG}</G>
<Y>{dsaY}</Y>
<J>{dsaJ}</J>
<Seed>{dsaSeed}</Seed>
<PgenCounter>{dsaPgenCounter}</PgenCounter>
</DSAKeyValue>
</KeyValue>
<KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<RSAKeyValue>
<Modulus>{rsaModulus}</Modulus>
<Exponent>{rsaExponent}</Exponent>
</RSAKeyValue>
</KeyValue>
<RetrievalElement URI=""{retrievalElementUri}"" />
<X509Data xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<X509Certificate>{x509cert}</X509Certificate>
</X509Data>
</KeyInfo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(value);
info.LoadXml(doc.DocumentElement);
Assert.Equal(5, info.Count);
int i = 0;
int pathsCovered = 0;
foreach (var clause in info)
{
i++;
if (clause is KeyInfoName)
{
pathsCovered |= 1 << 0;
var name = clause as KeyInfoName;
Assert.Equal(keyName, name.Value);
}
else if (clause is DSAKeyValue)
{
pathsCovered |= 1 << 1;
var dsaKV = clause as DSAKeyValue;
DSA dsaKey = dsaKV.Key;
DSAParameters dsaParams = dsaKey.ExportParameters(false);
Assert.Equal(Convert.FromBase64String(dsaP), dsaParams.P);
Assert.Equal(Convert.FromBase64String(dsaQ), dsaParams.Q);
Assert.Equal(Convert.FromBase64String(dsaG), dsaParams.G);
Assert.Equal(Convert.FromBase64String(dsaY), dsaParams.Y);
// J is an optimization it should either be null or correct value
if (dsaParams.J != null)
{
Assert.Equal(Convert.FromBase64String(dsaJ), dsaParams.J);
}
// Seed and Counter are not guaranteed to roundtrip
// they should either both be non-null or both null
if (dsaParams.Seed != null)
{
Assert.Equal(Convert.FromBase64String(dsaSeed), dsaParams.Seed);
byte[] counter = Convert.FromBase64String(dsaPgenCounter);
Assert.InRange(counter.Length, 1, 4);
int counterVal = 0;
for (int j = 0; j < counter.Length; j++)
{
counterVal <<= 8;
counterVal |= counter[j];
}
Assert.Equal(counterVal, dsaParams.Counter);
}
else
{
Assert.Null(dsaParams.Seed);
Assert.Equal(default(int), dsaParams.Counter);
}
}
else if (clause is RSAKeyValue)
{
pathsCovered |= 1 << 2;
var rsaKV = clause as RSAKeyValue;
RSA rsaKey = rsaKV.Key;
RSAParameters rsaParameters = rsaKey.ExportParameters(false);
Assert.Equal(Convert.FromBase64String(rsaModulus), rsaParameters.Modulus);
Assert.Equal(Convert.FromBase64String(rsaExponent), rsaParameters.Exponent);
}
else if (clause is KeyInfoNode)
{
pathsCovered |= 1 << 3;
var keyInfo = clause as KeyInfoNode;
XmlElement keyInfoEl = keyInfo.GetXml();
Assert.Equal("RetrievalElement", keyInfoEl.LocalName);
Assert.Equal("http://www.w3.org/2000/09/xmldsig#", keyInfoEl.NamespaceURI);
Assert.Equal(1, keyInfoEl.Attributes.Count);
Assert.Equal("URI", keyInfoEl.Attributes[0].Name);
Assert.Equal(retrievalElementUri, keyInfoEl.GetAttribute("URI"));
}
else if (clause is KeyInfoX509Data)
{
pathsCovered |= 1 << 4;
var x509data = clause as KeyInfoX509Data;
Assert.Equal(1, x509data.Certificates.Count);
X509Certificate cert = x509data.Certificates[0] as X509Certificate;
Assert.NotNull(cert);
Assert.Equal(Convert.FromBase64String(x509cert), cert.GetRawCertData());
}
else
{
Assert.True(false, $"Unexpected clause type: {clause.GetType().FullName}");
}
}
// 0x1f = b11111, number of ones = 5
Assert.Equal(pathsCovered, 0x1f);
Assert.Equal(5, i);
}
[Fact]
public void NullClause()
{
Assert.Equal(0, info.Count);
// null is accepted...
info.AddClause(null);
Assert.Equal(1, info.Count);
// but can't get XML out if it!
Assert.Throws<NullReferenceException>(() => info.GetXml());
}
[Fact]
public void NullXml()
{
Assert.Throws<ArgumentNullException>(() => info.LoadXml(null));
}
[Fact]
public void InvalidXml()
{
string bad = "<Test></Test>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(bad);
info.LoadXml(doc.DocumentElement);
// no expection but Xml isn't loaded
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (info.GetXml().OuterXml));
Assert.Equal(0, info.Count);
}
}
}
| |
/***************************************************************************\
*
* File: StaticResourceExtension.cs
*
* Class for Xaml markup extension for static resource references.
*
* Copyright (C) 2004 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.Collections;
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Reflection;
using MS.Internal;
using System.Xaml;
using System.Collections.Generic;
namespace System.Windows
{
/// <summary>
/// Class for Xaml markup extension for static resource references.
/// </summary>
[MarkupExtensionReturnType(typeof(object))]
[Localizability(LocalizationCategory.NeverLocalize)] // cannot be localized
public class StaticResourceExtension : MarkupExtension
{
/// <summary>
/// Constructor that takes no parameters
/// </summary>
public StaticResourceExtension()
{
}
/// <summary>
/// Constructor that takes the resource key that this is a static reference to.
/// </summary>
public StaticResourceExtension(
object resourceKey)
{
if (resourceKey == null)
{
throw new ArgumentNullException("resourceKey");
}
_resourceKey = resourceKey;
}
/// <summary>
/// Return an object that should be set on the targetObject's targetProperty
/// for this markup extension. For StaticResourceExtension, this is the object found in
/// a resource dictionary in the current parent chain that is keyed by ResourceKey
/// </summary>
/// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
/// <returns>
/// The object to set on this property.
/// </returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (ResourceKey is SystemResourceKey)
{
return (ResourceKey as SystemResourceKey).Resource;
}
return ProvideValueInternal(serviceProvider, false);
}
/// <summary>
/// The key in a Resource Dictionary used to find the object refered to by this
/// Markup Extension.
/// </summary>
[ConstructorArgument("resourceKey")]
public object ResourceKey
{
get { return _resourceKey; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_resourceKey = value;
}
}
/// <summary>
/// This value is used to resolved StaticResourceIds
/// </summary>
internal virtual DeferredResourceReference PrefetchedValue
{
get { return null; }
}
internal object ProvideValueInternal(IServiceProvider serviceProvider, bool allowDeferredReference)
{
object value = TryProvideValueInternal(serviceProvider, allowDeferredReference, false /* mustReturnDeferredResourceReference */);
if (value == DependencyProperty.UnsetValue)
{
throw new Exception(SR.Get(SRID.ParserNoResource, ResourceKey.ToString()));
}
return value;
}
internal object TryProvideValueInternal(IServiceProvider serviceProvider, bool allowDeferredReference, bool mustReturnDeferredResourceReference)
{
// Get prefetchedValue
DeferredResourceReference prefetchedValue = PrefetchedValue;
object value;
if (prefetchedValue == null)
{
// Do a normal look up.
value = FindResourceInEnviroment(serviceProvider, allowDeferredReference, mustReturnDeferredResourceReference);
}
else
{
// If we have a Deferred Value, first check the current parse stack for a better (nearer)
// value. This happens when this is a parse of deferred content and there is another
// Resource Dictionary availible above this, yet still part of this deferred content.
// This searches up to the outer most enclosing resource dictionary.
value = FindResourceInDeferredContent(serviceProvider, allowDeferredReference, mustReturnDeferredResourceReference);
// If we didn't find a new value in this part of deferred content
// then use the existing prefetchedValue (DeferredResourceReference)
if (value == DependencyProperty.UnsetValue)
{
value = allowDeferredReference
? prefetchedValue
: prefetchedValue.GetValue(BaseValueSourceInternal.Unknown);
}
}
return value;
}
private ResourceDictionary FindTheResourceDictionary(IServiceProvider serviceProvider, bool isDeferredContentSearch)
{
var schemaContextProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;
if (schemaContextProvider == null)
{
throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IXamlSchemaContextProvider"));
}
var ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider)) as IAmbientProvider;
if (ambientProvider == null)
{
throw new InvalidOperationException(SR.Get(SRID.MarkupExtensionNoContext, GetType().Name, "IAmbientProvider"));
}
XamlSchemaContext schemaContext = schemaContextProvider.SchemaContext;
// This seems like a lot of work to do on every Provide Value
// but that types and properties are cached in the schema.
//
XamlType feXType = schemaContext.GetXamlType(typeof(FrameworkElement));
XamlType styleXType = schemaContext.GetXamlType(typeof(Style));
XamlType templateXType = schemaContext.GetXamlType(typeof(FrameworkTemplate));
XamlType appXType = schemaContext.GetXamlType(typeof(Application));
XamlType fceXType = schemaContext.GetXamlType(typeof(FrameworkContentElement));
XamlMember fceResourcesProperty = fceXType.GetMember("Resources");
XamlMember feResourcesProperty = feXType.GetMember("Resources");
XamlMember styleResourcesProperty = styleXType.GetMember("Resources");
XamlMember styleBasedOnProperty = styleXType.GetMember("BasedOn");
XamlMember templateResourcesProperty = templateXType.GetMember("Resources");
XamlMember appResourcesProperty = appXType.GetMember("Resources");
XamlType[] types = new XamlType[1] { schemaContext.GetXamlType(typeof(ResourceDictionary)) };
IEnumerable<AmbientPropertyValue> ambientValues = null;
ambientValues = ambientProvider.GetAllAmbientValues(null, // ceilingTypes
isDeferredContentSearch,
types,
fceResourcesProperty,
feResourcesProperty,
styleResourcesProperty,
styleBasedOnProperty,
templateResourcesProperty,
appResourcesProperty);
List<AmbientPropertyValue> ambientList;
ambientList = ambientValues as List<AmbientPropertyValue>;
Debug.Assert(ambientList != null, "IAmbientProvider.GetAllAmbientValues no longer returns List<>, please copy the list");
for(int i=0; i<ambientList.Count; i++)
{
AmbientPropertyValue ambientValue = ambientList[i];
if (ambientValue.Value is ResourceDictionary)
{
var resourceDictionary = (ResourceDictionary)ambientValue.Value;
if (resourceDictionary.Contains(ResourceKey))
{
return resourceDictionary;
}
}
if (ambientValue.Value is Style)
{
var style = (Style)ambientValue.Value;
var resourceDictionary = style.FindResourceDictionary(ResourceKey);
if (resourceDictionary != null)
{
return resourceDictionary;
}
}
}
return null;
}
internal object FindResourceInDeferredContent(IServiceProvider serviceProvider, bool allowDeferredReference, bool mustReturnDeferredResourceReference)
{
ResourceDictionary dictionaryWithKey = FindTheResourceDictionary(serviceProvider, /* isDeferredContentSearch */ true);
object value = DependencyProperty.UnsetValue;
if (dictionaryWithKey != null)
{
value = dictionaryWithKey.Lookup(ResourceKey, allowDeferredReference, mustReturnDeferredResourceReference, canCacheAsThemeResource:false);
}
if (mustReturnDeferredResourceReference && value == DependencyProperty.UnsetValue)
{
value = new DeferredResourceReferenceHolder(ResourceKey, value);
}
return value;
}
/// <summary>
/// Search just the App and Theme Resources.
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="allowDeferredReference"></param>
/// <param name="mustReturnDeferredResourceReference"></param>
/// <returns></returns>
private object FindResourceInAppOrSystem(IServiceProvider serviceProvider,
bool allowDeferredReference,
bool mustReturnDeferredResourceReference)
{
object val;
if (!SystemResources.IsSystemResourcesParsing)
{
object source;
val = FrameworkElement.FindResourceFromAppOrSystem(ResourceKey,
out source,
false, // disableThrowOnResourceFailure
allowDeferredReference,
mustReturnDeferredResourceReference);
}
else
{
val = SystemResources.FindResourceInternal(ResourceKey,
allowDeferredReference,
mustReturnDeferredResourceReference);
}
return val;
}
private object FindResourceInEnviroment(IServiceProvider serviceProvider,
bool allowDeferredReference,
bool mustReturnDeferredResourceReference)
{
ResourceDictionary dictionaryWithKey = FindTheResourceDictionary(serviceProvider, /* isDeferredContentSearch */ false);
if (dictionaryWithKey != null)
{
object value = dictionaryWithKey.Lookup(ResourceKey, allowDeferredReference, mustReturnDeferredResourceReference, canCacheAsThemeResource:false);
return value;
}
// Look at app or themes
object val = FindResourceInAppOrSystem(serviceProvider, allowDeferredReference, mustReturnDeferredResourceReference);
if (val == null)
{
val = DependencyProperty.UnsetValue;
}
if (mustReturnDeferredResourceReference)
{
if (!(val is DeferredResourceReference))
{
val = new DeferredResourceReferenceHolder(ResourceKey, val);
}
}
return val;
}
private object _resourceKey;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MGTK.Services;
namespace MGTK.Controls
{
public class InnerListBox : Control
{
public List<ListBoxItem> items = new List<ListBoxItem>();
private int selectedIndex;
private int scrollX, scrollY;
private int nrItemsVisible = 0;
private int fontHeight;
private int TextXPadding = 4;
public int NrItemsVisible
{
get
{
if (nrItemsVisible <= 0)
UpdateNrItemsVisible();
return nrItemsVisible;
}
set
{
nrItemsVisible = value;
}
}
public int SelectedIndex
{
get
{
return selectedIndex;
}
set
{
if (selectedIndex != value)
{
selectedIndex = value;
if (selectedIndex < 0)
selectedIndex = 0;
else if (Items != null && selectedIndex > Items.Count - 1)
selectedIndex = Items.Count - 1;
if (SelectedIndexChanged != null)
SelectedIndexChanged(this, new EventArgs());
}
}
}
public object SelectedValue
{
get
{
if (Items.Count > 0 && SelectedIndex < Items.Count)
return Items[SelectedIndex];
return null;
}
}
public int ScrollX
{
get
{
return scrollX;
}
set
{
scrollX = value;
UpdateNrCharsVisible();
}
}
public int ScrollY
{
get
{
return scrollY;
}
set
{
scrollY = value;
}
}
private int FontHeight
{
get
{
if (fontHeight <= 0)
fontHeight = DrawingService.GetBMFontHeight(Font);
return fontHeight;
}
}
public List<ListBoxItem> Items
{
get
{
return items;
}
set
{
if (value != items)
{
items = value;
UpdateControlList();
}
}
}
public event EventHandler SelectedIndexChanged;
public InnerListBox(Form formowner)
: base(formowner)
{
this.WidthChanged += new EventHandler(InnerListBox_WidthChanged);
this.HeightChanged += new EventHandler(InnerListBox_HeightChanged);
this.Init += new EventHandler(InnerListBox_Init);
this.Click += new EventHandler(InnerListBox_Click);
}
void InnerListBox_Click(object sender, EventArgs e)
{
for (int i = ScrollY; i < ScrollY + NrItemsVisible && i < Items.Count; i++)
{
if (WindowManager.MouseX >= X + OwnerX && WindowManager.MouseX <= X + OwnerX + Width &&
WindowManager.MouseY >= Y + OwnerY + (i - scrollY) * FontHeight &&
WindowManager.MouseY <= Y + OwnerY + (i - scrollY) * FontHeight + FontHeight)
SelectedIndex = i;
}
}
void InnerListBox_Init(object sender, EventArgs e)
{
UpdateNrItemsVisible();
UpdateNrCharsVisible();
}
void InnerListBox_HeightChanged(object sender, EventArgs e)
{
UpdateNrItemsVisible();
}
void InnerListBox_WidthChanged(object sender, EventArgs e)
{
UpdateNrCharsVisible();
}
public void UpdateNrCharsVisible()
{
if (Items != null)
for (int i = 0; i < Items.Count; i++)
{
string itemText = Items[i].Text;
int xPadding = TextXPadding + Items[i].TextXPadding;
if (itemText.Length - ScrollX <= 0)
{
Items[i].NrCharsVisible = 0;
continue;
}
itemText = itemText.Substring(ScrollX, itemText.Length - ScrollX);
Items[i].NrCharsVisible = itemText.Length;
if (Items[i].Ctrl != null)
xPadding += Items[i].Ctrl.Width;
while (Font.MeasureString(itemText.Substring(0, Items[i].NrCharsVisible)) + xPadding > Width &&
Items[i].NrCharsVisible > 0)
{
if (Items[i].NrCharsVisible - 1 >= 0)
{
Items[i].NrCharsVisible--;
itemText = itemText.Substring(0, Items[i].NrCharsVisible);
}
}
}
}
public override void Draw()
{
SetListBoxItemsControlVisibility(false);
for (int i = ScrollY; i < ScrollY + NrItemsVisible && i < Items.Count; i++)
{
int itemXPadding = 0;
string itemText = Items[i].Text;
if (i == SelectedIndex)
DrawingService.DrawRectangle(spriteBatch, Theme.SelectedListItemBackground, Color.White, X + OwnerX,
Y + OwnerY + (i - ScrollY) * FontHeight, Width, FontHeight, Z - 0.001f);
if (itemText.Length < ScrollX)
continue;
itemText = itemText.Substring(ScrollX, Items[i].NrCharsVisible);
itemXPadding = TextXPadding + Items[i].TextXPadding;
if (Items[i].Ctrl != null)
{
Items[i].Ctrl.X = itemXPadding;
Items[i].Ctrl.Y = (i - ScrollY) * FontHeight + Items[i].Ctrl.Height / 2 - FontHeight / 2 + 3;
Items[i].Ctrl.Z = Z - 0.0016f;
Items[i].Ctrl.Visible = true;
itemXPadding += Items[i].Ctrl.Width;
}
DrawingService.DrawBMString(spriteBatch, Font, itemText, X + OwnerX + itemXPadding,
Y + OwnerY + (i - ScrollY) * FontHeight, ForeColor, Z - 0.0015f);
}
base.Draw();
}
public void UpdateNrItemsVisible()
{
NrItemsVisible = (int)((double)Height / (double)FontHeight);
}
public void UpdateControlList()
{
if (Controls == null)
Controls = new List<Control>();
Controls.Clear();
if (Items != null)
foreach (ListBoxItem item in Items)
{
if (item.Ctrl != null && !Controls.Contains(item.Ctrl))
Controls.Add(item.Ctrl);
}
}
private void SetListBoxItemsControlVisibility(bool visible)
{
foreach (ListBoxItem item in Items)
{
if (item.Ctrl != null)
item.Ctrl.Visible = visible;
}
}
public void AddItem(ListBoxItem item)
{
Items.Add(item);
if (item.Ctrl != null)
Controls.Add(item.Ctrl);
}
public void RemoveItem(ListBoxItem item)
{
if (item.Ctrl != null)
Controls.Remove(item.Ctrl);
Items.Remove(item);
}
}
public class ListBoxItem
{
public object Value;
public string Text;
public int NrCharsVisible = -1;
public int TextXPadding = 0;
public Control Ctrl = null;
public object tag = null;
public ListBoxItem(object value, string text, int textxpadding, Control ctrl)
{
Value = value;
Text = text;
TextXPadding = textxpadding;
Ctrl = ctrl;
}
public ListBoxItem()
{
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
/// <summary>
/// Transactional cache tests.
/// </summary>
public abstract class CacheAbstractTransactionalTest : CacheAbstractTest
{
/// <summary>
/// Simple cache lock test (while <see cref="TestLock"/> is ignored).
/// </summary>
[Test]
public void TestLockSimple()
{
var cache = Cache();
const int key = 7;
Action<ICacheLock> checkLock = lck =>
{
using (lck)
{
Assert.Throws<InvalidOperationException>(lck.Exit); // can't exit if not entered
lck.Enter();
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
Assert.IsTrue(lck.TryEnter());
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
lck.Exit();
}
Assert.Throws<ObjectDisposedException>(lck.Enter); // Can't enter disposed lock
};
checkLock(cache.Lock(key));
checkLock(cache.LockAll(new[] { key, 1, 2, 3 }));
}
/// <summary>
/// Tests cache locks.
/// </summary>
[Test]
[Ignore("IGNITE-835")]
public void TestLock()
{
var cache = Cache();
const int key = 7;
// Lock
CheckLock(cache, key, () => cache.Lock(key));
// LockAll
CheckLock(cache, key, () => cache.LockAll(new[] { key, 2, 3, 4, 5 }));
}
/// <summary>
/// Internal lock test routine.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="key">Key.</param>
/// <param name="getLock">Function to get the lock.</param>
private static void CheckLock(ICache<int, int> cache, int key, Func<ICacheLock> getLock)
{
var sharedLock = getLock();
using (sharedLock)
{
Assert.Throws<InvalidOperationException>(() => sharedLock.Exit()); // can't exit if not entered
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
sharedLock.Enter();
try
{
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
}
finally
{
sharedLock.Exit();
}
Assert.IsTrue(cache.IsLocalLocked(key, true));
Assert.IsTrue(cache.IsLocalLocked(key, false));
EnsureCannotLock(getLock, sharedLock);
Assert.Throws<SynchronizationLockException>(() => sharedLock.Dispose()); // can't dispose while locked
}
finally
{
sharedLock.Exit();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var innerTask = new Task(() =>
{
Assert.IsTrue(sharedLock.TryEnter());
sharedLock.Exit();
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
innerTask.Start();
innerTask.Wait();
}
Assert.IsFalse(cache.IsLocalLocked(key, true));
Assert.IsFalse(cache.IsLocalLocked(key, false));
var outerTask = new Task(() =>
{
using (var otherLock = getLock())
{
Assert.IsTrue(otherLock.TryEnter());
otherLock.Exit();
}
});
outerTask.Start();
outerTask.Wait();
Assert.Throws<ObjectDisposedException>(() => sharedLock.Enter()); // Can't enter disposed lock
}
/// <summary>
/// Ensure that lock cannot be obtained by other threads.
/// </summary>
/// <param name="getLock">Get lock function.</param>
/// <param name="sharedLock">Shared lock.</param>
private static void EnsureCannotLock(Func<ICacheLock> getLock, ICacheLock sharedLock)
{
var task = new Task(() =>
{
Assert.IsFalse(sharedLock.TryEnter());
Assert.IsFalse(sharedLock.TryEnter(TimeSpan.FromMilliseconds(100)));
using (var otherLock = getLock())
{
Assert.IsFalse(otherLock.TryEnter());
Assert.IsFalse(otherLock.TryEnter(TimeSpan.FromMilliseconds(100)));
}
});
task.Start();
task.Wait();
}
/// <summary>
/// Tests that commit applies cache changes.
/// </summary>
[Test]
public void TestTxCommit([Values(true, false)] bool async)
{
var cache = Cache();
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
cache.Put(2, 2);
if (async)
{
var task = tx.CommitAsync();
task.Wait();
Assert.IsTrue(task.IsCompleted);
}
else
tx.Commit();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that rollback reverts cache changes.
/// </summary>
[Test]
public void TestTxRollback()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (var tx = Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
tx.Rollback();
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests that Dispose without Commit reverts changes.
/// </summary>
[Test]
public void TestTxClose()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
Assert.IsNull(Transactions.Tx);
using (Transactions.TxStart())
{
cache.Put(1, 10);
cache.Put(2, 20);
}
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests all concurrency and isolation modes with and without timeout.
/// </summary>
[Test]
public void TestTxAllModes([Values(true, false)] bool withTimeout)
{
var cache = Cache();
int cntr = 0;
foreach (TransactionConcurrency concurrency in Enum.GetValues(typeof(TransactionConcurrency)))
{
foreach (TransactionIsolation isolation in Enum.GetValues(typeof(TransactionIsolation)))
{
Console.WriteLine("Test tx [concurrency=" + concurrency + ", isolation=" + isolation + "]");
Assert.IsNull(Transactions.Tx);
using (var tx = withTimeout
? Transactions.TxStart(concurrency, isolation, TimeSpan.FromMilliseconds(1100), 10)
: Transactions.TxStart(concurrency, isolation))
{
Assert.AreEqual(concurrency, tx.Concurrency);
Assert.AreEqual(isolation, tx.Isolation);
if (withTimeout)
Assert.AreEqual(1100, tx.Timeout.TotalMilliseconds);
cache.Put(1, cntr);
tx.Commit();
}
Assert.IsNull(Transactions.Tx);
Assert.AreEqual(cntr, cache.Get(1));
cntr++;
}
}
}
/// <summary>
/// Tests that transaction properties are applied and propagated properly.
/// </summary>
[Test]
public void TestTxAttributes()
{
ITransaction tx = Transactions.TxStart(TransactionConcurrency.Optimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.AreEqual(tx.NodeId, GetIgnite(0).GetCluster().GetLocalNode().Id);
DateTime startTime1 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime1, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted,
TimeSpan.FromMilliseconds(3500), 200);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime.Ticks > 0);
Assert.IsTrue(tx.StartTime > startTime1);
DateTime startTime2 = tx.StartTime;
tx.Rollback();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.AreEqual(TransactionConcurrency.Pessimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.ReadCommitted, tx.Isolation);
Assert.AreEqual(3500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime2, tx.StartTime);
Thread.Sleep(100);
tx = Transactions.TxStart(TransactionConcurrency.Optimistic, TransactionIsolation.RepeatableRead,
TimeSpan.FromMilliseconds(2500), 100);
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.IsTrue(tx.StartTime > startTime2);
DateTime startTime3 = tx.StartTime;
tx.Commit();
Assert.IsFalse(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.Committed, tx.State);
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.Concurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.Isolation);
Assert.AreEqual(2500, tx.Timeout.TotalMilliseconds);
Assert.AreEqual(startTime3, tx.StartTime);
// Check defaults.
tx = Transactions.TxStart();
Assert.AreEqual(Transactions.DefaultTransactionConcurrency, tx.Concurrency);
Assert.AreEqual(Transactions.DefaultTransactionIsolation, tx.Isolation);
Assert.AreEqual(Transactions.DefaultTimeout, tx.Timeout);
tx.Commit();
}
/// <summary>
/// Tests <see cref="ITransaction.IsRollbackOnly"/> flag.
/// </summary>
[Test]
public void TestTxRollbackOnly()
{
var cache = Cache();
cache.Put(1, 1);
cache.Put(2, 2);
var tx = Transactions.TxStart();
cache.Put(1, 10);
cache.Put(2, 20);
Assert.IsFalse(tx.IsRollbackOnly);
tx.SetRollbackonly();
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(TransactionState.MarkedRollback, tx.State);
var ex = Assert.Throws<TransactionRollbackException>(() => tx.Commit());
Assert.IsTrue(ex.Message.StartsWith("Invalid transaction state for prepare [state=MARKED_ROLLBACK"));
tx.Dispose();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.IsTrue(tx.IsRollbackOnly);
Assert.AreEqual(1, cache.Get(1));
Assert.AreEqual(2, cache.Get(2));
Assert.IsNull(Transactions.Tx);
}
/// <summary>
/// Tests transaction metrics.
/// </summary>
[Test]
public void TestTxMetrics()
{
var cache = Cache();
var startTime = DateTime.UtcNow.AddSeconds(-1);
Transactions.ResetMetrics();
var metrics = Transactions.GetMetrics();
Assert.AreEqual(0, metrics.TxCommits);
Assert.AreEqual(0, metrics.TxRollbacks);
using (Transactions.TxStart())
{
cache.Put(1, 1);
}
using (var tx = Transactions.TxStart())
{
cache.Put(1, 1);
tx.Commit();
}
metrics = Transactions.GetMetrics();
Assert.AreEqual(1, metrics.TxCommits);
Assert.AreEqual(1, metrics.TxRollbacks);
Assert.LessOrEqual(startTime, metrics.CommitTime);
Assert.LessOrEqual(startTime, metrics.RollbackTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.CommitTime);
Assert.GreaterOrEqual(DateTime.UtcNow, metrics.RollbackTime);
}
/// <summary>
/// Tests transaction state transitions.
/// </summary>
[Test]
public void TestTxStateAndExceptions()
{
var tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, tx.ThreadId);
tx.AddMeta("myMeta", 42);
Assert.AreEqual(42, tx.Meta<int>("myMeta"));
Assert.AreEqual(42, tx.RemoveMeta<int>("myMeta"));
tx.RollbackAsync().Wait();
Assert.AreEqual(TransactionState.RolledBack, tx.State);
Assert.Throws<InvalidOperationException>(() => tx.Commit());
tx = Transactions.TxStart();
Assert.AreEqual(TransactionState.Active, tx.State);
tx.CommitAsync().Wait();
Assert.AreEqual(TransactionState.Committed, tx.State);
var task = tx.RollbackAsync(); // Illegal, but should not fail here; will fail in task
Assert.Throws<AggregateException>(() => task.Wait());
}
/// <summary>
/// Tests the transaction deadlock detection.
/// </summary>
[Test]
public void TestTxDeadlockDetection()
{
var cache = Cache();
var keys0 = Enumerable.Range(1, 100).ToArray();
cache.PutAll(keys0.ToDictionary(x => x, x => x));
var barrier = new Barrier(2);
Action<int[]> increment = keys =>
{
using (var tx = Transactions.TxStart(TransactionConcurrency.Pessimistic,
TransactionIsolation.RepeatableRead, TimeSpan.FromSeconds(0.5), 0))
{
foreach (var key in keys)
cache[key]++;
barrier.SignalAndWait(500);
tx.Commit();
}
};
// Increment keys within tx in different order to cause a deadlock.
var aex = Assert.Throws<AggregateException>(() =>
Task.WaitAll(Task.Factory.StartNew(() => increment(keys0)),
Task.Factory.StartNew(() => increment(keys0.Reverse().ToArray()))));
Assert.AreEqual(2, aex.InnerExceptions.Count);
var deadlockEx = aex.InnerExceptions.OfType<TransactionDeadlockException>().First();
Assert.IsTrue(deadlockEx.Message.Trim().StartsWith("Deadlock detected:"), deadlockEx.Message);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeSingleCache()
{
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Commit.
using (var ts = new TransactionScope())
{
cache[1] = 10;
cache[2] = 20;
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx);
ts.Complete();
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
// Rollback.
using (new TransactionScope())
{
cache[1] = 100;
cache[2] = 200;
}
Assert.AreEqual(10, cache[1]);
Assert.AreEqual(20, cache[2]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// with multiple participating caches.
/// </summary>
[Test]
[Ignore("IGNITE-1561")]
public void TestTransactionScopeMultiCache()
{
var cache1 = Cache();
var cache2 = GetIgnite(0).GetOrCreateCache<int, int>(new CacheConfiguration(cache1.Name + "_")
{
AtomicityMode = CacheAtomicityMode.Transactional
});
cache1[1] = 1;
cache2[1] = 2;
// Commit.
using (var ts = new TransactionScope())
{
cache1[1] = 10;
cache2[1] = 20;
ts.Complete();
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
// Rollback.
using (new TransactionScope())
{
cache1[1] = 100;
cache2[1] = 200;
}
Assert.AreEqual(10, cache1[1]);
Assert.AreEqual(20, cache2[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/>
/// when Ignite tx is started manually.
/// </summary>
[Test]
public void TestTransactionScopeWithManualIgniteTx()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
cache[1] = 1;
// When Ignite tx is started manually, it won't be enlisted in TransactionScope.
using (var tx = transactions.TxStart())
{
using (new TransactionScope())
{
cache[1] = 2;
} // Revert transaction scope.
tx.Commit(); // Commit manual tx.
}
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction with <see cref="TransactionScopeOption.Suppress"/> option.
/// </summary>
[Test]
public void TestSuppressedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
using (new TransactionScope(TransactionScopeOption.Suppress))
{
cache[1] = 2;
}
// Even though transaction is not completed, the value is updated, because tx is suppressed.
Assert.AreEqual(2, cache[1]);
}
/// <summary>
/// Test Ignite transaction enlistment in ambient <see cref="TransactionScope"/> with nested scopes.
/// </summary>
[Test]
public void TestNestedTransactionScope()
{
var cache = Cache();
cache[1] = 1;
foreach (var option in new[] {TransactionScopeOption.Required, TransactionScopeOption.RequiresNew})
{
// Commit.
using (var ts1 = new TransactionScope())
{
using (var ts2 = new TransactionScope(option))
{
cache[1] = 2;
ts2.Complete();
}
cache[1] = 3;
ts1.Complete();
}
Assert.AreEqual(3, cache[1]);
// Rollback.
using (new TransactionScope())
{
using (new TransactionScope(option))
cache[1] = 4;
cache[1] = 5;
}
// In case with Required option there is a single tx
// that gets aborted, second put executes outside the tx.
Assert.AreEqual(option == TransactionScopeOption.Required ? 5 : 3, cache[1], option.ToString());
}
}
/// <summary>
/// Test that ambient <see cref="TransactionScope"/> options propagate to Ignite transaction.
/// </summary>
[Test]
public void TestTransactionScopeOptions()
{
var cache = Cache();
var transactions = cache.Ignite.GetTransactions();
var modes = new[]
{
Tuple.Create(IsolationLevel.Serializable, TransactionIsolation.Serializable),
Tuple.Create(IsolationLevel.RepeatableRead, TransactionIsolation.RepeatableRead),
Tuple.Create(IsolationLevel.ReadCommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.ReadUncommitted, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Snapshot, TransactionIsolation.ReadCommitted),
Tuple.Create(IsolationLevel.Chaos, TransactionIsolation.ReadCommitted),
};
foreach (var mode in modes)
{
using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
{
IsolationLevel = mode.Item1
}))
{
cache[1] = 1;
var tx = transactions.Tx;
Assert.AreEqual(mode.Item2, tx.Isolation);
Assert.AreEqual(transactions.DefaultTransactionConcurrency, tx.Concurrency);
}
}
}
/// <summary>
/// Tests all transactional operations with <see cref="TransactionScope"/>.
/// </summary>
[Test]
public void TestTransactionScopeAllOperations()
{
for (var i = 0; i < 10; i++)
{
CheckTxOp((cache, key) => cache.Put(key, -5));
CheckTxOp((cache, key) => cache.PutAsync(key, -5).Wait());
CheckTxOp((cache, key) => cache.PutAll(new Dictionary<int, int> {{key, -7}}));
CheckTxOp((cache, key) => cache.PutAllAsync(new Dictionary<int, int> {{key, -7}}).Wait());
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.PutIfAbsentAsync(key, -10).Wait();
});
CheckTxOp((cache, key) => cache.GetAndPut(key, -9));
CheckTxOp((cache, key) => cache.GetAndPutAsync(key, -9).Wait());
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsent(key, -10);
});
CheckTxOp((cache, key) =>
{
cache.Remove(key);
cache.GetAndPutIfAbsentAsync(key, -10).Wait();
});
CheckTxOp((cache, key) => cache.GetAndRemove(key));
CheckTxOp((cache, key) => cache.GetAndRemoveAsync(key).Wait());
CheckTxOp((cache, key) => cache.GetAndReplace(key, -11));
CheckTxOp((cache, key) => cache.GetAndReplaceAsync(key, -11).Wait());
CheckTxOp((cache, key) => cache.Invoke(key, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAsync(key, new AddProcessor(), 1).Wait());
CheckTxOp((cache, key) => cache.InvokeAll(new[] {key}, new AddProcessor(), 1));
CheckTxOp((cache, key) => cache.InvokeAllAsync(new[] {key}, new AddProcessor(), 1).Wait());
CheckTxOp((cache, key) => cache.Remove(key));
CheckTxOp((cache, key) => cache.RemoveAsync(key).Wait());
CheckTxOp((cache, key) => cache.RemoveAll(new[] {key}));
CheckTxOp((cache, key) => cache.RemoveAllAsync(new[] {key}).Wait());
CheckTxOp((cache, key) => cache.Replace(key, 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, 100).Wait());
CheckTxOp((cache, key) => cache.Replace(key, cache[key], 100));
CheckTxOp((cache, key) => cache.ReplaceAsync(key, cache[key], 100).Wait());
}
}
/// <summary>
/// Checks that cache operation behaves transactionally.
/// </summary>
private void CheckTxOp(Action<ICache<int, int>, int> act)
{
var isolationLevels = new[]
{
IsolationLevel.Serializable, IsolationLevel.RepeatableRead, IsolationLevel.ReadCommitted,
IsolationLevel.ReadUncommitted, IsolationLevel.Snapshot, IsolationLevel.Chaos
};
foreach (var isolationLevel in isolationLevels)
{
var txOpts = new TransactionOptions {IsolationLevel = isolationLevel};
const TransactionScopeOption scope = TransactionScopeOption.Required;
var cache = Cache();
cache[1] = 1;
cache[2] = 2;
// Rollback.
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
Assert.IsNotNull(cache.Ignite.GetTransactions().Tx, "Transaction has not started.");
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
using (new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
}
Assert.AreEqual(1, cache[1]);
Assert.AreEqual(2, cache[2]);
// Commit.
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.AreEqual(2, cache[2]);
using (var ts = new TransactionScope(scope, txOpts))
{
act(cache, 1);
act(cache, 2);
ts.Complete();
}
Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1);
Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2);
}
}
[Serializable]
private class AddProcessor : ICacheEntryProcessor<int, int, int, int>
{
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value += arg;
return arg;
}
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using System.Windows.Threading;
namespace System.Windows.Browser
{
// Summary:
// Defines the core behavior for the System.Windows.Browser.HtmlObject class,
// and provides a base class for browser Document Object Model (DOM) access
// types.
public class ScriptObject
{
internal ScriptObject() { }
// Summary:
// Gets an instance of the dispatcher.
public Dispatcher Dispatcher
{
get
{
Contract.Ensures(Contract.Result<Dispatcher>() != null);
return default(Dispatcher);
}
}
//
// Summary:
// Gets the underlying managed object reference of the System.Windows.Browser.ScriptObject.
//
// Returns:
// A managed object reference if the current System.Windows.Browser.ScriptObject
// wraps a managed type; otherwise, null.
extern public object ManagedObject { get; }
// Summary:
// Determines whether the current thread is the browser's UI thread.
//
// Returns:
// true if the current thread is the browser's UI thread; false if it is a background
// thread.
[Pure]
extern public bool CheckAccess();
//
// Summary:
// Converts the current scriptable object to a specified type.
//
// Type parameters:
// T:
// The type to convert the current scriptable object to.
//
// Returns:
// An object of type T.
//
// Exceptions:
// System.ArgumentException:
// The conversion failed or is not supported.
[Pure]
extern public T ConvertTo<T>();
//
// Summary:
// Converts the current scriptable object to a specified type, with serialization
// support.
//
// Parameters:
// targetType:
// The type to convert the current scriptable object to.
//
// allowSerialization:
// A flag which enables the current scriptable object to be serialized.
//
// Returns:
// An object of type targetType.
//
// Exceptions:
// System.ArgumentException:
// The conversion failed or is not supported.
[Pure]
protected internal virtual object ConvertTo(Type targetType, bool allowSerialization)
{
Contract.Ensures(Contract.Result<object>() != null);
return default(object);
}
//
// Summary:
// Gets the value of a property that is identified by ordinal number on the
// current scriptable object.
//
// Parameters:
// index:
// The ordinal number of the property.
//
// Returns:
// A null reference (Nothing in Visual Basic) if the property does not exist
// or if the underlying System.Windows.Browser.ScriptObject is a managed type.
[Pure]
extern public object GetProperty(int index);
//
// Summary:
// Gets the value of a property that is identified by name on the current scriptable
// object.
//
// Parameters:
// name:
// The name of the property.
//
// Returns:
// A null reference (Nothing in Visual Basic) if the property does not exist
// or if the underlying System.Windows.Browser.ScriptObject is a managed type.
//
// Exceptions:
// System.ArgumentNullException:
// name is null.
//
// System.ArgumentException:
// name is an empty string. -or- name contains an embedded null character (\0).
[Pure]
public virtual object GetProperty(string name)
{
Contract.Requires(name != null);
return default(object);
}
//
// Summary:
// Initializes a scriptable object.
//
// Parameters:
// handle:
// The handle to the object to initialize.
//
// identity:
// The identity of the object.
//
// addReference:
// true to specify that the HTML Bridge should assign a reference count to this
// object; otherwise, false.
//
// releaseReferenceOnDispose:
// true to release the reference on dispose; otherwise, false.
extern protected void Initialize(IntPtr handle, IntPtr identity, bool addReference, bool releaseReferenceOnDispose);
//
// Summary:
// Invokes a method on the current scriptable object, and optionally passes
// in one or more method parameters.
//
// Parameters:
// name:
// The method to invoke.
//
// args:
// Parameters to be passed to the method.
//
// Returns:
// An object that represents the return value from the underlying JavaScript
// method.
//
// Exceptions:
// System.ArgumentNullException:
// name is null.
//
// System.ArgumentException:
// name is an empty string. -or- name contains an embedded null character (\0).
// -or- The method does not exist or is not scriptable.
//
// System.InvalidOperationException:
// The underlying method invocation results in an error. The .NET Framework
// attempts to return the error text that is associated with the error.
public virtual object Invoke(string name, params object[] args)
{
Contract.Requires(name != null);
Contract.Ensures(Contract.Result<object>() != null);
return default(object);
}
//
// Summary:
// Invokes the current System.Windows.Browser.ScriptObject and assumes that
// it represents a JavaScript method.
//
// Parameters:
// args:
// Parameters to be passed to the underlying JavaScript method.
//
// Returns:
// An object that represents the return value from the underlying JavaScript
// method.
//
// Exceptions:
// System.InvalidOperationException:
// The current System.Windows.Browser.ScriptObject is not a method. -or- The
// underlying method invocation results in an error.
public virtual object InvokeSelf(params object[] args)
{
Contract.Ensures(Contract.Result<object>() != null);
return default(object);
}
//
// Summary:
// Sets the value of a property that is identified by ordinal number on the
// current scriptable object.
//
// Parameters:
// index:
// The ordinal number of the property.
//
// value:
// The value to set the property to.
//
// Exceptions:
// System.ArgumentNullException:
// index is null.
//
// System.ArgumentException:
// index identifies an empty string.
//
// System.InvalidOperationException:
// A type mismatch exists between the supplied type and the target property.
// -or- The property is not settable. -or- All other failures.
extern public void SetProperty(int index, object value);
//
// Summary:
// Sets a property that is identified by name on the current scriptable object.
//
// Parameters:
// name:
// The name of the property.
//
// value:
// The value to set the property to.
//
// Exceptions:
// System.ArgumentNullException:
// name is null.
//
// System.ArgumentException:
// name is an empty string. -or- name contains an embedded null character (\0).
//
// System.InvalidOperationException:
// A type mismatch exists between the supplied type and the target property.
// -or- The property is not settable. -or- All other failures.
public virtual void SetProperty(string name, object value)
{
Contract.Requires(name != null);
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Routing
{
/// <summary>
/// Provides the default <see cref="IPublishedRouter"/> implementation.
/// </summary>
public class PublishedRouter : IPublishedRouter
{
private readonly WebRoutingSettings _webRoutingSettings;
private readonly ContentFinderCollection _contentFinders;
private readonly IContentLastChanceFinder _contentLastChanceFinder;
private readonly IProfilingLogger _profilingLogger;
private readonly IVariationContextAccessor _variationContextAccessor;
private readonly ILogger<PublishedRouter> _logger;
private readonly IPublishedUrlProvider _publishedUrlProvider;
private readonly IRequestAccessor _requestAccessor;
private readonly IPublishedValueFallback _publishedValueFallback;
private readonly IFileService _fileService;
private readonly IContentTypeService _contentTypeService;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly IEventAggregator _eventAggregator;
/// <summary>
/// Initializes a new instance of the <see cref="PublishedRouter"/> class.
/// </summary>
public PublishedRouter(
IOptions<WebRoutingSettings> webRoutingSettings,
ContentFinderCollection contentFinders,
IContentLastChanceFinder contentLastChanceFinder,
IVariationContextAccessor variationContextAccessor,
IProfilingLogger proflog,
ILogger<PublishedRouter> logger,
IPublishedUrlProvider publishedUrlProvider,
IRequestAccessor requestAccessor,
IPublishedValueFallback publishedValueFallback,
IFileService fileService,
IContentTypeService contentTypeService,
IUmbracoContextAccessor umbracoContextAccessor,
IEventAggregator eventAggregator)
{
_webRoutingSettings = webRoutingSettings.Value ?? throw new ArgumentNullException(nameof(webRoutingSettings));
_contentFinders = contentFinders ?? throw new ArgumentNullException(nameof(contentFinders));
_contentLastChanceFinder = contentLastChanceFinder ?? throw new ArgumentNullException(nameof(contentLastChanceFinder));
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
_variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
_logger = logger;
_publishedUrlProvider = publishedUrlProvider;
_requestAccessor = requestAccessor;
_publishedValueFallback = publishedValueFallback;
_fileService = fileService;
_contentTypeService = contentTypeService;
_umbracoContextAccessor = umbracoContextAccessor;
_eventAggregator = eventAggregator;
}
/// <inheritdoc />
public async Task<IPublishedRequestBuilder> CreateRequestAsync(Uri uri)
{
// trigger the Creating event - at that point the URL can be changed
// this is based on this old task here: https://issues.umbraco.org/issue/U4-7914 which was fulfiled by
// this PR https://github.com/umbraco/Umbraco-CMS/pull/1137
// It's to do with proxies, quote:
/*
"Thinking about another solution.
We already have an event, PublishedContentRequest.Prepared, which triggers once the request has been prepared and domain, content, template have been figured out -- but before it renders -- so ppl can change things before rendering.
Wondering whether we could have a event, PublishedContentRequest.Preparing, which would trigger before the request is prepared, and would let ppl change the value of the request's URI (which by default derives from the HttpContext request).
That way, if an in-between equipement changes the URI, you could replace it with the original, public-facing URI before we process the request, meaning you could register your HTTPS domain and it would work. And you would have to supply code for each equipment. Less magic in Core."
*/
// but now we'll just have one event for creating so if people wish to change the URL here they can but nothing else
var creatingRequest = new CreatingRequestNotification(uri);
await _eventAggregator.PublishAsync(creatingRequest);
var publishedRequestBuilder = new PublishedRequestBuilder(creatingRequest.Url, _fileService);
return publishedRequestBuilder;
}
private IPublishedRequest TryRouteRequest(IPublishedRequestBuilder request)
{
FindDomain(request);
if (request.IsRedirect())
{
return request.Build();
}
if (request.HasPublishedContent())
{
return request.Build();
}
FindPublishedContent(request);
return request.Build();
}
private void SetVariationContext(string culture)
{
VariationContext variationContext = _variationContextAccessor.VariationContext;
if (variationContext != null && variationContext.Culture == culture)
{
return;
}
_variationContextAccessor.VariationContext = new VariationContext(culture);
}
/// <inheritdoc />
public async Task<IPublishedRequest> RouteRequestAsync(IPublishedRequestBuilder builder, RouteRequestOptions options)
{
// outbound routing performs different/simpler logic
if (options.RouteDirection == RouteDirection.Outbound)
{
return TryRouteRequest(builder);
}
// find domain
if (builder.Domain == null)
{
FindDomain(builder);
}
await RouteRequestInternalAsync(builder);
// complete the PCR and assign the remaining values
return BuildRequest(builder);
}
private async Task RouteRequestInternalAsync(IPublishedRequestBuilder builder)
{
// if request builder was already flagged to redirect then return
// whoever called us is in charge of actually redirecting
if (builder.IsRedirect())
{
return;
}
// set the culture
SetVariationContext(builder.Culture);
var foundContentByFinders = false;
// Find the published content if it's not assigned.
// This could be manually assigned with a custom route handler, etc...
// which in turn could call this method
// to setup the rest of the pipeline but we don't want to run the finders since there's one assigned.
if (!builder.HasPublishedContent())
{
_logger.LogDebug("FindPublishedContentAndTemplate: Path={UriAbsolutePath}", builder.Uri.AbsolutePath);
// run the document finders
foundContentByFinders = FindPublishedContent(builder);
}
// if we are not a redirect
if (!builder.IsRedirect())
{
// handle not-found, redirects, access...
HandlePublishedContent(builder);
// find a template
FindTemplate(builder, foundContentByFinders);
// handle umbracoRedirect
FollowExternalRedirect(builder);
// handle wildcard domains
HandleWildcardDomains(builder);
// set the culture -- again, 'cos it might have changed due to a finder or wildcard domain
SetVariationContext(builder.Culture);
}
// trigger the routing request (used to be called Prepared) event - at that point it is still possible to change about anything
// even though the request might be flagged for redirection - we'll redirect _after_ the event
var routingRequest = new RoutingRequestNotification(builder);
await _eventAggregator.PublishAsync(routingRequest);
// we don't take care of anything so if the content has changed, it's up to the user
// to find out the appropriate template
}
/// <summary>
/// This method finalizes/builds the PCR with the values assigned.
/// </summary>
/// <returns>
/// Returns false if the request was not successfully configured
/// </returns>
/// <remarks>
/// This method logic has been put into it's own method in case developers have created a custom PCR or are assigning their own values
/// but need to finalize it themselves.
/// </remarks>
internal IPublishedRequest BuildRequest(IPublishedRequestBuilder builder)
{
IPublishedRequest result = builder.Build();
if (!builder.HasPublishedContent())
{
return result;
}
// set the culture -- again, 'cos it might have changed in the event handler
SetVariationContext(result.Culture);
return result;
}
/// <inheritdoc />
public async Task<IPublishedRequest> UpdateRequestAsync(IPublishedRequest request, IPublishedContent publishedContent)
{
// store the original (if any)
IPublishedContent content = request.PublishedContent;
IPublishedRequestBuilder builder = new PublishedRequestBuilder(request.Uri, _fileService);
// set to the new content (or null if specified)
builder.SetPublishedContent(publishedContent);
// re-route
await RouteRequestInternalAsync(builder);
// return if we are redirect
if (builder.IsRedirect())
{
return BuildRequest(builder);
}
// this will occur if publishedContent is null and the last chance finders also don't assign content
if (!builder.HasPublishedContent())
{
// means the engine could not find a proper document to handle 404
// restore the saved content so we know it exists
builder.SetPublishedContent(content);
}
if (!builder.HasDomain())
{
FindDomain(builder);
}
return BuildRequest(builder);
}
/// <summary>
/// Finds the site root (if any) matching the http request, and updates the PublishedRequest accordingly.
/// </summary>
/// <returns>A value indicating whether a domain was found.</returns>
internal bool FindDomain(IPublishedRequestBuilder request)
{
const string tracePrefix = "FindDomain: ";
// note - we are not handling schemes nor ports here.
_logger.LogDebug("{TracePrefix}Uri={RequestUri}", tracePrefix, request.Uri);
var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
IDomainCache domainsCache = umbracoContext.PublishedSnapshot.Domains;
var domains = domainsCache.GetAll(includeWildcards: false).ToList();
// determines whether a domain corresponds to a published document, since some
// domains may exist but on a document that has been unpublished - as a whole - or
// that is not published for the domain's culture - in which case the domain does
// not apply
bool IsPublishedContentDomain(Domain domain)
{
// just get it from content cache - optimize there, not here
IPublishedContent domainDocument = umbracoContext.PublishedSnapshot.Content.GetById(domain.ContentId);
// not published - at all
if (domainDocument == null)
{
return false;
}
// invariant - always published
if (!domainDocument.ContentType.VariesByCulture())
{
return true;
}
// variant, ensure that the culture corresponding to the domain's language is published
return domainDocument.Cultures.ContainsKey(domain.Culture);
}
domains = domains.Where(IsPublishedContentDomain).ToList();
var defaultCulture = domainsCache.DefaultCulture;
// try to find a domain matching the current request
DomainAndUri domainAndUri = DomainUtilities.SelectDomain(domains, request.Uri, defaultCulture: defaultCulture);
// handle domain - always has a contentId and a culture
if (domainAndUri != null)
{
// matching an existing domain
_logger.LogDebug("{TracePrefix}Matches domain={Domain}, rootId={RootContentId}, culture={Culture}", tracePrefix, domainAndUri.Name, domainAndUri.ContentId, domainAndUri.Culture);
request.SetDomain(domainAndUri);
// canonical? not implemented at the moment
// if (...)
// {
// _pcr.RedirectUrl = "...";
// return true;
// }
}
else
{
// not matching any existing domain
_logger.LogDebug("{TracePrefix}Matches no domain", tracePrefix);
request.SetCulture(defaultCulture ?? CultureInfo.CurrentUICulture.Name);
}
_logger.LogDebug("{TracePrefix}Culture={CultureName}", tracePrefix, request.Culture);
return request.Domain != null;
}
/// <summary>
/// Looks for wildcard domains in the path and updates <c>Culture</c> accordingly.
/// </summary>
internal void HandleWildcardDomains(IPublishedRequestBuilder request)
{
const string tracePrefix = "HandleWildcardDomains: ";
if (request.PublishedContent == null)
{
return;
}
var nodePath = request.PublishedContent.Path;
_logger.LogDebug("{TracePrefix}Path={NodePath}", tracePrefix, nodePath);
var rootNodeId = request.Domain != null ? request.Domain.ContentId : (int?)null;
var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
Domain domain = DomainUtilities.FindWildcardDomainInPath(umbracoContext.PublishedSnapshot.Domains.GetAll(true), nodePath, rootNodeId);
// always has a contentId and a culture
if (domain != null)
{
request.SetCulture(domain.Culture);
_logger.LogDebug("{TracePrefix}Got domain on node {DomainContentId}, set culture to {CultureName}", tracePrefix, domain.ContentId, request.Culture);
}
else
{
_logger.LogDebug("{TracePrefix}No match.", tracePrefix);
}
}
internal bool FindTemplateRenderingEngineInDirectory(DirectoryInfo directory, string alias, string[] extensions)
{
if (directory == null || directory.Exists == false)
{
return false;
}
var pos = alias.IndexOf('/');
if (pos > 0)
{
// recurse
DirectoryInfo subdir = directory.GetDirectories(alias.Substring(0, pos)).FirstOrDefault();
alias = alias.Substring(pos + 1);
return subdir != null && FindTemplateRenderingEngineInDirectory(subdir, alias, extensions);
}
// look here
return directory.GetFiles().Any(f => extensions.Any(e => f.Name.InvariantEquals(alias + e)));
}
/// <summary>
/// Tries to find the document matching the request, by running the IPublishedContentFinder instances.
/// </summary>
/// <exception cref="InvalidOperationException">There is no finder collection.</exception>
internal bool FindPublishedContent(IPublishedRequestBuilder request)
{
const string tracePrefix = "FindPublishedContent: ";
// look for the document
// the first successful finder, if any, will set this.PublishedContent, and may also set this.Template
// some finders may implement caching
using (_profilingLogger.DebugDuration<PublishedRouter>(
$"{tracePrefix}Begin finders",
$"{tracePrefix}End finders"))
{
// iterate but return on first one that finds it
var found = _contentFinders.Any(finder =>
{
_logger.LogDebug("Finder {ContentFinderType}", finder.GetType().FullName);
return finder.TryFindContent(request);
});
_logger.LogDebug(
"Found? {Found}, Content: {PublishedContentId}, Template: {TemplateAlias}, Domain: {Domain}, Culture: {Culture}, StatusCode: {StatusCode}",
found,
request.HasPublishedContent() ? request.PublishedContent.Id : "NULL",
request.HasTemplate() ? request.Template?.Alias : "NULL",
request.HasDomain() ? request.Domain.ToString() : "NULL",
request.Culture ?? "NULL",
request.ResponseStatusCode);
return found;
}
}
/// <summary>
/// Handles the published content (if any).
/// </summary>
/// <param name="request">The request builder.</param>
/// <remarks>
/// Handles "not found", internal redirects ...
/// things that must be handled in one place because they can create loops
/// </remarks>
private void HandlePublishedContent(IPublishedRequestBuilder request)
{
// because these might loop, we have to have some sort of infinite loop detection
int i = 0, j = 0;
const int maxLoop = 8;
do
{
_logger.LogDebug("HandlePublishedContent: Loop {LoopCounter}", i);
// handle not found
if (request.PublishedContent == null)
{
request.SetIs404();
_logger.LogDebug("HandlePublishedContent: No document, try last chance lookup");
// if it fails then give up, there isn't much more that we can do
if (_contentLastChanceFinder.TryFindContent(request) == false)
{
_logger.LogDebug("HandlePublishedContent: Failed to find a document, give up");
break;
}
_logger.LogDebug("HandlePublishedContent: Found a document");
}
// follow internal redirects as long as it's not running out of control ie infinite loop of some sort
j = 0;
while (FollowInternalRedirects(request) && j++ < maxLoop)
{ }
// we're running out of control
if (j == maxLoop)
{
break;
}
// loop while we don't have page, ie the redirect or access
// got us to nowhere and now we need to run the notFoundLookup again
// as long as it's not running out of control ie infinite loop of some sort
} while (request.PublishedContent == null && i++ < maxLoop);
if (i == maxLoop || j == maxLoop)
{
_logger.LogDebug("HandlePublishedContent: Looks like we are running into an infinite loop, abort");
request.SetPublishedContent(null);
}
_logger.LogDebug("HandlePublishedContent: End");
}
/// <summary>
/// Follows internal redirections through the <c>umbracoInternalRedirectId</c> document property.
/// </summary>
/// <param name="request">The request builder.</param>
/// <returns>A value indicating whether redirection took place and led to a new published document.</returns>
/// <remarks>
/// <para>Redirecting to a different site root and/or culture will not pick the new site root nor the new culture.</para>
/// <para>As per legacy, if the redirect does not work, we just ignore it.</para>
/// </remarks>
private bool FollowInternalRedirects(IPublishedRequestBuilder request)
{
if (request.PublishedContent == null)
{
throw new InvalidOperationException("There is no PublishedContent.");
}
// don't try to find a redirect if the property doesn't exist
if (request.PublishedContent.HasProperty(Constants.Conventions.Content.InternalRedirectId) == false)
{
return false;
}
var redirect = false;
var valid = false;
IPublishedContent internalRedirectNode = null;
var internalRedirectId = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.InternalRedirectId, defaultValue: -1);
var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
if (internalRedirectId > 0)
{
// try and get the redirect node from a legacy integer ID
valid = true;
internalRedirectNode = umbracoContext.Content.GetById(internalRedirectId);
}
else
{
GuidUdi udiInternalRedirectId = request.PublishedContent.Value<GuidUdi>(_publishedValueFallback, Constants.Conventions.Content.InternalRedirectId);
if (udiInternalRedirectId != null)
{
// try and get the redirect node from a UDI Guid
valid = true;
internalRedirectNode = umbracoContext.Content.GetById(udiInternalRedirectId.Guid);
}
}
if (valid == false)
{
// bad redirect - log and display the current page (legacy behavior)
_logger.LogDebug(
"FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: value is not an int nor a GuidUdi.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
if (internalRedirectNode == null)
{
_logger.LogDebug(
"FollowInternalRedirects: Failed to redirect to id={InternalRedirectId}: no such published document.",
request.PublishedContent.GetProperty(Constants.Conventions.Content.InternalRedirectId).GetSourceValue());
}
else if (internalRedirectId == request.PublishedContent.Id)
{
// redirect to self
_logger.LogDebug("FollowInternalRedirects: Redirecting to self, ignore");
}
else
{
// save since it will be cleared
ITemplate template = request.Template;
request.SetInternalRedirect(internalRedirectNode); // don't use .PublishedContent here
// must restore the template if it's an internal redirect & the config option is set
if (request.IsInternalRedirect && _webRoutingSettings.InternalRedirectPreservesTemplate)
{
// restore
request.SetTemplate(template);
}
redirect = true;
_logger.LogDebug("FollowInternalRedirects: Redirecting to id={InternalRedirectId}", internalRedirectId);
}
return redirect;
}
/// <summary>
/// Finds a template for the current node, if any.
/// </summary>
/// <param name="request">The request builder.</param>
/// <param name="contentFoundByFinders">If the content was found by the finders, before anything such as 404, redirect... took place.</param>
private void FindTemplate(IPublishedRequestBuilder request, bool contentFoundByFinders)
{
// TODO: We've removed the event, might need to re-add?
// NOTE: at the moment there is only 1 way to find a template, and then ppl must
// use the Prepared event to change the template if they wish. Should we also
// implement an ITemplateFinder logic?
if (request.PublishedContent == null)
{
request.SetTemplate(null);
return;
}
// read the alternate template alias, from querystring, form, cookie or server vars,
// only if the published content is the initial once, else the alternate template
// does not apply
// + optionally, apply the alternate template on internal redirects
var useAltTemplate = contentFoundByFinders
|| (_webRoutingSettings.InternalRedirectPreservesTemplate && request.IsInternalRedirect);
var altTemplate = useAltTemplate
? _requestAccessor.GetRequestValue(Constants.Conventions.Url.AltTemplate)
: null;
if (string.IsNullOrWhiteSpace(altTemplate))
{
// we don't have an alternate template specified. use the current one if there's one already,
// which can happen if a content lookup also set the template (LookupByNiceUrlAndTemplate...),
// else lookup the template id on the document then lookup the template with that id.
if (request.HasTemplate())
{
_logger.LogDebug("FindTemplate: Has a template already, and no alternate template.");
return;
}
// TODO: We need to limit altTemplate to only allow templates that are assigned to the current document type!
// if the template isn't assigned to the document type we should log a warning and return 404
var templateId = request.PublishedContent.TemplateId;
ITemplate template = GetTemplate(templateId);
request.SetTemplate(template);
if (template != null)
{
_logger.LogDebug("FindTemplate: Running with template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
}
else
{
_logger.LogWarning("FindTemplate: Could not find template with id {TemplateId}", templateId);
}
}
else
{
// we have an alternate template specified. lookup the template with that alias
// this means the we override any template that a content lookup might have set
// so /path/to/page/template1?altTemplate=template2 will use template2
// ignore if the alias does not match - just trace
if (request.HasTemplate())
{
_logger.LogDebug("FindTemplate: Has a template already, but also an alternative template.");
}
_logger.LogDebug("FindTemplate: Look for alternative template alias={AltTemplate}", altTemplate);
// IsAllowedTemplate deals both with DisableAlternativeTemplates and ValidateAlternativeTemplates settings
if (request.PublishedContent.IsAllowedTemplate(
_fileService,
_contentTypeService,
_webRoutingSettings.DisableAlternativeTemplates,
_webRoutingSettings.ValidateAlternativeTemplates,
altTemplate))
{
// allowed, use
ITemplate template = _fileService.GetTemplate(altTemplate);
if (template != null)
{
request.SetTemplate(template);
_logger.LogDebug("FindTemplate: Got alternative template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
}
else
{
_logger.LogDebug("FindTemplate: The alternative template with alias={AltTemplate} does not exist, ignoring.", altTemplate);
}
}
else
{
_logger.LogWarning("FindTemplate: Alternative template {TemplateAlias} is not allowed on node {NodeId}, ignoring.", altTemplate, request.PublishedContent.Id);
// no allowed, back to default
var templateId = request.PublishedContent.TemplateId;
ITemplate template = GetTemplate(templateId);
request.SetTemplate(template);
_logger.LogDebug("FindTemplate: Running with template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
}
}
if (!request.HasTemplate())
{
_logger.LogDebug("FindTemplate: No template was found.");
// initial idea was: if we're not already 404 and UmbracoSettings.HandleMissingTemplateAs404 is true
// then reset _pcr.Document to null to force a 404.
//
// but: because we want to let MVC hijack routes even though no template is defined, we decide that
// a missing template is OK but the request will then be forwarded to MVC, which will need to take
// care of everything.
//
// so, don't set _pcr.Document to null here
}
}
private ITemplate GetTemplate(int? templateId)
{
if (templateId.HasValue == false || templateId.Value == default)
{
_logger.LogDebug("GetTemplateModel: No template.");
return null;
}
_logger.LogDebug("GetTemplateModel: Get template id={TemplateId}", templateId);
if (templateId == null)
{
throw new InvalidOperationException("The template is not set, the page cannot render.");
}
ITemplate template = _fileService.GetTemplate(templateId.Value);
if (template == null)
{
throw new InvalidOperationException("The template with Id " + templateId + " does not exist, the page cannot render.");
}
_logger.LogDebug("GetTemplateModel: Got template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias);
return template;
}
/// <summary>
/// Follows external redirection through <c>umbracoRedirect</c> document property.
/// </summary>
/// <remarks>As per legacy, if the redirect does not work, we just ignore it.</remarks>
private void FollowExternalRedirect(IPublishedRequestBuilder request)
{
if (request.PublishedContent == null)
{
return;
}
// don't try to find a redirect if the property doesn't exist
if (request.PublishedContent.HasProperty(Constants.Conventions.Content.Redirect) == false)
{
return;
}
var redirectId = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.Redirect, defaultValue: -1);
var redirectUrl = "#";
if (redirectId > 0)
{
redirectUrl = _publishedUrlProvider.GetUrl(redirectId);
}
else
{
// might be a UDI instead of an int Id
GuidUdi redirectUdi = request.PublishedContent.Value<GuidUdi>(_publishedValueFallback, Constants.Conventions.Content.Redirect);
if (redirectUdi != null)
{
redirectUrl = _publishedUrlProvider.GetUrl(redirectUdi.Guid);
}
}
if (redirectUrl != "#")
{
request.SetRedirect(redirectUrl);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Meekys.Common.Helpers;
namespace Meekys.OData.Expressions
{
public class DefaultFunctionSource : IFunctionSource
{
protected enum MatchResult
{
NoMatch,
Exact,
CanCast
}
private readonly Dictionary<Type, Type[]> _implicitCastMap = new Dictionary<Type, Type[]>
{
{ typeof(double), new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(char), typeof(float), typeof(ulong) } },
{ typeof(float), new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(char), typeof(ulong) } },
{ typeof(decimal), new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(char), typeof(ulong) } },
{ typeof(ulong), new[] { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
{ typeof(long), new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
{ typeof(uint), new[] { typeof(byte), typeof(ushort), typeof(char) } },
{ typeof(int), new[] { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
{ typeof(ushort), new[] { typeof(byte), typeof(char) } },
{ typeof(short), new[] { typeof(sbyte), typeof(byte) } }
};
private readonly Dictionary<string, MemberInfo[]> _functionMap;
[SuppressMessage(
"Microsoft.CodeAnalysis.Analyzers",
"CA1304:BehaviorCouldVaryBasedOnCurrentUsersLocaleSettings",
Justification = "Functions ToLower and ToUpper are interpreted by Query Provider")]
[SuppressMessage(
"Microsoft.CodeAnalysis.Analyzers",
"CA1307:BehaviorCouldVaryBasedOnCurrentUsersLocaleSettings",
Justification = "Functions EndsWith, StartsWith and IndexOf are interpreted by Query Provider")]
public DefaultFunctionSource()
{
string refString = string.Empty;
DateTime refDate = default(DateTime);
decimal refDecimal = 0m;
double refDouble = 0.0;
_functionMap = new Dictionary<string, MemberInfo[]>(StringComparer.OrdinalIgnoreCase)
{
// String functions
// { "substringof", },
{ "endswith", new[] { MethodHelpers.GetMethodInfo(() => refString.EndsWith(refString)) } },
{ "startswith", new[] { MethodHelpers.GetMethodInfo(() => refString.StartsWith(refString)) } },
{ "length", new[] { MethodHelpers.GetPropertyInfo(() => refString.Length) } },
{ "indexof", new[] { MethodHelpers.GetMethodInfo(() => refString.IndexOf(refString)) } },
{ "replace", new[] { MethodHelpers.GetMethodInfo(() => refString.Replace(refString, refString)) } },
{
"substring",
new[]
{
MethodHelpers.GetMethodInfo(() => refString.Substring(0)),
MethodHelpers.GetMethodInfo(() => refString.Substring(0, 0))
}
},
{ "tolower", new[] { MethodHelpers.GetMethodInfo(() => refString.ToLower()) } },
{ "toupper", new[] { MethodHelpers.GetMethodInfo(() => refString.ToUpper()) } },
{ "trim", new[] { MethodHelpers.GetMethodInfo(() => refString.Trim()) } },
{ "concat", new[] { MethodHelpers.GetMethodInfo(string.Concat, refString, refString) } },
// Date functions
{ "day", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Day) } },
{ "hour", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Hour) } },
{ "minute", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Minute) } },
{ "month", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Month) } },
{ "second", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Second) } },
{ "year", new[] { MethodHelpers.GetPropertyInfo(() => refDate.Year) } },
// Math functions
{
"round",
new[]
{
MethodHelpers.GetMethodInfo(() => Math.Round(refDecimal)),
MethodHelpers.GetMethodInfo(() => Math.Round(refDouble))
}
},
{
"floor",
new[]
{
MethodHelpers.GetMethodInfo(() => Math.Floor(refDecimal)),
MethodHelpers.GetMethodInfo(() => Math.Floor(refDouble))
}
},
{
"ceiling",
new[]
{
MethodHelpers.GetMethodInfo(() => Math.Ceiling(refDecimal)),
MethodHelpers.GetMethodInfo(() => Math.Ceiling(refDouble))
}
}
};
}
public virtual MemberInfo Find(string name, Type[] paramTypes)
{
MemberInfo[] methods;
if (!_functionMap.TryGetValue(name, out methods))
return null;
var method = methods
.Select(m => new { MemberInfo = m, Weight = GetMemberWeight(m, paramTypes) })
.Where(x => x.Weight >= 0)
.OrderBy(x => x.Weight)
.Select(x => x.MemberInfo)
.FirstOrDefault();
return method;
}
private int GetMemberWeight(MemberInfo memberInfo, Type[] paramTypes)
{
if (memberInfo is MethodInfo)
return GetMethodWeight(memberInfo as MethodInfo, paramTypes);
if (memberInfo is PropertyInfo)
return GetPropertyWeight(memberInfo as PropertyInfo, paramTypes);
throw new NotSupportedException($"memberInfo of type {memberInfo.GetType()} is not supported");
}
private int GetPropertyWeight(PropertyInfo propertyInfo, Type[] paramTypes)
{
if (paramTypes.Length != 1)
return -1;
var result = MatchParameter(propertyInfo.DeclaringType, paramTypes[0]);
switch (result)
{
case MatchResult.NoMatch:
return -1;
case MatchResult.Exact:
return 0;
default:
return 1;
}
}
private int GetMethodWeight(MethodInfo methodInfo, Type[] paramTypes)
{
if (methodInfo.IsStatic)
return GetStaticMethodWeight(methodInfo, paramTypes);
return GetMemberMethodWeight(methodInfo, paramTypes);
}
private int GetStaticMethodWeight(MethodInfo methodInfo, Type[] paramTypes)
{
var methodParams = methodInfo.GetParameters();
if (methodParams.Length != paramTypes.Length)
return -1;
return MatchParameters(methodParams.Select(p => p.ParameterType).ToArray(), paramTypes);
}
private int GetMemberMethodWeight(MethodInfo methodInfo, Type[] paramTypes)
{
var methodParams = methodInfo.GetParameters();
if (paramTypes.Length == 0 || methodParams.Length != paramTypes.Length - 1)
return -1;
var methodTypes = new[] { methodInfo.DeclaringType }
.Union(methodParams.Select(p => p.ParameterType))
.ToArray();
return MatchParameters(methodTypes, paramTypes);
}
protected int MatchParameters(Type[] methodTypes, Type[] paramTypes)
{
var matches = methodTypes.Zip(paramTypes, MatchParameter).ToList();
if (matches.Any(m => m == MatchResult.NoMatch))
return -1;
return matches.Count(m => m == MatchResult.CanCast);
}
protected MatchResult MatchParameter(Type methodType, Type paramType)
{
if (methodType == paramType)
return MatchResult.Exact;
if (CanCastTo(paramType, methodType))
return MatchResult.CanCast;
return MatchResult.NoMatch;
}
protected bool CanCastTo(Type fromType, Type toType)
{
Type[] fromTypes;
return _implicitCastMap.TryGetValue(toType, out fromTypes) && fromTypes.Contains(fromType);
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse.Packets;
using System.IO;
using System.Reflection;
using OpenMetaverse.StructuredData;
using ComponentAce.Compression.Libs.zlib;
namespace OpenMetaverse
{
/// <summary>
/// Static helper functions and global variables
/// </summary>
public static class Helpers
{
/// <summary>This header flag signals that ACKs are appended to the packet</summary>
public const byte MSG_APPENDED_ACKS = 0x10;
/// <summary>This header flag signals that this packet has been sent before</summary>
public const byte MSG_RESENT = 0x20;
/// <summary>This header flags signals that an ACK is expected for this packet</summary>
public const byte MSG_RELIABLE = 0x40;
/// <summary>This header flag signals that the message is compressed using zerocoding</summary>
public const byte MSG_ZEROCODED = 0x80;
/// <summary>
/// Passed to Logger.Log() to identify the severity of a log entry
/// </summary>
public enum LogLevel
{
/// <summary>No logging information will be output</summary>
None,
/// <summary>Non-noisy useful information, may be helpful in
/// debugging a problem</summary>
Info,
/// <summary>A non-critical error occurred. A warning will not
/// prevent the rest of the library from operating as usual,
/// although it may be indicative of an underlying issue</summary>
Warning,
/// <summary>A critical error has occurred. Generally this will
/// be followed by the network layer shutting down, although the
/// stability of the library after an error is uncertain</summary>
Error,
/// <summary>Used for internal testing, this logging level can
/// generate very noisy (long and/or repetitive) messages. Don't
/// pass this to the Log() function, use DebugLog() instead.
/// </summary>
Debug
};
/// <summary>
///
/// </summary>
/// <param name="offset"></param>
/// <returns></returns>
public static short TEOffsetShort(float offset)
{
offset = Utils.Clamp(offset, -1.0f, 1.0f);
offset *= 32767.0f;
return (short)Math.Round(offset);
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static float TEOffsetFloat(byte[] bytes, int pos)
{
float offset = (float)BitConverter.ToInt16(bytes, pos);
return offset / 32767.0f;
}
/// <summary>
///
/// </summary>
/// <param name="rotation"></param>
/// <returns></returns>
public static short TERotationShort(float rotation)
{
const float TWO_PI = 6.283185307179586476925286766559f;
return (short)Math.Round(((Math.IEEERemainder(rotation, TWO_PI) / TWO_PI) * 32768.0f) + 0.5f);
}
/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static float TERotationFloat(byte[] bytes, int pos)
{
const float TWO_PI = 6.283185307179586476925286766559f;
return ((float)(bytes[pos] | (bytes[pos + 1] << 8)) / 32768.0f) * TWO_PI;
}
public static byte TEGlowByte(float glow)
{
return (byte)(glow * 255.0f);
}
public static float TEGlowFloat(byte[] bytes, int pos)
{
return (float)bytes[pos] / 255.0f;
}
/// <summary>
/// Given an X/Y location in absolute (grid-relative) terms, a region
/// handle is returned along with the local X/Y location in that region
/// </summary>
/// <param name="globalX">The absolute X location, a number such as
/// 255360.35</param>
/// <param name="globalY">The absolute Y location, a number such as
/// 255360.35</param>
/// <param name="localX">The sim-local X position of the global X
/// position, a value from 0.0 to 256.0</param>
/// <param name="localY">The sim-local Y position of the global Y
/// position, a value from 0.0 to 256.0</param>
/// <returns>A 64-bit region handle that can be used to teleport to</returns>
public static ulong GlobalPosToRegionHandle(float globalX, float globalY, out float localX, out float localY)
{
uint x = ((uint)globalX / 256) * 256;
uint y = ((uint)globalY / 256) * 256;
localX = globalX - (float)x;
localY = globalY - (float)y;
return Utils.UIntsToLong(x, y);
}
/// <summary>
/// Converts a floating point number to a terse string format used for
/// transmitting numbers in wearable asset files
/// </summary>
/// <param name="val">Floating point number to convert to a string</param>
/// <returns>A terse string representation of the input number</returns>
public static string FloatToTerseString(float val)
{
string s = string.Format(Utils.EnUsCulture, "{0:.00}", val);
if (val == 0)
return ".00";
// Trim trailing zeroes
while (s[s.Length - 1] == '0')
s = s.Remove(s.Length - 1, 1);
// Remove superfluous decimal places after the trim
if (s[s.Length - 1] == '.')
s = s.Remove(s.Length - 1, 1);
// Remove leading zeroes after a negative sign
else if (s[0] == '-' && s[1] == '0')
s = s.Remove(1, 1);
// Remove leading zeroes in positive numbers
else if (s[0] == '0')
s = s.Remove(0, 1);
return s;
}
/// <summary>
/// Convert a variable length field (byte array) to a string, with a
/// field name prepended to each line of the output
/// </summary>
/// <remarks>If the byte array has unprintable characters in it, a
/// hex dump will be written instead</remarks>
/// <param name="output">The StringBuilder object to write to</param>
/// <param name="bytes">The byte array to convert to a string</param>
/// <param name="fieldName">A field name to prepend to each line of output</param>
internal static void FieldToString(StringBuilder output, byte[] bytes, string fieldName)
{
// Check for a common case
if (bytes.Length == 0) return;
bool printable = true;
for (int i = 0; i < bytes.Length; ++i)
{
// Check if there are any unprintable characters in the array
if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
&& bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
{
printable = false;
break;
}
}
if (printable)
{
if (fieldName.Length > 0)
{
output.Append(fieldName);
output.Append(": ");
}
if (bytes[bytes.Length - 1] == 0x00)
output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1));
else
output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length));
}
else
{
for (int i = 0; i < bytes.Length; i += 16)
{
if (i != 0)
output.Append('\n');
if (fieldName.Length > 0)
{
output.Append(fieldName);
output.Append(": ");
}
for (int j = 0; j < 16; j++)
{
if ((i + j) < bytes.Length)
output.Append(String.Format("{0:X2} ", bytes[i + j]));
else
output.Append(" ");
}
}
}
}
/// <summary>
/// Decode a zerocoded byte array, used to decompress packets marked
/// with the zerocoded flag
/// </summary>
/// <remarks>Any time a zero is encountered, the next byte is a count
/// of how many zeroes to expand. One zero is encoded with 0x00 0x01,
/// two zeroes is 0x00 0x02, three zeroes is 0x00 0x03, etc. The
/// first four bytes are copied directly to the output buffer.
/// </remarks>
/// <param name="src">The byte array to decode</param>
/// <param name="srclen">The length of the byte array to decode. This
/// would be the length of the packet up to (but not including) any
/// appended ACKs</param>
/// <param name="dest">The output byte array to decode to</param>
/// <returns>The length of the output buffer</returns>
public static int ZeroDecode(byte[] src, int srclen, byte[] dest)
{
if (srclen > src.Length)
throw new ArgumentException("srclen cannot be greater than src.Length");
uint zerolen = 0;
int bodylen = 0;
uint i = 0;
try
{
Buffer.BlockCopy(src, 0, dest, 0, 6);
zerolen = 6;
bodylen = srclen;
for (i = zerolen; i < bodylen; i++)
{
if (src[i] == 0x00)
{
for (byte j = 0; j < src[i + 1]; j++)
{
dest[zerolen++] = 0x00;
}
i++;
}
else
{
dest[zerolen++] = src[i];
}
}
// Copy appended ACKs
for (; i < srclen; i++)
{
dest[zerolen++] = src[i];
}
return (int)zerolen;
}
catch (Exception ex)
{
Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}",
i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex), LogLevel.Error);
throw new IndexOutOfRangeException(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}",
i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex.InnerException));
}
}
/// <summary>
/// Encode a byte array with zerocoding. Used to compress packets marked
/// with the zerocoded flag. Any zeroes in the array are compressed down
/// to a single zero byte followed by a count of how many zeroes to expand
/// out. A single zero becomes 0x00 0x01, two zeroes becomes 0x00 0x02,
/// three zeroes becomes 0x00 0x03, etc. The first four bytes are copied
/// directly to the output buffer.
/// </summary>
/// <param name="src">The byte array to encode</param>
/// <param name="srclen">The length of the byte array to encode</param>
/// <param name="dest">The output byte array to encode to</param>
/// <returns>The length of the output buffer</returns>
public static int ZeroEncode(byte[] src, int srclen, byte[] dest)
{
uint zerolen = 0;
byte zerocount = 0;
Buffer.BlockCopy(src, 0, dest, 0, 6);
zerolen += 6;
int bodylen;
if ((src[0] & MSG_APPENDED_ACKS) == 0)
{
bodylen = srclen;
}
else
{
bodylen = srclen - src[srclen - 1] * 4 - 1;
}
uint i;
for (i = zerolen; i < bodylen; i++)
{
if (src[i] == 0x00)
{
zerocount++;
if (zerocount == 0)
{
dest[zerolen++] = 0x00;
dest[zerolen++] = 0xff;
zerocount++;
}
}
else
{
if (zerocount != 0)
{
dest[zerolen++] = 0x00;
dest[zerolen++] = (byte)zerocount;
zerocount = 0;
}
dest[zerolen++] = src[i];
}
}
if (zerocount != 0)
{
dest[zerolen++] = 0x00;
dest[zerolen++] = (byte)zerocount;
}
// copy appended ACKs
for (; i < srclen; i++)
{
dest[zerolen++] = src[i];
}
return (int)zerolen;
}
/// <summary>
/// Calculates the CRC (cyclic redundancy check) needed to upload inventory.
/// </summary>
/// <param name="creationDate">Creation date</param>
/// <param name="saleType">Sale type</param>
/// <param name="invType">Inventory type</param>
/// <param name="type">Type</param>
/// <param name="assetID">Asset ID</param>
/// <param name="groupID">Group ID</param>
/// <param name="salePrice">Sale price</param>
/// <param name="ownerID">Owner ID</param>
/// <param name="creatorID">Creator ID</param>
/// <param name="itemID">Item ID</param>
/// <param name="folderID">Folder ID</param>
/// <param name="everyoneMask">Everyone mask (permissions)</param>
/// <param name="flags">Flags</param>
/// <param name="nextOwnerMask">Next owner mask (permissions)</param>
/// <param name="groupMask">Group mask (permissions)</param>
/// <param name="ownerMask">Owner mask (permissions)</param>
/// <returns>The calculated CRC</returns>
public static uint InventoryCRC(int creationDate, byte saleType, sbyte invType, sbyte type,
UUID assetID, UUID groupID, int salePrice, UUID ownerID, UUID creatorID,
UUID itemID, UUID folderID, uint everyoneMask, uint flags, uint nextOwnerMask,
uint groupMask, uint ownerMask)
{
uint CRC = 0;
// IDs
CRC += assetID.CRC(); // AssetID
CRC += folderID.CRC(); // FolderID
CRC += itemID.CRC(); // ItemID
// Permission stuff
CRC += creatorID.CRC(); // CreatorID
CRC += ownerID.CRC(); // OwnerID
CRC += groupID.CRC(); // GroupID
// CRC += another 4 words which always seem to be zero -- unclear if this is a UUID or what
CRC += ownerMask;
CRC += nextOwnerMask;
CRC += everyoneMask;
CRC += groupMask;
// The rest of the CRC fields
CRC += flags; // Flags
CRC += (uint)invType; // InvType
CRC += (uint)type; // Type
CRC += (uint)creationDate; // CreationDate
CRC += (uint)salePrice; // SalePrice
CRC += (uint)((uint)saleType * 0x07073096); // SaleType
return CRC;
}
/// <summary>
/// Attempts to load a file embedded in the assembly
/// </summary>
/// <param name="resourceName">The filename of the resource to load</param>
/// <returns>A Stream for the requested file, or null if the resource
/// was not successfully loaded</returns>
public static System.IO.Stream GetResourceStream(string resourceName)
{
return GetResourceStream(resourceName, "openmetaverse_data");
}
/// <summary>
/// Attempts to load a file either embedded in the assembly or found in
/// a given search path
/// </summary>
/// <param name="resourceName">The filename of the resource to load</param>
/// <param name="searchPath">An optional path that will be searched if
/// the asset is not found embedded in the assembly</param>
/// <returns>A Stream for the requested file, or null if the resource
/// was not successfully loaded</returns>
public static System.IO.Stream GetResourceStream(string resourceName, string searchPath)
{
if (searchPath != null)
{
Assembly gea = Assembly.GetEntryAssembly();
if (gea == null) gea = typeof(Helpers).Assembly;
string dirname = ".";
if (gea != null && gea.Location != null)
{
dirname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(gea.Location), searchPath);
}
string filename = System.IO.Path.Combine(dirname, resourceName);
try
{
return new System.IO.FileStream(
filename,
System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
}
catch (Exception ex)
{
Logger.Log(string.Format("Failed opening resource from file {0}: {1}", filename, ex.Message), LogLevel.Error);
}
}
else
{
try
{
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream s = a.GetManifestResourceStream("OpenMetaverse.Resources." + resourceName);
if (s != null) return s;
}
catch (Exception ex)
{
Logger.Log(string.Format("Failed opening resource stream: {0}", ex.Message), LogLevel.Error);
}
}
return null;
}
/// <summary>
/// Converts a list of primitives to an object that can be serialized
/// with the LLSD system
/// </summary>
/// <param name="prims">Primitives to convert to a serializable object</param>
/// <returns>An object that can be serialized with LLSD</returns>
public static StructuredData.OSD PrimListToOSD(List<Primitive> prims)
{
StructuredData.OSDMap map = new OpenMetaverse.StructuredData.OSDMap(prims.Count);
for (int i = 0; i < prims.Count; i++)
map.Add(prims[i].LocalID.ToString(), prims[i].GetOSD());
return map;
}
/// <summary>
/// Deserializes OSD in to a list of primitives
/// </summary>
/// <param name="osd">Structure holding the serialized primitive list,
/// must be of the SDMap type</param>
/// <returns>A list of deserialized primitives</returns>
public static List<Primitive> OSDToPrimList(StructuredData.OSD osd)
{
if (osd.Type != StructuredData.OSDType.Map)
throw new ArgumentException("LLSD must be in the Map structure");
StructuredData.OSDMap map = (StructuredData.OSDMap)osd;
List<Primitive> prims = new List<Primitive>(map.Count);
foreach (KeyValuePair<string, StructuredData.OSD> kvp in map)
{
Primitive prim = Primitive.FromOSD(kvp.Value);
prim.LocalID = UInt32.Parse(kvp.Key);
prims.Add(prim);
}
return prims;
}
/// <summary>
/// Converts a struct or class object containing fields only into a key value separated string
/// </summary>
/// <param name="t">The struct object</param>
/// <returns>A string containing the struct fields as the keys, and the field value as the value separated</returns>
/// <example>
/// <code>
/// // Add the following code to any struct or class containing only fields to override the ToString()
/// // method to display the values of the passed object
///
/// /// <summary>Print the struct data as a string</summary>
/// ///<returns>A string containing the field name, and field value</returns>
///public override string ToString()
///{
/// return Helpers.StructToString(this);
///}
/// </code>
/// </example>
public static string StructToString(object t)
{
StringBuilder result = new StringBuilder();
Type structType = t.GetType();
FieldInfo[] fields = structType.GetFields();
foreach (FieldInfo field in fields)
{
result.Append(field.Name + ": " + field.GetValue(t) + " ");
}
result.AppendLine();
return result.ToString().TrimEnd();
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
public static byte[] ZCompressOSD(OSD data)
{
byte[] ret = null;
using (MemoryStream outMemoryStream = new MemoryStream())
using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_BEST_COMPRESSION))
using (Stream inMemoryStream = new MemoryStream(OSDParser.SerializeLLSDBinary(data, false)))
{
CopyStream(inMemoryStream, outZStream);
outZStream.finish();
ret = outMemoryStream.ToArray();
}
return ret;
}
public static OSD ZDecompressOSD(byte[] data)
{
OSD ret;
using (MemoryStream input = new MemoryStream(data))
using (MemoryStream output = new MemoryStream())
using (ZOutputStream zout = new ZOutputStream(output))
{
CopyStream(input, zout);
zout.finish();
output.Seek(0, SeekOrigin.Begin);
ret = OSDParser.DeserializeLLSDBinary(output);
}
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Internal.Sessions;
using Marten.Testing.Harness;
using Newtonsoft.Json;
using Shouldly;
using Xunit;
namespace Marten.Testing.Events.SchemaChange
{
#region sample_old_event_namespace
namespace OldEventNamespace
{
public class OrderStatusChanged
{
public Guid OrderId { get; }
public int Status { get; }
public OrderStatusChanged(Guid orderId, int status)
{
OrderId = orderId;
Status = status;
}
}
}
#endregion sample_old_event_namespace
#region sample_new_event_namespace
namespace NewEventNamespace
{
public class OrderStatusChanged
{
public Guid OrderId { get; }
public int Status { get; }
public OrderStatusChanged(Guid orderId, int status)
{
OrderId = orderId;
Status = status;
}
}
}
#endregion sample_new_event_namespace
#region sample_new_event_type_name
namespace OldEventNamespace
{
public class ConfirmedOrderStatusChanged
{
public Guid OrderId { get; }
public int Status { get; }
public ConfirmedOrderStatusChanged(Guid orderId, int status)
{
OrderId = orderId;
Status = status;
}
}
}
#endregion sample_new_event_type_name
public static class SampleEventsSchemaMigration
{
public static void SampleAddEventsRegistration()
{
#region sample_event_namespace_migration_options
var options = new StoreOptions();
options.Events.AddEventTypes(new[] {typeof(NewEventNamespace.OrderStatusChanged)});
var store = new DocumentStore(options);
#endregion sample_event_namespace_migration_options
}
public static void SampleEventMappingRegistration()
{
#region sample_event_type_name_migration_options
var options = new StoreOptions();
var orderStatusChangedMapping = options.EventGraph.EventMappingFor<OldEventNamespace.ConfirmedOrderStatusChanged>();
orderStatusChangedMapping.EventTypeName = "order_status_changed";
var store = new DocumentStore(options);
#endregion sample_event_type_name_migration_options
}
}
public abstract class AggregateBase
{
public Guid Id { get; protected set; }
public long Version { get; protected set; }
[JsonIgnore] private readonly List<object> _uncommittedEvents = new List<object>();
public IEnumerable<object> DequeueEvents()
{
var events = _uncommittedEvents.ToList();
_uncommittedEvents.Clear();
return events;
}
protected void EnqueueEvent(object @event)
{
// add the event to the uncommitted list
_uncommittedEvents.Add(@event);
Version++;
}
}
// Events in old namespace `Old`
namespace Old
{
public class TaskCreated
{
public Guid TaskId { get; }
public string Description { get; }
public TaskCreated(Guid taskId, string description)
{
TaskId = taskId;
Description = description;
}
}
public class TaskDescriptionUpdated
{
public string Description { get; }
public TaskDescriptionUpdated(string description)
{
Description = description;
}
}
public class Task : AggregateBase
{
public string Description { get; private set; }
private Task() {}
public Task(Guid id, string description)
{
var @event = new TaskCreated(id, description);
EnqueueEvent(@event);
Apply(@event);
}
public void UpdateDescription(string description)
{
var @event = new TaskDescriptionUpdated(description);
EnqueueEvent(@event);
Apply(@event);
}
public void Apply(TaskCreated @event)
{
Id = @event.TaskId;
Description = @event.Description;
}
public void Apply(TaskDescriptionUpdated @event)
{
Description = @event.Description;
}
}
}
// Events in new namespace `New`
namespace New
{
public class TaskCreated
{
public Guid TaskId { get; }
public string Description { get; }
public TaskCreated(Guid taskId, string description)
{
TaskId = taskId;
Description = description;
}
}
// Type name has changed - Event will be stored with `TaskDescriptionChanged`
public class TaskDescriptionChanged
{
public Guid TaskId { get; }
public string Description { get; }
public TaskDescriptionChanged(string description)
{
Description = description;
}
}
public class Task : AggregateBase
{
public string Description { get; private set; }
private Task() {}
public Task(Guid id, string description)
{
var @event = new TaskCreated(id, description);
EnqueueEvent(@event);
Apply(@event);
}
public void UpdateDescription(string description)
{
var @event = new TaskDescriptionChanged(description);
EnqueueEvent(@event);
Apply(@event);
}
public void Apply(TaskCreated @event)
{
Id = @event.TaskId;
Description = @event.Description;
}
public void Apply(TaskDescriptionChanged @event)
{
Description = @event.Description;
}
}
}
[Collection("events_namespace_migration")]
public class EventsNamespaceChange: OneOffConfigurationsContext
{
[Fact]
public async Task HavingEvents_WithSchemaChange_AggregationShouldWork()
{
// test events data
var taskId = Guid.NewGuid();
var task = new Old.Task(taskId, "Initial Description");
task.UpdateDescription("updated description");
theStore.Tenancy.Default.EnsureStorageExists(typeof(StreamAction));
using (var session = (DocumentSessionBase)theStore.OpenSession())
{
session.Events.Append(taskId, task.DequeueEvents());
await session.SaveChangesAsync();
}
using (var store = SeparateStore(_ =>
{
// Add new Event types, if type names won't change then the same type name will be generated
// and we don't need additional config
_.Events.AddEventTypes(new []{typeof(New.TaskCreated), typeof(New.TaskDescriptionChanged)});
// When type name has changed we need to define custom mapping
_.EventGraph.EventMappingFor<New.TaskDescriptionChanged>()
.EventTypeName = "task_description_updated";
}))
{
using (var session = store.OpenSession())
{
var taskNew = await session.Events.AggregateStreamAsync<New.Task>(taskId);
taskNew.Id.ShouldBe(taskId);
taskNew.Description.ShouldBe(task.Description);
}
}
}
public EventsNamespaceChange() : base("events_namespace_migration")
{
}
}
}
| |
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
namespace YAF.Lucene.Net.Codecs.Compressing
{
/*
* 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 CorruptIndexException = YAF.Lucene.Net.Index.CorruptIndexException;
using DataInput = YAF.Lucene.Net.Store.DataInput;
using DataOutput = YAF.Lucene.Net.Store.DataOutput;
/// <summary>
/// A compression mode. Tells how much effort should be spent on compression and
/// decompression of stored fields.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class CompressionMode
{
/// <summary>
/// A compression mode that trades compression ratio for speed. Although the
/// compression ratio might remain high, compression and decompression are
/// very fast. Use this mode with indices that have a high update rate but
/// should be able to load documents from disk quickly.
/// </summary>
public static readonly CompressionMode FAST = new CompressionModeAnonymousInnerClassHelper();
private class CompressionModeAnonymousInnerClassHelper : CompressionMode
{
public CompressionModeAnonymousInnerClassHelper()
{
}
public override Compressor NewCompressor()
{
return new LZ4FastCompressor();
}
public override Decompressor NewDecompressor()
{
return LZ4_DECOMPRESSOR;
}
public override string ToString()
{
return "FAST";
}
}
/// <summary>
/// A compression mode that trades speed for compression ratio. Although
/// compression and decompression might be slow, this compression mode should
/// provide a good compression ratio. this mode might be interesting if/when
/// your index size is much bigger than your OS cache.
/// </summary>
public static readonly CompressionMode HIGH_COMPRESSION = new CompressionModeAnonymousInnerClassHelper2();
private class CompressionModeAnonymousInnerClassHelper2 : CompressionMode
{
public CompressionModeAnonymousInnerClassHelper2()
{
}
public override Compressor NewCompressor()
{
return new DeflateCompressor(System.IO.Compression.CompressionLevel.Optimal);
}
public override Decompressor NewDecompressor()
{
return new DeflateDecompressor();
}
public override string ToString()
{
return "HIGH_COMPRESSION";
}
}
/// <summary>
/// This compression mode is similar to <see cref="FAST"/> but it spends more time
/// compressing in order to improve the compression ratio. This compression
/// mode is best used with indices that have a low update rate but should be
/// able to load documents from disk quickly.
/// </summary>
public static readonly CompressionMode FAST_DECOMPRESSION = new CompressionModeAnonymousInnerClassHelper3();
private class CompressionModeAnonymousInnerClassHelper3 : CompressionMode
{
public CompressionModeAnonymousInnerClassHelper3()
{
}
public override Compressor NewCompressor()
{
return new LZ4HighCompressor();
}
public override Decompressor NewDecompressor()
{
return LZ4_DECOMPRESSOR;
}
public override string ToString()
{
return "FAST_DECOMPRESSION";
}
}
/// <summary>
/// Sole constructor. </summary>
protected internal CompressionMode()
{
}
/// <summary>
/// Create a new <see cref="Compressor"/> instance.
/// </summary>
public abstract Compressor NewCompressor();
/// <summary>
/// Create a new <see cref="Decompressor"/> instance.
/// </summary>
public abstract Decompressor NewDecompressor();
private static readonly Decompressor LZ4_DECOMPRESSOR = new DecompressorAnonymousInnerClassHelper();
private class DecompressorAnonymousInnerClassHelper : Decompressor
{
public DecompressorAnonymousInnerClassHelper()
{
}
public override void Decompress(DataInput @in, int originalLength, int offset, int length, BytesRef bytes)
{
Debug.Assert(offset + length <= originalLength);
// add 7 padding bytes, this is not necessary but can help decompression run faster
if (bytes.Bytes.Length < originalLength + 7)
{
bytes.Bytes = new byte[ArrayUtil.Oversize(originalLength + 7, 1)];
}
int decompressedLength = LZ4.Decompress(@in, offset + length, bytes.Bytes, 0);
if (decompressedLength > originalLength)
{
throw new CorruptIndexException("Corrupted: lengths mismatch: " + decompressedLength + " > " + originalLength + " (resource=" + @in + ")");
}
bytes.Offset = offset;
bytes.Length = length;
}
public override object Clone()
{
return this;
}
}
private sealed class LZ4FastCompressor : Compressor
{
private readonly LZ4.HashTable ht;
internal LZ4FastCompressor()
{
ht = new LZ4.HashTable();
}
public override void Compress(byte[] bytes, int off, int len, DataOutput @out)
{
LZ4.Compress(bytes, off, len, @out, ht);
}
}
private sealed class LZ4HighCompressor : Compressor
{
internal readonly LZ4.HCHashTable ht;
internal LZ4HighCompressor()
{
ht = new LZ4.HCHashTable();
}
public override void Compress(byte[] bytes, int off, int len, DataOutput @out)
{
LZ4.CompressHC(bytes, off, len, @out, ht);
}
}
private sealed class DeflateDecompressor : Decompressor
{
internal DeflateDecompressor()
{
}
public override void Decompress(DataInput input, int originalLength, int offset, int length, BytesRef bytes)
{
Debug.Assert(offset + length <= originalLength);
if (length == 0)
{
bytes.Length = 0;
return;
}
byte[] compressedBytes = new byte[input.ReadVInt32()];
input.ReadBytes(compressedBytes, 0, compressedBytes.Length);
byte[] decompressedBytes = null;
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressedStream = new MemoryStream(compressedBytes))
{
using (DeflateStream dStream = new DeflateStream(compressedStream, System.IO.Compression.CompressionMode.Decompress))
{
dStream.CopyTo(decompressedStream);
}
}
decompressedBytes = decompressedStream.ToArray();
}
if (decompressedBytes.Length != originalLength)
{
throw new CorruptIndexException("Length mismatch: " + decompressedBytes.Length + " != " + originalLength + " (resource=" + input + ")");
}
bytes.Bytes = decompressedBytes;
bytes.Offset = offset;
bytes.Length = length;
}
public override object Clone()
{
return new DeflateDecompressor();
}
}
private class DeflateCompressor : Compressor
{
private CompressionLevel compressionLevel;
internal DeflateCompressor(CompressionLevel level)
{
compressionLevel = level;
}
public override void Compress(byte[] bytes, int off, int len, DataOutput output)
{
byte[] resultArray = null;
using (MemoryStream compressionMemoryStream = new MemoryStream())
{
using (DeflateStream deflateStream = new DeflateStream(compressionMemoryStream, compressionLevel))
{
deflateStream.Write(bytes, off, len);
}
resultArray = compressionMemoryStream.ToArray();
}
if (resultArray.Length == 0)
{
Debug.Assert(len == 0, len.ToString());
output.WriteVInt32(0);
return;
}
else
{
output.WriteVInt32(resultArray.Length);
output.WriteBytes(resultArray, resultArray.Length);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private static readonly Task<Stream> s_nullStreamTask = Task.FromResult(Stream.Null);
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Uri _baseAddress;
private TimeSpan _timeout;
private long _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, "value");
CheckDisposedOrStarted();
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.UriBaseAddress(this, value != null ? value.ToString() : string.Empty);
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
_maxResponseContentBufferSize = value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler);
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri)
{
return GetStringAsync(CreateUri(requestUri));
}
public Task<string> GetStringAsync(Uri requestUri)
{
return GetContentAsync(
GetAsync(requestUri, HttpCompletionOption.ResponseContentRead),
content => content != null ? content.ReadBufferedContentAsString() : string.Empty);
}
public Task<byte[]> GetByteArrayAsync(string requestUri)
{
return GetByteArrayAsync(CreateUri(requestUri));
}
public Task<byte[]> GetByteArrayAsync(Uri requestUri)
{
return GetContentAsync(
GetAsync(requestUri, HttpCompletionOption.ResponseContentRead),
content => content != null ? content.ReadBufferedContentAsByteArray() : Array.Empty<byte>());
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return GetContentAsync(
GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead),
content => content != null ? content.ReadAsStreamAsync() : s_nullStreamTask);
}
private async Task<T> GetContentAsync<T>(Task<HttpResponseMessage> getTask, Func<HttpContent, T> readAs)
{
HttpResponseMessage response = await getTask.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return readAs(response.Content);
}
private async Task<T> GetContentAsync<T>(Task<HttpResponseMessage> getTask, Func<HttpContent, Task<T>> readAsAsync)
{
HttpResponseMessage response = await getTask.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await readAsAsync(response.Content).ConfigureAwait(false);
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
_pendingRequestsCts.Token);
SetTimeout(linkedCts);
return FinishSendAsync(
base.SendAsync(request, linkedCts.Token),
request,
linkedCts,
completionOption == HttpCompletionOption.ResponseContentRead);
}
private async Task<HttpResponseMessage> FinishSendAsync(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource linkedCts, bool bufferResponseContent)
{
HttpResponseMessage response = null;
try
{
try
{
// Wait for the send request to complete, getting back the response.
response = await sendTask.ConfigureAwait(false);
}
finally
{
// When a request completes, dispose the request content so the user doesn't have to. This also
// ensures that a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages
// that can also be sent only once).
request.Content?.Dispose();
}
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
// Buffer the response content if we've been asked to and we have a Content to buffer.
if (bufferResponseContent && response.Content != null)
{
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ConfigureAwait(false);
}
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
response?.Dispose();
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (linkedCts.IsCancellationRequested && e is HttpRequestException)
{
LogSendError(request, linkedCts, nameof(SendAsync), null);
throw new OperationCanceledException(linkedCts.Token);
}
else
{
LogSendError(request, linkedCts, nameof(SendAsync), e);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, nameof(SendAsync), e);
throw;
}
}
finally
{
linkedCts.Dispose();
}
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private void SetTimeout(CancellationTokenSource cancellationTokenSource)
{
Contract.Requires(cancellationTokenSource != null);
if (_timeout != s_infiniteTimeout)
{
cancellationTokenSource.CancelAfter(_timeout);
}
}
private void LogSendError(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
string method, Exception e)
{
Contract.Requires(request != null);
if (cancellationTokenSource.IsCancellationRequested)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_canceled, LoggingHash.GetObjectLogHash(request)));
}
else
{
Debug.Assert(e != null);
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_error, LoggingHash.GetObjectLogHash(request), e));
}
}
private Uri CreateUri(String uri)
{
if (string.IsNullOrEmpty(uri))
{
return null;
}
return new Uri(uri, UriKind.RelativeOrAbsolute);
}
#endregion Private Helpers
}
}
| |
using System;
using xmljr.math;
using System.ComponentModel;
using uint16 = System.UInt16;
using uint32 = System.UInt32;
namespace DemoGame
{
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class Monster
{
public int _ActivatedAt;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedAt { get { return _ActivatedAt; } set { _ActivatedAt = value; } }
public int _Floor;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Floor { get { return _Floor; } set { _Floor = value; } }
public float _X;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float X { get { return _X; } set { _X = value; } }
public float _Y;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float Y { get { return _Y; } set { _Y = value; } }
public bool _HasObjective;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public bool HasObjective { get { return _HasObjective; } set { _HasObjective = value; } }
public int _GoalX;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int GoalX { get { return _GoalX; } set { _GoalX = value; } }
public int _GoalY;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int GoalY { get { return _GoalY; } set { _GoalY = value; } }
public bool _Angry;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public bool Angry { get { return _Angry; } set { _Angry = value; } }
public double _DistanceToGoal;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double DistanceToGoal { get { return _DistanceToGoal; } set { _DistanceToGoal = value; } }
public Monster _NextMonster;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Monster NextMonster { get { return _NextMonster; } set { _NextMonster = value; } }
public Monster()
{
ActivatedAt = 0;
Floor = 0;
X = 0.0f;
Y = 0.0f;
HasObjective = false;
GoalX = 0;
GoalY = 0;
Angry = false;
DistanceToGoal = 0.0;
NextMonster = null;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-Monster
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("Monster",this);
//ActivatedAt-stage0
_XB.write_int("ActivatedAt",ActivatedAt);
//Floor-stage0
_XB.write_int("Floor",Floor);
//X-stage0
_XB.write_float("X",X);
//Y-stage0
_XB.write_float("Y",Y);
//HasObjective-stage0
_XB.write_bool("HasObjective",HasObjective);
//GoalX-stage0
_XB.write_int("GoalX",GoalX);
//GoalY-stage0
_XB.write_int("GoalY",GoalY);
//Angry-stage0
_XB.write_bool("Angry",Angry);
//DistanceToGoal-stage0
_XB.write_double("DistanceToGoal",DistanceToGoal);
//NextMonster-stage0
if(NextMonster != null)
_XB.write_addr("NextMonster",NextMonster.WriteXML(__XW));
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-Monster
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//ActivatedAt-stageR
if(__C._Name.Equals("ActivatedAt"))
{
ActivatedAt = __C.read_int();
}
//Floor-stageR
if(__C._Name.Equals("Floor"))
{
Floor = __C.read_int();
}
//X-stageR
if(__C._Name.Equals("X"))
{
X = __C.read_float();
}
//Y-stageR
if(__C._Name.Equals("Y"))
{
Y = __C.read_float();
}
//HasObjective-stageR
if(__C._Name.Equals("HasObjective"))
{
HasObjective = __C.read_bool();
}
//GoalX-stageR
if(__C._Name.Equals("GoalX"))
{
GoalX = __C.read_int();
}
//GoalY-stageR
if(__C._Name.Equals("GoalY"))
{
GoalY = __C.read_int();
}
//Angry-stageR
if(__C._Name.Equals("Angry"))
{
Angry = __C.read_bool();
}
//DistanceToGoal-stageR
if(__C._Name.Equals("DistanceToGoal"))
{
DistanceToGoal = __C.read_double();
}
//NextMonster-stageR
if(__C._Name.Equals("NextMonster"))
{
NextMonster = (Monster) __table.LookUpObject(__C.read_int());
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class Turret
{
public int _ActivatedAt;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedAt { get { return _ActivatedAt; } set { _ActivatedAt = value; } }
public int _Floor;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Floor { get { return _Floor; } set { _Floor = value; } }
public int _X;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int X { get { return _X; } set { _X = value; } }
public int _Y;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Y { get { return _Y; } set { _Y = value; } }
public float _TargetX;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float TargetX { get { return _TargetX; } set { _TargetX = value; } }
public float _TargetY;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float TargetY { get { return _TargetY; } set { _TargetY = value; } }
public double _CooldownReset;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double CooldownReset { get { return _CooldownReset; } set { _CooldownReset = value; } }
public double _Cooldown;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double Cooldown { get { return _Cooldown; } set { _Cooldown = value; } }
public int [] _TargetSearch;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int [] TargetSearch { get { return _TargetSearch; } set { _TargetSearch = value; } }
public int _ActivatedTargets;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedTargets { get { return _ActivatedTargets; } set { _ActivatedTargets = value; } }
public Turret()
{
ActivatedAt = 0;
Floor = 0;
X = 0;
Y = 0;
TargetX = 0.0f;
TargetY = 0.0f;
CooldownReset = 0.0;
Cooldown = 0.0;
TargetSearch = null;
ActivatedTargets = 0;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-Turret
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("Turret",this);
//ActivatedAt-stage0
_XB.write_int("ActivatedAt",ActivatedAt);
//Floor-stage0
_XB.write_int("Floor",Floor);
//X-stage0
_XB.write_int("X",X);
//Y-stage0
_XB.write_int("Y",Y);
//TargetX-stage0
_XB.write_float("TargetX",TargetX);
//TargetY-stage0
_XB.write_float("TargetY",TargetY);
//CooldownReset-stage0
_XB.write_double("CooldownReset",CooldownReset);
//Cooldown-stage0
_XB.write_double("Cooldown",Cooldown);
//TargetSearch-stage0
if(TargetSearch != null)
{
_XB.write_array("TargetSearch",TargetSearch.Length);
for(__idx = 0 ; __idx < TargetSearch.Length; __idx++)
_XB.write_int("r",TargetSearch[__idx]);
_XB.finish_array("TargetSearch");
}
//ActivatedTargets-stage0
_XB.write_int("ActivatedTargets",ActivatedTargets);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-Turret
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//ActivatedAt-stageR
if(__C._Name.Equals("ActivatedAt"))
{
ActivatedAt = __C.read_int();
}
//Floor-stageR
if(__C._Name.Equals("Floor"))
{
Floor = __C.read_int();
}
//X-stageR
if(__C._Name.Equals("X"))
{
X = __C.read_int();
}
//Y-stageR
if(__C._Name.Equals("Y"))
{
Y = __C.read_int();
}
//TargetX-stageR
if(__C._Name.Equals("TargetX"))
{
TargetX = __C.read_float();
}
//TargetY-stageR
if(__C._Name.Equals("TargetY"))
{
TargetY = __C.read_float();
}
//CooldownReset-stageR
if(__C._Name.Equals("CooldownReset"))
{
CooldownReset = __C.read_double();
}
//Cooldown-stageR
if(__C._Name.Equals("Cooldown"))
{
Cooldown = __C.read_double();
}
//TargetSearch-stageR
if(__C._Name.Equals("TargetSearch"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
TargetSearch = new int[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
TargetSearch[__idx] = sub.read_int();
__idx++;
}
}
}
}
//ActivatedTargets-stageR
if(__C._Name.Equals("ActivatedTargets"))
{
ActivatedTargets = __C.read_int();
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class Projectile
{
public int _ActivatedAt;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedAt { get { return _ActivatedAt; } set { _ActivatedAt = value; } }
public float _X;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float X { get { return _X; } set { _X = value; } }
public float _Y;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float Y { get { return _Y; } set { _Y = value; } }
public float _DeltaX;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float DeltaX { get { return _DeltaX; } set { _DeltaX = value; } }
public float _DeltaY;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float DeltaY { get { return _DeltaY; } set { _DeltaY = value; } }
public float _Lifetime;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public float Lifetime { get { return _Lifetime; } set { _Lifetime = value; } }
public Projectile()
{
ActivatedAt = 0;
X = 0.0f;
Y = 0.0f;
DeltaX = 0.0f;
DeltaY = 0.0f;
Lifetime = 0.0f;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-Projectile
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("Projectile",this);
//ActivatedAt-stage0
_XB.write_int("ActivatedAt",ActivatedAt);
//X-stage0
_XB.write_float("X",X);
//Y-stage0
_XB.write_float("Y",Y);
//DeltaX-stage0
_XB.write_float("DeltaX",DeltaX);
//DeltaY-stage0
_XB.write_float("DeltaY",DeltaY);
//Lifetime-stage0
_XB.write_float("Lifetime",Lifetime);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-Projectile
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//ActivatedAt-stageR
if(__C._Name.Equals("ActivatedAt"))
{
ActivatedAt = __C.read_int();
}
//X-stageR
if(__C._Name.Equals("X"))
{
X = __C.read_float();
}
//Y-stageR
if(__C._Name.Equals("Y"))
{
Y = __C.read_float();
}
//DeltaX-stageR
if(__C._Name.Equals("DeltaX"))
{
DeltaX = __C.read_float();
}
//DeltaY-stageR
if(__C._Name.Equals("DeltaY"))
{
DeltaY = __C.read_float();
}
//Lifetime-stageR
if(__C._Name.Equals("Lifetime"))
{
Lifetime = __C.read_float();
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class Tile
{
public int _Type;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Type { get { return _Type; } set { _Type = value; } }
public int _GoalX;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int GoalX { get { return _GoalX; } set { _GoalX = value; } }
public int _GoalY;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int GoalY { get { return _GoalY; } set { _GoalY = value; } }
public double _Distance;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double Distance { get { return _Distance; } set { _Distance = value; } }
public Monster _BestMonster;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Monster BestMonster { get { return _BestMonster; } set { _BestMonster = value; } }
public Monster _WorstMonster;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Monster WorstMonster { get { return _WorstMonster; } set { _WorstMonster = value; } }
public Tile()
{
Type = 0;
GoalX = 0;
GoalY = 0;
Distance = 0.0;
BestMonster = null;
WorstMonster = null;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-Tile
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("Tile",this);
//Type-stage0
_XB.write_int("Type",Type);
//GoalX-stage0
_XB.write_int("GoalX",GoalX);
//GoalY-stage0
_XB.write_int("GoalY",GoalY);
//Distance-stage0
_XB.write_double("Distance",Distance);
//BestMonster-stage0
if(BestMonster != null)
_XB.write_addr("BestMonster",BestMonster.WriteXML(__XW));
//WorstMonster-stage0
if(WorstMonster != null)
_XB.write_addr("WorstMonster",WorstMonster.WriteXML(__XW));
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-Tile
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//Type-stageR
if(__C._Name.Equals("Type"))
{
Type = __C.read_int();
}
//GoalX-stageR
if(__C._Name.Equals("GoalX"))
{
GoalX = __C.read_int();
}
//GoalY-stageR
if(__C._Name.Equals("GoalY"))
{
GoalY = __C.read_int();
}
//Distance-stageR
if(__C._Name.Equals("Distance"))
{
Distance = __C.read_double();
}
//BestMonster-stageR
if(__C._Name.Equals("BestMonster"))
{
BestMonster = (Monster) __table.LookUpObject(__C.read_int());
}
//WorstMonster-stageR
if(__C._Name.Equals("WorstMonster"))
{
WorstMonster = (Monster) __table.LookUpObject(__C.read_int());
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class TileGrid
{
public Tile [] _Tiles;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Tile [] Tiles { get { return _Tiles; } set { _Tiles = value; } }
public int _Width;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Width { get { return _Width; } set { _Width = value; } }
public int _Height;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Height { get { return _Height; } set { _Height = value; } }
public TileGrid()
{
Tiles = null;
Width = 0;
Height = 0;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-TileGrid
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("TileGrid",this);
//Tiles-stage0
if(Tiles != null)
{
_XB.write_array("Tiles",Tiles.Length);
for(__idx = 0 ; __idx < Tiles.Length; __idx++)
_XB.write_addr("r",Tiles[__idx].WriteXML(__XW));
_XB.finish_array("Tiles");
}
//Width-stage0
_XB.write_int("Width",Width);
//Height-stage0
_XB.write_int("Height",Height);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-TileGrid
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//Tiles-stageR
if(__C._Name.Equals("Tiles"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
Tiles = new Tile[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
Tiles[__idx] = (Tile) __table.LookUpObject(sub.read_int());
__idx++;
}
}
}
}
//Width-stageR
if(__C._Name.Equals("Width"))
{
Width = __C.read_int();
}
//Height-stageR
if(__C._Name.Equals("Height"))
{
Height = __C.read_int();
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class TileMark
{
public int _Floor;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Floor { get { return _Floor; } set { _Floor = value; } }
public int _X;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int X { get { return _X; } set { _X = value; } }
public int _Y;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int Y { get { return _Y; } set { _Y = value; } }
public TileMark()
{
Floor = 0;
X = 0;
Y = 0;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-TileMark
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("TileMark",this);
//Floor-stage0
_XB.write_int("Floor",Floor);
//X-stage0
_XB.write_int("X",X);
//Y-stage0
_XB.write_int("Y",Y);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-TileMark
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//Floor-stageR
if(__C._Name.Equals("Floor"))
{
Floor = __C.read_int();
}
//X-stageR
if(__C._Name.Equals("X"))
{
X = __C.read_int();
}
//Y-stageR
if(__C._Name.Equals("Y"))
{
Y = __C.read_int();
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class TileMap
{
public TileGrid [] _Floors;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileGrid [] Floors { get { return _Floors; } set { _Floors = value; } }
public TileMark _Start;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileMark Start { get { return _Start; } set { _Start = value; } }
public TileMark _Exit;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileMark Exit { get { return _Exit; } set { _Exit = value; } }
public bool _Dirty;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public bool Dirty { get { return _Dirty; } set { _Dirty = value; } }
public TileMap()
{
Floors = null;
Start = null;
Exit = null;
Dirty = false;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-TileMap
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("TileMap",this);
//Floors-stage0
if(Floors != null)
{
_XB.write_array("Floors",Floors.Length);
for(__idx = 0 ; __idx < Floors.Length; __idx++)
_XB.write_addr("r",Floors[__idx].WriteXML(__XW));
_XB.finish_array("Floors");
}
//Start-stage0
if(Start != null)
_XB.write_addr("Start",Start.WriteXML(__XW));
//Exit-stage0
if(Exit != null)
_XB.write_addr("Exit",Exit.WriteXML(__XW));
//Dirty-stage0
_XB.write_bool("Dirty",Dirty);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-TileMap
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//Floors-stageR
if(__C._Name.Equals("Floors"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
Floors = new TileGrid[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
Floors[__idx] = (TileGrid) __table.LookUpObject(sub.read_int());
__idx++;
}
}
}
}
//Start-stageR
if(__C._Name.Equals("Start"))
{
Start = (TileMark) __table.LookUpObject(__C.read_int());
}
//Exit-stageR
if(__C._Name.Equals("Exit"))
{
Exit = (TileMark) __table.LookUpObject(__C.read_int());
}
//Dirty-stageR
if(__C._Name.Equals("Dirty"))
{
Dirty = __C.read_bool();
}
}
#endregion
}
}
[TypeConverter(typeof(ExpandableObjectConverter)),Serializable]
public class GameDocument
{
public Monster [] _Monsters;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Monster [] Monsters { get { return _Monsters; } set { _Monsters = value; } }
public int _ActivatedMonsters;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedMonsters { get { return _ActivatedMonsters; } set { _ActivatedMonsters = value; } }
public Turret [] _Turrets;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Turret [] Turrets { get { return _Turrets; } set { _Turrets = value; } }
public int _ActivatedTurrets;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedTurrets { get { return _ActivatedTurrets; } set { _ActivatedTurrets = value; } }
public Projectile [] _Projectiles;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public Projectile [] Projectiles { get { return _Projectiles; } set { _Projectiles = value; } }
public int _ActivatedProjectiles;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public int ActivatedProjectiles { get { return _ActivatedProjectiles; } set { _ActivatedProjectiles = value; } }
public string _RenderScene;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public string RenderScene { get { return _RenderScene; } set { _RenderScene = value; } }
public TileMap _CurrentMap;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileMap CurrentMap { get { return _CurrentMap; } set { _CurrentMap = value; } }
public TileMark _Cursor;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileMark Cursor { get { return _Cursor; } set { _Cursor = value; } }
public TileMark _CapturedCursor;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public TileMark CapturedCursor { get { return _CapturedCursor; } set { _CapturedCursor = value; } }
public double _SpawnTimer;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double SpawnTimer { get { return _SpawnTimer; } set { _SpawnTimer = value; } }
public double _SpawnTimerReset;
[CategoryAttribute("Uncategorized"),DescriptionAttribute("")]
public double SpawnTimerReset { get { return _SpawnTimerReset; } set { _SpawnTimerReset = value; } }
public GameDocument()
{
Monsters = null;
ActivatedMonsters = 0;
Turrets = null;
ActivatedTurrets = 0;
Projectiles = null;
ActivatedProjectiles = 0;
RenderScene = "";
CurrentMap = null;
Cursor = null;
CapturedCursor = null;
SpawnTimer = 0.0;
SpawnTimerReset = 0.0;
}
//WriteXML
public virtual int WriteXML(xmljr.XmlJrWriter __XW)
{
#region WriteXML-GameDocument
int __idx; __idx = 0; __idx++; __idx--;
int __testaddr = __XW.Exist(this);
if(__testaddr > 0) return __testaddr;
xmljr.XmlJrBuffer _XB = __XW.NewObject("GameDocument",this);
//Monsters-stage0
if(Monsters != null)
{
_XB.write_array("Monsters",Monsters.Length);
for(__idx = 0 ; __idx < Monsters.Length; __idx++)
_XB.write_addr("r",Monsters[__idx].WriteXML(__XW));
_XB.finish_array("Monsters");
}
//ActivatedMonsters-stage0
_XB.write_int("ActivatedMonsters",ActivatedMonsters);
//Turrets-stage0
if(Turrets != null)
{
_XB.write_array("Turrets",Turrets.Length);
for(__idx = 0 ; __idx < Turrets.Length; __idx++)
_XB.write_addr("r",Turrets[__idx].WriteXML(__XW));
_XB.finish_array("Turrets");
}
//ActivatedTurrets-stage0
_XB.write_int("ActivatedTurrets",ActivatedTurrets);
//Projectiles-stage0
if(Projectiles != null)
{
_XB.write_array("Projectiles",Projectiles.Length);
for(__idx = 0 ; __idx < Projectiles.Length; __idx++)
_XB.write_addr("r",Projectiles[__idx].WriteXML(__XW));
_XB.finish_array("Projectiles");
}
//ActivatedProjectiles-stage0
_XB.write_int("ActivatedProjectiles",ActivatedProjectiles);
//RenderScene-stage0
_XB.write_fun("RenderScene",RenderScene);
//CurrentMap-stage0
if(CurrentMap != null)
_XB.write_addr("CurrentMap",CurrentMap.WriteXML(__XW));
//Cursor-stage0
if(Cursor != null)
_XB.write_addr("Cursor",Cursor.WriteXML(__XW));
//CapturedCursor-stage0
if(CapturedCursor != null)
_XB.write_addr("CapturedCursor",CapturedCursor.WriteXML(__XW));
//SpawnTimer-stage0
_XB.write_double("SpawnTimer",SpawnTimer);
//SpawnTimerReset-stage0
_XB.write_double("SpawnTimerReset",SpawnTimerReset);
_XB.finish();
return _XB._Addr;
#endregion
}
//ReadXML
public virtual void ReadDetailsXML(xmljr.XmlJrObjectTable __table, xmljr.XmlJrDom __src)
{
#region ReadXML-GameDocument
int __idx; __idx = 0; __idx++; __idx--;
int __size; __size = 0; __size++; __size--;
foreach(xmljr.XmlJrDom __C in __src._Children)
{
//Monsters-stageR
if(__C._Name.Equals("Monsters"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
Monsters = new Monster[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
Monsters[__idx] = (Monster) __table.LookUpObject(sub.read_int());
__idx++;
}
}
}
}
//ActivatedMonsters-stageR
if(__C._Name.Equals("ActivatedMonsters"))
{
ActivatedMonsters = __C.read_int();
}
//Turrets-stageR
if(__C._Name.Equals("Turrets"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
Turrets = new Turret[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
Turrets[__idx] = (Turret) __table.LookUpObject(sub.read_int());
__idx++;
}
}
}
}
//ActivatedTurrets-stageR
if(__C._Name.Equals("ActivatedTurrets"))
{
ActivatedTurrets = __C.read_int();
}
//Projectiles-stageR
if(__C._Name.Equals("Projectiles"))
{
__size = __C.GetIntParam("size");
if(__size > 0)
{
Projectiles = new Projectile[__size];
__idx = 0;
foreach(xmljr.XmlJrDom sub in __C._Children)
{
if(sub._Name.Equals("r"))
{
Projectiles[__idx] = (Projectile) __table.LookUpObject(sub.read_int());
__idx++;
}
}
}
}
//ActivatedProjectiles-stageR
if(__C._Name.Equals("ActivatedProjectiles"))
{
ActivatedProjectiles = __C.read_int();
}
//RenderScene-stageR
if(__C._Name.Equals("RenderScene"))
{
RenderScene = __C.read_fun();
}
//CurrentMap-stageR
if(__C._Name.Equals("CurrentMap"))
{
CurrentMap = (TileMap) __table.LookUpObject(__C.read_int());
}
//Cursor-stageR
if(__C._Name.Equals("Cursor"))
{
Cursor = (TileMark) __table.LookUpObject(__C.read_int());
}
//CapturedCursor-stageR
if(__C._Name.Equals("CapturedCursor"))
{
CapturedCursor = (TileMark) __table.LookUpObject(__C.read_int());
}
//SpawnTimer-stageR
if(__C._Name.Equals("SpawnTimer"))
{
SpawnTimer = __C.read_double();
}
//SpawnTimerReset-stageR
if(__C._Name.Equals("SpawnTimerReset"))
{
SpawnTimerReset = __C.read_double();
}
}
#endregion
}
}
public class DemoGame
{
public static xmljr.XmlJrObjectTable BuildObjectTable(xmljr.XmlJrDom root, xmljr.ProgressNotify note)
#region TableBuilder-DemoGame
{ xmljr.XmlJrObjectTable __table = new xmljr.XmlJrObjectTable();
foreach(xmljr.XmlJrDom obj in root._Children)
{
int __addr = obj.GetAddr();
if(__addr >= 0)
{
Object __o = null;
if( obj._Name.Equals("Monster")) __o = new Monster();
else if( obj._Name.Equals("Turret")) __o = new Turret();
else if( obj._Name.Equals("Projectile")) __o = new Projectile();
else if( obj._Name.Equals("Tile")) __o = new Tile();
else if( obj._Name.Equals("TileGrid")) __o = new TileGrid();
else if( obj._Name.Equals("TileMark")) __o = new TileMark();
else if( obj._Name.Equals("TileMap")) __o = new TileMap();
else if( obj._Name.Equals("GameDocument")) __o = new GameDocument();
if(__o != null) __table.Map(__addr,__o);;
}
}
int _cnt = 0;
foreach(xmljr.XmlJrDom obj in root._Children)
{
if(note != null) { note.SetProgress(_cnt / (double) root._Children.Count); _cnt++; }
int __addr = obj.GetAddr();
if(__addr >= 0)
{
Object __o = __table.LookUpObject(__addr);
if( obj._Name.Equals("Monster")) ((Monster) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("Turret")) ((Turret) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("Projectile")) ((Projectile) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("Tile")) ((Tile) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("TileGrid")) ((TileGrid) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("TileMark")) ((TileMark) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("TileMap")) ((TileMap) __o).ReadDetailsXML(__table, obj);
else if( obj._Name.Equals("GameDocument")) ((GameDocument) __o).ReadDetailsXML(__table, obj);
}
}
return __table;
#endregion
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Rules;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.Base.Deployments;
using Stratis.Bitcoin.BlockPulling;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Consensus.Rules;
using Stratis.Bitcoin.Consensus.Validators;
using Stratis.Bitcoin.Controllers;
using Stratis.Bitcoin.EventBus;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.P2P;
using Stratis.Bitcoin.P2P.Peer;
using Stratis.Bitcoin.P2P.Protocol.Behaviors;
using Stratis.Bitcoin.P2P.Protocol.Payloads;
using Stratis.Bitcoin.Signals;
using Stratis.Bitcoin.Utilities;
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests.Common")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests.Common")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.Consensus.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")]
namespace Stratis.Bitcoin.Base
{
/// <summary>
/// Base node services, these are the services a node has to have.
/// The ConnectionManager feature is also part of the base but may go in a feature of its own.
/// The base features are the minimal components required to connect to peers and maintain the best chain.
/// <para>
/// The base node services for a node are:
/// <list type="bullet">
/// <item>the ConcurrentChain to keep track of the best chain,</item>
/// <item>the ConnectionManager to connect with the network,</item>
/// <item>DatetimeProvider and Cancellation,</item>
/// <item>CancellationProvider and Cancellation,</item>
/// <item>DataFolder,</item>
/// <item>ChainState.</item>
/// </list>
/// </para>
/// </summary>
public sealed class BaseFeature : FullNodeFeature
{
/// <summary>Global application life cycle control - triggers when application shuts down.</summary>
private readonly INodeLifetime nodeLifetime;
/// <summary>Information about node's chain.</summary>
private readonly IChainState chainState;
/// <summary>Access to the database of blocks.</summary>
private readonly IChainRepository chainRepository;
/// <summary>User defined node settings.</summary>
private readonly NodeSettings nodeSettings;
/// <summary>Locations of important folders and files on disk.</summary>
private readonly DataFolder dataFolder;
/// <summary>Thread safe chain of block headers from genesis.</summary>
private readonly ChainIndexer chainIndexer;
/// <summary>Manager of node's network connections.</summary>
private readonly IConnectionManager connectionManager;
/// <summary>Provider of time functions.</summary>
private readonly IDateTimeProvider dateTimeProvider;
/// <summary>Provider for creating and managing background async loop tasks.</summary>
private readonly IAsyncProvider asyncProvider;
/// <summary>Logger for the node.</summary>
private readonly ILogger logger;
/// <summary>Factory for creating loggers.</summary>
private readonly ILoggerFactory loggerFactory;
/// <summary>State of time synchronization feature that stores collected data samples.</summary>
private readonly ITimeSyncBehaviorState timeSyncBehaviorState;
/// <summary>Manager of node's network peers.</summary>
private IPeerAddressManager peerAddressManager;
/// <summary>Periodic task to save list of peers to disk.</summary>
private IAsyncLoop flushAddressManagerLoop;
/// <summary>Periodic task to save the chain to the database.</summary>
private IAsyncLoop flushChainLoop;
/// <summary>A handler that can manage the lifetime of network peers.</summary>
private readonly IPeerBanning peerBanning;
/// <summary>Provider of IBD state.</summary>
private readonly IInitialBlockDownloadState initialBlockDownloadState;
/// <inheritdoc cref="Network"/>
private readonly Network network;
private readonly INodeStats nodeStats;
private readonly IProvenBlockHeaderStore provenBlockHeaderStore;
private readonly IConsensusManager consensusManager;
private readonly IConsensusRuleEngine consensusRules;
private readonly IBlockPuller blockPuller;
private readonly IBlockStore blockStore;
private readonly ITipsManager tipsManager;
private readonly IKeyValueRepository keyValueRepo;
/// <inheritdoc cref="IFinalizedBlockInfoRepository"/>
private readonly IFinalizedBlockInfoRepository finalizedBlockInfoRepository;
/// <inheritdoc cref="IPartialValidator"/>
private readonly IPartialValidator partialValidator;
public BaseFeature(NodeSettings nodeSettings,
DataFolder dataFolder,
INodeLifetime nodeLifetime,
ChainIndexer chainIndexer,
IChainState chainState,
IConnectionManager connectionManager,
IChainRepository chainRepository,
IFinalizedBlockInfoRepository finalizedBlockInfo,
IDateTimeProvider dateTimeProvider,
IAsyncProvider asyncProvider,
ITimeSyncBehaviorState timeSyncBehaviorState,
ILoggerFactory loggerFactory,
IInitialBlockDownloadState initialBlockDownloadState,
IPeerBanning peerBanning,
IPeerAddressManager peerAddressManager,
IConsensusManager consensusManager,
IConsensusRuleEngine consensusRules,
IPartialValidator partialValidator,
IBlockPuller blockPuller,
IBlockStore blockStore,
Network network,
ITipsManager tipsManager,
IKeyValueRepository keyValueRepo,
INodeStats nodeStats,
IProvenBlockHeaderStore provenBlockHeaderStore = null)
{
this.chainState = Guard.NotNull(chainState, nameof(chainState));
this.chainRepository = Guard.NotNull(chainRepository, nameof(chainRepository));
this.finalizedBlockInfoRepository = Guard.NotNull(finalizedBlockInfo, nameof(finalizedBlockInfo));
this.nodeSettings = Guard.NotNull(nodeSettings, nameof(nodeSettings));
this.dataFolder = Guard.NotNull(dataFolder, nameof(dataFolder));
this.nodeLifetime = Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
this.chainIndexer = Guard.NotNull(chainIndexer, nameof(chainIndexer));
this.connectionManager = Guard.NotNull(connectionManager, nameof(connectionManager));
this.consensusManager = consensusManager;
this.consensusRules = consensusRules;
this.blockPuller = blockPuller;
this.blockStore = blockStore;
this.network = network;
this.nodeStats = nodeStats;
this.provenBlockHeaderStore = provenBlockHeaderStore;
this.partialValidator = partialValidator;
this.peerBanning = Guard.NotNull(peerBanning, nameof(peerBanning));
this.tipsManager = Guard.NotNull(tipsManager, nameof(tipsManager));
this.keyValueRepo = Guard.NotNull(keyValueRepo, nameof(keyValueRepo));
this.peerAddressManager = Guard.NotNull(peerAddressManager, nameof(peerAddressManager));
this.peerAddressManager.PeerFilePath = this.dataFolder;
this.initialBlockDownloadState = initialBlockDownloadState;
this.dateTimeProvider = dateTimeProvider;
this.asyncProvider = asyncProvider;
this.timeSyncBehaviorState = timeSyncBehaviorState;
this.loggerFactory = loggerFactory;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
}
/// <inheritdoc />
public override async Task InitializeAsync()
{
// TODO rewrite chain starting logic. Tips manager should be used.
await this.StartChainAsync().ConfigureAwait(false);
if (this.provenBlockHeaderStore != null)
{
// If we find at this point that proven header store is behind chain we can rewind chain (this will cause a ripple effect and rewind block store and consensus)
// This problem should go away once we implement a component to keep all tips up to date
// https://github.com/stratisproject/StratisBitcoinFullNode/issues/2503
ChainedHeader initializedAt = await this.provenBlockHeaderStore.InitializeAsync(this.chainIndexer.Tip);
this.chainIndexer.Initialize(initializedAt);
}
NetworkPeerConnectionParameters connectionParameters = this.connectionManager.Parameters;
connectionParameters.IsRelay = this.connectionManager.ConnectionSettings.RelayTxes;
connectionParameters.TemplateBehaviors.Add(new PingPongBehavior());
connectionParameters.TemplateBehaviors.Add(new ConsensusManagerBehavior(this.chainIndexer, this.initialBlockDownloadState, this.consensusManager, this.peerBanning, this.loggerFactory));
// TODO: Once a proper rate limiting strategy has been implemented, this check will be removed.
if (!this.network.IsRegTest())
connectionParameters.TemplateBehaviors.Add(new RateLimitingBehavior(this.dateTimeProvider, this.loggerFactory, this.peerBanning));
connectionParameters.TemplateBehaviors.Add(new PeerBanningBehavior(this.loggerFactory, this.peerBanning, this.nodeSettings));
connectionParameters.TemplateBehaviors.Add(new BlockPullerBehavior(this.blockPuller, this.initialBlockDownloadState, this.dateTimeProvider, this.loggerFactory));
connectionParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(this.connectionManager, this.loggerFactory));
this.StartAddressManager(connectionParameters);
if (this.connectionManager.ConnectionSettings.SyncTimeEnabled)
{
connectionParameters.TemplateBehaviors.Add(new TimeSyncBehavior(this.timeSyncBehaviorState, this.dateTimeProvider, this.loggerFactory));
}
else
{
this.logger.LogDebug("Time synchronization with peers is disabled.");
}
// Block store must be initialized before consensus manager.
// This may be a temporary solution until a better way is found to solve this dependency.
this.blockStore.Initialize();
this.consensusRules.Initialize(this.chainIndexer.Tip);
await this.consensusManager.InitializeAsync(this.chainIndexer.Tip).ConfigureAwait(false);
this.chainState.ConsensusTip = this.consensusManager.Tip;
this.nodeStats.RegisterStats(sb => sb.Append(this.asyncProvider.GetStatistics(!this.nodeSettings.Log.DebugArgs.Any())), StatsType.Component, this.GetType().Name, 100);
}
/// <summary>
/// Initializes node's chain repository.
/// Creates periodic task to persist changes to the database.
/// </summary>
private async Task StartChainAsync()
{
if (!Directory.Exists(this.dataFolder.ChainPath))
{
this.logger.LogInformation("Creating {0}.", this.dataFolder.ChainPath);
Directory.CreateDirectory(this.dataFolder.ChainPath);
}
if (!Directory.Exists(this.dataFolder.KeyValueRepositoryPath))
{
this.logger.LogInformation("Creating {0}.", this.dataFolder.KeyValueRepositoryPath);
Directory.CreateDirectory(this.dataFolder.KeyValueRepositoryPath);
}
this.logger.LogInformation("Loading finalized block height.");
await this.finalizedBlockInfoRepository.LoadFinalizedBlockInfoAsync(this.network).ConfigureAwait(false);
this.logger.LogInformation("Loading chain.");
ChainedHeader chainTip = await this.chainRepository.LoadAsync(this.chainIndexer.Genesis).ConfigureAwait(false);
this.chainIndexer.Initialize(chainTip);
this.logger.LogInformation("Chain loaded at height {0}.", this.chainIndexer.Height);
this.flushChainLoop = this.asyncProvider.CreateAndRunAsyncLoop("FlushChain", async token =>
{
await this.chainRepository.SaveAsync(this.chainIndexer).ConfigureAwait(false);
if (this.provenBlockHeaderStore != null)
await this.provenBlockHeaderStore.SaveAsync().ConfigureAwait(false);
},
this.nodeLifetime.ApplicationStopping,
repeatEvery: TimeSpan.FromMinutes(1.0),
startAfter: TimeSpan.FromMinutes(1.0));
}
/// <summary>
/// Initializes node's address manager. Loads previously known peers from the file
/// or creates new peer file if it does not exist. Creates periodic task to persist changes
/// in peers to disk.
/// </summary>
private void StartAddressManager(NetworkPeerConnectionParameters connectionParameters)
{
var addressManagerBehaviour = new PeerAddressManagerBehaviour(this.dateTimeProvider, this.peerAddressManager, this.peerBanning, this.loggerFactory);
connectionParameters.TemplateBehaviors.Add(addressManagerBehaviour);
if (File.Exists(Path.Combine(this.dataFolder.AddressManagerFilePath, PeerAddressManager.PeerFileName)))
{
this.logger.LogInformation($"Loading peers from : {this.dataFolder.AddressManagerFilePath}.");
this.peerAddressManager.LoadPeers();
}
this.flushAddressManagerLoop = this.asyncProvider.CreateAndRunAsyncLoop("Periodic peer flush", token =>
{
this.peerAddressManager.SavePeers();
return Task.CompletedTask;
},
this.nodeLifetime.ApplicationStopping,
repeatEvery: TimeSpan.FromMinutes(5.0),
startAfter: TimeSpan.FromMinutes(5.0));
}
/// <inheritdoc />
public override void Dispose()
{
this.logger.LogInformation("Flushing peers.");
this.flushAddressManagerLoop.Dispose();
this.logger.LogInformation("Disposing peer address manager.");
this.peerAddressManager.Dispose();
if (this.flushChainLoop != null)
{
this.logger.LogInformation("Flushing headers chain.");
this.flushChainLoop.Dispose();
}
this.logger.LogInformation("Disposing time sync behavior.");
this.timeSyncBehaviorState.Dispose();
this.logger.LogInformation("Disposing block puller.");
this.blockPuller.Dispose();
this.logger.LogInformation("Disposing partial validator.");
this.partialValidator.Dispose();
this.logger.LogInformation("Disposing consensus manager.");
this.consensusManager.Dispose();
this.logger.LogInformation("Disposing consensus rules.");
this.consensusRules.Dispose();
this.logger.LogInformation("Saving chain repository.");
this.chainRepository.SaveAsync(this.chainIndexer).GetAwaiter().GetResult();
this.chainRepository.Dispose();
if (this.provenBlockHeaderStore != null)
{
this.logger.LogInformation("Saving proven header store.");
this.provenBlockHeaderStore.SaveAsync().GetAwaiter().GetResult();
this.provenBlockHeaderStore.Dispose();
}
this.logger.LogInformation("Disposing finalized block info repository.");
this.finalizedBlockInfoRepository.Dispose();
this.logger.LogInformation("Disposing address indexer.");
this.logger.LogInformation("Disposing block store.");
this.blockStore.Dispose();
this.keyValueRepo.Dispose();
}
}
/// <summary>
/// A class providing extension methods for <see cref="IFullNodeBuilder"/>.
/// </summary>
public static class FullNodeBuilderBaseFeatureExtension
{
/// <summary>
/// Makes the full node use all the required features - <see cref="BaseFeature"/>.
/// </summary>
/// <param name="fullNodeBuilder">Builder responsible for creating the node.</param>
/// <returns>Full node builder's interface to allow fluent code.</returns>
public static IFullNodeBuilder UseBaseFeature(this IFullNodeBuilder fullNodeBuilder)
{
fullNodeBuilder.ConfigureFeature(features =>
{
features
.AddFeature<BaseFeature>()
.FeatureServices(services =>
{
services.AddSingleton(fullNodeBuilder.Network.Consensus.ConsensusFactory);
services.AddSingleton<DBreezeSerializer>();
services.AddSingleton(fullNodeBuilder.NodeSettings.LoggerFactory);
services.AddSingleton(fullNodeBuilder.NodeSettings.DataFolder);
services.AddSingleton<INodeLifetime, NodeLifetime>();
services.AddSingleton<IPeerBanning, PeerBanning>();
services.AddSingleton<FullNodeFeatureExecutor>();
services.AddSingleton<ISignals, Signals.Signals>();
services.AddSingleton<ISubscriptionErrorHandler, DefaultSubscriptionErrorHandler>();
services.AddSingleton<FullNode>().AddSingleton((provider) => { return provider.GetService<FullNode>() as IFullNode; });
services.AddSingleton<ChainIndexer>(new ChainIndexer(fullNodeBuilder.Network));
services.AddSingleton<IDateTimeProvider>(DateTimeProvider.Default);
services.AddSingleton<IInvalidBlockHashStore, InvalidBlockHashStore>();
services.AddSingleton<IChainState, ChainState>();
services.AddSingleton<IChainRepository, ChainRepository>();
services.AddSingleton<IFinalizedBlockInfoRepository, FinalizedBlockInfoRepository>();
services.AddSingleton<ITimeSyncBehaviorState, TimeSyncBehaviorState>();
services.AddSingleton<NodeDeployments>();
services.AddSingleton<IInitialBlockDownloadState, InitialBlockDownloadState>();
services.AddSingleton<IKeyValueRepository, KeyValueRepository>();
services.AddSingleton<ITipsManager, TipsManager>();
services.AddSingleton<IAsyncProvider, AsyncProvider>();
// Consensus
services.AddSingleton<ConsensusSettings>();
services.AddSingleton<ICheckpoints, Checkpoints>();
services.AddSingleton<ConsensusRulesContainer>();
foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.HeaderValidationRules)
services.AddSingleton(typeof(IHeaderValidationConsensusRule), ruleType);
foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.IntegrityValidationRules)
services.AddSingleton(typeof(IIntegrityValidationConsensusRule), ruleType);
foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.PartialValidationRules)
services.AddSingleton(typeof(IPartialValidationConsensusRule), ruleType);
foreach (var ruleType in fullNodeBuilder.Network.Consensus.ConsensusRules.FullValidationRules)
services.AddSingleton(typeof(IFullValidationConsensusRule), ruleType);
// Connection
services.AddSingleton<INetworkPeerFactory, NetworkPeerFactory>();
services.AddSingleton<NetworkPeerConnectionParameters>();
services.AddSingleton<IConnectionManager, ConnectionManager>();
services.AddSingleton<ConnectionManagerSettings>();
services.AddSingleton<PayloadProvider>(new PayloadProvider().DiscoverPayloads());
services.AddSingleton<IVersionProvider, VersionProvider>();
services.AddSingleton<IBlockPuller, BlockPuller>();
// Peer address manager
services.AddSingleton<IPeerAddressManager, PeerAddressManager>();
services.AddSingleton<IPeerConnector, PeerConnectorAddNode>();
services.AddSingleton<IPeerConnector, PeerConnectorConnectNode>();
services.AddSingleton<IPeerConnector, PeerConnectorDiscovery>();
services.AddSingleton<IPeerDiscovery, PeerDiscovery>();
services.AddSingleton<ISelfEndpointTracker, SelfEndpointTracker>();
// Consensus
// Consensus manager is created like that due to CM's constructor being internal. This is done
// in order to prevent access to CM creation and CHT usage from another features. CHT is supposed
// to be used only by CM and no other component.
services.AddSingleton<IConsensusManager>(provider => new ConsensusManager(
chainedHeaderTree: provider.GetService<IChainedHeaderTree>(),
network: provider.GetService<Network>(),
loggerFactory: provider.GetService<ILoggerFactory>(),
chainState: provider.GetService<IChainState>(),
integrityValidator: provider.GetService<IIntegrityValidator>(),
partialValidator: provider.GetService<IPartialValidator>(),
fullValidator: provider.GetService<IFullValidator>(),
consensusRules: provider.GetService<IConsensusRuleEngine>(),
finalizedBlockInfo: provider.GetService<IFinalizedBlockInfoRepository>(),
signals: provider.GetService<ISignals>(),
peerBanning: provider.GetService<IPeerBanning>(),
ibdState: provider.GetService<IInitialBlockDownloadState>(),
chainIndexer: provider.GetService<ChainIndexer>(),
blockPuller: provider.GetService<IBlockPuller>(),
blockStore: provider.GetService<IBlockStore>(),
connectionManager: provider.GetService<IConnectionManager>(),
nodeStats: provider.GetService<INodeStats>(),
nodeLifetime: provider.GetService<INodeLifetime>(),
consensusSettings: provider.GetService<ConsensusSettings>(),
dateTimeProvider: provider.GetService<IDateTimeProvider>()));
services.AddSingleton<IChainedHeaderTree, ChainedHeaderTree>();
services.AddSingleton<IHeaderValidator, HeaderValidator>();
services.AddSingleton<IIntegrityValidator, IntegrityValidator>();
services.AddSingleton<IPartialValidator, PartialValidator>();
services.AddSingleton<IFullValidator, FullValidator>();
// Console
services.AddSingleton<INodeStats, NodeStats>();
// Controller
services.AddTransient<NodeController>();
});
});
return fullNodeBuilder;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// CustomField
/// </summary>
[DataContract]
public partial class CustomField : IEquatable<CustomField>, IValidatableObject
{
public CustomField()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="CustomField" /> class.
/// </summary>
/// <param name="CustomFieldType">.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="FieldId">.</param>
/// <param name="ListItems">.</param>
/// <param name="Name">.</param>
/// <param name="Required">When set to **true**, the signer is required to fill out this tab.</param>
/// <param name="Show">.</param>
/// <param name="Value">Specifies the value of the tab. .</param>
public CustomField(string CustomFieldType = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string FieldId = default(string), List<string> ListItems = default(List<string>), string Name = default(string), string Required = default(string), string Show = default(string), string Value = default(string))
{
this.CustomFieldType = CustomFieldType;
this.ErrorDetails = ErrorDetails;
this.FieldId = FieldId;
this.ListItems = ListItems;
this.Name = Name;
this.Required = Required;
this.Show = Show;
this.Value = Value;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="customFieldType", EmitDefaultValue=false)]
public string CustomFieldType { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="fieldId", EmitDefaultValue=false)]
public string FieldId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="listItems", EmitDefaultValue=false)]
public List<string> ListItems { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// When set to **true**, the signer is required to fill out this tab
/// </summary>
/// <value>When set to **true**, the signer is required to fill out this tab</value>
[DataMember(Name="required", EmitDefaultValue=false)]
public string Required { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="show", EmitDefaultValue=false)]
public string Show { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab. </value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CustomField {\n");
sb.Append(" CustomFieldType: ").Append(CustomFieldType).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" FieldId: ").Append(FieldId).Append("\n");
sb.Append(" ListItems: ").Append(ListItems).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Required: ").Append(Required).Append("\n");
sb.Append(" Show: ").Append(Show).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CustomField);
}
/// <summary>
/// Returns true if CustomField instances are equal
/// </summary>
/// <param name="other">Instance of CustomField to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CustomField other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CustomFieldType == other.CustomFieldType ||
this.CustomFieldType != null &&
this.CustomFieldType.Equals(other.CustomFieldType)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.FieldId == other.FieldId ||
this.FieldId != null &&
this.FieldId.Equals(other.FieldId)
) &&
(
this.ListItems == other.ListItems ||
this.ListItems != null &&
this.ListItems.SequenceEqual(other.ListItems)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Required == other.Required ||
this.Required != null &&
this.Required.Equals(other.Required)
) &&
(
this.Show == other.Show ||
this.Show != null &&
this.Show.Equals(other.Show)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CustomFieldType != null)
hash = hash * 59 + this.CustomFieldType.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.FieldId != null)
hash = hash * 59 + this.FieldId.GetHashCode();
if (this.ListItems != null)
hash = hash * 59 + this.ListItems.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Required != null)
hash = hash * 59 + this.Required.GetHashCode();
if (this.Show != null)
hash = hash * 59 + this.Show.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Diagnostics;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
/// <summary>
/// A <see cref="ICollector"/> implementation that collects the top-scoring hits,
/// returning them as a <see cref="TopDocs"/>. this is used by <see cref="IndexSearcher"/> to
/// implement <see cref="TopDocs"/>-based search. Hits are sorted by score descending
/// and then (when the scores are tied) docID ascending. When you create an
/// instance of this collector you should know in advance whether documents are
/// going to be collected in doc Id order or not.
///
/// <para/><b>NOTE</b>: The values <see cref="float.NaN"/> and
/// <see cref="float.NegativeInfinity"/> are not valid scores. This
/// collector will not properly collect hits with such
/// scores.
/// </summary>
public abstract class TopScoreDocCollector : TopDocsCollector<ScoreDoc>
{
// Assumes docs are scored in order.
private class InOrderTopScoreDocCollector : TopScoreDocCollector
{
internal InOrderTopScoreDocCollector(int numHits)
: base(numHits)
{
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle these scores:
Debug.Assert(score != float.NegativeInfinity);
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score <= pqTop.Score)
{
// Since docs are returned in-order (i.e., increasing doc Id), a document
// with equal score to pqTop.score cannot compete since HitQueue favors
// documents with lower doc Ids. Therefore reject those docs too.
return;
}
pqTop.Doc = doc + docBase;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder => false;
}
// Assumes docs are scored in order.
private class InOrderPagingScoreDocCollector : TopScoreDocCollector
{
internal readonly ScoreDoc after;
// this is always after.doc - docBase, to save an add when score == after.score
internal int afterDoc;
internal int collectedHits;
internal InOrderPagingScoreDocCollector(ScoreDoc after, int numHits)
: base(numHits)
{
this.after = after;
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle these scores:
Debug.Assert(score != float.NegativeInfinity);
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score > after.Score || (score == after.Score && doc <= afterDoc))
{
// hit was collected on a previous page
return;
}
if (score <= pqTop.Score)
{
// Since docs are returned in-order (i.e., increasing doc Id), a document
// with equal score to pqTop.score cannot compete since HitQueue favors
// documents with lower doc Ids. Therefore reject those docs too.
return;
}
collectedHits++;
pqTop.Doc = doc + docBase;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder => false;
public override void SetNextReader(AtomicReaderContext context)
{
base.SetNextReader(context);
afterDoc = after.Doc - docBase;
}
protected override int TopDocsCount => collectedHits < m_pq.Count ? collectedHits : m_pq.Count;
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
// LUCENENET specific - optimized empty array creation
return results == null ? new TopDocs(m_totalHits, EMPTY_SCOREDOCS, float.NaN) : new TopDocs(m_totalHits, results);
}
}
// LUCENENET specific - optimized empty array creation
private static readonly ScoreDoc[] EMPTY_SCOREDOCS =
#if FEATURE_ARRAYEMPTY
Array.Empty<ScoreDoc>();
#else
new ScoreDoc[0];
#endif
// Assumes docs are scored out of order.
private class OutOfOrderTopScoreDocCollector : TopScoreDocCollector
{
internal OutOfOrderTopScoreDocCollector(int numHits)
: base(numHits)
{
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle NaN
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score < pqTop.Score)
{
// Doesn't compete w/ bottom entry in queue
return;
}
doc += docBase;
if (score == pqTop.Score && doc > pqTop.Doc)
{
// Break tie in score by doc ID:
return;
}
pqTop.Doc = doc;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder => true;
}
// Assumes docs are scored out of order.
private class OutOfOrderPagingScoreDocCollector : TopScoreDocCollector
{
internal readonly ScoreDoc after;
// this is always after.doc - docBase, to save an add when score == after.score
internal int afterDoc;
internal int collectedHits;
internal OutOfOrderPagingScoreDocCollector(ScoreDoc after, int numHits)
: base(numHits)
{
this.after = after;
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle NaN
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score > after.Score || (score == after.Score && doc <= afterDoc))
{
// hit was collected on a previous page
return;
}
if (score < pqTop.Score)
{
// Doesn't compete w/ bottom entry in queue
return;
}
doc += docBase;
if (score == pqTop.Score && doc > pqTop.Doc)
{
// Break tie in score by doc ID:
return;
}
collectedHits++;
pqTop.Doc = doc;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder => true;
public override void SetNextReader(AtomicReaderContext context)
{
base.SetNextReader(context);
afterDoc = after.Doc - docBase;
}
protected override int TopDocsCount => collectedHits < m_pq.Count ? collectedHits : m_pq.Count;
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
// LUCENENET specific - optimized empty array creation
return results == null ? new TopDocs(m_totalHits, EMPTY_SCOREDOCS, float.NaN) : new TopDocs(m_totalHits, results);
}
}
/// <summary>
/// Creates a new <see cref="TopScoreDocCollector"/> given the number of hits to
/// collect and whether documents are scored in order by the input
/// <see cref="Scorer"/> to <see cref="SetScorer(Scorer)"/>.
///
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length
/// <paramref name="numHits"/>, and fill the array with sentinel
/// objects.
/// </summary>
public static TopScoreDocCollector Create(int numHits, bool docsScoredInOrder)
{
return Create(numHits, null, docsScoredInOrder);
}
/// <summary>
/// Creates a new <see cref="TopScoreDocCollector"/> given the number of hits to
/// collect, the bottom of the previous page, and whether documents are scored in order by the input
/// <see cref="Scorer"/> to <see cref="SetScorer(Scorer)"/>.
///
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length
/// <paramref name="numHits"/>, and fill the array with sentinel
/// objects.
/// </summary>
public static TopScoreDocCollector Create(int numHits, ScoreDoc after, bool docsScoredInOrder)
{
if (numHits <= 0)
{
throw new ArgumentException("numHits must be > 0; please use TotalHitCountCollector if you just need the total hit count");
}
if (docsScoredInOrder)
{
return after == null ? (TopScoreDocCollector)new InOrderTopScoreDocCollector(numHits) : new InOrderPagingScoreDocCollector(after, numHits);
}
else
{
return after == null ? (TopScoreDocCollector)new OutOfOrderTopScoreDocCollector(numHits) : new OutOfOrderPagingScoreDocCollector(after, numHits);
}
}
internal ScoreDoc pqTop;
internal int docBase = 0;
internal Scorer scorer;
// prevents instantiation
private TopScoreDocCollector(int numHits)
: base(new HitQueue(numHits, true))
{
// HitQueue implements getSentinelObject to return a ScoreDoc, so we know
// that at this point top() is already initialized.
pqTop = m_pq.Top;
}
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
if (results == null)
{
return EMPTY_TOPDOCS;
}
// We need to compute maxScore in order to set it in TopDocs. If start == 0,
// it means the largest element is already in results, use its score as
// maxScore. Otherwise pop everything else, until the largest element is
// extracted and use its score as maxScore.
float maxScore = float.NaN;
if (start == 0)
{
maxScore = results[0].Score;
}
else
{
for (int i = m_pq.Count; i > 1; i--)
{
m_pq.Pop();
}
maxScore = m_pq.Pop().Score;
}
return new TopDocs(m_totalHits, results, maxScore);
}
public override void SetNextReader(AtomicReaderContext context)
{
docBase = context.DocBase;
}
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
}
}
| |
using System;
using System.Text;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HETSAPI.Models
{
/// <summary>
/// Contact Database Model
/// </summary>
[MetaData(Description = "A person and their related contact information linked to one or more entities in the system. For examples, there are contacts for Owners, Projects.")]
public sealed class Contact : AuditableEntity, IEquatable<Contact>
{
/// <summary>
/// Contact Database Model Constructor (required by entity framework)
/// </summary>
public Contact()
{
Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact" /> class.
/// </summary>
/// <param name="id">A system-generated unique identifier for a Contact (required).</param>
/// <param name="givenName">The given name of the contact..</param>
/// <param name="surname">The surname of the contact..</param>
/// <param name="role">The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform..</param>
/// <param name="notes">A note about the contact maintained by the users..</param>
/// <param name="emailAddress">The email address for the contact..</param>
/// <param name="workPhoneNumber">The work phone number for the contact..</param>
/// <param name="mobilePhoneNumber">The mobile phone number for the contact..</param>
/// <param name="faxPhoneNumber">The fax phone number for the contact..</param>
/// <param name="address1">Address 1 line of the address..</param>
/// <param name="address2">Address 2 line of the address..</param>
/// <param name="city">The City of the address..</param>
/// <param name="province">The Province of the address..</param>
/// <param name="postalCode">The postal code of the address..</param>
public Contact(int id, string givenName = null, string surname = null, string role = null,
string notes = null, string emailAddress = null, string workPhoneNumber = null, string mobilePhoneNumber = null,
string faxPhoneNumber = null, string address1 = null, string address2 = null, string city = null, string province = null,
string postalCode = null)
{
Id = id;
GivenName = givenName;
Surname = surname;
Role = role;
Notes = notes;
EmailAddress = emailAddress;
WorkPhoneNumber = workPhoneNumber;
MobilePhoneNumber = mobilePhoneNumber;
FaxPhoneNumber = faxPhoneNumber;
Address1 = address1;
Address2 = address2;
City = city;
Province = province;
PostalCode = postalCode;
}
/// <summary>
/// A system-generated unique identifier for a Contact
/// </summary>
/// <value>A system-generated unique identifier for a Contact</value>
[MetaData(Description = "A system-generated unique identifier for a Contact")]
public int Id { get; set; }
/// <summary>
/// The given name of the contact.
/// </summary>
/// <value>The given name of the contact.</value>
[MetaData(Description = "The given name of the contact.")]
[MaxLength(50)]
public string GivenName { get; set; }
/// <summary>
/// The surname of the contact.
/// </summary>
/// <value>The surname of the contact.</value>
[MetaData(Description = "The surname of the contact.")]
[MaxLength(50)]
public string Surname { get; set; }
/// <summary>
/// The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.
/// </summary>
/// <value>The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.</value>
[MetaData(Description = "The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.")]
[MaxLength(100)]
public string Role { get; set; }
/// <summary>
/// A note about the contact maintained by the users.
/// </summary>
/// <value>A note about the contact maintained by the users.</value>
[MetaData(Description = "A note about the contact maintained by the users.")]
[MaxLength(512)]
public string Notes { get; set; }
/// <summary>
/// The email address for the contact.
/// </summary>
/// <value>The email address for the contact.</value>
[MetaData(Description = "The email address for the contact.")]
[MaxLength(255)]
public string EmailAddress { get; set; }
/// <summary>
/// The work phone number for the contact.
/// </summary>
/// <value>The work phone number for the contact.</value>
[MetaData(Description = "The work phone number for the contact.")]
[MaxLength(20)]
public string WorkPhoneNumber { get; set; }
/// <summary>
/// The mobile phone number for the contact.
/// </summary>
/// <value>The mobile phone number for the contact.</value>
[MetaData(Description = "The mobile phone number for the contact.")]
[MaxLength(20)]
public string MobilePhoneNumber { get; set; }
/// <summary>
/// The fax phone number for the contact.
/// </summary>
/// <value>The fax phone number for the contact.</value>
[MetaData(Description = "The fax phone number for the contact.")]
[MaxLength(20)]
public string FaxPhoneNumber { get; set; }
/// <summary>
/// Address 1 line of the address.
/// </summary>
/// <value>Address 1 line of the address.</value>
[MetaData(Description = "Address 1 line of the address.")]
[MaxLength(80)]
public string Address1 { get; set; }
/// <summary>
/// Address 2 line of the address.
/// </summary>
/// <value>Address 2 line of the address.</value>
[MetaData(Description = "Address 2 line of the address.")]
[MaxLength(80)]
public string Address2 { get; set; }
/// <summary>
/// The City of the address.
/// </summary>
/// <value>The City of the address.</value>
[MetaData(Description = "The City of the address.")]
[MaxLength(100)]
public string City { get; set; }
/// <summary>
/// The Province of the address.
/// </summary>
/// <value>The Province of the address.</value>
[MetaData(Description = "The Province of the address.")]
[MaxLength(50)]
public string Province { get; set; }
/// <summary>
/// The postal code of the address.
/// </summary>
/// <value>The postal code of the address.</value>
[MetaData(Description = "The postal code of the address.")]
[MaxLength(15)]
public string PostalCode { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Contact {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Role: ").Append(Role).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" EmailAddress: ").Append(EmailAddress).Append("\n");
sb.Append(" WorkPhoneNumber: ").Append(WorkPhoneNumber).Append("\n");
sb.Append(" MobilePhoneNumber: ").Append(MobilePhoneNumber).Append("\n");
sb.Append(" FaxPhoneNumber: ").Append(FaxPhoneNumber).Append("\n");
sb.Append(" Address1: ").Append(Address1).Append("\n");
sb.Append(" Address2: ").Append(Address2).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" Province: ").Append(Province).Append("\n");
sb.Append(" PostalCode: ").Append(PostalCode).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((Contact)obj);
}
/// <summary>
/// Returns true if Contact instances are equal
/// </summary>
/// <param name="other">Instance of Contact to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Contact other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id.Equals(other.Id)
) &&
(
GivenName == other.GivenName ||
GivenName != null &&
GivenName.Equals(other.GivenName)
) &&
(
Surname == other.Surname ||
Surname != null &&
Surname.Equals(other.Surname)
) &&
(
Role == other.Role ||
Role != null &&
Role.Equals(other.Role)
) &&
(
Notes == other.Notes ||
Notes != null &&
Notes.Equals(other.Notes)
) &&
(
EmailAddress == other.EmailAddress ||
EmailAddress != null &&
EmailAddress.Equals(other.EmailAddress)
) &&
(
WorkPhoneNumber == other.WorkPhoneNumber ||
WorkPhoneNumber != null &&
WorkPhoneNumber.Equals(other.WorkPhoneNumber)
) &&
(
MobilePhoneNumber == other.MobilePhoneNumber ||
MobilePhoneNumber != null &&
MobilePhoneNumber.Equals(other.MobilePhoneNumber)
) &&
(
FaxPhoneNumber == other.FaxPhoneNumber ||
FaxPhoneNumber != null &&
FaxPhoneNumber.Equals(other.FaxPhoneNumber)
) &&
(
Address1 == other.Address1 ||
Address1 != null &&
Address1.Equals(other.Address1)
) &&
(
Address2 == other.Address2 ||
Address2 != null &&
Address2.Equals(other.Address2)
) &&
(
City == other.City ||
City != null &&
City.Equals(other.City)
) &&
(
Province == other.Province ||
Province != null &&
Province.Equals(other.Province)
) &&
(
PostalCode == other.PostalCode ||
PostalCode != null &&
PostalCode.Equals(other.PostalCode)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + Id.GetHashCode();
if (GivenName != null)
{
hash = hash * 59 + GivenName.GetHashCode();
}
if (Surname != null)
{
hash = hash * 59 + Surname.GetHashCode();
}
if (Role != null)
{
hash = hash * 59 + Role.GetHashCode();
}
if (Notes != null)
{
hash = hash * 59 + Notes.GetHashCode();
}
if (EmailAddress != null)
{
hash = hash * 59 + EmailAddress.GetHashCode();
}
if (WorkPhoneNumber != null)
{
hash = hash * 59 + WorkPhoneNumber.GetHashCode();
}
if (MobilePhoneNumber != null)
{
hash = hash * 59 + MobilePhoneNumber.GetHashCode();
}
if (FaxPhoneNumber != null)
{
hash = hash * 59 + FaxPhoneNumber.GetHashCode();
}
if (Address1 != null)
{
hash = hash * 59 + Address1.GetHashCode();
}
if (Address2 != null)
{
hash = hash * 59 + Address2.GetHashCode();
}
if (City != null)
{
hash = hash * 59 + City.GetHashCode();
}
if (Province != null)
{
hash = hash * 59 + Province.GetHashCode();
}
if (PostalCode != null)
{
hash = hash * 59 + PostalCode.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Contact left, Contact right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Contact left, Contact right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
using System;
using GooglePlayGames.Native.PInvoke;
using System.Runtime.InteropServices;
using GooglePlayGames.OurUtils;
using System.Collections.Generic;
using GooglePlayGames.Native.Cwrapper;
using C = GooglePlayGames.Native.Cwrapper.TurnBasedMultiplayerManager;
using Types = GooglePlayGames.Native.Cwrapper.Types;
using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus;
using MultiplayerStatus = GooglePlayGames.Native.Cwrapper.CommonErrorStatus.MultiplayerStatus;
namespace GooglePlayGames.Native.PInvoke {
internal class TurnBasedManager {
private readonly GameServices mGameServices;
internal TurnBasedManager(GameServices services) {
this.mGameServices = services;
}
internal delegate void TurnBasedMatchCallback(TurnBasedMatchResponse response);
internal void GetMatch(string matchId, Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_FetchMatch(mGameServices.AsHandle(),
matchId, InternalTurnBasedMatchCallback,
ToCallbackPointer(callback));
}
[AOT.MonoPInvokeCallback(typeof(C.TurnBasedMatchCallback))]
internal static void InternalTurnBasedMatchCallback(IntPtr response, IntPtr data) {
Callbacks.PerformInternalCallback(
"TurnBasedManager#InternalTurnBasedMatchCallback",
Callbacks.Type.Temporary, response, data);
}
internal void CreateMatch(TurnBasedMatchConfig config,
Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_CreateTurnBasedMatch(mGameServices.AsHandle(),
config.AsPointer(), InternalTurnBasedMatchCallback,
ToCallbackPointer(callback));
}
internal void ShowPlayerSelectUI(uint minimumPlayers, uint maxiumPlayers,
bool allowAutomatching, Action<PlayerSelectUIResponse> callback) {
C.TurnBasedMultiplayerManager_ShowPlayerSelectUI(mGameServices.AsHandle(), minimumPlayers,
maxiumPlayers, allowAutomatching, InternalPlayerSelectUIcallback,
Callbacks.ToIntPtr(callback, PlayerSelectUIResponse.FromPointer));
}
[AOT.MonoPInvokeCallback(typeof(C.PlayerSelectUICallback))]
internal static void InternalPlayerSelectUIcallback(IntPtr response, IntPtr data) {
Callbacks.PerformInternalCallback(
"TurnBasedManager#PlayerSelectUICallback", Callbacks.Type.Temporary, response, data);
}
internal void GetAllTurnbasedMatches(Action<TurnBasedMatchesResponse> callback) {
C.TurnBasedMultiplayerManager_FetchMatches(mGameServices.AsHandle(),
InternalTurnBasedMatchesCallback,
Callbacks.ToIntPtr<TurnBasedMatchesResponse>(
callback, TurnBasedMatchesResponse.FromPointer));
}
[AOT.MonoPInvokeCallback(typeof(C.TurnBasedMatchesCallback))]
internal static void InternalTurnBasedMatchesCallback(IntPtr response, IntPtr data) {
Callbacks.PerformInternalCallback(
"TurnBasedManager#TurnBasedMatchesCallback", Callbacks.Type.Temporary, response, data);
}
internal void AcceptInvitation(MultiplayerInvitation invitation,
Action<TurnBasedMatchResponse> callback) {
Logger.d("Accepting invitation: " + invitation.AsPointer().ToInt64());
C.TurnBasedMultiplayerManager_AcceptInvitation(mGameServices.AsHandle(),
invitation.AsPointer(), InternalTurnBasedMatchCallback, ToCallbackPointer(callback));
}
internal void DeclineInvitation(MultiplayerInvitation invitation) {
C.TurnBasedMultiplayerManager_DeclineInvitation(mGameServices.AsHandle(),
invitation.AsPointer());
}
internal void TakeTurn(NativeTurnBasedMatch match, byte[] data,
MultiplayerParticipant nextParticipant, Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_TakeMyTurn(
mGameServices.AsHandle(),
match.AsPointer(),
data,
new UIntPtr((uint)data.Length),
// Just pass along the old results. Technically the API allows updates here, but
// we never need them.
match.Results().AsPointer(),
nextParticipant.AsPointer(),
InternalTurnBasedMatchCallback,
ToCallbackPointer(callback));
}
[AOT.MonoPInvokeCallback(typeof(C.MatchInboxUICallback))]
internal static void InternalMatchInboxUICallback(IntPtr response, IntPtr data) {
Callbacks.PerformInternalCallback(
"TurnBasedManager#MatchInboxUICallback", Callbacks.Type.Temporary, response, data);
}
internal void ShowInboxUI(Action<MatchInboxUIResponse> callback) {
C.TurnBasedMultiplayerManager_ShowMatchInboxUI(mGameServices.AsHandle(),
InternalMatchInboxUICallback,
Callbacks.ToIntPtr<MatchInboxUIResponse>(callback, MatchInboxUIResponse.FromPointer));
}
[AOT.MonoPInvokeCallback(typeof(C.MultiplayerStatusCallback))]
internal static void InternalMultiplayerStatusCallback(MultiplayerStatus status, IntPtr data) {
Logger.d("InternalMultiplayerStatusCallback: " + status);
var callback = Callbacks.IntPtrToTempCallback<Action<MultiplayerStatus>>(data);
try {
callback(status);
} catch (Exception e) {
Logger.e("Error encountered executing InternalMultiplayerStatusCallback. " +
"Smothering to avoid passing exception into Native: " + e);
}
}
internal void LeaveDuringMyTurn(NativeTurnBasedMatch match,
MultiplayerParticipant nextParticipant, Action<MultiplayerStatus> callback) {
C.TurnBasedMultiplayerManager_LeaveMatchDuringMyTurn(
mGameServices.AsHandle(),
match.AsPointer(),
nextParticipant.AsPointer(),
InternalMultiplayerStatusCallback,
Callbacks.ToIntPtr(callback)
);
}
internal void FinishMatchDuringMyTurn(NativeTurnBasedMatch match, byte[] data,
ParticipantResults results, Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_FinishMatchDuringMyTurn(
mGameServices.AsHandle(),
match.AsPointer(),
data,
new UIntPtr((uint)data.Length),
results.AsPointer(),
InternalTurnBasedMatchCallback,
ToCallbackPointer(callback)
);
}
internal void ConfirmPendingCompletion(NativeTurnBasedMatch match,
Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_ConfirmPendingCompletion(
mGameServices.AsHandle(),
match.AsPointer(),
InternalTurnBasedMatchCallback,
ToCallbackPointer(callback));
}
internal void LeaveMatchDuringTheirTurn(NativeTurnBasedMatch match,
Action<MultiplayerStatus> callback) {
C.TurnBasedMultiplayerManager_LeaveMatchDuringTheirTurn(
mGameServices.AsHandle(),
match.AsPointer(),
InternalMultiplayerStatusCallback,
Callbacks.ToIntPtr(callback));
}
internal void CancelMatch(NativeTurnBasedMatch match,
Action<MultiplayerStatus> callback) {
C.TurnBasedMultiplayerManager_CancelMatch(
mGameServices.AsHandle(),
match.AsPointer(),
InternalMultiplayerStatusCallback,
Callbacks.ToIntPtr(callback));
}
internal void Rematch(NativeTurnBasedMatch match,
Action<TurnBasedMatchResponse> callback) {
C.TurnBasedMultiplayerManager_Rematch(
mGameServices.AsHandle(),
match.AsPointer(),
InternalTurnBasedMatchCallback,
ToCallbackPointer(callback));
}
private static IntPtr ToCallbackPointer(Action<TurnBasedMatchResponse> callback) {
return Callbacks.ToIntPtr<TurnBasedMatchResponse>(
callback,
TurnBasedMatchResponse.FromPointer
);
}
internal class MatchInboxUIResponse : BaseReferenceHolder {
internal MatchInboxUIResponse(IntPtr selfPointer) : base(selfPointer) {
}
internal CommonErrorStatus.UIStatus UiStatus() {
return C.TurnBasedMultiplayerManager_MatchInboxUIResponse_GetStatus(SelfPtr());
}
internal NativeTurnBasedMatch Match() {
if (UiStatus() != CommonErrorStatus.UIStatus.VALID) {
return null;
}
return new NativeTurnBasedMatch(
C.TurnBasedMultiplayerManager_MatchInboxUIResponse_GetMatch(SelfPtr()));
}
protected override void CallDispose(HandleRef selfPointer) {
C.TurnBasedMultiplayerManager_MatchInboxUIResponse_Dispose(selfPointer);
}
internal static MatchInboxUIResponse FromPointer(IntPtr pointer) {
if (pointer.Equals(IntPtr.Zero)) {
return null;
}
return new MatchInboxUIResponse(pointer);
}
}
internal class TurnBasedMatchResponse : BaseReferenceHolder {
internal TurnBasedMatchResponse(IntPtr selfPointer) : base(selfPointer) {
}
internal CommonErrorStatus.MultiplayerStatus ResponseStatus() {
return C.TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetStatus(SelfPtr());
}
internal bool RequestSucceeded() {
return ResponseStatus() > 0;
}
internal NativeTurnBasedMatch Match() {
if (!RequestSucceeded()) {
return null;
}
return new NativeTurnBasedMatch(
C.TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetMatch(SelfPtr()));
}
protected override void CallDispose(HandleRef selfPointer) {
C.TurnBasedMultiplayerManager_TurnBasedMatchResponse_Dispose(selfPointer);
}
internal static TurnBasedMatchResponse FromPointer(IntPtr pointer) {
if (pointer.Equals(IntPtr.Zero)) {
return null;
}
return new TurnBasedMatchResponse(pointer);
}
}
internal class TurnBasedMatchesResponse : BaseReferenceHolder {
internal TurnBasedMatchesResponse(IntPtr selfPointer) : base(selfPointer) {
}
protected override void CallDispose(HandleRef selfPointer) {
C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_Dispose(SelfPtr());
}
internal CommonErrorStatus.MultiplayerStatus Status() {
return C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetStatus(SelfPtr());
}
internal IEnumerable<MultiplayerInvitation> Invitations() {
return PInvokeUtilities.ToEnumerable(
C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_Length(SelfPtr()),
index => new MultiplayerInvitation(C.TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_GetElement(SelfPtr(), index)));
}
internal static TurnBasedMatchesResponse FromPointer(IntPtr pointer) {
if (PInvokeUtilities.IsNull(pointer)) {
return null;
}
return new TurnBasedMatchesResponse(pointer);
}
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.