context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using UnityEngine;
using System.Collections;
public class Menu : MonoBehaviour {
public TextMesh title;
public TextMesh play;
public TextMesh levelSelect;
public TextMesh options;
public TextMesh quit;
public TextMesh maxSpheres;
public TextMesh maxSpheresValue;
public TextMesh maxSpheresPlus;
public TextMesh maxSpheresMinus;
public TextMesh moveSpeed;
public TextMesh moveSpeedValue;
public TextMesh moveSpeedPlus;
public TextMesh moveSpeedMinus;
public TextMesh optionsClose;
public TextMesh level1;
public TextMesh level2;
public TextMesh level3;
public TextMesh level4;
public TextMesh levelClose;
int shootingMaxSpheres;
float shootingMoveSpeed;
int oMaxSpheres;
float oMoveSpeed;
Ray ray;
RaycastHit hit;
float charSize;
void Start () {
charSize = title.characterSize;
}
void Update () {
maxSpheresValue.text = "" + shootingMaxSpheres;
moveSpeedValue.text = "" + shootingMoveSpeed;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
if(hit.transform.name == "Title"){
title.fontStyle = FontStyle.BoldAndItalic;
if(Input.GetMouseButtonDown(0)){
if(title.characterSize < charSize+1)
title.characterSize++;
}
}
if(hit.transform.name == "Play"){
play.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.LoadLevel(1);
}
if(hit.transform.name == "Level Select"){
levelSelect.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0)){
level1.renderer.enabled = !level1.renderer.enabled;
level2.renderer.enabled = !level2.renderer.enabled;
level3.renderer.enabled = !level3.renderer.enabled;
level4.renderer.enabled = !level4.renderer.enabled;
levelClose.renderer.enabled = !levelClose.renderer.enabled;
maxSpheres.renderer.enabled = false;
maxSpheresValue.renderer.enabled = false;
maxSpheresPlus.renderer.enabled = false;
maxSpheresMinus.renderer.enabled = false;
moveSpeed.renderer.enabled = false;
moveSpeedValue.renderer.enabled = false;
moveSpeedPlus.renderer.enabled = false;
moveSpeedMinus.renderer.enabled = false;
optionsClose.renderer.enabled = false;
}
}
if(hit.transform.name == "Options"){
options.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0)){
maxSpheres.renderer.enabled = !maxSpheres.renderer.enabled;
maxSpheresValue.renderer.enabled = !maxSpheresValue.renderer.enabled;
maxSpheresPlus.renderer.enabled = !maxSpheresPlus.renderer.enabled;
maxSpheresMinus.renderer.enabled = !maxSpheresMinus.renderer.enabled;
moveSpeed.renderer.enabled = !moveSpeed.renderer.enabled;
moveSpeedValue.renderer.enabled = !moveSpeedValue.renderer.enabled;
moveSpeedPlus.renderer.enabled = !moveSpeedPlus.renderer.enabled;
moveSpeedMinus.renderer.enabled = !moveSpeedMinus.renderer.enabled;
optionsClose.renderer.enabled = !optionsClose.renderer.enabled;
level1.renderer.enabled = false;
level2.renderer.enabled = false;
level3.renderer.enabled = false;
level4.renderer.enabled = false;
levelClose.renderer.enabled = false;
}
}
if(hit.transform.name == "Quit"){
quit.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.Quit();
}
if(hit.transform.name == "Max Spheres"){
maxSpheres.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMaxSpheres = oMaxSpheres;
}
if(hit.transform.name == "Max Spheres Plus"){
maxSpheresPlus.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMaxSpheres++;
}
if(hit.transform.name == "Max Spheres Minus"){
maxSpheresMinus.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMaxSpheres--;
}
if(hit.transform.name == "Move Speed"){
moveSpeed.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMoveSpeed = oMoveSpeed;
}
if(hit.transform.name == "Move Speed Plus"){
moveSpeedPlus.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMoveSpeed++;
}
if(hit.transform.name == "Move Speed Minus"){
moveSpeedMinus.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
shootingMoveSpeed--;
}
if(hit.transform.name == "Options Close"){
optionsClose.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0)){
maxSpheres.renderer.enabled = !maxSpheres.renderer.enabled;
maxSpheresValue.renderer.enabled = !maxSpheresValue.renderer.enabled;
maxSpheresPlus.renderer.enabled = !maxSpheresPlus.renderer.enabled;
maxSpheresMinus.renderer.enabled = !maxSpheresMinus.renderer.enabled;
moveSpeed.renderer.enabled = !moveSpeed.renderer.enabled;
moveSpeedValue.renderer.enabled = !moveSpeedValue.renderer.enabled;
moveSpeedPlus.renderer.enabled = !moveSpeedPlus.renderer.enabled;
moveSpeedMinus.renderer.enabled = !moveSpeedMinus.renderer.enabled;
optionsClose.renderer.enabled = !optionsClose.renderer.enabled;
}
}
if(hit.transform.name == "Level 1"){
level1.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.LoadLevel(1);
}
if(hit.transform.name == "Level 2"){
level2.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.LoadLevel(2);
}
if(hit.transform.name == "Level 3"){
level3.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.LoadLevel(3);
}
if(hit.transform.name == "Level 4"){
level4.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0))
Application.LoadLevel(4);
}
if(hit.transform.name == "Level Select Close"){
levelClose.fontStyle = FontStyle.Bold;
if(Input.GetMouseButtonDown(0)){
level1.renderer.enabled = !level1.renderer.enabled;
level2.renderer.enabled = !level2.renderer.enabled;
level3.renderer.enabled = !level3.renderer.enabled;
level4.renderer.enabled = !level4.renderer.enabled;
levelClose.renderer.enabled = !levelClose.renderer.enabled;
}
}
}
else
{
title.fontStyle = FontStyle.Bold;
play.fontStyle = FontStyle.Normal;
levelSelect.fontStyle = FontStyle.Normal;
options.fontStyle = FontStyle.Normal;
quit.fontStyle = FontStyle.Normal;
maxSpheres.fontStyle = FontStyle.Normal;
maxSpheresPlus.fontStyle = FontStyle.Normal;
maxSpheresMinus.fontStyle = FontStyle.Normal;
moveSpeed.fontStyle = FontStyle.Normal;
moveSpeedPlus.fontStyle = FontStyle.Normal;
moveSpeedMinus.fontStyle = FontStyle.Normal;
optionsClose.fontStyle = FontStyle.Normal;
level1.fontStyle = FontStyle.Normal;
level2.fontStyle = FontStyle.Normal;
level3.fontStyle = FontStyle.Normal;
level4.fontStyle = FontStyle.Normal;
levelClose.fontStyle = FontStyle.Normal;
title.characterSize = charSize;
}
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.Kinect.Face
{
//
// Microsoft.Kinect.Face.FaceModelBuilder
//
public sealed partial class FaceModelBuilder : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal FaceModelBuilder(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Microsoft_Kinect_Face_FaceModelBuilder_AddRefObject(ref _pNative);
}
~FaceModelBuilder()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<FaceModelBuilder>(_pNative);
if (disposing)
{
Microsoft_Kinect_Face_FaceModelBuilder_Dispose(_pNative);
}
Microsoft_Kinect_Face_FaceModelBuilder_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern Microsoft.Kinect.Face.FaceModelBuilderCaptureStatus Microsoft_Kinect_Face_FaceModelBuilder_get_CaptureStatus(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.FaceModelBuilderCaptureStatus CaptureStatus
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceModelBuilder");
}
return Microsoft_Kinect_Face_FaceModelBuilder_get_CaptureStatus(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern Microsoft.Kinect.Face.FaceModelBuilderCollectionStatus Microsoft_Kinect_Face_FaceModelBuilder_get_CollectionStatus(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.FaceModelBuilderCollectionStatus CollectionStatus
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceModelBuilder");
}
return Microsoft_Kinect_Face_FaceModelBuilder_get_CollectionStatus(_pNative);
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.CaptureStatusChangedEventArgs>>> Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.CaptureStatusChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate))]
private static void Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Microsoft.Kinect.Face.CaptureStatusChangedEventArgs>> callbackList = null;
Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<FaceModelBuilder>(pNative);
var args = new Microsoft.Kinect.Face.CaptureStatusChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_add_CaptureStatusChanged(RootSystem.IntPtr pNative, _Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Microsoft.Kinect.Face.CaptureStatusChangedEventArgs> CaptureStatusChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate(Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handler);
_Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Microsoft_Kinect_Face_FaceModelBuilder_add_CaptureStatusChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_CaptureStatusChanged(_pNative, Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handler, true);
_Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.CollectionStatusChangedEventArgs>>> Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.CollectionStatusChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate))]
private static void Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Microsoft.Kinect.Face.CollectionStatusChangedEventArgs>> callbackList = null;
Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<FaceModelBuilder>(pNative);
var args = new Microsoft.Kinect.Face.CollectionStatusChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_add_CollectionStatusChanged(RootSystem.IntPtr pNative, _Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Microsoft.Kinect.Face.CollectionStatusChangedEventArgs> CollectionStatusChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate(Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handler);
_Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Microsoft_Kinect_Face_FaceModelBuilder_add_CollectionStatusChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_CollectionStatusChanged(_pNative, Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handler, true);
_Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<FaceModelBuilder>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
Helper.EventPump.EnsureInitialized();
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Microsoft_Kinect_Face_FaceModelBuilder_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
private void __EventCleanup()
{
{
Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_CaptureStatusChanged(_pNative, Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handler, true);
}
_Microsoft_Kinect_Face_CaptureStatusChangedEventArgs_Delegate_Handle.Free();
}
}
}
{
Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_CollectionStatusChanged(_pNative, Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handler, true);
}
_Microsoft_Kinect_Face_CollectionStatusChangedEventArgs_Delegate_Handle.Free();
}
}
}
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
if (callbackList.Count > 0)
{
callbackList.Clear();
if (_pNative != RootSystem.IntPtr.Zero)
{
Microsoft_Kinect_Face_FaceModelBuilder_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
}
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
}
}
| |
/* Copyright (c) 2008 Robert Adams
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the copyright holder may not 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 AUTHORS 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.
*/
/*
* Portions of this code are:
* Copyright (c) Contributors, http://idealistviewer.org
* The basic logic of the extrusion code is based on the Idealist viewer code.
* The Idealist viewer is licensed under the three clause BSD license.
*/
/*
* MeshmerizerR class implments OpenMetaverse.Rendering.IRendering interface
* using PrimMesher (http://forge.opensimulator.org/projects/primmesher).
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using OMV = OpenMetaverse;
using OMVR = OpenMetaverse.Rendering;
namespace OpenMetaverse.Rendering
{
/// <summary>
/// Meshing code based on the Idealist Viewer (20081213).
/// </summary>
[RendererName("MeshmerizerR")]
public class MeshmerizerR : OMVR.IRendering
{
/// <summary>
/// Generates a basic mesh structure from a primitive
/// </summary>
/// <param name="prim">Primitive to generate the mesh from</param>
/// <param name="lod">Level of detail to generate the mesh at</param>
/// <returns>The generated mesh or null on failure</returns>
public OMVR.SimpleMesh GenerateSimpleMesh(OMV.Primitive prim, OMVR.DetailLevel lod)
{
PrimMesher.PrimMesh newPrim = GeneratePrimMesh(prim, lod, false);
if (newPrim == null)
return null;
SimpleMesh mesh = new SimpleMesh();
mesh.Path = new Path();
mesh.Prim = prim;
mesh.Profile = new Profile();
mesh.Vertices = new List<Vertex>(newPrim.coords.Count);
for (int i = 0; i < newPrim.coords.Count; i++)
{
PrimMesher.Coord c = newPrim.coords[i];
mesh.Vertices.Add(new Vertex { Position = new Vector3(c.X, c.Y, c.Z) });
}
mesh.Indices = new List<ushort>(newPrim.faces.Count * 3);
for (int i = 0; i < newPrim.faces.Count; i++)
{
PrimMesher.Face face = newPrim.faces[i];
mesh.Indices.Add((ushort)face.v1);
mesh.Indices.Add((ushort)face.v2);
mesh.Indices.Add((ushort)face.v3);
}
return mesh;
}
/// <summary>
/// Generates a basic mesh structure from a sculpted primitive
/// </summary>
/// <param name="prim">Sculpted primitive to generate the mesh from</param>
/// <param name="sculptTexture">Sculpt texture</param>
/// <param name="lod">Level of detail to generate the mesh at</param>
/// <returns>The generated mesh or null on failure</returns>
public OMVR.SimpleMesh GenerateSimpleSculptMesh(OMV.Primitive prim, System.Drawing.Bitmap sculptTexture, OMVR.DetailLevel lod)
{
OMVR.FacetedMesh faceted = GenerateFacetedSculptMesh(prim, sculptTexture, lod);
if (faceted != null && faceted.Faces.Count == 1)
{
Face face = faceted.Faces[0];
SimpleMesh mesh = new SimpleMesh();
mesh.Indices = face.Indices;
mesh.Vertices = face.Vertices;
mesh.Path = faceted.Path;
mesh.Prim = prim;
mesh.Profile = faceted.Profile;
mesh.Vertices = face.Vertices;
return mesh;
}
return null;
}
/// <summary>
/// Generates a a series of faces, each face containing a mesh and
/// metadata
/// </summary>
/// <param name="prim">Primitive to generate the mesh from</param>
/// <param name="lod">Level of detail to generate the mesh at</param>
/// <returns>The generated mesh</returns >
public OMVR.FacetedMesh GenerateFacetedMesh(OMV.Primitive prim, OMVR.DetailLevel lod)
{
bool isSphere = ((OMV.ProfileCurve)(prim.PrimData.profileCurve & 0x07) == OMV.ProfileCurve.HalfCircle);
PrimMesher.PrimMesh newPrim = GeneratePrimMesh(prim, lod, true);
if (newPrim == null)
return null;
int numViewerFaces = newPrim.viewerFaces.Count;
int numPrimFaces = newPrim.numPrimFaces;
for (uint i = 0; i < numViewerFaces; i++)
{
PrimMesher.ViewerFace vf = newPrim.viewerFaces[(int)i];
if (isSphere)
{
vf.uv1.U = (vf.uv1.U - 0.5f) * 2.0f;
vf.uv2.U = (vf.uv2.U - 0.5f) * 2.0f;
vf.uv3.U = (vf.uv3.U - 0.5f) * 2.0f;
}
}
// copy the vertex information into OMVR.IRendering structures
OMVR.FacetedMesh omvrmesh = new OMVR.FacetedMesh();
omvrmesh.Faces = new List<OMVR.Face>();
omvrmesh.Prim = prim;
omvrmesh.Profile = new OMVR.Profile();
omvrmesh.Profile.Faces = new List<OMVR.ProfileFace>();
omvrmesh.Profile.Positions = new List<OMV.Vector3>();
omvrmesh.Path = new OMVR.Path();
omvrmesh.Path.Points = new List<OMVR.PathPoint>();
Dictionary<OMV.Vector3, int> vertexAccount = new Dictionary<OMV.Vector3, int>();
for (int ii = 0; ii < numPrimFaces; ii++)
{
OMVR.Face oface = new OMVR.Face();
oface.Vertices = new List<OMVR.Vertex>();
oface.Indices = new List<ushort>();
oface.TextureFace = prim.Textures.GetFace((uint)ii);
int faceVertices = 0;
vertexAccount.Clear();
OMV.Vector3 pos;
int indx;
OMVR.Vertex vert;
foreach (PrimMesher.ViewerFace vface in newPrim.viewerFaces)
{
if (vface.primFaceNumber == ii)
{
faceVertices++;
pos = new OMV.Vector3(vface.v1.X, vface.v1.Y, vface.v1.Z);
if (vertexAccount.ContainsKey(pos))
{
// we aleady have this vertex in the list. Just point the index at it
oface.Indices.Add((ushort)vertexAccount[pos]);
}
else
{
// the vertex is not in the list. Add it and the new index.
vert = new OMVR.Vertex();
vert.Position = pos;
vert.TexCoord = new OMV.Vector2(vface.uv1.U, 1.0f - vface.uv1.V);
vert.Normal = new OMV.Vector3(vface.n1.X, vface.n1.Y, vface.n1.Z);
oface.Vertices.Add(vert);
indx = oface.Vertices.Count - 1;
vertexAccount.Add(pos, indx);
oface.Indices.Add((ushort)indx);
}
pos = new OMV.Vector3(vface.v2.X, vface.v2.Y, vface.v2.Z);
if (vertexAccount.ContainsKey(pos))
{
oface.Indices.Add((ushort)vertexAccount[pos]);
}
else
{
vert = new OMVR.Vertex();
vert.Position = pos;
vert.TexCoord = new OMV.Vector2(vface.uv2.U, 1.0f - vface.uv2.V);
vert.Normal = new OMV.Vector3(vface.n2.X, vface.n2.Y, vface.n2.Z);
oface.Vertices.Add(vert);
indx = oface.Vertices.Count - 1;
vertexAccount.Add(pos, indx);
oface.Indices.Add((ushort)indx);
}
pos = new OMV.Vector3(vface.v3.X, vface.v3.Y, vface.v3.Z);
if (vertexAccount.ContainsKey(pos))
{
oface.Indices.Add((ushort)vertexAccount[pos]);
}
else
{
vert = new OMVR.Vertex();
vert.Position = pos;
vert.TexCoord = new OMV.Vector2(vface.uv3.U, 1.0f - vface.uv3.V);
vert.Normal = new OMV.Vector3(vface.n3.X, vface.n3.Y, vface.n3.Z);
oface.Vertices.Add(vert);
indx = oface.Vertices.Count - 1;
vertexAccount.Add(pos, indx);
oface.Indices.Add((ushort)indx);
}
}
}
if (faceVertices > 0)
{
oface.TextureFace = prim.Textures.FaceTextures[ii];
if (oface.TextureFace == null)
{
oface.TextureFace = prim.Textures.DefaultTexture;
}
oface.ID = ii;
omvrmesh.Faces.Add(oface);
}
}
return omvrmesh;
}
/// <summary>
/// Create a sculpty faceted mesh. The actual scuplt texture is fetched and passed to this
/// routine since all the context for finding teh texture is elsewhere.
/// </summary>
/// <returns>The faceted mesh or null if can't do it</returns>
public OMVR.FacetedMesh GenerateFacetedSculptMesh(OMV.Primitive prim, System.Drawing.Bitmap scupltTexture, OMVR.DetailLevel lod)
{
PrimMesher.SculptMesh.SculptType smSculptType;
switch (prim.Sculpt.Type)
{
case OpenMetaverse.SculptType.Cylinder:
smSculptType = PrimMesher.SculptMesh.SculptType.cylinder;
break;
case OpenMetaverse.SculptType.Plane:
smSculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
case OpenMetaverse.SculptType.Sphere:
smSculptType = PrimMesher.SculptMesh.SculptType.sphere;
break;
case OpenMetaverse.SculptType.Torus:
smSculptType = PrimMesher.SculptMesh.SculptType.torus;
break;
default:
smSculptType = PrimMesher.SculptMesh.SculptType.plane;
break;
}
// The lod for sculpties is the resolution of the texture passed.
// The first guess is 1:1 then lower resolutions after that
// int mesherLod = (int)Math.Sqrt(scupltTexture.Width * scupltTexture.Height);
int mesherLod = 32; // number used in Idealist viewer
switch (lod)
{
case OMVR.DetailLevel.Highest:
break;
case OMVR.DetailLevel.High:
break;
case OMVR.DetailLevel.Medium:
mesherLod /= 2;
break;
case OMVR.DetailLevel.Low:
mesherLod /= 4;
break;
}
PrimMesher.SculptMesh newMesh =
new PrimMesher.SculptMesh(scupltTexture, smSculptType, mesherLod, true, prim.Sculpt.Mirror, prim.Sculpt.Invert);
int numPrimFaces = 1; // a scuplty has only one face
// copy the vertex information into OMVR.IRendering structures
OMVR.FacetedMesh omvrmesh = new OMVR.FacetedMesh();
omvrmesh.Faces = new List<OMVR.Face>();
omvrmesh.Prim = prim;
omvrmesh.Profile = new OMVR.Profile();
omvrmesh.Profile.Faces = new List<OMVR.ProfileFace>();
omvrmesh.Profile.Positions = new List<OMV.Vector3>();
omvrmesh.Path = new OMVR.Path();
omvrmesh.Path.Points = new List<OMVR.PathPoint>();
Dictionary<OMVR.Vertex, int> vertexAccount = new Dictionary<OMVR.Vertex, int>();
for (int ii = 0; ii < numPrimFaces; ii++)
{
vertexAccount.Clear();
OMVR.Face oface = new OMVR.Face();
oface.Vertices = new List<OMVR.Vertex>();
oface.Indices = new List<ushort>();
oface.TextureFace = prim.Textures.GetFace((uint)ii);
int faceVertices = newMesh.coords.Count;
OMVR.Vertex vert;
for (int j = 0; j < faceVertices; j++)
{
vert = new OMVR.Vertex();
vert.Position = new Vector3(newMesh.coords[j].X, newMesh.coords[j].Y, newMesh.coords[j].Z);
vert.Normal = new Vector3(newMesh.normals[j].X, newMesh.normals[j].Y, newMesh.normals[j].Z);
vert.TexCoord = new Vector2(newMesh.uvs[j].U, newMesh.uvs[j].V);
oface.Vertices.Add(vert);
}
for (int j = 0; j < newMesh.faces.Count; j++)
{
oface.Indices.Add((ushort)newMesh.faces[j].v1);
oface.Indices.Add((ushort)newMesh.faces[j].v2);
oface.Indices.Add((ushort)newMesh.faces[j].v3);
}
if (faceVertices > 0)
{
oface.TextureFace = prim.Textures.FaceTextures[ii];
if (oface.TextureFace == null)
{
oface.TextureFace = prim.Textures.DefaultTexture;
}
oface.ID = ii;
omvrmesh.Faces.Add(oface);
}
}
return omvrmesh;
}
/// <summary>
/// Apply texture coordinate modifications from a
/// <seealso cref="TextureEntryFace"/> to a list of vertices
/// </summary>
/// <param name="vertices">Vertex list to modify texture coordinates for</param>
/// <param name="center">Center-point of the face</param>
/// <param name="teFace">Face texture parameters</param>
public void TransformTexCoords(List<OMVR.Vertex> vertices, OMV.Vector3 center, OMV.Primitive.TextureEntryFace teFace, Vector3 primScale)
{
// compute trig stuff up front
float cosineAngle = (float)Math.Cos(teFace.Rotation);
float sinAngle = (float)Math.Sin(teFace.Rotation);
for (int ii = 0; ii < vertices.Count; ii++)
{
// tex coord comes to us as a number between zero and one
// transform about the center of the texture
OMVR.Vertex vert = vertices[ii];
// aply planar tranforms to the UV first if applicable
if (teFace.TexMapType == MappingType.Planar)
{
Vector3 binormal;
float d = Vector3.Dot(vert.Normal, Vector3.UnitX);
if (d >= 0.5f || d <= -0.5f)
{
binormal = Vector3.UnitY;
if (vert.Normal.X < 0f) binormal *= -1;
}
else
{
binormal = Vector3.UnitX;
if (vert.Normal.Y > 0f) binormal *= -1;
}
Vector3 tangent = binormal % vert.Normal;
Vector3 scaledPos = vert.Position * primScale;
vert.TexCoord.X = 1f + (Vector3.Dot(binormal, scaledPos) * 2f - 0.5f);
vert.TexCoord.Y = -(Vector3.Dot(tangent, scaledPos) * 2f - 0.5f);
}
float repeatU = teFace.RepeatU;
float repeatV = teFace.RepeatV;
float tX = vert.TexCoord.X - 0.5f;
float tY = vert.TexCoord.Y - 0.5f;
vert.TexCoord.X = (tX * cosineAngle + tY * sinAngle) * repeatU + teFace.OffsetU + 0.5f;
vert.TexCoord.Y = (-tX * sinAngle + tY * cosineAngle) * repeatV + teFace.OffsetV + 0.5f;
vertices[ii] = vert;
}
return;
}
private PrimMesher.PrimMesh GeneratePrimMesh(Primitive prim, DetailLevel lod, bool viewerMode)
{
OMV.Primitive.ConstructionData primData = prim.PrimData;
int sides = 4;
int hollowsides = 4;
float profileBegin = primData.ProfileBegin;
float profileEnd = primData.ProfileEnd;
bool isSphere = false;
if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.Circle)
{
switch (lod)
{
case OMVR.DetailLevel.Low:
sides = 6;
break;
case OMVR.DetailLevel.Medium:
sides = 12;
break;
default:
sides = 24;
break;
}
}
else if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.EqualTriangle)
sides = 3;
else if ((OMV.ProfileCurve)(primData.profileCurve & 0x07) == OMV.ProfileCurve.HalfCircle)
{
// half circle, prim is a sphere
isSphere = true;
switch (lod)
{
case OMVR.DetailLevel.Low:
sides = 6;
break;
case OMVR.DetailLevel.Medium:
sides = 12;
break;
default:
sides = 24;
break;
}
profileBegin = 0.5f * profileBegin + 0.5f;
profileEnd = 0.5f * profileEnd + 0.5f;
}
if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Same)
hollowsides = sides;
else if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Circle)
{
switch (lod)
{
case OMVR.DetailLevel.Low:
hollowsides = 6;
break;
case OMVR.DetailLevel.Medium:
hollowsides = 12;
break;
default:
hollowsides = 24;
break;
}
}
else if ((OMV.HoleType)primData.ProfileHole == OMV.HoleType.Triangle)
hollowsides = 3;
PrimMesher.PrimMesh newPrim = new PrimMesher.PrimMesh(sides, profileBegin, profileEnd, (float)primData.ProfileHollow, hollowsides);
newPrim.viewerMode = viewerMode;
newPrim.sphereMode = isSphere;
newPrim.holeSizeX = primData.PathScaleX;
newPrim.holeSizeY = primData.PathScaleY;
newPrim.pathCutBegin = primData.PathBegin;
newPrim.pathCutEnd = primData.PathEnd;
newPrim.topShearX = primData.PathShearX;
newPrim.topShearY = primData.PathShearY;
newPrim.radius = primData.PathRadiusOffset;
newPrim.revolutions = primData.PathRevolutions;
newPrim.skew = primData.PathSkew;
switch (lod)
{
case OMVR.DetailLevel.Low:
newPrim.stepsPerRevolution = 6;
break;
case OMVR.DetailLevel.Medium:
newPrim.stepsPerRevolution = 12;
break;
default:
newPrim.stepsPerRevolution = 24;
break;
}
if ((primData.PathCurve == OMV.PathCurve.Line) || (primData.PathCurve == OMV.PathCurve.Flexible))
{
newPrim.taperX = 1.0f - primData.PathScaleX;
newPrim.taperY = 1.0f - primData.PathScaleY;
newPrim.twistBegin = (int)(180 * primData.PathTwistBegin);
newPrim.twistEnd = (int)(180 * primData.PathTwist);
newPrim.ExtrudeLinear();
}
else
{
newPrim.taperX = primData.PathTaperX;
newPrim.taperY = primData.PathTaperY;
newPrim.twistBegin = (int)(360 * primData.PathTwistBegin);
newPrim.twistEnd = (int)(360 * primData.PathTwist);
newPrim.ExtrudeCircular();
}
return newPrim;
}
/// <summary>
/// Method for generating mesh Face from a heightmap
/// </summary>
/// <param name="zMap">Two dimension array of floats containing height information</param>
/// <param name="xBegin">Starting value for X</param>
/// <param name="xEnd">Max value for X</param>
/// <param name="yBegin">Starting value for Y</param>
/// <param name="yEnd">Max value of Y</param>
/// <returns></returns>
public OMVR.Face TerrainMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd)
{
PrimMesher.SculptMesh newMesh = new PrimMesher.SculptMesh(zMap, xBegin, xEnd, yBegin, yEnd, true);
OMVR.Face terrain = new OMVR.Face();
int faceVertices = newMesh.coords.Count;
terrain.Vertices = new List<Vertex>(faceVertices);
terrain.Indices = new List<ushort>(newMesh.faces.Count * 3);
for (int j = 0; j < faceVertices; j++)
{
var vert = new OMVR.Vertex();
vert.Position = new Vector3(newMesh.coords[j].X, newMesh.coords[j].Y, newMesh.coords[j].Z);
vert.Normal = new Vector3(newMesh.normals[j].X, newMesh.normals[j].Y, newMesh.normals[j].Z);
vert.TexCoord = new Vector2(newMesh.uvs[j].U, newMesh.uvs[j].V);
terrain.Vertices.Add(vert);
}
for (int j = 0; j < newMesh.faces.Count; j++)
{
terrain.Indices.Add((ushort)newMesh.faces[j].v1);
terrain.Indices.Add((ushort)newMesh.faces[j].v2);
terrain.Indices.Add((ushort)newMesh.faces[j].v3);
}
return terrain;
}
}
}
| |
//
// 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.
//
#if !SILVERLIGHT
#define DEBUG
namespace NLog.UnitTests
{
using System;
using System.Diagnostics;
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
[TestFixture]
public class NLogTraceListenerTests : NLogTestBase
{
[Test]
public void TraceWriteTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.Write(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Test]
public void TraceWriteLineTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Debug.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Debug.WriteLine(3.1415);
AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415));
Debug.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415));
}
[Test]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Debug.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
#if !NET_CF
[Test]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
Assert.AreEqual(LogLevel.Warn, listener.DefaultLogLevel);
Assert.AreEqual(LogLevel.Error, listener.ForceLogLevel);
Assert.IsTrue(listener.AutoLoggerName);
}
[Test]
public void TraceFailTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Debug.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Debug.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Test]
public void AutoLoggerNameTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Debug.Listeners.Clear();
Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Debug.Write("Hello");
AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello");
}
[Test]
public void TraceDataTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", string.Format("MySource1 Fatal 42, {0}, foo 145", 3.14));
}
[Test]
public void LogInformationTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Test]
public void TraceEventTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
[Test]
public void ForceLogLevelTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
#endif
}
}
#endif
| |
//
// HttpMultipart.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Apache.Http.Entity.Mime;
using Apache.Http.Entity.Mime.Content;
using Apache.Http.Util;
using Sharpen;
namespace Apache.Http.Entity.Mime
{
/// <summary>HttpMultipart represents a collection of MIME multipart encoded content bodies.
/// </summary>
/// <remarks>
/// HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
/// capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
/// the browser compatible modes.
/// </remarks>
/// <since>4.0</since>
public class HttpMultipart
{
private static ByteArrayBuffer Encode(Encoding charset, string @string)
{
ByteBuffer encoded = charset.Encode(CharBuffer.Wrap(@string));
ByteArrayBuffer bab = new ByteArrayBuffer(encoded.Remaining());
bab.Append(((byte[])encoded.Array()), encoded.Position(), encoded.Remaining());
return bab;
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(ByteArrayBuffer b, OutputStream @out)
{
@out.Write(b.Buffer(), 0, b.Length());
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(string s, Encoding charset, OutputStream @out)
{
ByteArrayBuffer b = Encode(charset, s);
WriteBytes(b, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(string s, OutputStream @out)
{
ByteArrayBuffer b = Encode(MIME.DefaultCharset, s);
WriteBytes(b, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteField(MinimalField field, OutputStream @out)
{
WriteBytes(field.GetName(), @out);
WriteBytes(FieldSep, @out);
WriteBytes(field.GetBody(), @out);
WriteBytes(CrLf, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteField(MinimalField field, Encoding charset, OutputStream
@out)
{
WriteBytes(field.GetName(), charset, @out);
WriteBytes(FieldSep, @out);
WriteBytes(field.GetBody(), charset, @out);
WriteBytes(CrLf, @out);
}
private static readonly ByteArrayBuffer FieldSep = Encode(MIME.DefaultCharset, ": "
);
private static readonly ByteArrayBuffer CrLf = Encode(MIME.DefaultCharset, "\r\n"
);
private static readonly ByteArrayBuffer TwoDashes = Encode(MIME.DefaultCharset, "--"
);
private readonly string subType;
private readonly Encoding charset;
private readonly string boundary;
private readonly IList<FormBodyPart> parts;
private readonly HttpMultipartMode mode;
/// <summary>Creates an instance with the specified settings.</summary>
/// <remarks>Creates an instance with the specified settings.</remarks>
/// <param name="subType">
/// mime subtype - must not be
/// <code>null</code>
/// </param>
/// <param name="charset">
/// the character set to use. May be
/// <code>null</code>
/// , in which case
/// <see cref="MIME.DefaultCharset">MIME.DefaultCharset</see>
/// - i.e. US-ASCII - is used.
/// </param>
/// <param name="boundary">
/// to use - must not be
/// <code>null</code>
/// </param>
/// <param name="mode">the mode to use</param>
/// <exception cref="System.ArgumentException">if charset is null or boundary is null
/// </exception>
public HttpMultipart(string subType, Encoding charset, string boundary, HttpMultipartMode
mode) : base()
{
if (subType == null)
{
throw new ArgumentException("Multipart subtype may not be null");
}
if (boundary == null)
{
throw new ArgumentException("Multipart boundary may not be null");
}
this.subType = subType;
this.charset = charset != null ? charset : MIME.DefaultCharset;
this.boundary = boundary;
this.parts = new AList<FormBodyPart>();
this.mode = mode;
}
/// <summary>Creates an instance with the specified settings.</summary>
/// <remarks>
/// Creates an instance with the specified settings.
/// Mode is set to
/// <see cref="HttpMultipartMode.Strict">HttpMultipartMode.Strict</see>
/// </remarks>
/// <param name="subType">
/// mime subtype - must not be
/// <code>null</code>
/// </param>
/// <param name="charset">
/// the character set to use. May be
/// <code>null</code>
/// , in which case
/// <see cref="MIME.DefaultCharset">MIME.DefaultCharset</see>
/// - i.e. US-ASCII - is used.
/// </param>
/// <param name="boundary">
/// to use - must not be
/// <code>null</code>
/// </param>
/// <exception cref="System.ArgumentException">if charset is null or boundary is null
/// </exception>
public HttpMultipart(string subType, Encoding charset, string boundary) : this(subType
, charset, boundary, HttpMultipartMode.Strict)
{
}
public HttpMultipart(string subType, string boundary) : this(subType, null, boundary
)
{
}
public virtual string GetSubType()
{
return this.subType;
}
public virtual Encoding GetCharset()
{
return this.charset;
}
public virtual HttpMultipartMode GetMode()
{
return this.mode;
}
public virtual IList<FormBodyPart> GetBodyParts()
{
return this.parts;
}
public virtual void AddBodyPart(FormBodyPart part)
{
if (part == null)
{
return;
}
this.parts.AddItem(part);
}
public virtual string GetBoundary()
{
return this.boundary;
}
/// <exception cref="System.IO.IOException"></exception>
private void DoWriteTo(HttpMultipartMode mode, OutputStream @out, bool writeContent
)
{
ByteArrayBuffer boundary = Encode(this.charset, GetBoundary());
foreach (FormBodyPart part in this.parts)
{
WriteBytes(TwoDashes, @out);
WriteBytes(boundary, @out);
WriteBytes(CrLf, @out);
Header header = part.GetHeader();
switch (mode)
{
case HttpMultipartMode.Strict:
{
foreach (MinimalField field in header)
{
WriteField(field, @out);
}
break;
}
case HttpMultipartMode.BrowserCompatible:
{
// Only write Content-Disposition
// Use content charset
MinimalField cd = part.GetHeader().GetField(MIME.ContentDisposition);
WriteField(cd, this.charset, @out);
string filename = part.GetBody().GetFilename();
if (filename != null)
{
MinimalField ct = part.GetHeader().GetField(MIME.ContentType);
WriteField(ct, this.charset, @out);
}
break;
}
}
WriteBytes(CrLf, @out);
if (writeContent)
{
part.GetBody().WriteTo(@out);
}
WriteBytes(CrLf, @out);
}
WriteBytes(TwoDashes, @out);
WriteBytes(boundary, @out);
WriteBytes(TwoDashes, @out);
WriteBytes(CrLf, @out);
}
/// <summary>Writes out the content in the multipart/form encoding.</summary>
/// <remarks>
/// Writes out the content in the multipart/form encoding. This method
/// produces slightly different formatting depending on its compatibility
/// mode.
/// </remarks>
/// <seealso cref="GetMode()">GetMode()</seealso>
/// <exception cref="System.IO.IOException"></exception>
public virtual void WriteTo(OutputStream @out)
{
DoWriteTo(this.mode, @out, true);
}
/// <summary>
/// Determines the total length of the multipart content (content length of
/// individual parts plus that of extra elements required to delimit the parts
/// from one another).
/// </summary>
/// <remarks>
/// Determines the total length of the multipart content (content length of
/// individual parts plus that of extra elements required to delimit the parts
/// from one another). If any of the @{link BodyPart}s contained in this object
/// is of a streaming entity of unknown length the total length is also unknown.
/// <p/>
/// This method buffers only a small amount of data in order to determine the
/// total length of the entire entity. The content of individual parts is not
/// buffered.
/// </remarks>
/// <returns>
/// total length of the multipart entity if known, <code>-1</code>
/// otherwise.
/// </returns>
public virtual long GetTotalLength()
{
long contentLen = 0;
foreach (FormBodyPart part in this.parts)
{
ContentBody body = part.GetBody();
long len = body.GetContentLength();
if (len >= 0)
{
contentLen += len;
}
else
{
return -1;
}
}
ByteArrayOutputStream @out = new ByteArrayOutputStream();
try
{
DoWriteTo(this.mode, @out, false);
byte[] extra = @out.ToByteArray();
return contentLen + extra.Length;
}
catch (IOException)
{
// Should never happen
return -1;
}
}
}
}
| |
// <copyright file="ManualResetEvent.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using IX.StandardExtensions.ComponentModel;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
namespace IX.System.Threading
{
/// <summary>
/// A set/reset event class that implements methods to block and unblock threads based on manual signal interaction.
/// </summary>
/// <seealso cref="IX.System.Threading.ISetResetEvent" />
[PublicAPI]
public class ManualResetEvent : DisposableBase, ISetResetEvent
{
private readonly bool eventLocal;
#pragma warning disable IDISP002 // Dispose member. - It is
#pragma warning disable IDISP006 // Implement IDisposable.
/// <summary>
/// The manual reset event.
/// </summary>
private readonly global::System.Threading.ManualResetEvent sre;
#pragma warning restore IDISP006 // Implement IDisposable.
#pragma warning restore IDISP002 // Dispose member.
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEvent" /> class.
/// </summary>
public ManualResetEvent()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEvent" /> class.
/// </summary>
/// <param name="initialState">The initial signal state.</param>
public ManualResetEvent(bool initialState)
{
this.sre = new global::System.Threading.ManualResetEvent(initialState);
this.eventLocal = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEvent" /> class.
/// </summary>
/// <param name="manualResetEvent">The manual reset event.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="manualResetEvent" /> is <see langword="null" /> (
/// <see langword="Nothing" /> in Visual Basic).
/// </exception>
public ManualResetEvent(global::System.Threading.ManualResetEvent manualResetEvent)
{
Contract.RequiresNotNull(
ref this.sre,
manualResetEvent,
nameof(manualResetEvent));
}
/// <summary>
/// Performs an implicit conversion from <see cref="ManualResetEvent" /> to
/// <see cref="T:System.Threading.ManualResetEvent" />.
/// </summary>
/// <param name="manualResetEvent">The manual reset event.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator global::System.Threading.ManualResetEvent(ManualResetEvent manualResetEvent) =>
manualResetEvent.sre;
/// <summary>
/// Performs an implicit conversion from <see cref="T:System.Threading.ManualResetEvent" /> to
/// <see cref="ManualResetEvent" />.
/// </summary>
/// <param name="manualResetEvent">The manual reset event.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator ManualResetEvent(global::System.Threading.ManualResetEvent manualResetEvent) =>
new ManualResetEvent(manualResetEvent);
/// <summary>
/// Sets the state of this event instance to non-signaled. Any thread entering a wait from this point will block.
/// </summary>
/// <returns><see langword="true" /> if the signal has been reset, <see langword="false" /> otherwise.</returns>
public bool Reset() => this.sre.Reset();
/// <summary>
/// Sets the state of this event instance to signaled. Any waiting thread will unblock.
/// </summary>
/// <returns><see langword="true" /> if the signal has been set, <see langword="false" /> otherwise.</returns>
public bool Set() => this.sre.Set();
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
public void WaitOne() => this.sre.WaitOne();
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(int millisecondsTimeout) =>
this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout));
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(double millisecondsTimeout) =>
this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout));
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="timeout">The timeout period.</param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(TimeSpan timeout) => this.sre.WaitOne(timeout);
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param>
/// <param name="exitSynchronizationDomain">
/// If set to <see langword="true" />, the synchronization domain is exited before
/// the call.
/// </param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(
int millisecondsTimeout,
bool exitSynchronizationDomain) =>
#if !STANDARD
this.sre.WaitOne(
TimeSpan.FromMilliseconds(millisecondsTimeout),
exitSynchronizationDomain);
#else
this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout));
#endif
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param>
/// <param name="exitSynchronizationDomain">
/// If set to <see langword="true" />, the synchronization domain is exited before
/// the call.
/// </param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(
double millisecondsTimeout,
bool exitSynchronizationDomain) =>
#if !STANDARD
this.sre.WaitOne(
TimeSpan.FromMilliseconds(millisecondsTimeout),
exitSynchronizationDomain);
#else
this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout));
#endif
/// <summary>
/// Enters a wait period and, should there be no signal set, blocks the thread calling.
/// </summary>
/// <param name="timeout">The timeout period.</param>
/// <param name="exitSynchronizationDomain">
/// If set to <see langword="true" />, the synchronization domain is exited before
/// the call.
/// </param>
/// <returns>
/// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout
/// is reached.
/// </returns>
public bool WaitOne(
TimeSpan timeout,
bool exitSynchronizationDomain) =>
#if !STANDARD
this.sre.WaitOne(
timeout,
exitSynchronizationDomain);
#else
this.sre.WaitOne(timeout);
#endif
/// <summary>
/// Disposes in the managed context.
/// </summary>
protected override void DisposeManagedContext()
{
base.DisposeManagedContext();
if (this.eventLocal)
{
this.sre.Dispose();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using MvcDemo.Core;
using MvcDemo.Core.Data;
namespace MvcDemo.Data
{
/// <summary>
/// Entity Framework repository
/// </summary>
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
#region Fields
private readonly IDbContext _context;
private IDbSet<T> _entities;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="context">Object context</param>
public EfRepository(IDbContext context)
{
this._context = context;
}
#endregion
#region Utilities
/// <summary>
/// Get full error
/// </summary>
/// <param name="exc">Exception</param>
/// <returns>Error</returns>
protected string GetFullErrorText(DbEntityValidationException exc)
{
var msg = string.Empty;
foreach (var validationErrors in exc.EntityValidationErrors)
foreach (var error in validationErrors.ValidationErrors)
msg += string.Format("Property: {0} Error: {1}", error.PropertyName, error.ErrorMessage) + Environment.NewLine;
return msg;
}
#endregion
#region Methods
/// <summary>
/// Get entity by identifier
/// </summary>
/// <param name="id">Identifier</param>
/// <returns>Entity</returns>
public virtual T GetById(object id)
{
//see some suggested performance optimization (not tested)
//http://stackoverflow.com/questions/11686225/dbset-find-method-ridiculously-slow-compared-to-singleordefault-on-id/11688189#comment34876113_11688189
return this.Entities.Find(id);
}
/// <summary>
/// Insert entity
/// </summary>
/// <param name="entity">Entity</param>
public virtual void Insert(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Add(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
/// <summary>
/// Insert entities
/// </summary>
/// <param name="entities">Entities</param>
public virtual void Insert(IEnumerable<T> entities)
{
try
{
if (entities == null)
throw new ArgumentNullException("entities");
foreach (var entity in entities)
this.Entities.Add(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
/// <summary>
/// Update entity
/// </summary>
/// <param name="entity">Entity</param>
public virtual void Update(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
/// <summary>
/// Update entities
/// </summary>
/// <param name="entities">Entities</param>
public virtual void Update(IEnumerable<T> entities)
{
try
{
if (entities == null)
throw new ArgumentNullException("entities");
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
/// <summary>
/// Delete entity
/// </summary>
/// <param name="entity">Entity</param>
public virtual void Delete(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Remove(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
/// <summary>
/// Delete entities
/// </summary>
/// <param name="entities">Entities</param>
public virtual void Delete(IEnumerable<T> entities)
{
try
{
if (entities == null)
throw new ArgumentNullException("entities");
foreach (var entity in entities)
this.Entities.Remove(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
#endregion
#region Properties
/// <summary>
/// Gets a table
/// </summary>
public virtual IQueryable<T> Table
{
get
{
return this.Entities;
}
}
/// <summary>
/// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations
/// </summary>
public virtual IQueryable<T> TableNoTracking
{
get
{
return this.Entities.AsNoTracking();
}
}
/// <summary>
/// Entities
/// </summary>
protected virtual IDbSet<T> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<T>();
return _entities;
}
}
#endregion
}
}
| |
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace NeoSmart.Web
{
public class EmailFilter
{
public static ILogger<EmailFilter>? Logger;
public enum BlockReason
{
/// The format of the email address did not conform to that of a public email account.
/// (This isn't the same as what is technically allowed.)
InvalidFormat,
/// The MX domain could not be resolved or resolved to an invalid value.
InvalidMx,
/// The email fell afoul of one or more statically defined checks, such as known typo
/// domains or user portion not consistent with domain mail server's published rules,
/// such as minimum length or allowed characters.
StaticRules,
/// Either the domain itself is blacklisted or its MX resolved to a blacklisted value
Blacklisted,
/// The user/domain combination tripped one or more heuristic filters that indicate a
/// (high) probability of being a fake email.
Heuristic
}
private static readonly Regex EmailRegex = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex NumericEmailRegex = new Regex(@"^[0-9]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex NumericDomainRegex = new Regex(@"^[0-9]+\.[^.]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex MistypedTldRegex = new Regex(@"\.(cm|cmo|om|comm)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex TldRegex = new Regex(@"\.(ru|cn|info|tk)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex ExpressionRegex = new Regex(@"\*|^a+b+c+|address|bastard|bitch|blabla|d+e+f+g+|example|fake|fuck|junk|junk|^lol$| (a|no|some)name" +
"|no1|nobody|none|noone|nope|nothank|noway|qwerty|sample|spam|suck|test|thanks|^user$|whatever|^x+y+z+", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex QwertyRegex = new Regex(@"^[asdfghjkvlxm]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex QwertyDomainRegex = new Regex(@"^[asdfghjkvlx]+\.[^.]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex RepeatedCharsRegex = new Regex(@"(.)(:?\1){3,}|^(.)\3+$?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
static private HashSet<IPAddress> BlockedMxAddresses = new HashSet<IPAddress>();
static private ManualResetEventSlim ReverseDnsCompleteEvent = new ManualResetEventSlim(false);
static private bool ReverseDnsComplete = false;
static EmailFilter()
{
//This cannot be run in the constructor and needs to run in a separate thread
//not our fault, see here: https://blogs.msdn.microsoft.com/pfxteam/2011/05/03/static-constructor-deadlocks/
new Thread((() =>
{
//Create a set of IP addresses for known bad domains
//used to reverse filter any future MX lookups for a match
//this will catch aliases for temporary email address services
BlockedMxAddresses = new HashSet<IPAddress>();
Parallel.ForEach(MxBlackList, () => new HashSet<IPAddress>(), (domain, state, local) =>
{
try
{
var results = DnsLookup.GetMXRecords(domain, out bool found);
foreach (var result in results)
{
DnsLookup.GetIpAddresses(result, out var addresses);
if (addresses == null)
{
continue;
}
foreach (var ip in addresses)
{
local.Add(ip);
}
}
}
catch
{
}
return local;
}, (local) =>
{
foreach (var ip in local)
{
BlockedMxAddresses.Add(ip);
}
});
ReverseDnsCompleteEvent.Set();
})).Start();
}
// aka IsDefinitelyFakeEmail
static public bool IsFakeEmail(string email)
{
return IsProbablyFakeEmail(email, 0, true);
}
static public bool HasValidMx(MailAddress address)
{
if (!ReverseDnsComplete)
{
ReverseDnsCompleteEvent.Wait();
ReverseDnsComplete = true;
}
if (ValidDomainCache.Contains(address.Host))
{
return true;
}
var mxRecords = DnsLookup.GetMXRecords(address.Host, out bool mxFound);
if (!mxFound || !mxRecords.Any())
{
// No MX record associated with this address or timeout
Logger?.LogInformation("Could not find MX record for domain {MailDomain}", address.Host);
return false;
}
// Compare against our blacklist
foreach (var record in mxRecords)
{
DnsLookup.GetIpAddresses(record, out var addresses);
if (addresses != null && addresses.Any(BlockedMxAddresses.Contains))
{
// This mx record points to the same IP as a blacklisted MX record or timeout
Logger?.LogInformation("Email domain {MailDomain} has MX record {MxRecord} in blacklist!",
address.Host, record);
return false;
}
}
lock (ValidDomainCache)
{
ValidDomainCache.Add(address.Host);
}
return true;
}
static public bool HasValidMx(string email)
{
try
{
return HasValidMx(new MailAddress(email));
}
catch (Exception ex)
{
Logger?.LogError(ex, "Error checking domain MX records");
// Err on the side of caution
return true;
}
}
static public bool IsProbablyFakeEmail(string email, int meanness, bool validateMx = false)
{
if (string.IsNullOrWhiteSpace(email))
{
return true;
}
//Instead of making all the regex rules case-insensitive
email = email.ToLower();
if (!IsValidFormat(email))
{
return true;
}
var mailAddress = new MailAddress(email);
if (meanness >= 0)
{
if (DomainMinimumPrefix.TryGetValue(mailAddress.Host, out var minimumPrefix)
&& minimumPrefix > mailAddress.User.Length)
{
return true;
}
if (MistypedDomains.Contains(mailAddress.Host))
{
return true;
}
if (MistypedTldRegex.IsMatch(mailAddress.Host))
{
return true;
}
}
if (meanness >= 1)
{
if (BlockedDomains.Contains(mailAddress.Host))
{
return true;
}
}
if (meanness >= 2)
{
if (ExpressionRegex.IsMatch(mailAddress.User))
{
return true;
}
}
if (meanness >= 4)
{
if (RepeatedCharsRegex.IsMatch(mailAddress.User) ||
RepeatedCharsRegex.IsMatch(mailAddress.Host))
{
return true;
}
}
if (meanness >= 5)
{
if (NumericEmailRegex.IsMatch(mailAddress.User))
{
return true;
}
if (ExpressionRegex.IsMatch(email))
{
return true;
}
}
if (meanness >= 6)
{
if (QwertyRegex.IsMatch(mailAddress.User))
{
return true;
}
if (QwertyDomainRegex.IsMatch(mailAddress.Host))
{
return true;
}
if (NumericDomainRegex.IsMatch(mailAddress.Host))
{
return true;
}
}
if (meanness >= 7)
{
//this is including the tld, so 3 is insanely generous
//2 letters + period + 3 tld = 6
if (mailAddress.Host.Length < 6)
{
return true;
}
}
if (meanness >= 8)
{
if (mailAddress.User.Length < 3)
{
return true;
}
}
if (meanness >= 9)
{
if (mailAddress.User.Length < 5)
{
return true;
}
}
if (meanness >= 10)
{
if (TldRegex.IsMatch(mailAddress.Host))
{
return true;
}
}
//Do this last because it's the most expensive
if (validateMx && !HasValidMx(mailAddress))
{
return true;
}
return false;
}
//From http://msdn.microsoft.com/en-us/library/01escwtf.aspx
static public bool IsValidFormat(string email)
{
bool invalid = false;
if (String.IsNullOrEmpty(email))
{
return false;
}
try
{
email = Regex.Replace(email, @"(@)(.+)$", match =>
{
//use IdnMapping class to convert Unicode domain names.
var idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
invalid = true;
}
return match.Groups[1].Value + domainName;
}, RegexOptions.Compiled, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException)
{
return false;
}
if (invalid)
{
return false;
}
//return true if input is in valid e-mail format.
try
{
return EmailRegex.IsMatch(email);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
// These domains will never fail an MX check
static private readonly HashSet<string> ValidDomainCache = new HashSet<string>()
{
"gmail.com",
"googlemail.com",
"hotmail.com",
"msn.com",
"outlook.com",
"yahoo.com",
"aol.com",
};
// Domains that have hard rules as to the length of the prefix (prefix@domain)
private readonly static Dictionary<string, int> DomainMinimumPrefix = new Dictionary<string, int>()
{
{ "gmail.com", 6 },
};
private readonly static HashSet<string> MxBlackList = new HashSet<string>(new[]
{
"mvrht.com", // 10minutemail.com
"mailinator.com",
"sharklasers.com", // guerrillamail.com
"teleworm.us", // fakemailgenerator.com
"hmamail.com", // hidemyass email
"generator.email", // primary web address and mx record for many different domains
});
private readonly static SortedSet<string> MistypedDomains = new SortedSet<string>()
{
"gail.com",
"gamil.com",
"gmai.com",
};
//Originally from http://www.digitalfaq.com/forum/web-tech/5050-throwaway-email-block.html
private readonly static HashSet<string> BlockedDomains = new HashSet<string>(new[]
{
"0clickemail.com",
"10minutemail.com",
"10minutemail.de",
"123-m.com",
"126.com",
"139.com",
"163.com",
"1pad.de",
"20minutemail.com",
"21cn.com",
"2prong.com",
"33mail.com",
"3d-painting.com",
"4warding.com",
"4warding.net",
"4warding.org",
"6paq.com",
"60minutemail.com",
"7days-printing.com",
"7tags.com",
"99experts.com",
"agedmail.com",
"amilegit.com",
"ano-mail.net",
"anonbox.net",
"anonymbox.com",
"antispam.de",
"anymail.com",
"armyspy.com",
"beefmilk.com",
"bigstring.com",
"binkmail.com",
"bio-muesli.net",
"bob.com",
"bobmail.info",
"bofthew.com",
"boxformail.in",
"brefmail.com",
"brennendesreich.de",
"broadbandninja.com",
"bsnow.net",
"buffemail.com",
"bugmenot.com",
"bumpymail.com",
"bund.us",
"cellurl.com",
"chammy.info",
"cheatmail.de",
"chogmail.com",
"chong-mail.com",
"chong-mail.net",
"chong-mail.org",
"clixser.com",
"cmail.com",
"cmail.net",
"cmail.org",
"consumerriot.com",
"cool.fr.nf",
"courriel.fr.nf",
"courrieltemporaire.com",
"c2.hu",
"curryworld.de",
"cust.in",
"cuvox.de",
"dacoolest.com",
"dandikmail.com",
"dayrep.com",
"dbunker.com",
"dcemail.com",
"deadaddress.com",
"deagot.com",
"dealja.com",
"despam.it",
"devnullmail.com",
"digitalsanctuary.com",
"dingbone.com",
"discardmail.com",
"discardmail.de",
"dispose.it",
"disposableinbox.com",
"disposeamail.com",
"dispostable.com",
"dodgeit.com",
"dodgit.com",
"dodgit.org",
"domozmail.com",
"dontreg.com",
"dontsendmespam.de",
"drdrb.com",
"drdrb.net",
"dudmail.com",
"dump-email.info",
"dumpyemail.com",
"duskmail.com",
"e-mail.com",
"e-mail.org",
"e4ward.com",
"easytrashmail.com",
"einrot.de",
"email.com",
"emailgo.de",
"emailias.com",
"email60.com",
"emailinfive.com",
"emaillime.com",
"emailmiser.com",
"emailtemporario.com.br",
"emailtemporar.ro",
"emailthe.net",
"emailtmp.com",
"emailwarden.com",
"example.com",
"example.net",
"example.org",
"explodemail.com",
"fakeinbox.com",
"fakeinformation.com",
"fakemail.fr",
"fantasymail.de",
"fastacura.com",
"fatflap.com",
"fdfdsfds.com",
"fightallspam.com",
"filzmail.com",
"fizmail.com",
"flyspam.com",
"fr33mail.info",
"frapmail.com",
"friendlymail.co.uk",
"fuckingduh.com",
"fudgerub.com",
"garliclife.com",
"get1mail.com",
"get2mail.fr",
"getairmail.com",
"getmails.eu",
"getonemail.com",
"getonemail.net",
"gishpuppy.com",
"goemailgo.com",
"gotmail.com",
"gotmail.net",
"gotmail.org",
"gotti.otherinbox.com",
"great-host.in",
"guerillamail.org",
"guerrillamail.biz",
"guerrillamail.com",
"guerrillamail.de",
"guerrillamail.net",
"guerrillamail.org",
"guerrillamailblock.com",
"hacccc.com",
"haltospam.com",
"herp.in",
"hidzz.com",
"hochsitze.com",
"hotmil.com",
"hotpop.com",
"hulapla.de",
"hushmail.com",
"ieatspam.eu",
"ieatspam.info",
"imails.info",
"incognitomail.com",
"incognitomail.net",
"incognitomail.org",
"instant-mail.de",
"internet.com",
"ipoo.org",
"irish2me.com",
"jetable.com",
"jetable.fr.nf",
"jetable.net",
"jetable.org",
"jsrsolutions.com",
"junk1e.com",
"jnxjn.com",
"kasmail.com",
"klassmaster.com",
"klzlk.com",
"kulturbetrieb.info",
"kurzepost.de",
"lavabit.com",
"letthemeatspam.com",
"lhsdv.com",
"lifebyfood.com",
"litedrop.com",
"lookugly.com",
"lr78.com",
"lroid.com",
"m4ilweb.info",
"mail.com",
"mail.net",
"mail.by",
"mail114.net",
"mail4trash.com",
"mailbucket.org",
"mailcatch.com",
"maileater.com",
"mailexpire.com",
"mailguard.me",
"mail-filter.com",
"mailin8r.com",
"mailinator.com",
"mailinator.net",
"mailinator.org",
"mailinator.us",
"mailinator2.com",
"mailme.lv",
"mailmetrash.com",
"mailmoat.com",
"mailnator.com",
"mailnesia.com",
"mailnull.com",
"mailquack.com",
"mailscrap.com",
"mailzilla.org",
"makemetheking.com",
"manybrain.com",
"mega.zik.dj",
"meltmail.com",
"mierdamail.com",
"migumail.com",
"mintemail.com",
"mbx.cc",
"mobileninja.co.uk",
"moburl.com",
"moncourrier.fr.nf",
"monemail.fr.nf",
"monmail.fr.nf",
"mt2009.com",
"myemailboxy.com",
"mymail-in.net",
"mypacks.net",
"mypartyclip.de",
"mytempemail.com",
"mytrashmail.com",
"nepwk.com",
"nervmich.net",
"nervtmich.net",
"nice-4u.com",
"no-spam.ws",
"nobulk.com",
"noclickemail.com",
"nogmailspam.info",
"nomail.xl.cx",
"nomail2me.com",
"none.com",
"none.net",
"nospam.ze.tc",
"nospam4.us",
"nospamfor.us",
"nospamthanks.info",
"notmailinator.com",
"nowhere.org",
"nowmymail.com",
"nwldx.com",
"objectmail.com",
"obobbo.com",
"onewaymail.com",
"otherinbox.com",
"owlpic.com",
"pcusers.otherinbox.com",
"pepbot.com",
"poczta.onet.pl",
"politikerclub.de",
"pookmail.com",
"privy-mail.com",
"proxymail.eu",
"prtnx.com",
"putthisinyourspamdatabase.com",
"qq.com",
"quickinbox.com",
"rcpt.at",
"recode.me",
"regbypass.com",
"rmqkr.net",
"royal.net",
"rppkn.com",
"rtrtr.com",
"s0ny.net",
"safe-mail.net",
"safetymail.info",
"safetypost.de",
"sample.com",
"sample.net",
"sample.org",
"saynotospams.com",
"sandelf.de",
"schafmail.de",
"selfdestructingmail.com",
"sendspamhere.com",
"sharklasers.com",
"shitmail.me",
"shitware.nl",
"sinnlos-mail.de",
"siteposter.net",
"skeefmail.com",
"slopsbox.com",
"smellfear.com",
"snakemail.com",
"sneakemail.com",
"snkmail.com",
"sofort-mail.de",
"sogetthis.com",
"spam.com",
"spam.la",
"spam.su",
"spam4.me",
"spamavert.com",
"spambob.net",
"spambob.org",
"spambog.com",
"spambog.de",
"spambox.info",
"spambog.ru",
"spambox.us",
"spamcero.com",
"spamday.com",
"spamex.com",
"spamfree24.com",
"spamfree24.de",
"spamfree24.eu",
"spamfree24.info",
"spamfree24.net",
"spamfree24.org",
"spamfree.eu",
"spamgourmet.com",
"spamherelots.com",
"spamhereplease.com",
"spamhole.com",
"spamify.com",
"spaminator.de",
"spamkill.info",
"spaml.com",
"spaml.de",
"spammotel.com",
"spamobox.com",
"spamsalad.in",
"spamspot.com",
"spamthis.co.uk",
"spamthisplease.com",
"spamtroll.net",
"speed.1s.fr",
"spoofmail.de",
"squizzy.de",
"stinkefinger.net",
"stuffmail.de",
"supergreatmail.com",
"superstachel.de",
"suremail.info",
"tagyourself.com",
"talkinator.com",
"tapchicuoihoi.com",
"teewars.org",
"teleworm.com",
"teleworm.us",
"temp.emeraldwebmail.com",
"tempalias.com",
"tempe-mail.com",
"tempemail.biz",
"tempemail.co.za",
"tempemail.com",
"tempemail.net",
"tempinbox.co.uk",
"tempinbox.com",
"tempmaildemo.com",
"tempmail.it",
"tempomail.fr",
"temporaryemail.net",
"temporaryemail.us",
"temporaryinbox.com",
"tempthe.net",
"test.com",
"test.net",
"thanksnospam.info",
"thankyou2010.com",
"thisisnotmyrealemail.com",
"throwawayemailaddress.com",
"tittbit.in",
"tmailinator.com",
"tradermail.info",
"trash2009.com",
"trash2010.com",
"trash2011.com",
"trash-amil.com",
"trash-mail.at",
"trash-mail.com",
"trash-mail.de",
"trashmail.at",
"trashmail.com",
"trashmail.me",
"trashmail.net",
"trashmail.ws",
"trashymail.com",
"trashymail.net",
"tyldd.com",
"umail.net",
"uggsrock.com",
"uroid.com",
"veryrealemail.com",
"vidchart.com",
"vubby.com",
"webemail.me",
"webm4il.info",
"weg-werf-email.de",
"wegwerf-email-addressen.de",
"wegwerf-emails.de",
"wegwerfadresse.de",
"wegwerfemail.de",
"wegwerfmail.de",
"wegwerfmail.info",
"wegwerfmail.net",
"wegwerfmail.org",
"whatiaas.com",
"whatsaas.com",
"wh4f.org",
"whyspam.me",
"willselfdestruct.com",
"winemaven.info",
"wuzupmail.net",
"www.com",
"yaho.com",
"yahoo.com.ph",
"yahoo.com.vn",
"yeah.net",
"yogamaven.com",
"yopmail.com",
"yopmail.fr",
"yopmail.net",
"yuurok.com",
"xoxy.net",
"xyzfree.net",
"za.com",
"zippymail.info",
"zoemail.net",
"zomg.info"
});
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Runtime.InteropServices;
namespace NntpClientLib
{
internal class NntpStreamReader : TextReader
{
const int DefaultBufferSize = 1024;
const int DefaultFileBufferSize = 4096;
const int MinimumBufferSize = 512;
//
// The input array
//
byte[] m_inputBuffer;
//
// The decoded array from the above input array
//
char[] m_decodedBuffer;
//
// Decoded bytes in m_decodedBuffer.
//
int m_decodedCount;
//
// Current position in the m_decodedBuffer
//
int m_currentDecodePosition;
//
// The array size that we are using
//
int m_bufferSize;
Encoding m_encoding;
Decoder m_decoder;
Stream m_baseStream;
bool m_mayBlock;
StringBuilder m_lineBuilder;
private NntpStreamReader() { }
public NntpStreamReader(Stream stream)
: this(stream, Rfc977NntpClient.DefaultEncoding, DefaultBufferSize) { }
public NntpStreamReader(Stream stream, Encoding encoding, int bufferSize)
{
Initialize(stream, encoding, bufferSize);
}
internal void Initialize(Stream stream, Encoding encoding, int bufferSize)
{
if (null == stream)
{
throw new ArgumentNullException("stream");
}
if (null == encoding)
{
throw new ArgumentNullException("encoding");
}
if (!stream.CanRead)
{
throw new ArgumentException(Resource.ErrorMessage44);
}
if (bufferSize <= 0)
{
throw new ArgumentException(Resource.ErrorMessage43, "bufferSize");
}
if (bufferSize < MinimumBufferSize)
{
bufferSize = MinimumBufferSize;
}
m_baseStream = stream;
m_inputBuffer = new byte[bufferSize];
this.m_bufferSize = bufferSize;
this.m_encoding = encoding;
m_decoder = encoding.GetDecoder();
m_decodedBuffer = new char[encoding.GetMaxCharCount(bufferSize)];
m_decodedCount = 0;
m_currentDecodePosition = 0;
}
public virtual Stream BaseStream
{
get { return m_baseStream; }
}
public virtual Encoding CurrentEncoding
{
get
{
if (m_encoding == null)
{
throw new InvalidOperationException();
}
return m_encoding;
}
}
public bool EndOfStream
{
get { return Peek() < 0; }
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && m_baseStream != null)
{
m_baseStream.Close();
}
m_inputBuffer = null;
m_decodedBuffer = null;
m_encoding = null;
m_decoder = null;
m_baseStream = null;
}
finally
{
base.Dispose(disposing);
}
}
public void DiscardBufferedData()
{
m_decoder = m_encoding.GetDecoder();
m_currentDecodePosition = 0;
m_decodedCount = 0;
m_mayBlock = false;
}
private int ReadBuffer()
{
m_currentDecodePosition = 0;
int cbEncoded = 0;
m_decodedCount = 0;
int parse_start = 0;
do
{
cbEncoded = m_baseStream.Read(m_inputBuffer, 0, m_bufferSize);
if (cbEncoded <= 0)
{
return 0;
}
m_mayBlock = (cbEncoded < m_bufferSize);
m_decodedCount += m_decoder.GetChars(m_inputBuffer, parse_start, cbEncoded, m_decodedBuffer, 0);
parse_start = 0;
} while (m_decodedCount == 0);
return m_decodedCount;
}
public override int Peek()
{
CheckObjectState();
if (m_currentDecodePosition >= m_decodedCount && (m_mayBlock || ReadBuffer() == 0))
{
return -1;
}
return m_decodedBuffer[m_currentDecodePosition];
}
public override int Read()
{
CheckObjectState();
if (m_currentDecodePosition >= m_decodedCount && ReadBuffer() == 0)
{
return -1;
}
return m_decodedBuffer[m_currentDecodePosition++];
}
public override int Read([In, Out] char[] destinationBuffer, int index, int count)
{
CheckObjectState();
if (destinationBuffer == null)
{
throw new ArgumentNullException("destinationBuffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (index > (destinationBuffer.Length - count))
{
throw new ArgumentOutOfRangeException("index");
}
int charsRead = 0;
while (count > 0)
{
if (m_currentDecodePosition >= m_decodedCount && ReadBuffer() == 0)
{
return charsRead > 0 ? charsRead : 0;
}
int cch = Math.Min(m_decodedCount - m_currentDecodePosition, count);
Array.Copy(m_decodedBuffer, m_currentDecodePosition, destinationBuffer, index, cch);
m_currentDecodePosition += cch;
index += cch;
count -= cch;
charsRead += cch;
}
return charsRead;
}
bool foundCR;
int FindNextEOL()
{
char c = '\0';
for (; m_currentDecodePosition < m_decodedCount; m_currentDecodePosition++)
{
c = m_decodedBuffer[m_currentDecodePosition];
if (c == '\n' && foundCR)
{
m_currentDecodePosition++;
int res = (m_currentDecodePosition - 2);
if (res < 0)
{
res = 0; // if a new array starts with a \n and there was a \r at the end of the previous one, we get here.
}
foundCR = false;
return res;
}
foundCR = (c == '\r');
}
return -1;
}
public override string ReadLine()
{
CheckObjectState();
if (m_currentDecodePosition >= m_decodedCount && ReadBuffer() == 0)
{
return null;
}
int begin = m_currentDecodePosition;
int end = FindNextEOL();
if (end < m_decodedCount && end >= begin)
{
return new string(m_decodedBuffer, begin, end - begin);
}
if (m_lineBuilder == null)
{
m_lineBuilder = new StringBuilder();
}
else
{
m_lineBuilder.Length = 0;
}
while (true)
{
if (foundCR) // don't include the trailing CR if present
{
m_decodedCount--;
}
m_lineBuilder.Append(m_decodedBuffer, begin, m_decodedCount - begin);
if (ReadBuffer() == 0)
{
if (m_lineBuilder.Capacity > 32768)
{
StringBuilder sb = m_lineBuilder;
m_lineBuilder = null;
return sb.ToString(0, sb.Length);
}
return m_lineBuilder.ToString(0, m_lineBuilder.Length);
}
begin = m_currentDecodePosition;
end = FindNextEOL();
if (end < m_decodedCount && end >= begin)
{
m_lineBuilder.Append(m_decodedBuffer, begin, end - begin);
if (m_lineBuilder.Capacity > 32768)
{
StringBuilder sb = m_lineBuilder;
m_lineBuilder = null;
return sb.ToString(0, sb.Length);
}
return m_lineBuilder.ToString(0, m_lineBuilder.Length);
}
}
}
public override string ReadToEnd()
{
CheckObjectState();
StringBuilder text = new StringBuilder();
int size = m_decodedBuffer.Length;
char[] buffer = new char[size];
int len;
while ((len = Read(buffer, 0, size)) > 0)
{
text.Append(buffer, 0, len);
}
return text.ToString();
}
private void CheckObjectState()
{
if (m_baseStream == null)
{
throw new InvalidOperationException(Resource.ErrorMessage45);
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.DeckProperties.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Command : IExternalCommand
{
private DeckPropertyForm m_displayForm;
private Document m_document;
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
// Get the application of revit
Autodesk.Revit.UI.UIApplication revit = commandData.Application;
m_document = revit.ActiveUIDocument.Document;
try
{
if (revit.ActiveUIDocument.Selection.Elements.IsEmpty)
{
System.Windows.Forms.MessageBox.Show("Please select one floor or slab at least.");
return Autodesk.Revit.UI.Result.Cancelled;
}
using (m_displayForm = new DeckPropertyForm())
{
List<Floor> floorList = new List<Floor>();
foreach (Element element in revit.ActiveUIDocument.Selection.Elements)
{
Floor floor = element as Floor;
if (floor != null)
{
floorList.Add(floor);
}
}
if (floorList.Count <= 0)
{
System.Windows.Forms.MessageBox.Show("Please select one floor or slab at least.");
return Autodesk.Revit.UI.Result.Cancelled;
}
foreach (Floor floor in floorList)
{
DumpSlab(floor);
}
m_displayForm.ShowDialog();
}
}
catch (Exception ex)
{
// If any error, store error information in message and return failed
message = ex.Message;
return Autodesk.Revit.UI.Result.Failed;
}
// If everything goes well, return succeeded.
return Autodesk.Revit.UI.Result.Succeeded;
}
/// <summary>
/// Dump the properties of interest for the slab passed as a parameter
/// </summary>
/// <param name="slab"></param>
private void DumpSlab(Floor slab)
{
m_displayForm.WriteLine("Dumping Slab" + slab.Id.IntegerValue.ToString());
Autodesk.Revit.DB.FloorType slabType = slab.FloorType;
if (slabType != null)
{
foreach (CompoundStructureLayer layer in slabType.GetCompoundStructure().GetLayers())
{
if (layer.Function == MaterialFunctionAssignment.StructuralDeck)
{
DumbDeck(layer);
}
else
{
DumpLayer(layer);
}
}
}
m_displayForm.WriteLine(" ");
}
/// <summary>
/// Dump properties specific to a decking layer
/// </summary>
/// <param name="deck"></param>
private void DumbDeck(CompoundStructureLayer deck)
{
m_displayForm.WriteLine("Dumping Deck");
if (deck.MaterialId != ElementId.InvalidElementId)
{
// get the deck material object. In this sample all we need to display is the
// name, but other properties are readily available from the material object.
Autodesk.Revit.DB.Material deckMaterial = m_document.get_Element(deck.MaterialId) as Material;
m_displayForm.WriteLine("Deck Material = " + deckMaterial.Name);
}
if (deck.DeckProfileId != ElementId.InvalidElementId)
{
// the deck profile is actually a family symbol from a family of profiles
Autodesk.Revit.DB.FamilySymbol deckProfile = m_document.get_Element(deck.DeckProfileId) as FamilySymbol;
// firstly display the full name as the user would see it in the user interface
// this is done in the format Family.Name and then Symbol.Name
m_displayForm.WriteLine("Deck Profile = "
+ deckProfile.Family.Name + " : " + deckProfile.Name);
// the symbol object also contains parameters that describe how the deck is
// specified. From these parameters an external application can generate
// identical decking for analysis purposes
DumpParameters(deckProfile);
}
}
/// <summary>
/// A generic parameter display method that displays all the parameters of an element
/// </summary>
/// <param name="element"></param>
private void DumpParameters(Element element)
{
foreach (Parameter parameter in element.Parameters)
{
string value = "";
switch (parameter.StorageType)
{
case Autodesk.Revit.DB.StorageType.Double:
value = parameter.AsDouble().ToString();
break;
case Autodesk.Revit.DB.StorageType.ElementId:
value = parameter.AsElementId().IntegerValue.ToString();
break;
case Autodesk.Revit.DB.StorageType.String:
value = parameter.AsString();
break;
case Autodesk.Revit.DB.StorageType.Integer:
value = parameter.AsInteger().ToString();
break;
}
m_displayForm.WriteLine(parameter.Definition.Name + " = " + value);
}
}
/// <summary>
/// for non deck layers this method is called and it displays minimal information
/// about the layer
/// </summary>
/// <param name="layer"></param>
private void DumpLayer(CompoundStructureLayer layer)
{
// Display the name of the material. More detailed material properties can
// be found form the material object
m_displayForm.WriteLine("Dumping Layer");
Autodesk.Revit.DB.Material material = m_document.get_Element(layer.MaterialId) as Material;
if (material != null)
{
m_displayForm.WriteLine("Layer material = " + material.Name);
}
// display the thickness of the layer in inches.
m_displayForm.WriteLine("Layer Thickness = " + layer.Width.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using Csla;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="F09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="F08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="F10_City"/> objects.
/// </remarks>
[Serializable]
public partial class F09_CityColl : BusinessListBase<F09_CityColl, F10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="F10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var f10_City in this)
{
if (f10_City.City_ID == city_ID)
{
Remove(f10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="F10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the F10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var f10_City in this)
{
if (f10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="F10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the F10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var f10_City in DeletedList)
{
if (f10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="F10_City"/> item of the <see cref="F09_CityColl"/> collection, based on item key properties.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="F10_City"/> object.</returns>
public F10_City FindF10_CityByParentProperties(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="F09_CityColl"/> collection.</returns>
internal static F09_CityColl NewF09_CityColl()
{
return DataPortal.CreateChild<F09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="F09_CityColl"/> object from the given list of F10_CityDto.
/// </summary>
/// <param name="data">The list of <see cref="F10_CityDto"/>.</param>
/// <returns>A reference to the fetched <see cref="F09_CityColl"/> object.</returns>
internal static F09_CityColl GetF09_CityColl(List<F10_CityDto> data)
{
F09_CityColl obj = new F09_CityColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="F09_CityColl"/> collection items from the given list of F10_CityDto.
/// </summary>
/// <param name="data">The list of <see cref="F10_CityDto"/>.</param>
private void Fetch(List<F10_CityDto> data)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(data);
OnFetchPre(args);
foreach (var dto in data)
{
Add(F10_City.GetF10_City(dto));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="F10_City"/> items on the F09_CityObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="F07_RegionColl"/> collection.</param>
internal void LoadItems(F07_RegionColl collection)
{
foreach (var item in this)
{
var obj = collection.FindF08_RegionByParentProperties(item.parent_Region_ID);
var rlce = obj.F09_CityObjects.RaiseListChangedEvents;
obj.F09_CityObjects.RaiseListChangedEvents = false;
obj.F09_CityObjects.Add(item);
obj.F09_CityObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Voodle.Web.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);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Services.LLLoginService
{
public class LLFailedLoginResponse : OpenSim.Services.Interfaces.FailedLoginResponse
{
protected string m_key;
protected string m_value;
protected string m_login;
public static LLFailedLoginResponse UserProblem;
public static LLFailedLoginResponse GridProblem;
public static LLFailedLoginResponse InventoryProblem;
public static LLFailedLoginResponse DeadRegionProblem;
public static LLFailedLoginResponse LoginBlockedProblem;
public static LLFailedLoginResponse AlreadyLoggedInProblem;
public static LLFailedLoginResponse InternalError;
static LLFailedLoginResponse()
{
UserProblem = new LLFailedLoginResponse("key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false");
GridProblem = new LLFailedLoginResponse("key",
"Error connecting to the desired location. Try connecting to another region.",
"false");
InventoryProblem = new LLFailedLoginResponse("key",
"The inventory service is not responding. Please notify your login region operator.",
"false");
DeadRegionProblem = new LLFailedLoginResponse("key",
"The region you are attempting to log into is not responding. Please select another region and try again.",
"false");
LoginBlockedProblem = new LLFailedLoginResponse("presence",
"Logins are currently restricted. Please try again later.",
"false");
AlreadyLoggedInProblem = new LLFailedLoginResponse("presence",
"You appear to be already logged in. " +
"If this is not the case please wait for your session to timeout. " +
"If this takes longer than a few minutes please contact the grid owner. " +
"Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.",
"false");
InternalError = new LLFailedLoginResponse("Internal Error", "Error generating Login Response", "false");
}
public LLFailedLoginResponse(string key, string value, string login)
{
m_key = key;
m_value = value;
m_login = login;
}
public override Hashtable ToHashtable()
{
Hashtable loginError = new Hashtable();
loginError["reason"] = m_key;
loginError["message"] = m_value;
loginError["login"] = m_login;
return loginError;
}
public override OSD ToOSDMap()
{
OSDMap map = new OSDMap();
map["reason"] = OSD.FromString(m_key);
map["message"] = OSD.FromString(m_value);
map["login"] = OSD.FromString(m_login);
return map;
}
}
/// <summary>
/// A class to handle LL login response.
/// </summary>
public class LLLoginResponse : OpenSim.Services.Interfaces.LoginResponse
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Hashtable globalTexturesHash;
// Global Textures
private static string sunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271";
private static string cloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621";
private static string moonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621";
private Hashtable loginFlagsHash;
private Hashtable uiConfigHash;
private ArrayList loginFlags;
private ArrayList globalTextures;
private ArrayList eventCategories;
private ArrayList uiConfig;
private ArrayList classifiedCategories;
private ArrayList inventoryRoot;
private ArrayList initialOutfit;
private ArrayList agentInventory;
private ArrayList inventoryLibraryOwner;
private ArrayList inventoryLibRoot;
private ArrayList inventoryLibrary;
private ArrayList activeGestures;
private UserInfo userProfile;
private UUID agentID;
private UUID sessionID;
private UUID secureSessionID;
// Login Flags
private string dst;
private string stipendSinceLogin;
private string gendered;
private string everLoggedIn;
private string login;
private uint simPort;
private uint simHttpPort;
private string simAddress;
private string agentAccess;
private string agentAccessMax;
private Int32 circuitCode;
private uint regionX;
private uint regionY;
// Login
private string firstname;
private string lastname;
// Web map
private string mapTileURL;
private string searchURL;
// Error Flags
private string errorReason;
private string errorMessage;
private string welcomeMessage;
private string startLocation;
private string allowFirstLife;
private string home;
private string seedCapability;
private string lookAt;
private BuddyList m_buddyList = null;
static LLLoginResponse()
{
// This is being set, but it's not used
// not sure why.
globalTexturesHash = new Hashtable();
globalTexturesHash["sun_texture_id"] = sunTexture;
globalTexturesHash["cloud_texture_id"] = cloudTexture;
globalTexturesHash["moon_texture_id"] = moonTexture;
}
public LLLoginResponse()
{
loginFlags = new ArrayList();
globalTextures = new ArrayList();
eventCategories = new ArrayList();
uiConfig = new ArrayList();
classifiedCategories = new ArrayList();
uiConfigHash = new Hashtable();
// defaultXmlRpcResponse = new XmlRpcResponse();
userProfile = new UserInfo();
inventoryRoot = new ArrayList();
initialOutfit = new ArrayList();
agentInventory = new ArrayList();
inventoryLibrary = new ArrayList();
inventoryLibraryOwner = new ArrayList();
activeGestures = new ArrayList();
SetDefaultValues();
}
public LLLoginResponse(UserAccount account, AgentCircuitData aCircuit, GridUserInfo pinfo,
GridRegion destination, List<InventoryFolderBase> invSkel, FriendInfo[] friendsList, ILibraryService libService,
string where, string startlocation, Vector3 position, Vector3 lookAt, List<InventoryItemBase> gestures, string message,
GridRegion home, IPEndPoint clientIP, string mapTileURL, string searchURL)
: this()
{
FillOutInventoryData(invSkel, libService);
FillOutActiveGestures(gestures);
CircuitCode = (int)aCircuit.circuitcode;
Lastname = account.LastName;
Firstname = account.FirstName;
AgentID = account.PrincipalID;
SessionID = aCircuit.SessionID;
SecureSessionID = aCircuit.SecureSessionID;
Message = message;
BuddList = ConvertFriendListItem(friendsList);
StartLocation = where;
MapTileURL = mapTileURL;
SearchURL = searchURL;
FillOutHomeData(pinfo, home);
LookAt = String.Format("[r{0},r{1},r{2}]", lookAt.X, lookAt.Y, lookAt.Z);
FillOutRegionData(destination);
FillOutSeedCap(aCircuit, destination, clientIP);
}
private void FillOutInventoryData(List<InventoryFolderBase> invSkel, ILibraryService libService)
{
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(invSkel);
}
catch (Exception e)
{
m_log.WarnFormat(
"[LLLOGIN SERVICE]: Error processing inventory skeleton of agent {0} - {1}",
agentID, e);
// ignore and continue
}
if (inventData != null)
{
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
InventorySkeleton = AgentInventoryArray;
}
// Inventory Library Section
if (libService != null && libService.LibraryRootFolder != null)
{
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
InventoryLibraryOwner = GetLibraryOwner(libService.LibraryRootFolder);
InventoryLibrary = GetInventoryLibrary(libService);
}
}
private void FillOutActiveGestures(List<InventoryItemBase> gestures)
{
ArrayList list = new ArrayList();
if (gestures != null)
{
foreach (InventoryItemBase gesture in gestures)
{
Hashtable item = new Hashtable();
item["item_id"] = gesture.ID.ToString();
item["asset_id"] = gesture.AssetID.ToString();
list.Add(item);
}
}
ActiveGestures = list;
}
private void FillOutHomeData(GridUserInfo pinfo, GridRegion home)
{
int x = 1000 * (int)Constants.RegionSize, y = 1000 * (int)Constants.RegionSize;
if (home != null)
{
x = home.RegionLocX;
y = home.RegionLocY;
}
Home = string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
x,
y,
pinfo.HomePosition.X, pinfo.HomePosition.Y, pinfo.HomePosition.Z,
pinfo.HomeLookAt.X, pinfo.HomeLookAt.Y, pinfo.HomeLookAt.Z);
}
private void FillOutRegionData(GridRegion destination)
{
IPEndPoint endPoint = destination.ExternalEndPoint;
SimAddress = endPoint.Address.ToString();
SimPort = (uint)endPoint.Port;
RegionX = (uint)destination.RegionLocX;
RegionY = (uint)destination.RegionLocY;
}
private void FillOutSeedCap(AgentCircuitData aCircuit, GridRegion destination, IPEndPoint ipepClient)
{
string capsSeedPath = String.Empty;
// Don't use the following! It Fails for logging into any region not on the same port as the http server!
// Kept here so it doesn't happen again!
// response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
#region IP Translation for NAT
if (ipepClient != null)
{
capsSeedPath
= "http://"
+ NetworkUtil.GetHostFor(ipepClient.Address, destination.ExternalHostName)
+ ":"
+ destination.HttpPort
+ CapsUtil.GetCapsSeedPath(aCircuit.CapsPath);
}
else
{
capsSeedPath
= "http://"
+ destination.ExternalHostName
+ ":"
+ destination.HttpPort
+ CapsUtil.GetCapsSeedPath(aCircuit.CapsPath);
}
#endregion
SeedCapability = capsSeedPath;
}
private void SetDefaultValues()
{
DST = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now) ? "Y" : "N";
StipendSinceLogin = "N";
Gendered = "Y";
EverLoggedIn = "Y";
login = "false";
firstname = "Test";
lastname = "User";
agentAccess = "M";
agentAccessMax = "A";
startLocation = "last";
allowFirstLife = "Y";
ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock.";
ErrorReason = "key";
welcomeMessage = "Welcome to OpenSim!";
seedCapability = String.Empty;
home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" +
userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" +
userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]";
RegionX = (uint) 255232;
RegionY = (uint) 254976;
// Classifieds;
AddClassifiedCategory((Int32) 1, "Shopping");
AddClassifiedCategory((Int32) 2, "Land Rental");
AddClassifiedCategory((Int32) 3, "Property Rental");
AddClassifiedCategory((Int32) 4, "Special Attraction");
AddClassifiedCategory((Int32) 5, "New Products");
AddClassifiedCategory((Int32) 6, "Employment");
AddClassifiedCategory((Int32) 7, "Wanted");
AddClassifiedCategory((Int32) 8, "Service");
AddClassifiedCategory((Int32) 9, "Personal");
SessionID = UUID.Random();
SecureSessionID = UUID.Random();
AgentID = UUID.Random();
Hashtable InitialOutfitHash = new Hashtable();
InitialOutfitHash["folder_name"] = "Nightclub Female";
InitialOutfitHash["gender"] = "female";
initialOutfit.Add(InitialOutfitHash);
mapTileURL = String.Empty;
searchURL = String.Empty;
}
public override Hashtable ToHashtable()
{
try
{
Hashtable responseData = new Hashtable();
loginFlagsHash = new Hashtable();
loginFlagsHash["daylight_savings"] = DST;
loginFlagsHash["stipend_since_login"] = StipendSinceLogin;
loginFlagsHash["gendered"] = Gendered;
loginFlagsHash["ever_logged_in"] = EverLoggedIn;
loginFlags.Add(loginFlagsHash);
responseData["first_name"] = Firstname;
responseData["last_name"] = Lastname;
responseData["agent_access"] = agentAccess;
responseData["agent_access_max"] = agentAccessMax;
globalTextures.Add(globalTexturesHash);
// this.eventCategories.Add(this.eventCategoriesHash);
AddToUIConfig("allow_first_life", allowFirstLife);
uiConfig.Add(uiConfigHash);
responseData["sim_port"] = (Int32) SimPort;
responseData["sim_ip"] = SimAddress;
responseData["http_port"] = (Int32)SimHttpPort;
responseData["agent_id"] = AgentID.ToString();
responseData["session_id"] = SessionID.ToString();
responseData["secure_session_id"] = SecureSessionID.ToString();
responseData["circuit_code"] = CircuitCode;
responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
responseData["login-flags"] = loginFlags;
responseData["global-textures"] = globalTextures;
responseData["seed_capability"] = seedCapability;
responseData["event_categories"] = eventCategories;
responseData["event_notifications"] = new ArrayList(); // todo
responseData["classified_categories"] = classifiedCategories;
responseData["ui-config"] = uiConfig;
if (agentInventory != null)
{
responseData["inventory-skeleton"] = agentInventory;
responseData["inventory-root"] = inventoryRoot;
}
responseData["inventory-skel-lib"] = inventoryLibrary;
responseData["inventory-lib-root"] = inventoryLibRoot;
responseData["gestures"] = activeGestures;
responseData["inventory-lib-owner"] = inventoryLibraryOwner;
responseData["initial-outfit"] = initialOutfit;
responseData["start_location"] = startLocation;
responseData["seed_capability"] = seedCapability;
responseData["home"] = home;
responseData["look_at"] = lookAt;
responseData["message"] = welcomeMessage;
responseData["region_x"] = (Int32)(RegionX);
responseData["region_y"] = (Int32)(RegionY);
if (searchURL != String.Empty)
responseData["search"] = searchURL;
if (mapTileURL != String.Empty)
responseData["map-server-url"] = mapTileURL;
if (m_buddyList != null)
{
responseData["buddy-list"] = m_buddyList.ToArray();
}
responseData["login"] = "true";
return responseData;
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating Hashtable Response: " + e.Message);
return LLFailedLoginResponse.InternalError.ToHashtable();
}
}
public override OSD ToOSDMap()
{
try
{
OSDMap map = new OSDMap();
map["first_name"] = OSD.FromString(Firstname);
map["last_name"] = OSD.FromString(Lastname);
map["agent_access"] = OSD.FromString(agentAccess);
map["agent_access_max"] = OSD.FromString(agentAccessMax);
map["sim_port"] = OSD.FromInteger(SimPort);
map["sim_ip"] = OSD.FromString(SimAddress);
map["agent_id"] = OSD.FromUUID(AgentID);
map["session_id"] = OSD.FromUUID(SessionID);
map["secure_session_id"] = OSD.FromUUID(SecureSessionID);
map["circuit_code"] = OSD.FromInteger(CircuitCode);
map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
#region Login Flags
OSDMap loginFlagsLLSD = new OSDMap();
loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST);
loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin);
loginFlagsLLSD["gendered"] = OSD.FromString(Gendered);
loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn);
map["login-flags"] = WrapOSDMap(loginFlagsLLSD);
#endregion Login Flags
#region Global Textures
OSDMap globalTexturesLLSD = new OSDMap();
globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture);
globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture);
globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture);
map["global-textures"] = WrapOSDMap(globalTexturesLLSD);
#endregion Global Textures
map["seed_capability"] = OSD.FromString(seedCapability);
map["event_categories"] = ArrayListToOSDArray(eventCategories);
//map["event_notifications"] = new OSDArray(); // todo
map["classified_categories"] = ArrayListToOSDArray(classifiedCategories);
#region UI Config
OSDMap uiConfigLLSD = new OSDMap();
uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife);
map["ui-config"] = WrapOSDMap(uiConfigLLSD);
#endregion UI Config
#region Inventory
map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory);
map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary);
map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ;
map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot);
map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner);
#endregion Inventory
map["gestures"] = ArrayListToOSDArray(activeGestures);
map["initial-outfit"] = ArrayListToOSDArray(initialOutfit);
map["start_location"] = OSD.FromString(startLocation);
map["seed_capability"] = OSD.FromString(seedCapability);
map["home"] = OSD.FromString(home);
map["look_at"] = OSD.FromString(lookAt);
map["message"] = OSD.FromString(welcomeMessage);
map["region_x"] = OSD.FromInteger(RegionX);
map["region_y"] = OSD.FromInteger(RegionY);
if (mapTileURL != String.Empty)
map["map-server-url"] = OSD.FromString(mapTileURL);
if (searchURL != String.Empty)
map["search"] = OSD.FromString(searchURL);
if (m_buddyList != null)
{
map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray());
}
map["login"] = OSD.FromString("true");
return map;
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message);
return LLFailedLoginResponse.InternalError.ToOSDMap();
}
}
public OSDArray ArrayListToOSDArray(ArrayList arrlst)
{
OSDArray llsdBack = new OSDArray();
foreach (Hashtable ht in arrlst)
{
OSDMap mp = new OSDMap();
foreach (DictionaryEntry deHt in ht)
{
mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value));
}
llsdBack.Add(mp);
}
return llsdBack;
}
private static OSDArray WrapOSDMap(OSDMap wrapMe)
{
OSDArray array = new OSDArray();
array.Add(wrapMe);
return array;
}
public void SetEventCategories(string category, string value)
{
// this.eventCategoriesHash[category] = value;
//TODO
}
public void AddToUIConfig(string itemName, string item)
{
uiConfigHash[itemName] = item;
}
public void AddClassifiedCategory(Int32 ID, string categoryName)
{
Hashtable hash = new Hashtable();
hash["category_name"] = categoryName;
hash["category_id"] = ID;
classifiedCategories.Add(hash);
// this.classifiedCategoriesHash.Clear();
}
private static LLLoginResponse.BuddyList ConvertFriendListItem(FriendInfo[] friendsList)
{
LLLoginResponse.BuddyList buddylistreturn = new LLLoginResponse.BuddyList();
foreach (FriendInfo finfo in friendsList)
{
if (finfo.TheirFlags == -1)
continue;
LLLoginResponse.BuddyList.BuddyInfo buddyitem = new LLLoginResponse.BuddyList.BuddyInfo(finfo.Friend);
buddyitem.BuddyID = finfo.Friend;
buddyitem.BuddyRightsHave = (int)finfo.TheirFlags;
buddyitem.BuddyRightsGiven = (int)finfo.MyFlags;
buddylistreturn.AddNewBuddy(buddyitem);
}
return buddylistreturn;
}
private InventoryData GetInventorySkeleton(List<InventoryFolderBase> folders)
{
UUID rootID = UUID.Zero;
ArrayList AgentInventoryArray = new ArrayList();
Hashtable TempHash;
foreach (InventoryFolderBase InvFolder in folders)
{
if (InvFolder.ParentID == UUID.Zero && InvFolder.Name == "My Inventory")
{
rootID = InvFolder.ID;
}
TempHash = new Hashtable();
TempHash["name"] = InvFolder.Name;
TempHash["parent_id"] = InvFolder.ParentID.ToString();
TempHash["version"] = (Int32)InvFolder.Version;
TempHash["type_default"] = (Int32)InvFolder.Type;
TempHash["folder_id"] = InvFolder.ID.ToString();
AgentInventoryArray.Add(TempHash);
}
return new InventoryData(AgentInventoryArray, rootID);
}
/// <summary>
/// Converts the inventory library skeleton into the form required by the rpc request.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetInventoryLibrary(ILibraryService library)
{
Dictionary<UUID, InventoryFolderImpl> rootFolders = library.GetAllFolders();
m_log.DebugFormat("[LLOGIN]: Library has {0} folders", rootFolders.Count);
//Dictionary<UUID, InventoryFolderImpl> rootFolders = new Dictionary<UUID,InventoryFolderImpl>();
ArrayList folderHashes = new ArrayList();
foreach (InventoryFolderBase folder in rootFolders.Values)
{
Hashtable TempHash = new Hashtable();
TempHash["name"] = folder.Name;
TempHash["parent_id"] = folder.ParentID.ToString();
TempHash["version"] = (Int32)folder.Version;
TempHash["type_default"] = (Int32)folder.Type;
TempHash["folder_id"] = folder.ID.ToString();
folderHashes.Add(TempHash);
}
return folderHashes;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetLibraryOwner(InventoryFolderImpl libFolder)
{
//for now create random inventory library owner
Hashtable TempHash = new Hashtable();
TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; // libFolder.Owner
ArrayList inventoryLibOwner = new ArrayList();
inventoryLibOwner.Add(TempHash);
return inventoryLibOwner;
}
public class InventoryData
{
public ArrayList InventoryArray = null;
public UUID RootFolderID = UUID.Zero;
public InventoryData(ArrayList invList, UUID rootID)
{
InventoryArray = invList;
RootFolderID = rootID;
}
}
#region Properties
public string Login
{
get { return login; }
set { login = value; }
}
public string DST
{
get { return dst; }
set { dst = value; }
}
public string StipendSinceLogin
{
get { return stipendSinceLogin; }
set { stipendSinceLogin = value; }
}
public string Gendered
{
get { return gendered; }
set { gendered = value; }
}
public string EverLoggedIn
{
get { return everLoggedIn; }
set { everLoggedIn = value; }
}
public uint SimPort
{
get { return simPort; }
set { simPort = value; }
}
public uint SimHttpPort
{
get { return simHttpPort; }
set { simHttpPort = value; }
}
public string SimAddress
{
get { return simAddress; }
set { simAddress = value; }
}
public UUID AgentID
{
get { return agentID; }
set { agentID = value; }
}
public UUID SessionID
{
get { return sessionID; }
set { sessionID = value; }
}
public UUID SecureSessionID
{
get { return secureSessionID; }
set { secureSessionID = value; }
}
public Int32 CircuitCode
{
get { return circuitCode; }
set { circuitCode = value; }
}
public uint RegionX
{
get { return regionX; }
set { regionX = value; }
}
public uint RegionY
{
get { return regionY; }
set { regionY = value; }
}
public string SunTexture
{
get { return sunTexture; }
set { sunTexture = value; }
}
public string CloudTexture
{
get { return cloudTexture; }
set { cloudTexture = value; }
}
public string MoonTexture
{
get { return moonTexture; }
set { moonTexture = value; }
}
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public string AgentAccess
{
get { return agentAccess; }
set { agentAccess = value; }
}
public string AgentAccessMax
{
get { return agentAccessMax; }
set { agentAccessMax = value; }
}
public string StartLocation
{
get { return startLocation; }
set { startLocation = value; }
}
public string LookAt
{
get { return lookAt; }
set { lookAt = value; }
}
public string SeedCapability
{
get { return seedCapability; }
set { seedCapability = value; }
}
public string ErrorReason
{
get { return errorReason; }
set { errorReason = value; }
}
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
public ArrayList InventoryRoot
{
get { return inventoryRoot; }
set { inventoryRoot = value; }
}
public ArrayList InventorySkeleton
{
get { return agentInventory; }
set { agentInventory = value; }
}
public ArrayList InventoryLibrary
{
get { return inventoryLibrary; }
set { inventoryLibrary = value; }
}
public ArrayList InventoryLibraryOwner
{
get { return inventoryLibraryOwner; }
set { inventoryLibraryOwner = value; }
}
public ArrayList InventoryLibRoot
{
get { return inventoryLibRoot; }
set { inventoryLibRoot = value; }
}
public ArrayList ActiveGestures
{
get { return activeGestures; }
set { activeGestures = value; }
}
public string Home
{
get { return home; }
set { home = value; }
}
public string MapTileURL
{
get { return mapTileURL; }
set { mapTileURL = value; }
}
public string SearchURL
{
get { return searchURL; }
set { searchURL = value; }
}
public string Message
{
get { return welcomeMessage; }
set { welcomeMessage = value; }
}
public BuddyList BuddList
{
get { return m_buddyList; }
set { m_buddyList = value; }
}
#endregion
public class UserInfo
{
public string firstname;
public string lastname;
public ulong homeregionhandle;
public Vector3 homepos;
public Vector3 homelookat;
}
public class BuddyList
{
public List<BuddyInfo> Buddies = new List<BuddyInfo>();
public void AddNewBuddy(BuddyInfo buddy)
{
if (!Buddies.Contains(buddy))
{
Buddies.Add(buddy);
}
}
public ArrayList ToArray()
{
ArrayList buddyArray = new ArrayList();
foreach (BuddyInfo buddy in Buddies)
{
buddyArray.Add(buddy.ToHashTable());
}
return buddyArray;
}
public class BuddyInfo
{
public int BuddyRightsHave = 1;
public int BuddyRightsGiven = 1;
public string BuddyID;
public BuddyInfo(string buddyID)
{
BuddyID = buddyID;
}
public BuddyInfo(UUID buddyID)
{
BuddyID = buddyID.ToString();
}
public Hashtable ToHashTable()
{
Hashtable hTable = new Hashtable();
hTable["buddy_rights_has"] = BuddyRightsHave;
hTable["buddy_rights_given"] = BuddyRightsGiven;
hTable["buddy_id"] = BuddyID;
return hTable;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace DoFactory.HeadFirst.Observer.WeatherStationObservable
{
class WeatherStationHeatIndex
{
static void Main(string[] args)
{
var weatherData = new WeatherData();
var currentConditions = new CurrentConditionsDisplay(weatherData);
var statisticsDisplay = new StatisticsDisplay(weatherData);
var forecastDisplay = new ForecastDisplay(weatherData);
var heatIndexDisplay = new HeatIndexDisplay(weatherData);
weatherData.SetMeasurements(80, 65, 30.4f);
weatherData.SetMeasurements(82, 70, 29.2f);
weatherData.SetMeasurements(78, 90, 29.2f);
// Wait for user
Console.ReadKey();
}
}
#region Observable
// This is what the Java built-in Observable class
// roughly looks like (except for the generic List)
public class Observable
{
private bool _changed;
private List<IObserver> _observers = new List<IObserver>();
public void AddObserver(IObserver observer)
{
_observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
_observers.Remove(observer);
}
public bool Changed
{
set { _changed = value; }
}
public void NotifyObservers()
{
foreach (IObserver observer in _observers)
{
observer.Update(this);
}
}
}
public class WeatherData : Observable
{
private float _temperature;
private float _humidity;
private float _pressure;
public void MeasurementsChanged()
{
Changed = true;
NotifyObservers();
}
public void SetMeasurements(float temperature, float humidity, float pressure)
{
this._temperature = temperature;
this._humidity = humidity;
this._pressure = pressure;
MeasurementsChanged();
}
public float Temperature
{
get { return _temperature; }
}
public float Humidity
{
get { return _humidity; }
}
public float Pressure
{
get { return _pressure; }
}
}
#endregion
#region Observer
// This is what the Java built-in Observer interface
// roughly looks like
public interface IObserver
{
void Update(object subject);
}
public interface IDisplayElement
{
void Display();
}
public class ForecastDisplay : IObserver, IDisplayElement
{
private float _currentPressure = 29.92f;
private float _lastPressure;
public ForecastDisplay(Observable observable)
{
observable.AddObserver(this);
}
public void Update(object subject)
{
if (subject is WeatherData)
{
WeatherData weatherData = (WeatherData)subject;
_lastPressure = _currentPressure;
_currentPressure = weatherData.Pressure;
Display();
}
}
public void Display()
{
Console.Write("Forecast: ");
if (_currentPressure > _lastPressure)
{
Console.WriteLine("Improving weather on the way!");
}
else if (_currentPressure == _lastPressure)
{
Console.WriteLine("More of the same");
}
else if (_currentPressure < _lastPressure)
{
Console.WriteLine("Watch out for cooler, rainy weather");
}
}
}
public class HeatIndexDisplay : IObserver, IDisplayElement
{
private float _heatIndex = 0.0f;
public HeatIndexDisplay(Observable observable)
{
observable.AddObserver(this);
}
public void Update(object subject)
{
if (subject is WeatherData)
{
WeatherData weatherData = (WeatherData)subject;
float t = weatherData.Temperature;
float rh = weatherData.Humidity;
_heatIndex = (float)
(
(16.923 + (0.185212 * t)) +
(5.37941 * rh) -
(0.100254 * t * rh) +
(0.00941695 * (t * t)) +
(0.00728898 * (rh * rh)) +
(0.000345372 * (t * t * rh)) -
(0.000814971 * (t * rh * rh)) +
(0.0000102102 * (t * t * rh * rh)) -
(0.000038646 * (t * t * t)) +
(0.0000291583 * (rh * rh * rh)) +
(0.00000142721 * (t * t * t * rh)) +
(0.000000197483 * (t * rh * rh * rh)) -
(0.0000000218429 * (t * t * t * rh * rh)) +
(0.000000000843296 * (t * t * rh * rh * rh)) -
(0.0000000000481975 * (t * t * t * rh * rh * rh)));
Display();
}
}
public void Display()
{
Console.WriteLine("Heat index is " + _heatIndex + "\n");
}
}
public class StatisticsDisplay : IObserver, IDisplayElement
{
private float _maxTemp = 0.0f;
private float _minTemp = 200;
private float _tempSum = 0.0f;
private int _numReadings;
public StatisticsDisplay(Observable observable)
{
observable.AddObserver(this);
}
public void Update(object subject)
{
if (subject is WeatherData)
{
WeatherData weatherData = (WeatherData)subject;
float temp = weatherData.Temperature;
_tempSum += temp;
_numReadings++;
if (temp > _maxTemp)
{
_maxTemp = temp;
}
if (temp < _minTemp)
{
_minTemp = temp;
}
Display();
}
}
public void Display()
{
Console.WriteLine("Avg/Max/Min temperature = " + (_tempSum / _numReadings)
+ "/" + _maxTemp + "/" + _minTemp);
}
}
public class CurrentConditionsDisplay : IObserver, IDisplayElement
{
private Observable _observable;
private float _temperature;
private float _humidity;
public CurrentConditionsDisplay(Observable observable)
{
this._observable = observable;
observable.AddObserver(this);
}
public void Update(object subject)
{
if (subject is WeatherData)
{
WeatherData weatherData = (WeatherData)subject;
this._temperature = weatherData.Temperature;
this._humidity = weatherData.Humidity;
Display();
}
}
public void Display()
{
Console.WriteLine("Current conditions: " + _temperature
+ "F degrees and " + _humidity + "% humidity");
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Security
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Util;
using System.Text;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
internal enum SecurityElementType
{
Regular = 0,
Format = 1,
Comment = 2
}
internal interface ISecurityElementFactory
{
SecurityElement CreateSecurityElement();
Object Copy();
String GetTag();
String Attribute( String attributeName );
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SecurityElement : ISecurityElementFactory
{
internal String m_strTag;
internal String m_strText;
private ArrayList m_lChildren;
internal ArrayList m_lAttributes;
internal SecurityElementType m_type = SecurityElementType.Regular;
private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' };
private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' };
private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' };
private const String s_strIndent = " ";
private const int c_AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute
private const int c_ChildrenTypical = 1;
private static readonly String[] s_escapeStringPairs = new String[]
{
// these must be all once character escape sequences or a new escaping algorithm is needed
"<", "<",
">", ">",
"\"", """,
"\'", "'",
"&", "&"
};
private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
//-------------------------- Constructors ---------------------------
internal SecurityElement()
{
}
////// ISecurityElementFactory implementation
SecurityElement ISecurityElementFactory.CreateSecurityElement()
{
return this;
}
String ISecurityElementFactory.GetTag()
{
return ((SecurityElement)this).Tag;
}
Object ISecurityElementFactory.Copy()
{
return ((SecurityElement)this).Copy();
}
String ISecurityElementFactory.Attribute( String attributeName )
{
return ((SecurityElement)this).Attribute( attributeName );
}
//////////////
#if FEATURE_CAS_POLICY
public static SecurityElement FromString( String xml )
{
if (xml == null)
throw new ArgumentNullException( "xml" );
Contract.EndContractBlock();
return new Parser( xml ).GetTopElement();
}
#endif // FEATURE_CAS_POLICY
public SecurityElement( String tag )
{
if (tag == null)
throw new ArgumentNullException( "tag" );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = null;
}
public SecurityElement( String tag, String text )
{
if (tag == null)
throw new ArgumentNullException( "tag" );
if (!IsValidTag( tag ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), tag ) );
if (text != null && !IsValidText( text ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementText" ), text ) );
Contract.EndContractBlock();
m_strTag = tag;
m_strText = text;
}
//-------------------------- Properties -----------------------------
public String Tag
{
[Pure]
get
{
return m_strTag;
}
set
{
if (value == null)
throw new ArgumentNullException( "Tag" );
if (!IsValidTag( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
Contract.EndContractBlock();
m_strTag = value;
}
}
public Hashtable Attributes
{
get
{
if (m_lAttributes == null || m_lAttributes.Count == 0)
{
return null;
}
else
{
Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
hashtable.Add( m_lAttributes[i], m_lAttributes[i+1]);
}
return hashtable;
}
}
set
{
if (value == null || value.Count == 0)
{
m_lAttributes = null;
}
else
{
ArrayList list = new ArrayList(value.Count);
System.Collections.IDictionaryEnumerator enumerator = (System.Collections.IDictionaryEnumerator)value.GetEnumerator();
while (enumerator.MoveNext())
{
String attrName = (String)enumerator.Key;
String attrValue = (String)enumerator.Value;
if (!IsValidAttributeName( attrName ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), (String)enumerator.Current ) );
if (!IsValidAttributeValue( attrValue ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), (String)enumerator.Value ) );
list.Add(attrName);
list.Add(attrValue);
}
m_lAttributes = list;
}
}
}
public String Text
{
get
{
return Unescape( m_strText );
}
set
{
if (value == null)
{
m_strText = null;
}
else
{
if (!IsValidText( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementTag" ), value ) );
m_strText = value;
}
}
}
public ArrayList Children
{
get
{
ConvertSecurityElementFactories();
return m_lChildren;
}
set
{
if (value != null)
{
IEnumerator enumerator = value.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current == null)
throw new ArgumentException( Environment.GetResourceString( "ArgumentNull_Child" ) );
}
}
m_lChildren = value;
}
}
internal void ConvertSecurityElementFactories()
{
if (m_lChildren == null)
return;
for (int i = 0; i < m_lChildren.Count; ++i)
{
ISecurityElementFactory iseFactory = m_lChildren[i] as ISecurityElementFactory;
if (iseFactory != null && !(m_lChildren[i] is SecurityElement))
m_lChildren[i] = iseFactory.CreateSecurityElement();
}
}
internal ArrayList InternalChildren
{
get
{
// Beware! This array list can contain SecurityElements and other ISecurityElementFactories.
// If you want to get a consistent SecurityElement view, call get_Children.
return m_lChildren;
}
}
//-------------------------- Public Methods -----------------------------
internal void AddAttributeSafe( String name, String value )
{
if (m_lAttributes == null)
{
m_lAttributes = new ArrayList( c_AttributesTypical );
}
else
{
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
throw new ArgumentException( Environment.GetResourceString( "Argument_AttributeNamesMustBeUnique" ) );
}
}
m_lAttributes.Add(name);
m_lAttributes.Add(value);
}
public void AddAttribute( String name, String value )
{
if (name == null)
throw new ArgumentNullException( "name" );
if (value == null)
throw new ArgumentNullException( "value" );
if (!IsValidAttributeName( name ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementName" ), name ) );
if (!IsValidAttributeValue( value ))
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidElementValue" ), value ) );
Contract.EndContractBlock();
AddAttributeSafe( name, value );
}
public void AddChild( SecurityElement child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChild( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
internal void AddChildNoDuplicates( ISecurityElementFactory child )
{
if (child == null)
throw new ArgumentNullException( "child" );
Contract.EndContractBlock();
if (m_lChildren == null)
{
m_lChildren = new ArrayList( c_ChildrenTypical );
m_lChildren.Add( child );
}
else
{
for (int i = 0; i < m_lChildren.Count; ++i)
{
if (m_lChildren[i] == child)
return;
}
m_lChildren.Add( child );
}
}
public bool Equal( SecurityElement other )
{
if (other == null)
return false;
// Check if the tags are the same
if (!String.Equals(m_strTag, other.m_strTag))
return false;
// Check if the text is the same
if (!String.Equals(m_strText, other.m_strText))
return false;
// Check if the attributes are the same and appear in the same
// order.
// Maybe we can get away by only checking the number of attributes
if (m_lAttributes == null || other.m_lAttributes == null)
{
if (m_lAttributes != other.m_lAttributes)
return false;
}
else
{
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
if (iMax != other.m_lAttributes.Count)
return false;
for (int i = 0; i < iMax; i++)
{
String lhs = (String)m_lAttributes[i];
String rhs = (String)other.m_lAttributes[i];
if (!String.Equals(lhs, rhs))
return false;
}
}
// Finally we must check the child and make sure they are
// equal and in the same order
// Maybe we can get away by only checking the number of children
if (m_lChildren == null || other.m_lChildren == null)
{
if (m_lChildren != other.m_lChildren)
return false;
}
else
{
if (m_lChildren.Count != other.m_lChildren.Count)
return false;
this.ConvertSecurityElementFactories();
other.ConvertSecurityElementFactories();
// Okay, we'll need to go through each one of them
IEnumerator lhs = m_lChildren.GetEnumerator();
IEnumerator rhs = other.m_lChildren.GetEnumerator();
SecurityElement e1, e2;
while (lhs.MoveNext())
{
rhs.MoveNext();
e1 = (SecurityElement)lhs.Current;
e2 = (SecurityElement)rhs.Current;
if (e1 == null || !e1.Equal(e2))
return false;
}
}
return true;
}
[System.Runtime.InteropServices.ComVisible(false)]
public SecurityElement Copy()
{
SecurityElement element = new SecurityElement( this.m_strTag, this.m_strText );
element.m_lChildren = this.m_lChildren == null ? null : new ArrayList( this.m_lChildren );
element.m_lAttributes = this.m_lAttributes == null ? null : new ArrayList(this.m_lAttributes);
return element;
}
[Pure]
public static bool IsValidTag( String tag )
{
if (tag == null)
return false;
return tag.IndexOfAny( s_tagIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidText( String text )
{
if (text == null)
return false;
return text.IndexOfAny( s_textIllegalCharacters ) == -1;
}
[Pure]
public static bool IsValidAttributeName( String name )
{
return IsValidTag( name );
}
[Pure]
public static bool IsValidAttributeValue( String value )
{
if (value == null)
return false;
return value.IndexOfAny( s_valueIllegalCharacters ) == -1;
}
private static String GetEscapeSequence( char c )
{
int iMax = s_escapeStringPairs.Length;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
if (strEscSeq[0] == c)
return strEscValue;
}
Contract.Assert( false, "Unable to find escape sequence for this character" );
return c.ToString();
}
public static String Escape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
do
{
index = str.IndexOfAny( s_escapeChars, newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append( str, newIndex, index - newIndex );
sb.Append( GetEscapeSequence( str[index] ) );
newIndex = ( index + 1 );
}
}
while (true);
// no normal exit is possible
}
private static String GetUnescapeSequence( String str, int index, out int newIndex )
{
int maxCompareLength = str.Length - index;
int iMax = s_escapeStringPairs.Length;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strEscSeq = s_escapeStringPairs[i];
String strEscValue = s_escapeStringPairs[i+1];
int length = strEscValue.Length;
if (length <= maxCompareLength && String.Compare( strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0)
{
newIndex = index + strEscValue.Length;
return strEscSeq;
}
}
newIndex = index + 1;
return str[index].ToString();
}
private static String Unescape( String str )
{
if (str == null)
return null;
StringBuilder sb = null;
int strLen = str.Length;
int index; // Pointer into the string that indicates the location of the current '&' character
int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed).
do
{
index = str.IndexOf( '&', newIndex );
if (index == -1)
{
if (sb == null)
return str;
else
{
sb.Append( str, newIndex, strLen - newIndex );
return sb.ToString();
}
}
else
{
if (sb == null)
sb = new StringBuilder();
sb.Append(str, newIndex, index - newIndex);
sb.Append( GetUnescapeSequence( str, index, out newIndex ) ); // updates the newIndex too
}
}
while (true);
// C# reports a warning if I leave this in, but I still kinda want to just in case.
// Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" );
// return str;
}
private delegate void ToStringHelperFunc( Object obj, String str );
private static void ToStringHelperStringBuilder( Object obj, String str )
{
((StringBuilder)obj).Append( str );
}
private static void ToStringHelperStreamWriter( Object obj, String str )
{
((StreamWriter)obj).Write( str );
}
public override String ToString ()
{
StringBuilder sb = new StringBuilder();
ToString( "", sb, new ToStringHelperFunc( ToStringHelperStringBuilder ) );
return sb.ToString();
}
internal void ToWriter( StreamWriter writer )
{
ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) );
}
private void ToString( String indent, Object obj, ToStringHelperFunc func )
{
// First add the indent
// func( obj, indent );
// Add in the opening bracket and the tag.
func( obj, "<" );
switch (m_type)
{
case SecurityElementType.Format:
func( obj, "?" );
break;
case SecurityElementType.Comment:
func( obj, "!" );
break;
default:
break;
}
func( obj, m_strTag );
// If there are any attributes, plop those in.
if (m_lAttributes != null && m_lAttributes.Count > 0)
{
func( obj, " " );
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
String strAttrValue = (String)m_lAttributes[i+1];
func( obj, strAttrName );
func( obj, "=\"" );
func( obj, strAttrValue );
func( obj, "\"" );
if (i != m_lAttributes.Count - 2)
{
if (m_type == SecurityElementType.Regular)
{
func( obj, Environment.NewLine );
}
else
{
func( obj, " " );
}
}
}
}
if (m_strText == null && (m_lChildren == null || m_lChildren.Count == 0))
{
// If we are a single tag with no children, just add the end of tag text.
switch (m_type)
{
case SecurityElementType.Comment:
func( obj, ">" );
break;
case SecurityElementType.Format:
func( obj, " ?>" );
break;
default:
func( obj, "/>" );
break;
}
func( obj, Environment.NewLine );
}
else
{
// Close the current tag.
func( obj, ">" );
// Output the text
func( obj, m_strText );
// Output any children.
if (m_lChildren != null)
{
this.ConvertSecurityElementFactories();
func( obj, Environment.NewLine );
// String childIndent = indent + s_strIndent;
for (int i = 0; i < m_lChildren.Count; ++i)
{
((SecurityElement)m_lChildren[i]).ToString( "", obj, func );
}
// In the case where we have children, the close tag will not be on the same line as the
// opening tag, so we need to indent.
// func( obj, indent );
}
// Output the closing tag
func( obj, "</" );
func( obj, m_strTag );
func( obj, ">" );
func( obj, Environment.NewLine );
}
}
public String Attribute( String name )
{
if (name == null)
throw new ArgumentNullException( "name" );
Contract.EndContractBlock();
// Note: we don't check for validity here because an
// if an invalid name is passed we simply won't find it.
if (m_lAttributes == null)
return null;
// Go through all the attribute and see if we know about
// the one we are asked for
int iMax = m_lAttributes.Count;
Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
String strAttrName = (String)m_lAttributes[i];
if (String.Equals(strAttrName, name))
{
String strAttrValue = (String)m_lAttributes[i+1];
return Unescape(strAttrValue);
}
}
// In the case where we didn't find it, we are expected to
// return null
return null;
}
public SecurityElement SearchForChildByTag( String tag )
{
// Go through all the children and see if we can
// find the one are are asked for (matching tags)
if (tag == null)
throw new ArgumentNullException( "tag" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
SecurityElement current = (SecurityElement)enumerator.Current;
if (current != null && String.Equals(current.Tag, tag))
return current;
}
return null;
}
#if FEATURE_CAS_POLICY
internal IPermission ToPermission(bool ignoreTypeLoadFailures)
{
IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures );
if (ip == null)
return null;
ip.FromXml(this);
// Get the permission token here to ensure that the token
// type is updated appropriately now that we've loaded the type.
PermissionToken token = PermissionToken.GetToken( ip );
Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned");
return ip;
}
[System.Security.SecurityCritical] // auto-generated
internal Object ToSecurityObject()
{
switch (m_strTag)
{
case "PermissionSet":
PermissionSet pset = new PermissionSet(PermissionState.None);
pset.FromXml(this);
return pset;
default:
return ToPermission(false);
}
}
#endif // FEATURE_CAS_POLICY
internal String SearchForTextOfLocalName(String strLocalName)
{
// Search on each child in order and each
// child's child, depth-first
if (strLocalName == null)
throw new ArgumentNullException( "strLocalName" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (m_strTag == null) return null;
if (m_strTag.Equals( strLocalName ) || m_strTag.EndsWith( ":" + strLocalName, StringComparison.Ordinal ))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfLocalName( strLocalName );
if (current != null)
return current;
}
return null;
}
public String SearchForTextOfTag( String tag )
{
// Search on each child in order and each
// child's child, depth-first
if (tag == null)
throw new ArgumentNullException( "tag" );
Contract.EndContractBlock();
// Note: we don't check for a valid tag here because
// an invalid tag simply won't be found.
// First we check this.
if (String.Equals(m_strTag, tag))
return Unescape( m_strText );
if (m_lChildren == null)
return null;
IEnumerator enumerator = m_lChildren.GetEnumerator();
this.ConvertSecurityElementFactories();
while (enumerator.MoveNext())
{
String current = ((SecurityElement)enumerator.Current).SearchForTextOfTag( tag );
if (current != null)
return current;
}
return null;
}
}
}
| |
//
// Copyright 2012-2013, 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.Net;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Linq;
using System.Text;
using System.Threading;
using Xamarin.Utilities;
namespace Xamarin.Auth
{
/// <summary>
/// An HTTP web request that provides a convenient way to make authenticated
/// requests using account objects obtained from an authenticator.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class Request
#else
public class Request
#endif
{
HttpRequestMessage request;
/// <summary>
/// The HTTP method.
/// </summary>
/// <value>A string representing the HTTP method to be used with this request.</value>
public string Method { get; protected set; }
/// <summary>
/// The URL of the resource to request.
/// </summary>
public Uri Url { get; protected set; }
/// <summary>
/// The parameters of the request. These will be added to the query string of the
/// URL for GET requests, encoded as form a parameters for POSTs, and added as
/// multipart values if the request uses <see cref="Multiparts"/>.
/// </summary>
public IDictionary<string, string> Parameters { get; protected set; }
/// <summary>
/// The account that will be used to authenticate this request.
/// </summary>
public virtual Account Account { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.Request"/> class.
/// </summary>
/// <param name='method'>
/// The HTTP method.
/// </param>
/// <param name='url'>
/// The URL.
/// </param>
/// <param name='parameters'>
/// Parameters that will pre-populate the <see cref="Parameters"/> property or null.
/// </param>
/// <param name='account'>
/// The account used to authenticate this request.
/// </param>
public Request (string method, Uri url, IDictionary<string, string> parameters = null, Account account = null)
{
Method = method;
Url = url;
Parameters = parameters == null ?
new Dictionary<string, string> () :
new Dictionary<string, string> (parameters);
Account = account;
}
/// <summary>
/// A single part of a multipart request.
/// </summary>
protected class Part
{
/// <summary>
/// The data.
/// </summary>
public Stream Data;
/// <summary>
/// The optional textual representation of the <see cref="Data"/>.
/// </summary>
public string TextData;
/// <summary>
/// The name.
/// </summary>
public string Name;
/// <summary>
/// The MIME type.
/// </summary>
public string MimeType;
/// <summary>
/// The filename of this part if it represents a file.
/// </summary>
public string Filename;
}
/// <summary>
/// The parts of a multipart request.
/// </summary>
protected readonly List<Part> Multiparts = new List<Part> ();
/// <summary>
/// Adds a part to the request. Doing so will make this request be sent as multipart/form-data.
/// </summary>
/// <param name='name'>
/// Name of the part.
/// </param>
/// <param name='data'>
/// Text value of the part.
/// </param>
public void AddMultipartData (string name, string data)
{
Multiparts.Add (new Part {
TextData = data,
Data = new MemoryStream (Encoding.UTF8.GetBytes (data)),
Name = name,
MimeType = "",
Filename = "",
});
}
/// <summary>
/// Adds a part to the request. Doing so will make this request be sent as multipart/form-data.
/// </summary>
/// <param name='name'>
/// Name of the part.
/// </param>
/// <param name='data'>
/// Data used when transmitting this part.
/// </param>
/// <param name='mimeType'>
/// The MIME type of this part.
/// </param>
/// <param name='filename'>
/// The filename of this part if it represents a file.
/// </param>
public virtual void AddMultipartData (string name, Stream data, string mimeType = "", string filename = "")
{
Multiparts.Add (new Part {
Data = data,
Name = name,
MimeType = mimeType,
Filename = filename,
});
}
/// <summary>
/// Gets the response.
/// </summary>
/// <returns>
/// The response.
/// </returns>
public virtual Task<Response> GetResponseAsync ()
{
return GetResponseAsync (CancellationToken.None);
}
/// <summary>
/// Gets the response.
/// </summary>
/// <remarks>
/// Service implementors should override this method to modify the PreparedWebRequest
/// to authenticate it.
/// </remarks>
/// <param name="cancellationToken"></param>
/// <returns>
/// The response.
/// </returns>
public virtual async Task<Response> GetResponseAsync (CancellationToken cancellationToken)
{
HttpClient client = new HttpClient();
var httpRequest = GetPreparedWebRequest ();
httpRequest.Headers.ExpectContinue = false;
if (Multiparts.Count > 0) {
var boundary = "---------------------------" + new Random ().Next ();
var content = new MultipartFormDataContent (boundary);
foreach (Part part in Multiparts) {
var partContent = new StreamContent (part.Data);
partContent.Headers.ContentDisposition = new ContentDispositionHeaderValue ("form-data");
partContent.Headers.ContentDisposition.FileName = part.Filename;
partContent.Headers.ContentType = new MediaTypeHeaderValue (part.MimeType);
content.Add (partContent);
}
httpRequest.Content = content;
} else if (Method == "POST" && Parameters.Count > 0) {
httpRequest.Content = new FormUrlEncodedContent (Parameters);
}
HttpResponseMessage response = await client.SendAsync (httpRequest, cancellationToken).ConfigureAwait (false);
return new Response (response);
}
static readonly byte[] CrLf = new byte[] { (byte)'\r', (byte)'\n' };
static readonly byte[] DashDash = new byte[] { (byte)'-', (byte)'-' };
/// <summary>
/// Gets the prepared URL.
/// </summary>
/// <remarks>
/// Service implementors should override this function and add any needed parameters
/// from the Account to the URL before it is used to get the response.
/// </remarks>
/// <returns>
/// The prepared URL.
/// </returns>
protected virtual Uri GetPreparedUrl ()
{
var url = Url.AbsoluteUri;
if (Parameters.Count > 0 && Method != "POST") {
#if !PORTABLE
var head = Url.AbsoluteUri.Contains ('?') ? "&" : "?";
#else
var head = Url.AbsoluteUri.Contains("?") ? "&" : "?";
#endif
foreach (var p in Parameters) {
url += head;
url += Uri.EscapeDataString (p.Key);
url += "=";
url += Uri.EscapeDataString (p.Value);
head = "&";
}
}
return new Uri (url);
}
/// <summary>
/// Returns the <see cref="T:System.Net.HttpWebRequest"/> that will be used for this <see cref="T:Xamarin.Auth.Request"/>. All properties
/// should be set to their correct values before accessing this object.
/// </summary>
/// <remarks>
/// Service implementors should modify the returned request to add whatever
/// authentication data is needed before getting the response.
/// </remarks>
/// <returns>
/// The prepared HTTP web request.
/// </returns>
protected virtual HttpRequestMessage GetPreparedWebRequest ()
{
Uri preparedUrl = null;
if (request == null) {
preparedUrl = GetPreparedUrl();
request = new HttpRequestMessage (GetMethod (Method), preparedUrl);
}
if (Account != null && !request.Headers.Contains ("Cookie")) {
if (preparedUrl == null)
preparedUrl = GetPreparedUrl();
CookieCollection cookies = Account.Cookies.GetCookies (preparedUrl);
if (cookies.Count > 0)
request.Headers.Add ("Cookie", Account.Cookies.GetCookieHeader (preparedUrl));
}
return request;
}
static HttpMethod GetMethod (string method)
{
method = method.ToUpper();
switch (method) {
case "GET":
return HttpMethod.Get;
case "POST":
return HttpMethod.Post;
case "PUT":
return HttpMethod.Put;
case "HEAD":
return HttpMethod.Head;
case "DELETE":
return HttpMethod.Delete;
case "TRACE":
return HttpMethod.Trace;
case "OPTIONS":
return HttpMethod.Options;
default:
throw new ArgumentException ("method");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace System.Runtime
{
internal class BufferedOutputStream : Stream
{
[Fx.Tag.Cache(typeof(byte), Fx.Tag.CacheAttrition.None, Scope = Fx.Tag.Strings.ExternallyManaged,
SizeLimit = Fx.Tag.Strings.ExternallyManaged)]
private InternalBufferManager _bufferManager;
[Fx.Tag.Queue(typeof(byte), SizeLimit = "BufferedOutputStream(maxSize)",
StaleElementsRemovedImmediately = true, EnqueueThrowsIfFull = true)]
private byte[][] _chunks;
private int _chunkCount;
private byte[] _currentChunk;
private int _currentChunkSize;
private int _maxSize;
private int _maxSizeQuota;
private int _totalSize;
private bool _callerReturnsBuffer;
private bool _bufferReturned;
private bool _initialized;
// requires an explicit call to Init() by the caller
public BufferedOutputStream()
{
_chunks = new byte[4][];
}
public BufferedOutputStream(int initialSize, int maxSize, InternalBufferManager bufferManager)
: this()
{
Reinitialize(initialSize, maxSize, bufferManager);
}
public BufferedOutputStream(int maxSize)
: this(0, maxSize, InternalBufferManager.Create(0, int.MaxValue))
{
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
return _totalSize;
}
}
public override long Position
{
get
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.SeekNotSupported));
}
set
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.SeekNotSupported));
}
}
public void Reinitialize(int initialSize, int maxSizeQuota, InternalBufferManager bufferManager)
{
Reinitialize(initialSize, maxSizeQuota, maxSizeQuota, bufferManager);
}
public void Reinitialize(int initialSize, int maxSizeQuota, int effectiveMaxSize, InternalBufferManager bufferManager)
{
Fx.Assert(!_initialized, "Clear must be called before re-initializing stream");
_maxSizeQuota = maxSizeQuota;
_maxSize = effectiveMaxSize;
_bufferManager = bufferManager;
_currentChunk = bufferManager.TakeBuffer(initialSize);
_currentChunkSize = 0;
_totalSize = 0;
_chunkCount = 1;
_chunks[0] = _currentChunk;
_initialized = true;
}
private void AllocNextChunk(int minimumChunkSize)
{
int newChunkSize;
if (_currentChunk.Length > (int.MaxValue / 2))
{
newChunkSize = int.MaxValue;
}
else
{
newChunkSize = _currentChunk.Length * 2;
}
if (minimumChunkSize > newChunkSize)
{
newChunkSize = minimumChunkSize;
}
byte[] newChunk = _bufferManager.TakeBuffer(newChunkSize);
if (_chunkCount == _chunks.Length)
{
byte[][] newChunks = new byte[_chunks.Length * 2][];
Array.Copy(_chunks, newChunks, _chunks.Length);
_chunks = newChunks;
}
_chunks[_chunkCount++] = newChunk;
_currentChunk = newChunk;
_currentChunkSize = 0;
}
public void Clear()
{
if (!_callerReturnsBuffer)
{
for (int i = 0; i < _chunkCount; i++)
{
_bufferManager.ReturnBuffer(_chunks[i]);
_chunks[i] = null;
}
}
_callerReturnsBuffer = false;
_initialized = false;
_bufferReturned = false;
_chunkCount = 0;
_currentChunk = null;
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int size)
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.ReadNotSupported));
}
public override int ReadByte()
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.ReadNotSupported));
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.SeekNotSupported));
}
public override void SetLength(long value)
{
throw Fx.Exception.AsError(new NotSupportedException(InternalSR.SeekNotSupported));
}
public MemoryStream ToMemoryStream()
{
int bufferSize;
byte[] buffer = ToArray(out bufferSize);
return new MemoryStream(buffer, 0, bufferSize);
}
public byte[] ToArray(out int bufferSize)
{
Fx.Assert(_initialized, "No data to return from uninitialized stream");
Fx.Assert(!_bufferReturned, "ToArray cannot be called more than once");
byte[] buffer;
if (_chunkCount == 1)
{
buffer = _currentChunk;
bufferSize = _currentChunkSize;
_callerReturnsBuffer = true;
}
else
{
buffer = _bufferManager.TakeBuffer(_totalSize);
int offset = 0;
int count = _chunkCount - 1;
for (int i = 0; i < count; i++)
{
byte[] chunk = _chunks[i];
Buffer.BlockCopy(chunk, 0, buffer, offset, chunk.Length);
offset += chunk.Length;
}
Buffer.BlockCopy(_currentChunk, 0, buffer, offset, _currentChunkSize);
bufferSize = _totalSize;
}
_bufferReturned = true;
return buffer;
}
public void Skip(int size)
{
WriteCore(null, 0, size);
}
public override void Write(byte[] buffer, int offset, int size)
{
WriteCore(buffer, offset, size);
}
protected virtual Exception CreateQuotaExceededException(int maxSizeQuota)
{
return new InvalidOperationException(InternalSR.BufferedOutputStreamQuotaExceeded(maxSizeQuota));
}
private void WriteCore(byte[] buffer, int offset, int size)
{
Fx.Assert(_initialized, "Cannot write to uninitialized stream");
Fx.Assert(!_bufferReturned, "Cannot write to stream once ToArray has been called.");
if (size < 0)
{
throw Fx.Exception.ArgumentOutOfRange("size", size, InternalSR.ValueMustBeNonNegative);
}
if ((int.MaxValue - size) < _totalSize)
{
throw Fx.Exception.AsError(CreateQuotaExceededException(_maxSizeQuota));
}
int newTotalSize = _totalSize + size;
if (newTotalSize > _maxSize)
{
throw Fx.Exception.AsError(CreateQuotaExceededException(_maxSizeQuota));
}
int remainingSizeInChunk = _currentChunk.Length - _currentChunkSize;
if (size > remainingSizeInChunk)
{
if (remainingSizeInChunk > 0)
{
if (buffer != null)
{
Buffer.BlockCopy(buffer, offset, _currentChunk, _currentChunkSize, remainingSizeInChunk);
}
_currentChunkSize = _currentChunk.Length;
offset += remainingSizeInChunk;
size -= remainingSizeInChunk;
}
AllocNextChunk(size);
}
if (buffer != null)
{
Buffer.BlockCopy(buffer, offset, _currentChunk, _currentChunkSize, size);
}
_totalSize = newTotalSize;
_currentChunkSize += size;
}
public override void WriteByte(byte value)
{
Fx.Assert(_initialized, "Cannot write to uninitialized stream");
Fx.Assert(!_bufferReturned, "Cannot write to stream once ToArray has been called.");
if (_totalSize == _maxSize)
{
throw Fx.Exception.AsError(CreateQuotaExceededException(_maxSize));
}
if (_currentChunkSize == _currentChunk.Length)
{
AllocNextChunk(1);
}
_currentChunk[_currentChunkSize++] = value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Http;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Tests
{
public class HttpWebRequestTest
{
private const string RequestBody = "This is data to POST.";
private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody);
private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain");
private HttpWebRequest _savedHttpWebRequest = null;
private WebHeaderCollection _savedResponseHeaders = null;
private Exception _savedRequestStreamException = null;
private Exception _savedResponseException = null;
private int _requestStreamCallbackCallCount = 0;
private int _responseCallbackCallCount = 0;
private readonly ITestOutputHelper _output;
public readonly static object[][] EchoServers = Configuration.Http.EchoServers;
public HttpWebRequestTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_VerifyDefaults_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Null(request.Accept);
Assert.False(request.AllowReadStreamBuffering);
Assert.Null(request.ContentType);
Assert.Equal(350, request.ContinueTimeout);
Assert.Null(request.CookieContainer);
Assert.Null(request.Credentials);
Assert.False(request.HaveResponse);
Assert.NotNull(request.Headers);
Assert.Equal(0, request.Headers.Count);
Assert.Equal("GET", request.Method);
Assert.NotNull(request.Proxy);
Assert.Equal(remoteServer, request.RequestUri);
Assert.True(request.SupportsCookieContainer);
Assert.False(request.UseDefaultCredentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer)
{
string remoteServerString = remoteServer.ToString();
HttpWebRequest request = WebRequest.CreateHttp(remoteServerString);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string acceptType = "*/*";
request.Accept = acceptType;
Assert.Equal(acceptType, request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = string.Empty;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Accept = null;
Assert.Null(request.Accept);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = false;
Assert.False(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.AllowReadStreamBuffering = true;
Assert.True(request.AllowReadStreamBuffering);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
long length = response.ContentLength;
Assert.Equal(strContent.Length, length);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
string myContent = "application/x-www-form-urlencoded";
request.ContentType = myContent;
Assert.Equal(myContent, request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContentType = string.Empty;
Assert.Null(request.ContentType);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = 0;
Assert.Equal(0, request.ContinueTimeout);
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.ContinueTimeout = -1;
}
[Theory, MemberData(nameof(EchoServers))]
public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = CredentialCache.DefaultCredentials;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
Assert.Equal(_explicitCredential, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = true;
Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Credentials = _explicitCredential;
request.UseDefaultCredentials = false;
Assert.Equal(null, request.Credentials);
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Head.Method;
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = "CONNECT";
Assert.Throws<ProtocolViolationException>(() =>
{
request.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Method = "POST";
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetRequestStream(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null);
Assert.Throws<InvalidOperationException>(() =>
{
_savedHttpWebRequest.BeginGetResponse(null, null);
});
}
[Theory, MemberData(nameof(EchoServers))]
public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
request.Abort();
WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null));
Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Stream requestStream;
using (requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
Assert.Throws<ArgumentException>(() =>
{
var sr = new StreamReader(requestStream);
});
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Stream requestStream = await request.GetRequestStreamAsync();
Assert.NotNull(requestStream);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.NotNull(response.GetResponseStream());
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
Assert.NotNull(myStream);
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
Assert.True(strContent.Contains("\"Host\": \"" + Configuration.Http.Host + "\""));
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
WebResponse response = await request.GetResponseAsync();
Stream myStream = response.GetResponseStream();
String strContent;
using (var sr = new StreamReader(myStream))
{
strContent = sr.ReadToEnd();
}
Assert.True(strContent.Contains(RequestBody));
}
[Theory, MemberData(nameof(EchoServers))]
public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.UseDefaultCredentials = true;
WebResponse response = await request.GetResponseAsync();
}
[OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses
[Fact]
public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException()
{
string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString());
HttpWebRequest request = WebRequest.CreateHttp(serverUrl);
WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult());
Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status);
}
public static object[][] StatusCodeServers = {
new object[] { Configuration.Http.StatusCodeUri(false, 404) },
new object[] { Configuration.Http.StatusCodeUri(true, 404) },
};
[Theory, MemberData(nameof(StatusCodeServers))]
public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync());
Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.True(request.HaveResponse);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
String headersString = response.Headers.ToString();
string headersPartialContent = "Content-Type: application/json";
Assert.True(headersString.Contains(headersPartialContent));
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Get.Method;
Assert.Equal(HttpMethod.Get.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
Assert.Equal(HttpMethod.Post.Method, request.Method);
}
[Theory, MemberData(nameof(EchoServers))]
public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.NotNull(request.Proxy);
}
[Theory, MemberData(nameof(EchoServers))]
public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.Equal(remoteServer, request.RequestUri);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
WebResponse response = await request.GetResponseAsync();
Assert.Equal(remoteServer, response.ResponseUri);
}
[Theory, MemberData(nameof(EchoServers))]
public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer)
{
HttpWebRequest request = WebRequest.CreateHttp(remoteServer);
Assert.True(request.SupportsCookieContainer);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.Method = HttpMethod.Post.Method;
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length);
}
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync();
Stream responseStream = response.GetResponseStream();
String responseBody;
using (var sr = new StreamReader(responseStream))
{
responseBody = sr.ReadToEnd();
}
_output.WriteLine(responseBody);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(responseBody.Contains("Content-Type"));
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Method = "POST";
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(RequestStreamCallback), null);
_savedHttpWebRequest.Abort();
_savedHttpWebRequest = null;
WebException wex = _savedRequestStreamException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null);
_savedHttpWebRequest.Abort();
Assert.Equal(1, _responseCallbackCallCount);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null);
_savedHttpWebRequest.Abort();
WebException wex = _savedResponseException as WebException;
Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status);
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.BeginGetResponse(null, null);
_savedHttpWebRequest.Abort();
}
[Theory, MemberData(nameof(EchoServers))]
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer)
{
_savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
_savedHttpWebRequest.Abort();
}
private void RequestStreamCallback(IAsyncResult asynchronousResult)
{
_requestStreamCallbackCallCount++;
try
{
Stream stream = (Stream)_savedHttpWebRequest.EndGetRequestStream(asynchronousResult);
stream.Dispose();
}
catch (Exception ex)
{
_savedRequestStreamException = ex;
}
}
private void ResponseCallback(IAsyncResult asynchronousResult)
{
_responseCallbackCallCount++;
try
{
using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult))
{
_savedResponseHeaders = response.Headers;
}
}
catch (Exception ex)
{
_savedResponseException = ex;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Subscription
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubscriptionDefinitionsOperationMetadataOperations operations.
/// </summary>
internal partial class SubscriptionDefinitionsOperationMetadataOperations : IServiceOperations<SubscriptionDefinitionsClient>, ISubscriptionDefinitionsOperationMetadataOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionDefinitionsOperationMetadataOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionDefinitionsOperationMetadataOperations(SubscriptionDefinitionsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SubscriptionDefinitionsClient
/// </summary>
public SubscriptionDefinitionsClient Client { get; private set; }
/// <summary>
/// Lists all of the available Microsoft.Subscription API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Subscription/operations").ToString();
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 HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_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<Operation>>(_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>
/// Lists all of the available Microsoft.Subscription API operations.
/// </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="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_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<Operation>>(_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 file="GPGSUtil.cs" company="Google Inc.">
// 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.
// </copyright>
namespace GooglePlayGames
{
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
public static class GPGSUtil
{
public const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__";
public const string SERVICEIDKEY = "App.NearbdServiceId";
public const string APPIDPLACEHOLDER = "___APP_ID___";
public const string APPIDKEY = "proj.AppId";
public const string IOSCLIENTIDPLACEHOLDER = "__CLIENTID__";
public const string IOSCLIENTIDKEY = "ios.ClientId";
public const string IOSBUNDLEIDKEY = "ios.BundleId";
public const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__";
private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs";
private const string GameInfoTemplatePath = "Assets/GooglePlayGames/Editor/GameInfo.template";
public static string SlashesToPlatformSeparator(string path)
{
return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
}
public static string ReadFile(string filePath)
{
filePath = SlashesToPlatformSeparator(filePath);
if (!File.Exists(filePath))
{
Alert("Plugin error: file not found: " + filePath);
return null;
}
StreamReader sr = new StreamReader(filePath);
string body = sr.ReadToEnd();
sr.Close();
return body;
}
public static string ReadEditorTemplate(string name)
{
return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt"));
}
public static string ReadFully(string path)
{
return ReadFile(SlashesToPlatformSeparator(path));
}
public static void WriteFile(string file, string body)
{
file = SlashesToPlatformSeparator(file);
using (var wr = new StreamWriter(file, false))
{
wr.Write(body);
}
}
public static bool LooksLikeValidServiceId(string s)
{
if (s.Length < 3)
{
return false;
}
foreach (char c in s)
{
if (!char.IsLetterOrDigit(c) && c != '.')
{
return false;
}
}
return true;
}
public static bool LooksLikeValidAppId(string s)
{
if (s.Length < 5)
{
return false;
}
foreach (char c in s)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
public static bool LooksLikeValidClientId(string s)
{
return s.EndsWith(".googleusercontent.com");
}
public static bool LooksLikeValidBundleId(string s)
{
return s.Length > 3;
}
public static bool LooksLikeValidPackageName(string s)
{
return !s.Contains(" ") && s.Split(new char[] { '.' }).Length > 1;
}
public static void Alert(string s)
{
Alert(GPGSStrings.Error, s);
}
public static void Alert(string title, string s)
{
EditorUtility.DisplayDialog(title, s, GPGSStrings.Ok);
}
public static string GetAndroidSdkPath()
{
string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
{
sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
}
return sdkPath;
}
public static bool HasAndroidSdk()
{
string sdkPath = GetAndroidSdkPath();
return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
}
public static void CopySupportLibs()
{
string sdkPath = GetAndroidSdkPath();
string supportJarPath = sdkPath +
GPGSUtil.SlashesToPlatformSeparator(
"/extras/android/support/v4/android-support-v4.jar");
string supportJarDest =
GPGSUtil.SlashesToPlatformSeparator("Assets/Plugins/Android/libs/android-support-v4.jar");
string libProjPath = sdkPath +
GPGSUtil.SlashesToPlatformSeparator(
"/extras/google/google_play_services/libproject/google-play-services_lib");
string libProjAM =
libProjPath + GPGSUtil.SlashesToPlatformSeparator("/AndroidManifest.xml");
string libProjDestDir = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/google-play-services_lib");
// check that the Google Play Services lib project is there
if (!System.IO.Directory.Exists(libProjPath) || !System.IO.File.Exists(libProjAM))
{
Debug.LogError("Google Play Services lib project not found at: " + libProjPath);
EditorUtility.DisplayDialog(GPGSStrings.AndroidSetup.LibProjNotFound,
GPGSStrings.AndroidSetup.LibProjNotFoundBlurb, GPGSStrings.Ok);
return;
}
// clear out the destination library project
GPGSUtil.DeleteDirIfExists(libProjDestDir);
// Copy Google Play Services library
FileUtil.CopyFileOrDirectory(libProjPath, libProjDestDir);
if (!System.IO.File.Exists(supportJarPath))
{
// check for the new location
supportJarPath = sdkPath + GPGSUtil.SlashesToPlatformSeparator(
"/extras/android/support/v7/appcompat/libs/android-support-v4.jar");
Debug.LogError("Android support library v4 not found at: " + supportJarPath);
if (!System.IO.File.Exists(supportJarPath))
{
EditorUtility.DisplayDialog(GPGSStrings.AndroidSetup.SupportJarNotFound,
GPGSStrings.AndroidSetup.SupportJarNotFoundBlurb, GPGSStrings.Ok);
return;
}
}
// create needed directories
GPGSUtil.EnsureDirExists("Assets/Plugins");
GPGSUtil.EnsureDirExists("Assets/Plugins/Android");
// Clear out any stale version of the support jar.
File.Delete(supportJarDest);
// Copy Android Support Library
FileUtil.CopyFileOrDirectory(supportJarPath, supportJarDest);
}
public static void GenerateAndroidManifest()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
// Generate AndroidManifest.xml
string appId = GPGSProjectSettings.Instance.Get(APPIDKEY, string.Empty);
string nearbyServiceId = GPGSProjectSettings.Instance.Get(SERVICEIDKEY, string.Empty);
string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
manifestBody = manifestBody.Replace(APPIDPLACEHOLDER, appId);
manifestBody = manifestBody.Replace(SERVICEIDPLACEHOLDER, nearbyServiceId);
GPGSUtil.WriteFile(destFilename, manifestBody);
GPGSUtil.UpdateGameInfo();
}
public static void UpdateGameInfo()
{
string fileBody = GPGSUtil.ReadFully(GameInfoTemplatePath);
var appId = GPGSProjectSettings.Instance.Get(APPIDKEY, null);
if (appId != null)
{
fileBody = fileBody.Replace(APPIDPLACEHOLDER, appId);
}
var nearbyServiceId = GPGSProjectSettings.Instance.Get(SERVICEIDKEY, null);
if (nearbyServiceId != null)
{
fileBody = fileBody.Replace(SERVICEIDPLACEHOLDER, appId);
}
var clientId = GPGSProjectSettings.Instance.Get(IOSCLIENTIDKEY, null);
if (clientId != null)
{
fileBody = fileBody.Replace(IOSCLIENTIDPLACEHOLDER, clientId);
}
var bundleId = GPGSProjectSettings.Instance.Get(IOSBUNDLEIDKEY, null);
if (bundleId != null)
{
fileBody = fileBody.Replace(IOSBUNDLEIDPLACEHOLDER, bundleId);
}
GPGSUtil.WriteFile(GameInfoPath, fileBody);
}
public static void EnsureDirExists(string dir)
{
dir = dir.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
if (!System.IO.Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
}
}
public static void DeleteDirIfExists(string dir)
{
if (System.IO.Directory.Exists(dir))
{
System.IO.Directory.Delete(dir, true);
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace Multiverse.Tools.TerrainGenerator
{
partial class SetAssetRepositoryDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetAssetRepositoryDialog));
this.label1 = new System.Windows.Forms.Label();
this.downloadButton = new System.Windows.Forms.Button();
this.repositoryButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.continueButton = new System.Windows.Forms.Button();
this.quitButton = new System.Windows.Forms.Button();
this.helpButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(25, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(349, 52);
this.label1.TabIndex = 0;
this.label1.Text = resources.GetString("label1.Text");
//
// downloadButton
//
this.downloadButton.Location = new System.Drawing.Point(46, 182);
this.downloadButton.Name = "downloadButton";
this.downloadButton.Size = new System.Drawing.Size(203, 23);
this.downloadButton.TabIndex = 1;
this.downloadButton.Text = "Download a new Asset Repository";
this.downloadButton.UseVisualStyleBackColor = true;
this.downloadButton.Click += new System.EventHandler(this.downloadButton_Click);
//
// repositoryButton
//
this.repositoryButton.Location = new System.Drawing.Point(46, 287);
this.repositoryButton.Name = "repositoryButton";
this.repositoryButton.Size = new System.Drawing.Size(203, 23);
this.repositoryButton.TabIndex = 2;
this.repositoryButton.Text = "Designate an existing Asset Repository";
this.repositoryButton.UseVisualStyleBackColor = true;
this.repositoryButton.Click += new System.EventHandler(this.repositoryButton_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(25, 95);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(195, 13);
this.label2.TabIndex = 3;
this.label2.Text = "1. Download an Asset Repository";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(43, 127);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(301, 39);
this.label3.TabIndex = 4;
this.label3.Text = "If you already have an Asset Repository, skip ahead to Step 2,\r\notherwise press t" +
"he button below to visit a web page that will\r\nassist you in downloading an Asse" +
"t Repository.";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(25, 221);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(196, 13);
this.label4.TabIndex = 5;
this.label4.Text = "2. Designate an Asset Repository";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(49, 255);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(270, 13);
this.label5.TabIndex = 6;
this.label5.Text = "Click the button below to designate an Asset Repository";
//
// continueButton
//
this.continueButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.continueButton.Enabled = false;
this.continueButton.Location = new System.Drawing.Point(28, 342);
this.continueButton.Name = "continueButton";
this.continueButton.Size = new System.Drawing.Size(75, 23);
this.continueButton.TabIndex = 7;
this.continueButton.Text = "&Continue";
this.continueButton.UseVisualStyleBackColor = true;
//
// quitButton
//
this.quitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.quitButton.Location = new System.Drawing.Point(324, 342);
this.quitButton.Name = "quitButton";
this.quitButton.Size = new System.Drawing.Size(75, 23);
this.quitButton.TabIndex = 8;
this.quitButton.Text = "&Quit";
this.quitButton.UseVisualStyleBackColor = true;
//
// helpButton
//
this.helpButton.Location = new System.Drawing.Point(217, 342);
this.helpButton.Name = "helpButton";
this.helpButton.Size = new System.Drawing.Size(75, 23);
this.helpButton.TabIndex = 9;
this.helpButton.Text = "&Help";
this.helpButton.UseVisualStyleBackColor = true;
this.helpButton.Click += new System.EventHandler(this.helpButton_Click);
//
// SetAssetRepositoryDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(428, 388);
this.Controls.Add(this.helpButton);
this.Controls.Add(this.quitButton);
this.Controls.Add(this.continueButton);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.repositoryButton);
this.Controls.Add(this.downloadButton);
this.Controls.Add(this.label1);
this.Name = "SetAssetRepositoryDialog";
this.ShowInTaskbar = false;
this.Text = "Designate an Asset Repository";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button downloadButton;
private System.Windows.Forms.Button repositoryButton;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button continueButton;
private System.Windows.Forms.Button quitButton;
private System.Windows.Forms.Button helpButton;
}
}
| |
// 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.Immutable;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class MissingAssemblyTests : ExpressionCompilerTestBase
{
[Fact]
public void ErrorsWithAssemblyIdentityArguments()
{
var identity = new AssemblyIdentity(GetUniqueName());
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity));
}
[Fact]
public void ErrorsWithAssemblySymbolArguments()
{
var assembly = CreateCompilation("").Assembly;
var identity = assembly.Identity;
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly));
}
[Fact]
public void ErrorsRequiringSystemCore()
{
var identity = EvaluationContextBase.SystemCoreIdentity;
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoSuchMemberOrExtension));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound));
}
[Fact]
public void MultipleAssemblyArguments()
{
var identity1 = new AssemblyIdentity(GetUniqueName());
var identity2 = new AssemblyIdentity(GetUniqueName());
Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2));
Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1));
}
[Fact]
public void NoAssemblyArguments()
{
Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef));
Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly"));
}
[Fact]
public void ERR_NoTypeDef()
{
var libSource = @"
public class Missing { }
";
var source = @"
public class C
{
public void M(Missing parameter)
{
}
}
";
var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference();
var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.";
var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib");
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"parameter",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[Fact]
public void ERR_QueryNoProviderStandard()
{
var source = @"
public class C
{
public void M(int[] array)
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var expectedError = "error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?";
var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity;
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"from i in array select i",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")]
[Fact]
public void ERR_NoSuchMemberOrExtension_CompilationReferencesSystemCore()
{
var source = @"
using System.Linq;
public class C
{
public void M(int[] array)
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)";
var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity;
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"array.Count()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
"array.NoSuchMethod()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
/// <remarks>
/// The fact that the compilation does not reference System.Core has no effect since
/// this test only covers our ability to identify an assembly to attempt to load, not
/// our ability to actually load or consume it.
/// </remarks>
[WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")]
[Fact]
public void ERR_NoSuchMemberOrExtension_CompilationDoesNotReferenceSystemCore()
{
var source = @"
using System.Linq;
public class C
{
public void M(int[] array)
{
}
}
namespace System.Linq
{
public class Dummy
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var expectedErrorTemplate = "error CS1061: 'int[]' does not contain a definition for '{0}' and no extension method '{0}' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)";
var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity;
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"array.Count()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(string.Format(expectedErrorTemplate, "Count"), actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
"array.NoSuchMethod()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(string.Format(expectedErrorTemplate, "NoSuchMethod"), actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[Fact]
public void ForwardingErrors()
{
var il = @"
.assembly extern mscorlib { }
.assembly extern pe2 { }
.assembly pe1 { }
.class extern forwarder Forwarded
{
.assembly extern pe2
}
.class extern forwarder NS.Forwarded
{
.assembly extern pe2
}
.class public auto ansi beforefieldinit Dummy
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
var csharp = @"
class C
{
static void M(Dummy d)
{
}
}
";
var ilRef = CompileIL(il, appendDefaultHeader: false);
var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef });
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2");
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"new global::Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
"new Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
"new NS.Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[Fact]
public unsafe void ShouldTryAgain_Success()
{
var comp = CreateCompilationWithMscorlib("public class C { }");
using (var pinned = new PinnedMetadata(GetMetadataBytes(comp)))
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
uSize = (uint)pinned.Size;
return pinned.Pointer;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentity = new AssemblyIdentity("A");
var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity);
Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
var newReference = references.Single();
Assert.Equal(pinned.Pointer, newReference.Pointer);
Assert.Equal(pinned.Size, newReference.Size);
}
}
[Fact]
public unsafe void ShouldTryAgain_Mixed()
{
var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: GetUniqueName());
var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: GetUniqueName());
using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)),
pinned2 = new PinnedMetadata(GetMetadataBytes(comp2)))
{
var assemblyIdentity1 = comp1.Assembly.Identity;
var assemblyIdentity2 = comp2.Assembly.Identity;
Assert.NotEqual(assemblyIdentity1, assemblyIdentity2);
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
if (assemblyIdentity == assemblyIdentity1)
{
uSize = (uint)pinned1.Size;
return pinned1.Pointer;
}
else if (assemblyIdentity == assemblyIdentity2)
{
uSize = (uint)pinned2.Size;
return pinned2.Pointer;
}
else
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA));
throw ExceptionUtilities.Unreachable;
}
};
var references = ImmutableArray.Create(default(MetadataBlock));
var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName());
var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2);
Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Equal(3, references.Length);
Assert.Equal(default(MetadataBlock), references[0]);
Assert.Equal(pinned1.Pointer, references[1].Pointer);
Assert.Equal(pinned1.Size, references[1].Size);
Assert.Equal(pinned2.Pointer, references[2].Pointer);
Assert.Equal(pinned2.Size, references[2].Size);
}
}
[Fact]
public void ShouldTryAgain_CORDBG_E_MISSING_METADATA()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA));
throw ExceptionUtilities.Unreachable;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Empty(references);
}
[Fact]
public void ShouldTryAgain_COR_E_BADIMAGEFORMAT()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT));
throw ExceptionUtilities.Unreachable;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Empty(references);
}
[Fact]
public void ShouldTryAgain_OtherException()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
throw new Exception();
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
}
[WorkItem(1124725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124725")]
[Fact]
public void PseudoVariableType()
{
var source =
@"class C
{
static void M()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { CSharpRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
const string expectedError = "error CS0012: The type 'Exception' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.";
var expectedMissingAssemblyIdentity = comp.Assembly.CorLibrary.Identity;
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"$stowedexception",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(ExceptionAlias("Microsoft.CSharp.RuntimeBinder.RuntimeBinderException, Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", stowed: true)),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[WorkItem(1114866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114866")]
[ConditionalFact(typeof(OSVersionWin8))]
public void NotYetLoadedWinMds()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f)
{
}
}";
var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");
Assert.True(runtimeAssemblies.Any());
WithRuntimeInstance(comp, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
const string expectedError = "error CS0234: The type or namespace name 'UI' does not exist in the namespace 'Windows' (are you missing an assembly reference?)";
var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI", contentType: System.Reflection.AssemblyContentType.WindowsRuntime);
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"typeof(@Windows.UI.Colors)",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
/// <remarks>
/// Windows.UI.Xaml is the only (win8) winmd with more than two parts.
/// </remarks>
[WorkItem(1114866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114866")]
[ConditionalFact(typeof(OSVersionWin8))]
public void NotYetLoadedWinMds_MultipleParts()
{
var source =
@"class C
{
static void M(Windows.UI.Colors c)
{
}
}";
var comp = CreateCompilationWithMscorlib(source, WinRtRefs, TestOptions.DebugDll);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI");
Assert.True(runtimeAssemblies.Any());
WithRuntimeInstance(comp, new[] { MscorlibRef }.Concat(runtimeAssemblies), runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
const string expectedError = "error CS0234: The type or namespace name 'Xaml' does not exist in the namespace 'Windows.UI' (are you missing an assembly reference?)";
var expectedMissingAssemblyIdentity = new AssemblyIdentity("Windows.UI.Xaml", contentType: System.Reflection.AssemblyContentType.WindowsRuntime);
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
"typeof(Windows.@UI.Xaml.Application)",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
});
}
[WorkItem(1154988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1154988")]
[Fact]
public void CompileWithRetrySameErrorReported()
{
var source = @"
class C
{
void M()
{
}
}";
var comp = CreateCompilationWithMscorlib(source);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var missingModule = runtime.Modules.First();
var missingIdentity = missingModule.GetMetadataReader().ReadAssemblyIdentityOrThrow();
var numRetries = 0;
string errorMessage;
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
context,
(_, diagnostics) =>
{
numRetries++;
Assert.InRange(numRetries, 0, 2); // We don't want to loop forever...
diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None));
return null;
},
(AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
uSize = (uint)missingModule.MetadataLength;
return missingModule.MetadataAddress;
},
out errorMessage);
Assert.Equal(2, numRetries); // Ensure that we actually retried and that we bailed out on the second retry if the same identity was seen in the diagnostics.
Assert.Equal($"error CS0012: The type 'MissingType' is defined in an assembly that is not referenced. You must add a reference to assembly '{missingIdentity}'.", errorMessage);
});
}
[WorkItem(1151888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1151888")]
[Fact]
public void SucceedOnRetry()
{
var source = @"
class C
{
void M()
{
}
}";
var comp = CreateCompilationWithMscorlib(source);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var missingModule = runtime.Modules.First();
var missingIdentity = missingModule.GetMetadataReader().ReadAssemblyIdentityOrThrow();
var shouldSucceed = false;
string errorMessage;
var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
context,
(_, diagnostics) =>
{
if (shouldSucceed)
{
return TestCompileResult.Instance;
}
else
{
shouldSucceed = true;
diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NoTypeDef, "MissingType", missingIdentity), Location.None));
return null;
}
},
(AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
uSize = (uint)missingModule.MetadataLength;
return missingModule.MetadataAddress;
},
out errorMessage);
Assert.Same(TestCompileResult.Instance, compileResult);
Assert.Null(errorMessage);
});
}
[WorkItem(2547, "https://github.com/dotnet/roslyn/issues/2547")]
[Fact]
public void TryDifferentLinqLibraryOnRetry()
{
var source = @"
using System.Linq;
class C
{
void M(string[] args)
{
}
}
class UseLinq
{
bool b = Enumerable.Any<int>(null);
}";
var compilation = CreateCompilation(source, new[] { MscorlibRef, SystemCoreRef });
WithRuntimeInstance(compilation, new[] { MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var systemCore = SystemCoreRef.ToModuleInstance();
var fakeSystemLinq = CreateCompilationWithMscorlib45("", assemblyName: "System.Linq").
EmitToImageReference().ToModuleInstance();
string errorMessage;
CompilationTestData testData;
int retryCount = 0;
var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
"args.Where(a => a.Length > 0)",
ImmutableArray<Alias>.Empty,
(_1, _2) => context, // ignore new blocks and just keep using the same failed context...
(AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
retryCount++;
MetadataBlock block;
switch (retryCount)
{
case 1:
Assert.Equal(EvaluationContextBase.SystemLinqIdentity, assemblyIdentity);
block = fakeSystemLinq.MetadataBlock;
break;
case 2:
Assert.Equal(EvaluationContextBase.SystemCoreIdentity, assemblyIdentity);
block = systemCore.MetadataBlock;
break;
default:
throw ExceptionUtilities.Unreachable;
}
uSize = (uint)block.Size;
return block.Pointer;
},
errorMessage: out errorMessage,
testData: out testData);
Assert.Equal(2, retryCount);
});
}
[Fact]
public void TupleNoSystemRuntime()
{
var source =
@"class C
{
static void M()
{
var x = 1;
var y = (x, 2);
var z = (3, 4, (5, 6));
}
}";
TupleContextNoSystemRuntime(
source,
"C.M",
"y",
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (int V_0, //x
(int, int) V_1, //y
(int, int, (int, int)) V_2) //z
IL_0000: ldloc.1
IL_0001: ret
}");
}
[WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")]
[Fact]
public void NonTupleNoSystemRuntime()
{
var source =
@"class C
{
static void M()
{
var x = 1;
var y = (x, 2);
var z = (3, 4, (5, 6));
}
}";
TupleContextNoSystemRuntime(
source,
"C.M",
"x",
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (int V_0, //x
(int, int) V_1, //y
(int, int, (int, int)) V_2) //z
IL_0000: ldloc.0
IL_0001: ret
}");
}
private static void TupleContextNoSystemRuntime(string source, string methodName, string expression, string expectedIL)
{
var comp = CreateCompilationWithMscorlib(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
using (var systemRuntime = SystemRuntimeFacadeRef.ToModuleInstance())
{
WithRuntimeInstance(comp, new[] { MscorlibRef, ValueTupleRef }, runtime =>
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
string errorMessage;
CompilationTestData testData;
int retryCount = 0;
var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(),
expression,
ImmutableArray<Alias>.Empty,
(b, u) => EvaluationContext.CreateMethodContext(b.ToCompilation(), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken),
(AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
retryCount++;
Assert.Equal("System.Runtime", assemblyIdentity.Name);
var block = systemRuntime.MetadataBlock;
uSize = (uint)block.Size;
return block.Pointer;
},
errorMessage: out errorMessage,
testData: out testData);
Assert.Equal(1, retryCount);
testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL);
});
}
}
private sealed class TestCompileResult : CompileResult
{
public static readonly CompileResult Instance = new TestCompileResult();
private TestCompileResult()
: base(null, null, null, null)
{
}
public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte> payload)
{
throw new NotImplementedException();
}
}
private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments)
{
var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments, EvaluationContextBase.SystemCoreIdentity);
return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single();
}
private static ImmutableArray<byte> GetMetadataBytes(Compilation comp)
{
var imageReference = (MetadataImageReference)comp.EmitToImageReference();
var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadataNoCopy();
var moduleMetadata = assemblyMetadata.GetModules()[0];
return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent();
}
}
}
| |
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Threading;
using Nerdbank.Streams;
using Xunit;
using Xunit.Abstractions;
#pragma warning disable SA1401 // Fields should be private
#pragma warning disable SA1414 // Tuple types in signatures should have element names
public class MultiplexingStreamTests : TestBase, IAsyncLifetime
{
protected Stream transport1;
protected Stream transport2;
protected MultiplexingStream mx1;
protected MultiplexingStream mx2;
#pragma warning disable CS8618 // Fields initialized in InitializeAsync
public MultiplexingStreamTests(ITestOutputHelper logger)
#pragma warning restore CS8618 // Fields initialized in InitializeAsync
: base(logger)
{
}
protected virtual int ProtocolMajorVersion { get; } = 1;
public async Task InitializeAsync()
{
var mx1TraceSource = new TraceSource(nameof(this.mx1), SourceLevels.All);
var mx2TraceSource = new TraceSource(nameof(this.mx2), SourceLevels.All);
mx1TraceSource.Listeners.Add(new XunitTraceListener(this.Logger));
mx2TraceSource.Listeners.Add(new XunitTraceListener(this.Logger));
Func<string, MultiplexingStream.QualifiedChannelId, string, TraceSource> traceSourceFactory = (string mxInstanceName, MultiplexingStream.QualifiedChannelId id, string name) =>
{
var traceSource = new TraceSource(mxInstanceName + " channel " + id, SourceLevels.All);
traceSource.Listeners.Clear(); // remove DefaultTraceListener
traceSource.Listeners.Add(new XunitTraceListener(this.Logger));
return traceSource;
};
Func<MultiplexingStream.QualifiedChannelId, string, TraceSource> mx1TraceSourceFactory = (MultiplexingStream.QualifiedChannelId id, string name) => traceSourceFactory(nameof(this.mx1), id, name);
Func<MultiplexingStream.QualifiedChannelId, string, TraceSource> mx2TraceSourceFactory = (MultiplexingStream.QualifiedChannelId id, string name) => traceSourceFactory(nameof(this.mx2), id, name);
(this.transport1, this.transport2) = FullDuplexStream.CreatePair(new PipeOptions(pauseWriterThreshold: 2 * 1024 * 1024));
var mx1 = MultiplexingStream.CreateAsync(this.transport1, new MultiplexingStream.Options { ProtocolMajorVersion = this.ProtocolMajorVersion, TraceSource = mx1TraceSource, DefaultChannelTraceSourceFactoryWithQualifier = mx1TraceSourceFactory }, this.TimeoutToken);
var mx2 = MultiplexingStream.CreateAsync(this.transport2, new MultiplexingStream.Options { ProtocolMajorVersion = this.ProtocolMajorVersion, TraceSource = mx2TraceSource, DefaultChannelTraceSourceFactoryWithQualifier = mx2TraceSourceFactory }, this.TimeoutToken);
this.mx1 = await mx1;
this.mx2 = await mx2;
}
public async Task DisposeAsync()
{
await (this.mx1?.DisposeAsync() ?? default);
await (this.mx2?.DisposeAsync() ?? default);
AssertNoFault(this.mx1);
AssertNoFault(this.mx2);
this.mx1?.TraceSource.Listeners.OfType<XunitTraceListener>().SingleOrDefault()?.Dispose();
this.mx2?.TraceSource.Listeners.OfType<XunitTraceListener>().SingleOrDefault()?.Dispose();
}
[Fact, Obsolete]
public async Task DefaultChannelTraceSourceFactory()
{
var factoryArgs = new TaskCompletionSource<(int, string)>();
var obsoleteFactory = new Func<int, string, TraceSource?>((id, name) =>
{
factoryArgs.SetResult((id, name));
return null;
});
(this.transport1, this.transport2) = FullDuplexStream.CreatePair();
var mx1Task = MultiplexingStream.CreateAsync(this.transport1, new MultiplexingStream.Options { ProtocolMajorVersion = this.ProtocolMajorVersion, DefaultChannelTraceSourceFactory = obsoleteFactory }, this.TimeoutToken);
var mx2Task = MultiplexingStream.CreateAsync(this.transport2, new MultiplexingStream.Options { ProtocolMajorVersion = this.ProtocolMajorVersion }, this.TimeoutToken);
var mx1 = await mx1Task;
var mx2 = await mx2Task;
var ch = await Task.WhenAll(mx1.OfferChannelAsync("myname"), mx2.AcceptChannelAsync("myname"));
var args = await factoryArgs.Task;
Assert.Equal(ch[0].QualifiedId.Id, (ulong)args.Item1);
Assert.Equal("myname", args.Item2);
}
[Fact]
public void DefaultMajorProtocolVersion()
{
Assert.Equal(1, new MultiplexingStream.Options().ProtocolMajorVersion);
}
[Fact]
public async Task OfferReadOnlyDuplexPipe()
{
// Prepare a readonly pipe that is already fully populated with data for the other end to read.
var pipe = new Pipe();
await pipe.Writer.WriteAsync(new byte[] { 1, 2, 3 }, this.TimeoutToken);
pipe.Writer.Complete();
var ch1 = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = new DuplexPipe(pipe.Reader) });
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var ch2 = this.mx2.AcceptChannel(ch1.QualifiedId.Id);
var readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.Equal(3, readResult.Buffer.Length);
ch2.Input.AdvanceTo(readResult.Buffer.End);
readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
ch2.Output.Complete();
await Task.WhenAll(ch1.Completion, ch2.Completion).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task OfferReadOnlyPipe()
{
// Prepare a readonly pipe that is already fully populated with data for the other end to read.
var pipePair = FullDuplexStream.CreatePipePair();
pipePair.Item1.Input.Complete(); // we don't read -- we only write.
await pipePair.Item1.Output.WriteAsync(new byte[] { 1, 2, 3 }, this.TimeoutToken);
pipePair.Item1.Output.Complete();
var ch1 = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = pipePair.Item2 });
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var ch2 = this.mx2.AcceptChannel(ch1.QualifiedId.Id);
var readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.Equal(3, readResult.Buffer.Length);
ch2.Input.AdvanceTo(readResult.Buffer.End);
readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
ch2.Output.Complete();
await Task.WhenAll(ch1.Completion, ch2.Completion).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task OfferWriteOnlyDuplexPipe()
{
var pipe = new Pipe();
var ch1 = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = new DuplexPipe(pipe.Writer) });
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var ch2 = this.mx2.AcceptChannel(ch1.QualifiedId.Id);
// Confirm that any attempt to read from the channel is immediately completed.
var readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
// Now write to the channel.
await ch2.Output.WriteAsync(new byte[] { 1, 2, 3 }, this.TimeoutToken);
ch2.Output.Complete();
readResult = await pipe.Reader.ReadAsync(this.TimeoutToken);
Assert.Equal(3, readResult.Buffer.Length);
pipe.Reader.AdvanceTo(readResult.Buffer.End);
readResult = await pipe.Reader.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
await Task.WhenAll(ch1.Completion, ch2.Completion).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task OfferWriteOnlyPipe()
{
var pipePair = FullDuplexStream.CreatePipePair();
pipePair.Item1.Output.Complete(); // we don't write -- we only read.
var ch1 = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = pipePair.Item2 });
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var ch2 = this.mx2.AcceptChannel(ch1.QualifiedId.Id);
// Confirm that any attempt to read from the channel is immediately completed.
var readResult = await ch2.Input.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
// Now write to the channel.
await ch2.Output.WriteAsync(new byte[] { 1, 2, 3 }, this.TimeoutToken);
ch2.Output.Complete();
readResult = await pipePair.Item1.Input.ReadAsync(this.TimeoutToken);
Assert.Equal(3, readResult.Buffer.Length);
pipePair.Item1.Input.AdvanceTo(readResult.Buffer.End);
readResult = await pipePair.Item1.Input.ReadAsync(this.TimeoutToken);
Assert.True(readResult.IsCompleted);
await Task.WhenAll(ch1.Completion, ch2.Completion).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task Dispose_CancelsOutstandingOperations()
{
Task offer = this.mx1.OfferChannelAsync("offer");
Task accept = this.mx1.AcceptChannelAsync("accept");
await this.mx1.DisposeAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => Task.WhenAll(offer, accept)).WithCancellation(this.TimeoutToken);
Assert.True(offer.IsCanceled);
Assert.True(accept.IsCanceled);
}
[Fact]
public async Task Disposal_DisposesTransportStream()
{
await this.mx1.DisposeAsync();
Assert.Throws<ObjectDisposedException>(() => this.transport1.Position);
}
[Fact]
public async Task Dispose_DisposesChannels()
{
var (channel1, channel2) = await this.EstablishChannelsAsync("A");
await this.mx1.DisposeAsync();
Assert.True(channel1.IsDisposed);
await channel1.Completion.WithCancellation(this.TimeoutToken);
#pragma warning disable CS0618 // Type or member is obsolete
await channel1.Input.WaitForWriterCompletionAsync().WithCancellation(this.TimeoutToken);
await channel1.Output.WaitForReaderCompletionAsync().WithCancellation(this.TimeoutToken);
#pragma warning restore CS0618 // Type or member is obsolete
}
[Fact]
public async Task ChannelDispose_ClosesExistingStream()
{
var ms = new MonitoringStream(FullDuplexStream.CreatePair().Item1);
var disposal = new AsyncManualResetEvent();
ms.Disposed += (s, e) => disposal.Set();
var channel = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = ms.UsePipe() });
channel.Dispose();
await disposal.WaitAsync(this.TimeoutToken);
}
[Fact]
public async Task RemoteChannelClose_ClosesExistingStream()
{
var ms = new MonitoringStream(FullDuplexStream.CreatePair().Item1);
var disposal = new AsyncManualResetEvent();
ms.Disposed += (s, e) => disposal.Set();
var ch1 = this.mx1.CreateChannel(new MultiplexingStream.ChannelOptions { ExistingPipe = ms.UsePipe() });
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var ch2 = this.mx2.AcceptChannel(ch1.QualifiedId.Id);
ch2.Dispose();
await disposal.WaitAsync(this.TimeoutToken);
}
[Fact]
public async Task CreateChannelAsync_ThrowsAfterDisposal()
{
await this.mx1.DisposeAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(() => this.mx1.OfferChannelAsync(string.Empty, this.TimeoutToken)).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task AcceptChannelAsync_ThrowsAfterDisposal()
{
await this.mx1.DisposeAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(() => this.mx1.AcceptChannelAsync(string.Empty, this.TimeoutToken)).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task Completion_CompletedAfterDisposal()
{
await this.mx1.DisposeAsync();
Assert.Equal(TaskStatus.RanToCompletion, this.mx1.Completion.Status);
}
[Fact]
public async Task CreateChannelAsync_NullId()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => this.mx1.OfferChannelAsync(null!, this.TimeoutToken));
}
[Fact]
public async Task AcceptChannelAsync_NullId()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => this.mx1.AcceptChannelAsync(null!, this.TimeoutToken));
}
[Fact]
public async Task CreateChannelAsync_EmptyId()
{
var stream2Task = this.mx2.AcceptChannelAsync(string.Empty, this.TimeoutToken).WithCancellation(this.TimeoutToken);
var channel1 = await this.mx1.OfferChannelAsync(string.Empty, this.TimeoutToken).WithCancellation(this.TimeoutToken);
var channel2 = await stream2Task.WithCancellation(this.TimeoutToken);
Assert.NotNull(channel1);
Assert.NotNull(channel2);
}
[Fact]
public async Task CreateChannelAsync_CanceledBeforeAcceptance()
{
var cts = new CancellationTokenSource();
var channel1Task = this.mx1.OfferChannelAsync("1st", cts.Token);
Assert.False(channel1Task.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => channel1Task).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task CreateChannelAsync()
{
await this.EstablishChannelStreamsAsync("a");
}
[Fact]
public async Task CreateChannelAsync_TwiceWithDifferentCapitalization()
{
var (channel1a, channel1b) = await this.EstablishChannelStreamsAsync("a");
var (channel2a, channel2b) = await this.EstablishChannelStreamsAsync("A");
Assert.Equal(4, new[] { channel1a, channel1b, channel2a, channel2b }.Distinct().Count());
}
[Fact]
public async Task CreateChannelAsync_IdCollidesWithPendingRequest()
{
var channel1aTask = this.mx1.OfferChannelAsync("1st", this.TimeoutToken);
var channel2aTask = this.mx1.OfferChannelAsync("1st", this.TimeoutToken);
var channel1b = await this.mx2.AcceptChannelAsync("1st", this.TimeoutToken).WithCancellation(this.TimeoutToken);
var channel2b = await this.mx2.AcceptChannelAsync("1st", this.TimeoutToken).WithCancellation(this.TimeoutToken);
await Task.WhenAll(channel1aTask, channel2aTask).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task CreateChannelAsync_IdCollidesWithExistingChannel()
{
for (int i = 0; i < 10; i++)
{
var channel1aTask = this.mx1.OfferChannelAsync("1st", this.TimeoutToken);
var channel1bTask = this.mx2.AcceptChannelAsync("1st", this.TimeoutToken);
await Task.WhenAll(channel1aTask, channel1bTask).WithCancellation(this.TimeoutToken);
}
}
[Fact]
public async Task CreateChannelAsync_IdRecycledFromPriorChannel()
{
var channel1aTask = this.mx1.OfferChannelAsync("1st", this.TimeoutToken);
var channel1bTask = this.mx2.AcceptChannelAsync("1st", this.TimeoutToken);
var channels = await Task.WhenAll(channel1aTask, channel1bTask).WithCancellation(this.TimeoutToken);
channels[0].Dispose();
channels[1].Dispose();
channel1aTask = this.mx1.OfferChannelAsync("1st", this.TimeoutToken);
channel1bTask = this.mx2.AcceptChannelAsync("1st", this.TimeoutToken);
channels = await Task.WhenAll(channel1aTask, channel1bTask).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task CreateChannelAsync_AcceptByAnotherId()
{
var cts = new CancellationTokenSource();
var createTask = this.mx1.OfferChannelAsync("1st", cts.Token);
var acceptTask = this.mx2.AcceptChannelAsync("2nd", cts.Token);
Assert.False(createTask.IsCompleted);
Assert.False(acceptTask.IsCompleted);
cts.CancelAfter(ExpectedTimeout);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => createTask).WithCancellation(this.TimeoutToken);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => acceptTask).WithCancellation(this.TimeoutToken);
}
[Fact]
public void ChannelExposesMultiplexingStream()
{
var channel = this.mx1.CreateChannel();
Assert.Same(this.mx1, channel.MultiplexingStream);
channel.Dispose();
Assert.Same(this.mx1, channel.MultiplexingStream);
}
[Fact]
public async Task CommunicateOverOneChannel()
{
var (a, b) = await this.EstablishChannelStreamsAsync("a");
await this.TransmitAndVerifyAsync(a, b, Guid.NewGuid().ToByteArray());
await this.TransmitAndVerifyAsync(b, a, Guid.NewGuid().ToByteArray());
}
[Fact]
[Trait("SkipInCodeCoverage", "true")] // far too slow and times out
public async Task ConcurrentChatOverManyChannels()
{
// Avoid tracing because it slows things down significantly for this test.
this.mx1.TraceSource.Switch.Level = SourceLevels.Error;
this.mx2.TraceSource.Switch.Level = SourceLevels.Error;
const int channels = 10;
const int iterations = 500;
await Task.WhenAll(Enumerable.Range(1, channels).Select(i => CoordinateChatAsync()));
async Task CoordinateChatAsync()
{
var (a, b) = await this.EstablishChannelStreamsAsync("chat").WithCancellation(this.TimeoutToken);
var messageA = Guid.NewGuid().ToByteArray();
var messageB = Guid.NewGuid().ToByteArray().Concat(Guid.NewGuid().ToByteArray()).ToArray();
await Task.WhenAll(
Task.Run(() => ChatAsync(a, messageA, messageB)),
Task.Run(() => ChatAsync(b, messageB, messageA)));
}
async Task ChatAsync(Stream s, byte[] send, byte[] receive)
{
byte[] recvBuffer = new byte[receive.Length];
for (int i = 0; i < iterations; i++)
{
await s.WriteAsync(send, 0, send.Length).WithCancellation(this.TimeoutToken);
await s.FlushAsync(this.TimeoutToken).WithCancellation(this.TimeoutToken);
Assert.Equal(recvBuffer.Length, await ReadAtLeastAsync(s, new ArraySegment<byte>(recvBuffer), recvBuffer.Length, this.TimeoutToken));
Assert.Equal(receive, recvBuffer);
}
}
}
[Fact]
public async Task ReadReturns0AfterRemoteEnd()
{
var (a, b) = await this.EstablishChannelStreamsAsync("a");
a.Dispose();
var buffer = new byte[1];
Assert.Equal(0, await b.ReadAsync(buffer, 0, buffer.Length, this.TimeoutToken).WithCancellation(this.TimeoutToken));
Assert.Equal(0, b.Read(buffer, 0, buffer.Length));
Assert.Equal(-1, b.ReadByte());
}
//// TODO: add test where the locally transmitting pipe is closed, the remote detects this, sends one more message, closes their end, and the channels close as the last message is sent and received.
[Fact]
public async Task ReadByte()
{
var (a, b) = await this.EstablishChannelStreamsAsync("a");
var buffer = new byte[] { 5 };
await a.WriteAsync(buffer, 0, buffer.Length, this.TimeoutToken).WithCancellation(this.TimeoutToken);
await a.FlushAsync(this.TimeoutToken).WithCancellation(this.TimeoutToken);
Assert.Equal(5, b.ReadByte());
}
[Theory]
[InlineData(1024 * 1024)]
[InlineData(5)]
[Trait("SkipInCodeCoverage", "true")]
public async Task TransmitOverStreamAndDisposeStream(int length)
{
var buffer = this.GetBuffer(length);
var (a, b) = await this.EstablishChannelStreamsAsync("a");
Task writerTask = Task.Run(async delegate
{
await a.WriteAsync(buffer, 0, buffer.Length, this.TimeoutToken).WithCancellation(this.TimeoutToken);
await a.FlushAsync(this.TimeoutToken);
a.Dispose();
});
var receivingBuffer = new byte[length + 1];
int readBytes = await ReadAtLeastAsync(b, new ArraySegment<byte>(receivingBuffer), buffer.Length, this.TimeoutToken);
Assert.Equal(buffer.Length, readBytes);
Assert.Equal(buffer, receivingBuffer.Take(buffer.Length));
Assert.Equal(0, await b.ReadAsync(receivingBuffer, 0, 1, this.TimeoutToken).WithCancellation(this.TimeoutToken));
await writerTask;
}
/// <summary>
/// Verifies that writing to a <see cref="MultiplexingStream.Channel"/> (without an <see cref="MultiplexingStream.ChannelOptions.ExistingPipe"/>)
/// and then immediately disposing the channel still writes everything that was pending.
/// </summary>
[Theory]
[InlineData(1024 * 1024)]
[InlineData(5)]
[Trait("SkipInCodeCoverage", "true")]
public async Task TransmitOverPipeAndDisposeChannel(int length)
{
var buffer = this.GetBuffer(length);
var (a, b) = await this.EstablishChannelsAsync("a");
Task writerTask = Task.Run(async delegate
{
await a.Output.WriteAsync(buffer, this.TimeoutToken);
a.Dispose();
});
var readBytes = await this.ReadAtLeastAsync(b.Input, length);
Assert.Equal(buffer.Length, readBytes.Length);
Assert.Equal(buffer, readBytes.ToArray());
#pragma warning disable CS0618 // Type or member is obsolete
await b.Input.WaitForWriterCompletionAsync().WithCancellation(this.TimeoutToken);
#pragma warning restore CS0618 // Type or member is obsolete
await writerTask;
}
/// <summary>
/// Verifies that writing to a <see cref="MultiplexingStream.Channel"/> (with an <see cref="MultiplexingStream.ChannelOptions.ExistingPipe"/>)
/// and then immediately disposing the channel still writes everything that was pending.
/// </summary>
[Theory]
[InlineData(1024 * 1024)]
[InlineData(5)]
[Trait("SkipInCodeCoverage", "true")]
public async Task TransmitOverPreexistingPipeAndDisposeChannel(int length)
{
var buffer = this.GetBuffer(length);
var pipePair = FullDuplexStream.CreatePipePair();
const string channelName = "a";
var mx1ChannelTask = this.mx1.OfferChannelAsync(channelName, new MultiplexingStream.ChannelOptions { ExistingPipe = pipePair.Item1 }, this.TimeoutToken);
var mx2ChannelTask = this.mx2.AcceptChannelAsync(channelName, this.TimeoutToken);
var (a, b) = await Task.WhenAll(mx1ChannelTask, mx2ChannelTask).WithCancellation(this.TimeoutToken);
Task writerTask = Task.Run(async delegate
{
await pipePair.Item2.Output.WriteAsync(buffer, this.TimeoutToken);
a.Dispose();
});
// In this scenario, there is actually no guarantee that bytes written previously were transmitted before the Channel was disposed.
// In practice, folks with ExistingPipe set should complete their writer instead of disposing so the channel can dispose when writing (on both sides) is done.
// In order for the b stream to recognize the closure, it does need to have read all the bytes that *were* transmitted though,
// so drain the pipe insofar as it has bytes. Just don't assert how many were read.
await this.DrainReaderTillCompletedAsync(b.Input);
#pragma warning disable CS0618 // Type or member is obsolete
await b.Input.WaitForWriterCompletionAsync().WithCancellation(this.TimeoutToken);
#pragma warning restore CS0618 // Type or member is obsolete
await writerTask;
}
/// <summary>
/// Verifies that disposing a <see cref="MultiplexingStream.Channel"/> that is still receiving data from the remote party
/// causes such received data to be silently dropped.
/// </summary>
[Theory]
[InlineData(1024 * 1024)]
[InlineData(5)]
[Trait("SkipInCodeCoverage", "true")]
public async Task DisposeChannel_WhileRemoteEndIsTransmitting(int length)
{
var buffer = this.GetBuffer(length);
var (a, b) = await this.EstablishChannelsAsync("a");
// We don't await this because with large input sizes it can't complete faster than the reader is reading it.
ValueTask<FlushResult> writerTask = a.Output.WriteAsync(buffer, this.TimeoutToken);
// While the prior transmission is going, dispose the channel on the receiving end.
b.Dispose();
// Prove that communication between the two streams is still possible.
// This is interesting particularly when the amount of data transmitted is high and would back up the pipes
// such that the reader would stop if the disposed channel's content were not being actively discarded.
await this.EstablishChannelsAsync("b");
// Confirm the writer task completes
await writerTask;
}
[Fact]
public async Task WriteLargeBuffer()
{
var sendBuffer = new byte[1024 * 1024];
var random = new Random();
random.NextBytes(sendBuffer);
var (a, b) = await this.EstablishChannelStreamsAsync("a");
Task writeAndFlush = Task.Run(async delegate
{
await a.WriteAsync(sendBuffer, 0, sendBuffer.Length, this.TimeoutToken).WithCancellation(this.TimeoutToken);
await a.FlushAsync(this.TimeoutToken).WithCancellation(this.TimeoutToken);
});
var recvBuffer = new byte[sendBuffer.Length];
await this.ReadAsync(b, recvBuffer);
Assert.Equal(sendBuffer, recvBuffer);
await writeAndFlush;
}
[Fact]
public async Task CanProperties()
{
var (s1, s2) = await this.EstablishChannelStreamsAsync(string.Empty);
Assert.False(s1.CanSeek);
Assert.True(s1.CanWrite);
Assert.True(s1.CanRead);
s1.Dispose();
Assert.False(s1.CanSeek);
Assert.False(s1.CanWrite);
Assert.False(s1.CanRead);
}
[Fact]
public async Task NotSupportedMethodsAndProperties()
{
var (s1, s2) = await this.EstablishChannelStreamsAsync(string.Empty);
Assert.Throws<NotSupportedException>(() => s1.Length);
Assert.Throws<NotSupportedException>(() => s1.Position);
Assert.Throws<NotSupportedException>(() => s1.Position = 0);
Assert.Throws<NotSupportedException>(() => s1.SetLength(0));
Assert.Throws<NotSupportedException>(() => s1.Seek(0, SeekOrigin.Begin));
s1.Dispose();
Assert.Throws<ObjectDisposedException>(() => s1.Length);
Assert.Throws<ObjectDisposedException>(() => s1.Position);
Assert.Throws<ObjectDisposedException>(() => s1.Position = 0);
Assert.Throws<ObjectDisposedException>(() => s1.SetLength(0));
Assert.Throws<ObjectDisposedException>(() => s1.Seek(0, SeekOrigin.Begin));
}
[Fact]
public async Task PartialFrameSentWithoutExplicitFlush()
{
var (s1, s2) = await this.EstablishChannelStreamsAsync(string.Empty);
byte[] smallData = new byte[] { 0x1, 0x2, 0x3 };
await s1.WriteAsync(smallData, 0, smallData.Length).WithCancellation(this.TimeoutToken);
byte[] recvBuffer = new byte[smallData.Length];
await ReadAtLeastAsync(s2, new ArraySegment<byte>(recvBuffer), recvBuffer.Length, this.TimeoutToken);
}
[SkippableTheory]
[InlineData(true)]
[InlineData(false)]
public async Task CancelChannelOfferBeforeAcceptance(bool cancelFirst)
{
// TODO: We need to test both the race condition where acceptance is sent before cancellation is received,
// and the case where cancellation is received before we call AcceptChannelAsync.
var cts = new CancellationTokenSource();
var offer = this.mx1.OfferChannelAsync(string.Empty, cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => offer).WithCancellation(this.TimeoutToken);
Stream? acceptedStream = null;
try
{
if (cancelFirst)
{
// Increase the odds that cancellation will be processed before acceptance.
await Task.Delay(250);
}
var acceptedChannel = await this.mx2.AcceptChannelAsync(string.Empty, ExpectedTimeoutToken).ConfigureAwait(false);
acceptedStream = acceptedChannel.AsStream();
// In this case, we accepted the channel before receiving the cancellation notice. The channel should be terminated by the remote side very soon.
int bytesRead = await acceptedStream.ReadAsync(new byte[1], 0, 1, this.TimeoutToken).WithCancellation(this.TimeoutToken);
Assert.Equal(0, bytesRead); // confirm that the stream was closed.
this.Logger.WriteLine("Verified the channel terminated condition.");
Skip.If(cancelFirst);
}
catch (OperationCanceledException) when (acceptedStream == null)
{
// In this case, the channel offer was canceled before we accepted it.
this.Logger.WriteLine("Verified the channel offer was canceled before acceptance condition.");
Skip.IfNot(cancelFirst);
}
}
[Fact]
public async Task EphemeralChannels()
{
var ephemeralMessage = new byte[10];
var random = new Random();
random.NextBytes(ephemeralMessage);
await Task.WhenAll(
Task.Run(async delegate
{
var rpcChannel = await this.mx1.OfferChannelAsync(string.Empty, this.TimeoutToken);
var eph = this.mx1.CreateChannel();
await rpcChannel.Output.WriteAsync(BitConverter.GetBytes(eph.QualifiedId.Id), this.TimeoutToken);
await eph.Output.WriteAsync(ephemeralMessage, this.TimeoutToken);
await eph.Acceptance;
}),
Task.Run(async delegate
{
var rpcChannel = await this.mx2.AcceptChannelAsync(string.Empty, this.TimeoutToken);
var buffer = new byte[ephemeralMessage.Length];
var readResult = await ReadAtLeastAsync(rpcChannel.AsStream(), new ArraySegment<byte>(buffer), sizeof(int), this.TimeoutToken);
int channelId = BitConverter.ToInt32(buffer, 0);
var eph = this.mx2.AcceptChannel(channelId);
Assert.True(eph.Acceptance.IsCompleted);
readResult = await ReadAtLeastAsync(eph.AsStream(), new ArraySegment<byte>(buffer), ephemeralMessage.Length, this.TimeoutToken);
Assert.Equal(ephemeralMessage, buffer);
})).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task EphemeralChannels_AcceptTwice_Throws()
{
await Task.WhenAll(
Task.Run(async delegate
{
var rpcChannel = await this.mx1.OfferChannelAsync(string.Empty, this.TimeoutToken);
var eph = this.mx1.CreateChannel();
await rpcChannel.Output.WriteAsync(BitConverter.GetBytes(eph.QualifiedId.Id), this.TimeoutToken);
await eph.Acceptance;
}),
Task.Run(async delegate
{
var buffer = new byte[sizeof(int)];
var rpcChannel = await this.mx2.AcceptChannelAsync(string.Empty, this.TimeoutToken);
var readResult = await ReadAtLeastAsync(rpcChannel.AsStream(), new ArraySegment<byte>(buffer), sizeof(int), this.TimeoutToken);
int channelId = BitConverter.ToInt32(buffer, 0);
var eph = this.mx2.AcceptChannel(channelId);
Assert.Throws<InvalidOperationException>(() => this.mx2.AcceptChannel(channelId));
})).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task EphemeralChannels_Rejected()
{
await Task.WhenAll(
Task.Run(async delegate
{
var rpcChannel = await this.mx1.OfferChannelAsync(string.Empty, this.TimeoutToken);
var eph = this.mx1.CreateChannel();
await rpcChannel.Output.WriteAsync(BitConverter.GetBytes(eph.QualifiedId.Id), this.TimeoutToken);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => eph.Acceptance).WithCancellation(this.TimeoutToken);
}),
Task.Run(async delegate
{
var buffer = new byte[sizeof(int)];
var rpcChannel = await this.mx2.AcceptChannelAsync(string.Empty, this.TimeoutToken);
var readResult = await ReadAtLeastAsync(rpcChannel.AsStream(), new ArraySegment<byte>(buffer), sizeof(int), this.TimeoutToken);
int channelId = BitConverter.ToInt32(buffer, 0);
this.mx2.RejectChannel(channelId);
// At this point, it's too late to accept
Assert.Throws<InvalidOperationException>(() => this.mx2.AcceptChannel(channelId));
})).WithCancellation(this.TimeoutToken);
}
[Fact]
public void AcceptChannel_NeverExisted()
{
Assert.Throws<InvalidOperationException>(() => this.mx1.AcceptChannel(15));
}
[Fact]
public async Task ChannelOfferedEvent_Anonymous_NotYetAccepted()
{
var mx1EventArgsSource = new TaskCompletionSource<MultiplexingStream.ChannelOfferEventArgs>();
var mx2EventArgsSource = new TaskCompletionSource<MultiplexingStream.ChannelOfferEventArgs>();
this.mx1.ChannelOffered += (s, e) =>
{
mx1EventArgsSource.SetResult(e);
};
this.mx2.ChannelOffered += (s, e) =>
{
mx2EventArgsSource.SetResult(e);
};
var channel = this.mx1.CreateChannel();
var mx2EventArgs = await mx2EventArgsSource.Task.WithCancellation(this.TimeoutToken);
Assert.Equal(channel.QualifiedId.Id, mx2EventArgs.QualifiedId.Id);
Assert.Equal(MultiplexingStream.ChannelSource.Remote, mx2EventArgs.QualifiedId.Source);
Assert.Equal(string.Empty, mx2EventArgs.Name);
Assert.False(mx2EventArgs.IsAccepted);
Assert.False(mx1EventArgsSource.Task.IsCompleted);
}
[Theory]
[PairwiseData]
public async Task ChannelOfferedEvent_Named(bool alreadyAccepted)
{
var mx1EventArgsSource = new TaskCompletionSource<MultiplexingStream.ChannelOfferEventArgs>();
var mx2EventArgsSource = new TaskCompletionSource<MultiplexingStream.ChannelOfferEventArgs>();
this.mx1.ChannelOffered += (s, e) =>
{
mx1EventArgsSource.SetResult(e);
};
this.mx2.ChannelOffered += (s, e) =>
{
mx2EventArgsSource.SetResult(e);
};
string channelName = "abc";
Task? acceptTask = null;
if (alreadyAccepted)
{
acceptTask = this.mx2.AcceptChannelAsync(channelName, this.TimeoutToken);
}
var channelOfferTask = this.mx1.OfferChannelAsync(channelName, this.TimeoutToken);
var mx2EventArgs = await mx2EventArgsSource.Task.WithCancellation(this.TimeoutToken);
if (!alreadyAccepted)
{
acceptTask = this.mx2.AcceptChannelAsync(channelName, this.TimeoutToken);
}
var offeredChannel = await channelOfferTask;
Assert.Equal(offeredChannel.QualifiedId.Id, mx2EventArgs.QualifiedId.Id);
Assert.Equal(MultiplexingStream.ChannelSource.Remote, mx2EventArgs.QualifiedId.Source);
Assert.Equal(channelName, mx2EventArgs.Name);
Assert.Equal(alreadyAccepted, mx2EventArgs.IsAccepted);
Assert.False(mx1EventArgsSource.Task.IsCompleted);
await acceptTask!.WithCancellation(this.TimeoutToken); // Rethrow any exceptions
}
[Fact]
public async Task ChannelAutoCloses_WhenBothEndsCompleteWriting()
{
var aMsg = new byte[] { 0x1 };
var bMsg = new byte[] { 0x2 };
var (a, b) = await this.EstablishChannelsAsync("a");
await a.Output.WriteAsync(aMsg, this.TimeoutToken);
a.Output.Complete();
var aMsgReceived = await b.Input.ReadAsync(this.TimeoutToken);
Assert.Equal(aMsg, aMsgReceived.Buffer.First.Span.ToArray());
b.Input.AdvanceTo(aMsgReceived.Buffer.End);
#pragma warning disable CS0618 // Type or member is obsolete
await b.Input.WaitForWriterCompletionAsync().WithCancellation(this.TimeoutToken);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.True((await b.Input.ReadAsync(this.TimeoutToken)).IsCompleted);
b.Input.Complete(); // ack the last message we received
await b.Output.WriteAsync(bMsg, this.TimeoutToken);
b.Output.Complete();
var bMsgReceived = await a.Input.ReadAsync(this.TimeoutToken);
Assert.Equal(bMsg, bMsgReceived.Buffer.First.Span.ToArray());
a.Input.AdvanceTo(bMsgReceived.Buffer.End);
#pragma warning disable CS0618 // Type or member is obsolete
await a.Input.WaitForWriterCompletionAsync().WithCancellation(this.TimeoutToken);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.True((await a.Input.ReadAsync(this.TimeoutToken)).IsCompleted);
a.Input.Complete(); // ack the last message we received
await Task.WhenAll(a.Completion, b.Completion).WithCancellation(this.TimeoutToken);
}
[Fact]
public async Task AcceptChannelAsync_WithExistingPipe_BeforeOffer()
{
var channel2OutboundPipe = new Pipe();
var channel2InboundPipe = new Pipe();
var channel2Stream = new DuplexPipe(channel2InboundPipe.Reader, channel2OutboundPipe.Writer).AsStream();
var channel2Options = new MultiplexingStream.ChannelOptions { ExistingPipe = new DuplexPipe(channel2OutboundPipe.Reader, channel2InboundPipe.Writer) };
const string channelName = "channelName";
var mx2ChannelTask = this.mx2.AcceptChannelAsync(channelName, channel2Options, this.TimeoutToken);
var mx1ChannelTask = this.mx1.OfferChannelAsync(channelName, this.TimeoutToken);
var channels = await Task.WhenAll(mx1ChannelTask, mx2ChannelTask).WithCancellation(this.TimeoutToken);
var channel1Stream = channels[0].AsStream();
await this.TransmitAndVerifyAsync(channel1Stream, channel2Stream, new byte[] { 1, 2, 3 });
await this.TransmitAndVerifyAsync(channel2Stream, channel1Stream, new byte[] { 4, 5, 6 });
}
[Fact]
public async Task OfferChannelAsync_WithExistingPipe()
{
var channel2OutboundPipe = new Pipe();
var channel2InboundPipe = new Pipe();
var channel2Stream = new DuplexPipe(channel2InboundPipe.Reader, channel2OutboundPipe.Writer).AsStream();
var channel2Options = new MultiplexingStream.ChannelOptions { ExistingPipe = new DuplexPipe(channel2OutboundPipe.Reader, channel2InboundPipe.Writer) };
const string channelName = "channelName";
var mx2ChannelTask = this.mx2.OfferChannelAsync(channelName, channel2Options, this.TimeoutToken);
var mx1ChannelTask = this.mx1.AcceptChannelAsync(channelName, this.TimeoutToken);
var channels = await Task.WhenAll(mx1ChannelTask, mx2ChannelTask).WithCancellation(this.TimeoutToken);
var channel1Stream = channels[0].AsStream();
await this.TransmitAndVerifyAsync(channel1Stream, channel2Stream, new byte[] { 1, 2, 3 });
await this.TransmitAndVerifyAsync(channel2Stream, channel1Stream, new byte[] { 4, 5, 6 });
}
/// <summary>
/// Create channel, send bytes before acceptance, accept and receive, then send more.
/// </summary>
[Fact]
public async Task ExistingPipe_Send_Accept_Recv_Send()
{
var packets = new byte[][]
{
new byte[] { 1, 2, 3 },
new byte[] { 4, 5, 6 },
new byte[] { 7, 8, 9 },
};
var channel2OutboundPipe = new Pipe();
var channel2InboundPipe = new Pipe();
var channel2Stream = new DuplexPipe(channel2InboundPipe.Reader, channel2OutboundPipe.Writer).AsStream();
var channel2Options = new MultiplexingStream.ChannelOptions { ExistingPipe = new DuplexPipe(channel2OutboundPipe.Reader, channel2InboundPipe.Writer) };
// Create the channel and transmit before it is accepted.
var channel1 = this.mx1.CreateChannel();
var channel1Stream = channel1.AsStream();
await channel1Stream.WriteAsync(packets[0], 0, packets[0].Length, this.TimeoutToken);
await channel1Stream.FlushAsync(this.TimeoutToken);
// Accept the channel and read the bytes
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var channel2 = this.mx2.AcceptChannel(channel1.QualifiedId.Id, channel2Options);
await this.VerifyReceivedDataAsync(channel2Stream, packets[0]);
// Verify we can transmit via the ExistingPipe.
await this.TransmitAndVerifyAsync(channel2Stream, channel1Stream, packets[1]);
// Verify we can receive more bytes via the ExistingPipe.
// MANUALLY VERIFY with debugger that received bytes are read DIRECTLY into channel2InboundPipe.Writer (no intermediary buffer copying).
await this.TransmitAndVerifyAsync(channel1Stream, channel2Stream, packets[2]);
}
/// <summary>
/// Create channel, send bytes before acceptance, then more before the accepting side is done draining the Pipe.
/// </summary>
[Fact]
public async Task ExistingPipe_Send_Accept_Send()
{
var packets = new byte[][]
{
new byte[] { 1, 2, 3 },
new byte[] { 4, 5, 6 },
};
var emptyReaderPipe = new Pipe();
emptyReaderPipe.Writer.Complete();
var slowWriter = new SlowPipeWriter();
var channel2Options = new MultiplexingStream.ChannelOptions
{
ExistingPipe = new DuplexPipe(emptyReaderPipe.Reader, slowWriter),
};
// Create the channel and transmit before it is accepted.
var channel1 = this.mx1.CreateChannel();
var channel1Stream = channel1.AsStream();
await channel1Stream.WriteAsync(packets[0], 0, packets[0].Length, this.TimeoutToken);
await channel1Stream.FlushAsync(this.TimeoutToken);
// Accept the channel
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var channel2 = this.mx2.AcceptChannel(channel1.QualifiedId.Id, channel2Options);
// Send MORE bytes
await channel1Stream.WriteAsync(packets[1], 0, packets[1].Length, this.TimeoutToken);
await channel1Stream.FlushAsync(this.TimeoutToken);
// Allow the copying of the first packet to our ExistingPipe to complete.
slowWriter.UnblockFlushAsync.Set();
// Wait for all bytes to be transmitted
channel1.Output.Complete();
await slowWriter.Completion;
// Verify that we received them all, in order.
Assert.Equal(packets[0].Concat(packets[1]).ToArray(), slowWriter.WrittenBytes.ToArray());
}
[Fact]
public async Task CreateChannel_BlastLotsOfData()
{
const int DataSize = 1024 * 1024;
var channelOptions = new MultiplexingStream.ChannelOptions
{
ChannelReceivingWindowSize = DataSize,
};
var channel1 = this.mx1.CreateChannel(channelOptions);
// Blast a bunch of data to the channel as soon as it is accepted.
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var channel2 = this.mx2.AcceptChannel(channel1.QualifiedId.Id, channelOptions);
await channel2.Output.WriteAsync(new byte[DataSize], this.TimeoutToken);
// Read all the data, such that the PipeReader has to buffer until the whole payload is read.
// Since this is a LOT of data, this would normally overrun the Pipe's max buffer size.
// If this succeeds, then we know the PipeOptions instance we supplied was taken into account.
int bytesRead = 0;
while (bytesRead < DataSize)
{
var readResult = await channel1.Input.ReadAsync(this.TimeoutToken);
bytesRead += (int)readResult.Buffer.Length;
SequencePosition consumed = bytesRead == DataSize ? readResult.Buffer.End : readResult.Buffer.Start;
channel1.Input.AdvanceTo(consumed, readResult.Buffer.End);
}
}
[Theory]
[PairwiseData]
public async Task AcceptChannel_InputPipeOptions(bool acceptBeforeTransmit)
{
// We have to use a smaller data size when transmitting before acceptance to avoid a deadlock due to the limited buffer size of channels.
int dataSize = acceptBeforeTransmit ? 1024 * 1024 : 16 * 1024;
var channelOptions = new MultiplexingStream.ChannelOptions
{
ChannelReceivingWindowSize = 2 * 1024 * 1024,
};
var channel1 = this.mx1.CreateChannel();
await this.WaitForEphemeralChannelOfferToPropagateAsync();
var bytesWrittenEvent = new AsyncManualResetEvent();
await Task.WhenAll(Party1Async(), Party2Async());
async Task Party1Async()
{
if (acceptBeforeTransmit)
{
await channel1.Acceptance.WithCancellation(this.TimeoutToken);
}
await channel1.Output.WriteAsync(new byte[dataSize], this.TimeoutToken);
bytesWrittenEvent.Set();
}
async Task Party2Async()
{
if (!acceptBeforeTransmit)
{
await bytesWrittenEvent.WaitAsync(this.TimeoutToken);
}
var channel2 = this.mx2.AcceptChannel(channel1.QualifiedId.Id, channelOptions);
// Read all the data, such that the PipeReader has to buffer until the whole payload is read.
// Since this is a LOT of data, this would normally overrun the Pipe's max buffer size.
// If this succeeds, then we know the PipeOptions instance we supplied was taken into account.
int bytesRead = 0;
while (bytesRead < dataSize)
{
var readResult = await channel2.Input.ReadAsync(this.TimeoutToken);
bytesRead += (int)readResult.Buffer.Length;
SequencePosition consumed = bytesRead == dataSize ? readResult.Buffer.End : readResult.Buffer.Start;
channel2.Input.AdvanceTo(consumed, readResult.Buffer.End);
}
}
}
[Fact]
public virtual async Task SeededChannels()
{
var pair = FullDuplexStream.CreatePair();
var options = new MultiplexingStream.Options
{
ProtocolMajorVersion = this.ProtocolMajorVersion,
SeededChannels =
{
new MultiplexingStream.ChannelOptions { },
new MultiplexingStream.ChannelOptions { },
},
};
await Assert.ThrowsAsync<NotSupportedException>(() => Task.WhenAll(
MultiplexingStream.CreateAsync(pair.Item1, options, this.TimeoutToken),
MultiplexingStream.CreateAsync(pair.Item2, options, this.TimeoutToken)));
}
protected static Task CompleteChannelsAsync(params MultiplexingStream.Channel[] channels)
{
foreach (var channel in channels)
{
channel.Output.Complete();
}
return Task.WhenAll(channels.Select(c => c.Completion));
}
protected async Task WaitForEphemeralChannelOfferToPropagateAsync()
{
// Propagation of ephemeral channel offers must occur before the remote end can accept it.
// The simplest way to guarantee that the offer has propagated is to send another message after the offer
// and wait for that message to be received.
// The "message" we send is an offer for a named channel, since that can be awaited on to accept.
const string ChannelName = "EphemeralChannelWaiter";
var channels = await Task.WhenAll(
this.mx1.OfferChannelAsync(ChannelName, this.TimeoutToken),
this.mx2.AcceptChannelAsync(ChannelName, this.TimeoutToken)).WithCancellation(this.TimeoutToken);
channels[0].Dispose();
channels[1].Dispose();
}
protected async Task<(MultiplexingStream.Channel, MultiplexingStream.Channel)> EstablishChannelsAsync(string identifier, long? receivingWindowSize = null)
{
var channelOptions = new MultiplexingStream.ChannelOptions { ChannelReceivingWindowSize = receivingWindowSize };
var mx1ChannelTask = this.mx1.OfferChannelAsync(identifier, channelOptions, this.TimeoutToken);
var mx2ChannelTask = this.mx2.AcceptChannelAsync(identifier, channelOptions, this.TimeoutToken);
var channels = await WhenAllSucceedOrAnyFail(mx1ChannelTask, mx2ChannelTask).WithCancellation(this.TimeoutToken);
Assert.NotNull(channels[0]);
Assert.NotNull(channels[1]);
return (channels[0], channels[1]);
}
protected async Task<(Stream, Stream)> EstablishChannelStreamsAsync(string identifier, long? receivingWindowSize = null)
{
var (channel1, channel2) = await this.EstablishChannelsAsync(identifier, receivingWindowSize);
return (channel1.AsStream(), channel2.AsStream());
}
protected class SlowPipeWriter : PipeWriter
{
private readonly Sequence<byte> writtenBytes = new Sequence<byte>();
private readonly TaskCompletionSource<object?> completionSource = new TaskCompletionSource<object?>();
private CancellationTokenSource nextFlushToken = new CancellationTokenSource();
internal AsyncManualResetEvent UnblockFlushAsync { get; } = new AsyncManualResetEvent();
internal ReadOnlySequence<byte> WrittenBytes => this.writtenBytes.AsReadOnlySequence;
internal Task Completion => this.completionSource.Task;
public override void Advance(int bytes)
{
Verify.Operation(!this.completionSource.Task.IsCompleted, "Writing already completed.");
this.writtenBytes.Advance(bytes);
}
public override void CancelPendingFlush() => this.nextFlushToken.Cancel();
public override void Complete(Exception? exception = null)
{
if (exception == null)
{
this.completionSource.TrySetResult(null);
}
else
{
this.completionSource.TrySetException(exception);
}
}
public override async ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default)
{
try
{
await this.UnblockFlushAsync.WaitAsync(cancellationToken);
return default;
}
finally
{
if (this.nextFlushToken.IsCancellationRequested)
{
this.nextFlushToken = new CancellationTokenSource();
}
}
}
public override Memory<byte> GetMemory(int sizeHint = 0)
{
Verify.Operation(!this.completionSource.Task.IsCompleted, "Writing already completed.");
return this.writtenBytes.GetMemory(sizeHint);
}
public override Span<byte> GetSpan(int sizeHint = 0) => this.GetMemory(sizeHint).Span;
[Obsolete]
public override void OnReaderCompleted(Action<Exception?, object> callback, object state)
{
// We don't have a reader that consumers of this mock need to worry about,
// so just say we're done when the writing is done.
this.Completion.ContinueWith(c => callback(c.Exception, state), TaskScheduler.Default).Forget();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations.Infrastructure;
using RemoteKatana.Models;
namespace RemoteKatana.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("RemoteKatana.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("RemoteKatana.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("RemoteKatana.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("RemoteKatana.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type int with 3 components, used for implementing swizzling for ivec3.
/// </summary>
[Serializable]
[DataContract(Namespace = "swizzle")]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_ivec3
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
internal readonly int x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
internal readonly int y;
/// <summary>
/// z-component
/// </summary>
[DataMember]
internal readonly int z;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_ivec3.
/// </summary>
internal swizzle_ivec3(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
#endregion
#region Properties
/// <summary>
/// Returns ivec3.xx swizzling.
/// </summary>
public ivec2 xx => new ivec2(x, x);
/// <summary>
/// Returns ivec3.rr swizzling (equivalent to ivec3.xx).
/// </summary>
public ivec2 rr => new ivec2(x, x);
/// <summary>
/// Returns ivec3.xxx swizzling.
/// </summary>
public ivec3 xxx => new ivec3(x, x, x);
/// <summary>
/// Returns ivec3.rrr swizzling (equivalent to ivec3.xxx).
/// </summary>
public ivec3 rrr => new ivec3(x, x, x);
/// <summary>
/// Returns ivec3.xxxx swizzling.
/// </summary>
public ivec4 xxxx => new ivec4(x, x, x, x);
/// <summary>
/// Returns ivec3.rrrr swizzling (equivalent to ivec3.xxxx).
/// </summary>
public ivec4 rrrr => new ivec4(x, x, x, x);
/// <summary>
/// Returns ivec3.xxxy swizzling.
/// </summary>
public ivec4 xxxy => new ivec4(x, x, x, y);
/// <summary>
/// Returns ivec3.rrrg swizzling (equivalent to ivec3.xxxy).
/// </summary>
public ivec4 rrrg => new ivec4(x, x, x, y);
/// <summary>
/// Returns ivec3.xxxz swizzling.
/// </summary>
public ivec4 xxxz => new ivec4(x, x, x, z);
/// <summary>
/// Returns ivec3.rrrb swizzling (equivalent to ivec3.xxxz).
/// </summary>
public ivec4 rrrb => new ivec4(x, x, x, z);
/// <summary>
/// Returns ivec3.xxy swizzling.
/// </summary>
public ivec3 xxy => new ivec3(x, x, y);
/// <summary>
/// Returns ivec3.rrg swizzling (equivalent to ivec3.xxy).
/// </summary>
public ivec3 rrg => new ivec3(x, x, y);
/// <summary>
/// Returns ivec3.xxyx swizzling.
/// </summary>
public ivec4 xxyx => new ivec4(x, x, y, x);
/// <summary>
/// Returns ivec3.rrgr swizzling (equivalent to ivec3.xxyx).
/// </summary>
public ivec4 rrgr => new ivec4(x, x, y, x);
/// <summary>
/// Returns ivec3.xxyy swizzling.
/// </summary>
public ivec4 xxyy => new ivec4(x, x, y, y);
/// <summary>
/// Returns ivec3.rrgg swizzling (equivalent to ivec3.xxyy).
/// </summary>
public ivec4 rrgg => new ivec4(x, x, y, y);
/// <summary>
/// Returns ivec3.xxyz swizzling.
/// </summary>
public ivec4 xxyz => new ivec4(x, x, y, z);
/// <summary>
/// Returns ivec3.rrgb swizzling (equivalent to ivec3.xxyz).
/// </summary>
public ivec4 rrgb => new ivec4(x, x, y, z);
/// <summary>
/// Returns ivec3.xxz swizzling.
/// </summary>
public ivec3 xxz => new ivec3(x, x, z);
/// <summary>
/// Returns ivec3.rrb swizzling (equivalent to ivec3.xxz).
/// </summary>
public ivec3 rrb => new ivec3(x, x, z);
/// <summary>
/// Returns ivec3.xxzx swizzling.
/// </summary>
public ivec4 xxzx => new ivec4(x, x, z, x);
/// <summary>
/// Returns ivec3.rrbr swizzling (equivalent to ivec3.xxzx).
/// </summary>
public ivec4 rrbr => new ivec4(x, x, z, x);
/// <summary>
/// Returns ivec3.xxzy swizzling.
/// </summary>
public ivec4 xxzy => new ivec4(x, x, z, y);
/// <summary>
/// Returns ivec3.rrbg swizzling (equivalent to ivec3.xxzy).
/// </summary>
public ivec4 rrbg => new ivec4(x, x, z, y);
/// <summary>
/// Returns ivec3.xxzz swizzling.
/// </summary>
public ivec4 xxzz => new ivec4(x, x, z, z);
/// <summary>
/// Returns ivec3.rrbb swizzling (equivalent to ivec3.xxzz).
/// </summary>
public ivec4 rrbb => new ivec4(x, x, z, z);
/// <summary>
/// Returns ivec3.xy swizzling.
/// </summary>
public ivec2 xy => new ivec2(x, y);
/// <summary>
/// Returns ivec3.rg swizzling (equivalent to ivec3.xy).
/// </summary>
public ivec2 rg => new ivec2(x, y);
/// <summary>
/// Returns ivec3.xyx swizzling.
/// </summary>
public ivec3 xyx => new ivec3(x, y, x);
/// <summary>
/// Returns ivec3.rgr swizzling (equivalent to ivec3.xyx).
/// </summary>
public ivec3 rgr => new ivec3(x, y, x);
/// <summary>
/// Returns ivec3.xyxx swizzling.
/// </summary>
public ivec4 xyxx => new ivec4(x, y, x, x);
/// <summary>
/// Returns ivec3.rgrr swizzling (equivalent to ivec3.xyxx).
/// </summary>
public ivec4 rgrr => new ivec4(x, y, x, x);
/// <summary>
/// Returns ivec3.xyxy swizzling.
/// </summary>
public ivec4 xyxy => new ivec4(x, y, x, y);
/// <summary>
/// Returns ivec3.rgrg swizzling (equivalent to ivec3.xyxy).
/// </summary>
public ivec4 rgrg => new ivec4(x, y, x, y);
/// <summary>
/// Returns ivec3.xyxz swizzling.
/// </summary>
public ivec4 xyxz => new ivec4(x, y, x, z);
/// <summary>
/// Returns ivec3.rgrb swizzling (equivalent to ivec3.xyxz).
/// </summary>
public ivec4 rgrb => new ivec4(x, y, x, z);
/// <summary>
/// Returns ivec3.xyy swizzling.
/// </summary>
public ivec3 xyy => new ivec3(x, y, y);
/// <summary>
/// Returns ivec3.rgg swizzling (equivalent to ivec3.xyy).
/// </summary>
public ivec3 rgg => new ivec3(x, y, y);
/// <summary>
/// Returns ivec3.xyyx swizzling.
/// </summary>
public ivec4 xyyx => new ivec4(x, y, y, x);
/// <summary>
/// Returns ivec3.rggr swizzling (equivalent to ivec3.xyyx).
/// </summary>
public ivec4 rggr => new ivec4(x, y, y, x);
/// <summary>
/// Returns ivec3.xyyy swizzling.
/// </summary>
public ivec4 xyyy => new ivec4(x, y, y, y);
/// <summary>
/// Returns ivec3.rggg swizzling (equivalent to ivec3.xyyy).
/// </summary>
public ivec4 rggg => new ivec4(x, y, y, y);
/// <summary>
/// Returns ivec3.xyyz swizzling.
/// </summary>
public ivec4 xyyz => new ivec4(x, y, y, z);
/// <summary>
/// Returns ivec3.rggb swizzling (equivalent to ivec3.xyyz).
/// </summary>
public ivec4 rggb => new ivec4(x, y, y, z);
/// <summary>
/// Returns ivec3.xyz swizzling.
/// </summary>
public ivec3 xyz => new ivec3(x, y, z);
/// <summary>
/// Returns ivec3.rgb swizzling (equivalent to ivec3.xyz).
/// </summary>
public ivec3 rgb => new ivec3(x, y, z);
/// <summary>
/// Returns ivec3.xyzx swizzling.
/// </summary>
public ivec4 xyzx => new ivec4(x, y, z, x);
/// <summary>
/// Returns ivec3.rgbr swizzling (equivalent to ivec3.xyzx).
/// </summary>
public ivec4 rgbr => new ivec4(x, y, z, x);
/// <summary>
/// Returns ivec3.xyzy swizzling.
/// </summary>
public ivec4 xyzy => new ivec4(x, y, z, y);
/// <summary>
/// Returns ivec3.rgbg swizzling (equivalent to ivec3.xyzy).
/// </summary>
public ivec4 rgbg => new ivec4(x, y, z, y);
/// <summary>
/// Returns ivec3.xyzz swizzling.
/// </summary>
public ivec4 xyzz => new ivec4(x, y, z, z);
/// <summary>
/// Returns ivec3.rgbb swizzling (equivalent to ivec3.xyzz).
/// </summary>
public ivec4 rgbb => new ivec4(x, y, z, z);
/// <summary>
/// Returns ivec3.xz swizzling.
/// </summary>
public ivec2 xz => new ivec2(x, z);
/// <summary>
/// Returns ivec3.rb swizzling (equivalent to ivec3.xz).
/// </summary>
public ivec2 rb => new ivec2(x, z);
/// <summary>
/// Returns ivec3.xzx swizzling.
/// </summary>
public ivec3 xzx => new ivec3(x, z, x);
/// <summary>
/// Returns ivec3.rbr swizzling (equivalent to ivec3.xzx).
/// </summary>
public ivec3 rbr => new ivec3(x, z, x);
/// <summary>
/// Returns ivec3.xzxx swizzling.
/// </summary>
public ivec4 xzxx => new ivec4(x, z, x, x);
/// <summary>
/// Returns ivec3.rbrr swizzling (equivalent to ivec3.xzxx).
/// </summary>
public ivec4 rbrr => new ivec4(x, z, x, x);
/// <summary>
/// Returns ivec3.xzxy swizzling.
/// </summary>
public ivec4 xzxy => new ivec4(x, z, x, y);
/// <summary>
/// Returns ivec3.rbrg swizzling (equivalent to ivec3.xzxy).
/// </summary>
public ivec4 rbrg => new ivec4(x, z, x, y);
/// <summary>
/// Returns ivec3.xzxz swizzling.
/// </summary>
public ivec4 xzxz => new ivec4(x, z, x, z);
/// <summary>
/// Returns ivec3.rbrb swizzling (equivalent to ivec3.xzxz).
/// </summary>
public ivec4 rbrb => new ivec4(x, z, x, z);
/// <summary>
/// Returns ivec3.xzy swizzling.
/// </summary>
public ivec3 xzy => new ivec3(x, z, y);
/// <summary>
/// Returns ivec3.rbg swizzling (equivalent to ivec3.xzy).
/// </summary>
public ivec3 rbg => new ivec3(x, z, y);
/// <summary>
/// Returns ivec3.xzyx swizzling.
/// </summary>
public ivec4 xzyx => new ivec4(x, z, y, x);
/// <summary>
/// Returns ivec3.rbgr swizzling (equivalent to ivec3.xzyx).
/// </summary>
public ivec4 rbgr => new ivec4(x, z, y, x);
/// <summary>
/// Returns ivec3.xzyy swizzling.
/// </summary>
public ivec4 xzyy => new ivec4(x, z, y, y);
/// <summary>
/// Returns ivec3.rbgg swizzling (equivalent to ivec3.xzyy).
/// </summary>
public ivec4 rbgg => new ivec4(x, z, y, y);
/// <summary>
/// Returns ivec3.xzyz swizzling.
/// </summary>
public ivec4 xzyz => new ivec4(x, z, y, z);
/// <summary>
/// Returns ivec3.rbgb swizzling (equivalent to ivec3.xzyz).
/// </summary>
public ivec4 rbgb => new ivec4(x, z, y, z);
/// <summary>
/// Returns ivec3.xzz swizzling.
/// </summary>
public ivec3 xzz => new ivec3(x, z, z);
/// <summary>
/// Returns ivec3.rbb swizzling (equivalent to ivec3.xzz).
/// </summary>
public ivec3 rbb => new ivec3(x, z, z);
/// <summary>
/// Returns ivec3.xzzx swizzling.
/// </summary>
public ivec4 xzzx => new ivec4(x, z, z, x);
/// <summary>
/// Returns ivec3.rbbr swizzling (equivalent to ivec3.xzzx).
/// </summary>
public ivec4 rbbr => new ivec4(x, z, z, x);
/// <summary>
/// Returns ivec3.xzzy swizzling.
/// </summary>
public ivec4 xzzy => new ivec4(x, z, z, y);
/// <summary>
/// Returns ivec3.rbbg swizzling (equivalent to ivec3.xzzy).
/// </summary>
public ivec4 rbbg => new ivec4(x, z, z, y);
/// <summary>
/// Returns ivec3.xzzz swizzling.
/// </summary>
public ivec4 xzzz => new ivec4(x, z, z, z);
/// <summary>
/// Returns ivec3.rbbb swizzling (equivalent to ivec3.xzzz).
/// </summary>
public ivec4 rbbb => new ivec4(x, z, z, z);
/// <summary>
/// Returns ivec3.yx swizzling.
/// </summary>
public ivec2 yx => new ivec2(y, x);
/// <summary>
/// Returns ivec3.gr swizzling (equivalent to ivec3.yx).
/// </summary>
public ivec2 gr => new ivec2(y, x);
/// <summary>
/// Returns ivec3.yxx swizzling.
/// </summary>
public ivec3 yxx => new ivec3(y, x, x);
/// <summary>
/// Returns ivec3.grr swizzling (equivalent to ivec3.yxx).
/// </summary>
public ivec3 grr => new ivec3(y, x, x);
/// <summary>
/// Returns ivec3.yxxx swizzling.
/// </summary>
public ivec4 yxxx => new ivec4(y, x, x, x);
/// <summary>
/// Returns ivec3.grrr swizzling (equivalent to ivec3.yxxx).
/// </summary>
public ivec4 grrr => new ivec4(y, x, x, x);
/// <summary>
/// Returns ivec3.yxxy swizzling.
/// </summary>
public ivec4 yxxy => new ivec4(y, x, x, y);
/// <summary>
/// Returns ivec3.grrg swizzling (equivalent to ivec3.yxxy).
/// </summary>
public ivec4 grrg => new ivec4(y, x, x, y);
/// <summary>
/// Returns ivec3.yxxz swizzling.
/// </summary>
public ivec4 yxxz => new ivec4(y, x, x, z);
/// <summary>
/// Returns ivec3.grrb swizzling (equivalent to ivec3.yxxz).
/// </summary>
public ivec4 grrb => new ivec4(y, x, x, z);
/// <summary>
/// Returns ivec3.yxy swizzling.
/// </summary>
public ivec3 yxy => new ivec3(y, x, y);
/// <summary>
/// Returns ivec3.grg swizzling (equivalent to ivec3.yxy).
/// </summary>
public ivec3 grg => new ivec3(y, x, y);
/// <summary>
/// Returns ivec3.yxyx swizzling.
/// </summary>
public ivec4 yxyx => new ivec4(y, x, y, x);
/// <summary>
/// Returns ivec3.grgr swizzling (equivalent to ivec3.yxyx).
/// </summary>
public ivec4 grgr => new ivec4(y, x, y, x);
/// <summary>
/// Returns ivec3.yxyy swizzling.
/// </summary>
public ivec4 yxyy => new ivec4(y, x, y, y);
/// <summary>
/// Returns ivec3.grgg swizzling (equivalent to ivec3.yxyy).
/// </summary>
public ivec4 grgg => new ivec4(y, x, y, y);
/// <summary>
/// Returns ivec3.yxyz swizzling.
/// </summary>
public ivec4 yxyz => new ivec4(y, x, y, z);
/// <summary>
/// Returns ivec3.grgb swizzling (equivalent to ivec3.yxyz).
/// </summary>
public ivec4 grgb => new ivec4(y, x, y, z);
/// <summary>
/// Returns ivec3.yxz swizzling.
/// </summary>
public ivec3 yxz => new ivec3(y, x, z);
/// <summary>
/// Returns ivec3.grb swizzling (equivalent to ivec3.yxz).
/// </summary>
public ivec3 grb => new ivec3(y, x, z);
/// <summary>
/// Returns ivec3.yxzx swizzling.
/// </summary>
public ivec4 yxzx => new ivec4(y, x, z, x);
/// <summary>
/// Returns ivec3.grbr swizzling (equivalent to ivec3.yxzx).
/// </summary>
public ivec4 grbr => new ivec4(y, x, z, x);
/// <summary>
/// Returns ivec3.yxzy swizzling.
/// </summary>
public ivec4 yxzy => new ivec4(y, x, z, y);
/// <summary>
/// Returns ivec3.grbg swizzling (equivalent to ivec3.yxzy).
/// </summary>
public ivec4 grbg => new ivec4(y, x, z, y);
/// <summary>
/// Returns ivec3.yxzz swizzling.
/// </summary>
public ivec4 yxzz => new ivec4(y, x, z, z);
/// <summary>
/// Returns ivec3.grbb swizzling (equivalent to ivec3.yxzz).
/// </summary>
public ivec4 grbb => new ivec4(y, x, z, z);
/// <summary>
/// Returns ivec3.yy swizzling.
/// </summary>
public ivec2 yy => new ivec2(y, y);
/// <summary>
/// Returns ivec3.gg swizzling (equivalent to ivec3.yy).
/// </summary>
public ivec2 gg => new ivec2(y, y);
/// <summary>
/// Returns ivec3.yyx swizzling.
/// </summary>
public ivec3 yyx => new ivec3(y, y, x);
/// <summary>
/// Returns ivec3.ggr swizzling (equivalent to ivec3.yyx).
/// </summary>
public ivec3 ggr => new ivec3(y, y, x);
/// <summary>
/// Returns ivec3.yyxx swizzling.
/// </summary>
public ivec4 yyxx => new ivec4(y, y, x, x);
/// <summary>
/// Returns ivec3.ggrr swizzling (equivalent to ivec3.yyxx).
/// </summary>
public ivec4 ggrr => new ivec4(y, y, x, x);
/// <summary>
/// Returns ivec3.yyxy swizzling.
/// </summary>
public ivec4 yyxy => new ivec4(y, y, x, y);
/// <summary>
/// Returns ivec3.ggrg swizzling (equivalent to ivec3.yyxy).
/// </summary>
public ivec4 ggrg => new ivec4(y, y, x, y);
/// <summary>
/// Returns ivec3.yyxz swizzling.
/// </summary>
public ivec4 yyxz => new ivec4(y, y, x, z);
/// <summary>
/// Returns ivec3.ggrb swizzling (equivalent to ivec3.yyxz).
/// </summary>
public ivec4 ggrb => new ivec4(y, y, x, z);
/// <summary>
/// Returns ivec3.yyy swizzling.
/// </summary>
public ivec3 yyy => new ivec3(y, y, y);
/// <summary>
/// Returns ivec3.ggg swizzling (equivalent to ivec3.yyy).
/// </summary>
public ivec3 ggg => new ivec3(y, y, y);
/// <summary>
/// Returns ivec3.yyyx swizzling.
/// </summary>
public ivec4 yyyx => new ivec4(y, y, y, x);
/// <summary>
/// Returns ivec3.gggr swizzling (equivalent to ivec3.yyyx).
/// </summary>
public ivec4 gggr => new ivec4(y, y, y, x);
/// <summary>
/// Returns ivec3.yyyy swizzling.
/// </summary>
public ivec4 yyyy => new ivec4(y, y, y, y);
/// <summary>
/// Returns ivec3.gggg swizzling (equivalent to ivec3.yyyy).
/// </summary>
public ivec4 gggg => new ivec4(y, y, y, y);
/// <summary>
/// Returns ivec3.yyyz swizzling.
/// </summary>
public ivec4 yyyz => new ivec4(y, y, y, z);
/// <summary>
/// Returns ivec3.gggb swizzling (equivalent to ivec3.yyyz).
/// </summary>
public ivec4 gggb => new ivec4(y, y, y, z);
/// <summary>
/// Returns ivec3.yyz swizzling.
/// </summary>
public ivec3 yyz => new ivec3(y, y, z);
/// <summary>
/// Returns ivec3.ggb swizzling (equivalent to ivec3.yyz).
/// </summary>
public ivec3 ggb => new ivec3(y, y, z);
/// <summary>
/// Returns ivec3.yyzx swizzling.
/// </summary>
public ivec4 yyzx => new ivec4(y, y, z, x);
/// <summary>
/// Returns ivec3.ggbr swizzling (equivalent to ivec3.yyzx).
/// </summary>
public ivec4 ggbr => new ivec4(y, y, z, x);
/// <summary>
/// Returns ivec3.yyzy swizzling.
/// </summary>
public ivec4 yyzy => new ivec4(y, y, z, y);
/// <summary>
/// Returns ivec3.ggbg swizzling (equivalent to ivec3.yyzy).
/// </summary>
public ivec4 ggbg => new ivec4(y, y, z, y);
/// <summary>
/// Returns ivec3.yyzz swizzling.
/// </summary>
public ivec4 yyzz => new ivec4(y, y, z, z);
/// <summary>
/// Returns ivec3.ggbb swizzling (equivalent to ivec3.yyzz).
/// </summary>
public ivec4 ggbb => new ivec4(y, y, z, z);
/// <summary>
/// Returns ivec3.yz swizzling.
/// </summary>
public ivec2 yz => new ivec2(y, z);
/// <summary>
/// Returns ivec3.gb swizzling (equivalent to ivec3.yz).
/// </summary>
public ivec2 gb => new ivec2(y, z);
/// <summary>
/// Returns ivec3.yzx swizzling.
/// </summary>
public ivec3 yzx => new ivec3(y, z, x);
/// <summary>
/// Returns ivec3.gbr swizzling (equivalent to ivec3.yzx).
/// </summary>
public ivec3 gbr => new ivec3(y, z, x);
/// <summary>
/// Returns ivec3.yzxx swizzling.
/// </summary>
public ivec4 yzxx => new ivec4(y, z, x, x);
/// <summary>
/// Returns ivec3.gbrr swizzling (equivalent to ivec3.yzxx).
/// </summary>
public ivec4 gbrr => new ivec4(y, z, x, x);
/// <summary>
/// Returns ivec3.yzxy swizzling.
/// </summary>
public ivec4 yzxy => new ivec4(y, z, x, y);
/// <summary>
/// Returns ivec3.gbrg swizzling (equivalent to ivec3.yzxy).
/// </summary>
public ivec4 gbrg => new ivec4(y, z, x, y);
/// <summary>
/// Returns ivec3.yzxz swizzling.
/// </summary>
public ivec4 yzxz => new ivec4(y, z, x, z);
/// <summary>
/// Returns ivec3.gbrb swizzling (equivalent to ivec3.yzxz).
/// </summary>
public ivec4 gbrb => new ivec4(y, z, x, z);
/// <summary>
/// Returns ivec3.yzy swizzling.
/// </summary>
public ivec3 yzy => new ivec3(y, z, y);
/// <summary>
/// Returns ivec3.gbg swizzling (equivalent to ivec3.yzy).
/// </summary>
public ivec3 gbg => new ivec3(y, z, y);
/// <summary>
/// Returns ivec3.yzyx swizzling.
/// </summary>
public ivec4 yzyx => new ivec4(y, z, y, x);
/// <summary>
/// Returns ivec3.gbgr swizzling (equivalent to ivec3.yzyx).
/// </summary>
public ivec4 gbgr => new ivec4(y, z, y, x);
/// <summary>
/// Returns ivec3.yzyy swizzling.
/// </summary>
public ivec4 yzyy => new ivec4(y, z, y, y);
/// <summary>
/// Returns ivec3.gbgg swizzling (equivalent to ivec3.yzyy).
/// </summary>
public ivec4 gbgg => new ivec4(y, z, y, y);
/// <summary>
/// Returns ivec3.yzyz swizzling.
/// </summary>
public ivec4 yzyz => new ivec4(y, z, y, z);
/// <summary>
/// Returns ivec3.gbgb swizzling (equivalent to ivec3.yzyz).
/// </summary>
public ivec4 gbgb => new ivec4(y, z, y, z);
/// <summary>
/// Returns ivec3.yzz swizzling.
/// </summary>
public ivec3 yzz => new ivec3(y, z, z);
/// <summary>
/// Returns ivec3.gbb swizzling (equivalent to ivec3.yzz).
/// </summary>
public ivec3 gbb => new ivec3(y, z, z);
/// <summary>
/// Returns ivec3.yzzx swizzling.
/// </summary>
public ivec4 yzzx => new ivec4(y, z, z, x);
/// <summary>
/// Returns ivec3.gbbr swizzling (equivalent to ivec3.yzzx).
/// </summary>
public ivec4 gbbr => new ivec4(y, z, z, x);
/// <summary>
/// Returns ivec3.yzzy swizzling.
/// </summary>
public ivec4 yzzy => new ivec4(y, z, z, y);
/// <summary>
/// Returns ivec3.gbbg swizzling (equivalent to ivec3.yzzy).
/// </summary>
public ivec4 gbbg => new ivec4(y, z, z, y);
/// <summary>
/// Returns ivec3.yzzz swizzling.
/// </summary>
public ivec4 yzzz => new ivec4(y, z, z, z);
/// <summary>
/// Returns ivec3.gbbb swizzling (equivalent to ivec3.yzzz).
/// </summary>
public ivec4 gbbb => new ivec4(y, z, z, z);
/// <summary>
/// Returns ivec3.zx swizzling.
/// </summary>
public ivec2 zx => new ivec2(z, x);
/// <summary>
/// Returns ivec3.br swizzling (equivalent to ivec3.zx).
/// </summary>
public ivec2 br => new ivec2(z, x);
/// <summary>
/// Returns ivec3.zxx swizzling.
/// </summary>
public ivec3 zxx => new ivec3(z, x, x);
/// <summary>
/// Returns ivec3.brr swizzling (equivalent to ivec3.zxx).
/// </summary>
public ivec3 brr => new ivec3(z, x, x);
/// <summary>
/// Returns ivec3.zxxx swizzling.
/// </summary>
public ivec4 zxxx => new ivec4(z, x, x, x);
/// <summary>
/// Returns ivec3.brrr swizzling (equivalent to ivec3.zxxx).
/// </summary>
public ivec4 brrr => new ivec4(z, x, x, x);
/// <summary>
/// Returns ivec3.zxxy swizzling.
/// </summary>
public ivec4 zxxy => new ivec4(z, x, x, y);
/// <summary>
/// Returns ivec3.brrg swizzling (equivalent to ivec3.zxxy).
/// </summary>
public ivec4 brrg => new ivec4(z, x, x, y);
/// <summary>
/// Returns ivec3.zxxz swizzling.
/// </summary>
public ivec4 zxxz => new ivec4(z, x, x, z);
/// <summary>
/// Returns ivec3.brrb swizzling (equivalent to ivec3.zxxz).
/// </summary>
public ivec4 brrb => new ivec4(z, x, x, z);
/// <summary>
/// Returns ivec3.zxy swizzling.
/// </summary>
public ivec3 zxy => new ivec3(z, x, y);
/// <summary>
/// Returns ivec3.brg swizzling (equivalent to ivec3.zxy).
/// </summary>
public ivec3 brg => new ivec3(z, x, y);
/// <summary>
/// Returns ivec3.zxyx swizzling.
/// </summary>
public ivec4 zxyx => new ivec4(z, x, y, x);
/// <summary>
/// Returns ivec3.brgr swizzling (equivalent to ivec3.zxyx).
/// </summary>
public ivec4 brgr => new ivec4(z, x, y, x);
/// <summary>
/// Returns ivec3.zxyy swizzling.
/// </summary>
public ivec4 zxyy => new ivec4(z, x, y, y);
/// <summary>
/// Returns ivec3.brgg swizzling (equivalent to ivec3.zxyy).
/// </summary>
public ivec4 brgg => new ivec4(z, x, y, y);
/// <summary>
/// Returns ivec3.zxyz swizzling.
/// </summary>
public ivec4 zxyz => new ivec4(z, x, y, z);
/// <summary>
/// Returns ivec3.brgb swizzling (equivalent to ivec3.zxyz).
/// </summary>
public ivec4 brgb => new ivec4(z, x, y, z);
/// <summary>
/// Returns ivec3.zxz swizzling.
/// </summary>
public ivec3 zxz => new ivec3(z, x, z);
/// <summary>
/// Returns ivec3.brb swizzling (equivalent to ivec3.zxz).
/// </summary>
public ivec3 brb => new ivec3(z, x, z);
/// <summary>
/// Returns ivec3.zxzx swizzling.
/// </summary>
public ivec4 zxzx => new ivec4(z, x, z, x);
/// <summary>
/// Returns ivec3.brbr swizzling (equivalent to ivec3.zxzx).
/// </summary>
public ivec4 brbr => new ivec4(z, x, z, x);
/// <summary>
/// Returns ivec3.zxzy swizzling.
/// </summary>
public ivec4 zxzy => new ivec4(z, x, z, y);
/// <summary>
/// Returns ivec3.brbg swizzling (equivalent to ivec3.zxzy).
/// </summary>
public ivec4 brbg => new ivec4(z, x, z, y);
/// <summary>
/// Returns ivec3.zxzz swizzling.
/// </summary>
public ivec4 zxzz => new ivec4(z, x, z, z);
/// <summary>
/// Returns ivec3.brbb swizzling (equivalent to ivec3.zxzz).
/// </summary>
public ivec4 brbb => new ivec4(z, x, z, z);
/// <summary>
/// Returns ivec3.zy swizzling.
/// </summary>
public ivec2 zy => new ivec2(z, y);
/// <summary>
/// Returns ivec3.bg swizzling (equivalent to ivec3.zy).
/// </summary>
public ivec2 bg => new ivec2(z, y);
/// <summary>
/// Returns ivec3.zyx swizzling.
/// </summary>
public ivec3 zyx => new ivec3(z, y, x);
/// <summary>
/// Returns ivec3.bgr swizzling (equivalent to ivec3.zyx).
/// </summary>
public ivec3 bgr => new ivec3(z, y, x);
/// <summary>
/// Returns ivec3.zyxx swizzling.
/// </summary>
public ivec4 zyxx => new ivec4(z, y, x, x);
/// <summary>
/// Returns ivec3.bgrr swizzling (equivalent to ivec3.zyxx).
/// </summary>
public ivec4 bgrr => new ivec4(z, y, x, x);
/// <summary>
/// Returns ivec3.zyxy swizzling.
/// </summary>
public ivec4 zyxy => new ivec4(z, y, x, y);
/// <summary>
/// Returns ivec3.bgrg swizzling (equivalent to ivec3.zyxy).
/// </summary>
public ivec4 bgrg => new ivec4(z, y, x, y);
/// <summary>
/// Returns ivec3.zyxz swizzling.
/// </summary>
public ivec4 zyxz => new ivec4(z, y, x, z);
/// <summary>
/// Returns ivec3.bgrb swizzling (equivalent to ivec3.zyxz).
/// </summary>
public ivec4 bgrb => new ivec4(z, y, x, z);
/// <summary>
/// Returns ivec3.zyy swizzling.
/// </summary>
public ivec3 zyy => new ivec3(z, y, y);
/// <summary>
/// Returns ivec3.bgg swizzling (equivalent to ivec3.zyy).
/// </summary>
public ivec3 bgg => new ivec3(z, y, y);
/// <summary>
/// Returns ivec3.zyyx swizzling.
/// </summary>
public ivec4 zyyx => new ivec4(z, y, y, x);
/// <summary>
/// Returns ivec3.bggr swizzling (equivalent to ivec3.zyyx).
/// </summary>
public ivec4 bggr => new ivec4(z, y, y, x);
/// <summary>
/// Returns ivec3.zyyy swizzling.
/// </summary>
public ivec4 zyyy => new ivec4(z, y, y, y);
/// <summary>
/// Returns ivec3.bggg swizzling (equivalent to ivec3.zyyy).
/// </summary>
public ivec4 bggg => new ivec4(z, y, y, y);
/// <summary>
/// Returns ivec3.zyyz swizzling.
/// </summary>
public ivec4 zyyz => new ivec4(z, y, y, z);
/// <summary>
/// Returns ivec3.bggb swizzling (equivalent to ivec3.zyyz).
/// </summary>
public ivec4 bggb => new ivec4(z, y, y, z);
/// <summary>
/// Returns ivec3.zyz swizzling.
/// </summary>
public ivec3 zyz => new ivec3(z, y, z);
/// <summary>
/// Returns ivec3.bgb swizzling (equivalent to ivec3.zyz).
/// </summary>
public ivec3 bgb => new ivec3(z, y, z);
/// <summary>
/// Returns ivec3.zyzx swizzling.
/// </summary>
public ivec4 zyzx => new ivec4(z, y, z, x);
/// <summary>
/// Returns ivec3.bgbr swizzling (equivalent to ivec3.zyzx).
/// </summary>
public ivec4 bgbr => new ivec4(z, y, z, x);
/// <summary>
/// Returns ivec3.zyzy swizzling.
/// </summary>
public ivec4 zyzy => new ivec4(z, y, z, y);
/// <summary>
/// Returns ivec3.bgbg swizzling (equivalent to ivec3.zyzy).
/// </summary>
public ivec4 bgbg => new ivec4(z, y, z, y);
/// <summary>
/// Returns ivec3.zyzz swizzling.
/// </summary>
public ivec4 zyzz => new ivec4(z, y, z, z);
/// <summary>
/// Returns ivec3.bgbb swizzling (equivalent to ivec3.zyzz).
/// </summary>
public ivec4 bgbb => new ivec4(z, y, z, z);
/// <summary>
/// Returns ivec3.zz swizzling.
/// </summary>
public ivec2 zz => new ivec2(z, z);
/// <summary>
/// Returns ivec3.bb swizzling (equivalent to ivec3.zz).
/// </summary>
public ivec2 bb => new ivec2(z, z);
/// <summary>
/// Returns ivec3.zzx swizzling.
/// </summary>
public ivec3 zzx => new ivec3(z, z, x);
/// <summary>
/// Returns ivec3.bbr swizzling (equivalent to ivec3.zzx).
/// </summary>
public ivec3 bbr => new ivec3(z, z, x);
/// <summary>
/// Returns ivec3.zzxx swizzling.
/// </summary>
public ivec4 zzxx => new ivec4(z, z, x, x);
/// <summary>
/// Returns ivec3.bbrr swizzling (equivalent to ivec3.zzxx).
/// </summary>
public ivec4 bbrr => new ivec4(z, z, x, x);
/// <summary>
/// Returns ivec3.zzxy swizzling.
/// </summary>
public ivec4 zzxy => new ivec4(z, z, x, y);
/// <summary>
/// Returns ivec3.bbrg swizzling (equivalent to ivec3.zzxy).
/// </summary>
public ivec4 bbrg => new ivec4(z, z, x, y);
/// <summary>
/// Returns ivec3.zzxz swizzling.
/// </summary>
public ivec4 zzxz => new ivec4(z, z, x, z);
/// <summary>
/// Returns ivec3.bbrb swizzling (equivalent to ivec3.zzxz).
/// </summary>
public ivec4 bbrb => new ivec4(z, z, x, z);
/// <summary>
/// Returns ivec3.zzy swizzling.
/// </summary>
public ivec3 zzy => new ivec3(z, z, y);
/// <summary>
/// Returns ivec3.bbg swizzling (equivalent to ivec3.zzy).
/// </summary>
public ivec3 bbg => new ivec3(z, z, y);
/// <summary>
/// Returns ivec3.zzyx swizzling.
/// </summary>
public ivec4 zzyx => new ivec4(z, z, y, x);
/// <summary>
/// Returns ivec3.bbgr swizzling (equivalent to ivec3.zzyx).
/// </summary>
public ivec4 bbgr => new ivec4(z, z, y, x);
/// <summary>
/// Returns ivec3.zzyy swizzling.
/// </summary>
public ivec4 zzyy => new ivec4(z, z, y, y);
/// <summary>
/// Returns ivec3.bbgg swizzling (equivalent to ivec3.zzyy).
/// </summary>
public ivec4 bbgg => new ivec4(z, z, y, y);
/// <summary>
/// Returns ivec3.zzyz swizzling.
/// </summary>
public ivec4 zzyz => new ivec4(z, z, y, z);
/// <summary>
/// Returns ivec3.bbgb swizzling (equivalent to ivec3.zzyz).
/// </summary>
public ivec4 bbgb => new ivec4(z, z, y, z);
/// <summary>
/// Returns ivec3.zzz swizzling.
/// </summary>
public ivec3 zzz => new ivec3(z, z, z);
/// <summary>
/// Returns ivec3.bbb swizzling (equivalent to ivec3.zzz).
/// </summary>
public ivec3 bbb => new ivec3(z, z, z);
/// <summary>
/// Returns ivec3.zzzx swizzling.
/// </summary>
public ivec4 zzzx => new ivec4(z, z, z, x);
/// <summary>
/// Returns ivec3.bbbr swizzling (equivalent to ivec3.zzzx).
/// </summary>
public ivec4 bbbr => new ivec4(z, z, z, x);
/// <summary>
/// Returns ivec3.zzzy swizzling.
/// </summary>
public ivec4 zzzy => new ivec4(z, z, z, y);
/// <summary>
/// Returns ivec3.bbbg swizzling (equivalent to ivec3.zzzy).
/// </summary>
public ivec4 bbbg => new ivec4(z, z, z, y);
/// <summary>
/// Returns ivec3.zzzz swizzling.
/// </summary>
public ivec4 zzzz => new ivec4(z, z, z, z);
/// <summary>
/// Returns ivec3.bbbb swizzling (equivalent to ivec3.zzzz).
/// </summary>
public ivec4 bbbb => new ivec4(z, z, z, z);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
#if NET46
internal static readonly Version HttpVersion20 = new Version(2, 0);
internal static readonly Version HttpVersionUnknown = new Version(0, 0);
#else
internal static Version HttpVersion20 => HttpVersionInternal.Version20;
internal static Version HttpVersionUnknown => HttpVersionInternal.Unknown;
#endif
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
[ThreadStatic]
private static StringBuilder t_requestHeadersBuilder;
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available.
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = null;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _maxResponseDrainSize = 64 * 1024;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
// Get a StringBuilder to use for creating the request headers.
// We cache one in TLS to avoid creating a new one for each request.
StringBuilder requestHeadersBuffer = t_requestHeadersBuilder;
if (requestHeadersBuffer != null)
{
requestHeadersBuffer.Clear();
}
else
{
t_requestHeadersBuilder = requestHeadersBuffer = new StringBuilder();
}
// Manually add cookies.
if (cookies != null && cookies.Count > 0)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO (#5523): Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
SafeWinHttpHandle sessionHandle;
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType);
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError);
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)sizeof(uint)))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
SetSessionHandleOptions(sessionHandle);
_sessionHandle = sessionHandle;
}
}
}
}
private async void StartRequest(WinHttpRequestState state)
{
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
state.ClearSendRequestState();
return;
}
SafeWinHttpHandle connectHandle = null;
try
{
EnsureSessionHandleExists(state);
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersionInternal.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersionInternal.Version11)
{
httpVersion = "HTTP/1.1";
}
// Turn off additional URI reserved character escaping (percent-encoding). This matches
// .NET Framework behavior. System.Uri establishes the baseline rules for percent-encoding
// of reserved characters.
uint flags = Interop.WinHttp.WINHTTP_FLAG_ESCAPE_DISABLE;
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
flags |= Interop.WinHttp.WINHTTP_FLAG_SECURE;
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
flags);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state) != 0;
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = unchecked((uint)_receiveDataTimeout.TotalMilliseconds);
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
HttpResponseMessage responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
state.Tcs.TrySetResult(responseMessage);
}
catch (Exception ex)
{
HandleAsyncException(state, state.SavedException ?? ex);
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
state.ClearSendRequestState();
}
}
private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle)
{
SetSessionHandleConnectionOptions(sessionHandle);
SetSessionHandleTlsOptions(sessionHandle);
SetSessionHandleTimeoutOptions(sessionHandle);
}
private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle)
{
uint optionData = 0;
SslProtocols sslProtocols =
(_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols;
if ((sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle)
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
sessionHandle,
0,
0,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = proxyUri.Scheme + "://" + proxyUri.Authority;
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo))
{
updateProxySettings = true;
}
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = CertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials
// (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends
// default credentials to a server (401 response) if the server is considered to be on the Intranet.
// WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between
// proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in
// the request processing (after getting a 401/407 response) when the proxy or server credential is set as
// CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials
// from being automatically sent until we get a 401/407 response.
_authHelper.ChangeDefaultCredentialsPolicy(
state.RequestHandle,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER,
allowDefaultCredentials:false);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)(_maxResponseHeadersLength * 1024);
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetRequestHandleHttp2Options(SafeWinHttpHandle requestHandle, Version requestVersion)
{
Debug.Assert(requestHandle != null);
uint optionData = (requestVersion == HttpVersion20) ? Interop.WinHttp.WINHTTP_PROTOCOL_FLAG_HTTP2 : 0;
if (Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL,
ref optionData))
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option supported, setting to {0}", optionData);
}
else
{
WinHttpTraceHelper.Trace("WinHttpHandler.SetRequestHandleHttp2Options: HTTP/2 option not supported");
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
Debug.Assert(handle != null);
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException || ex is InvalidOperationException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST;
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
notificationFlags,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError);
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
private RendezvousAwaitable<int> InternalSendRequestAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
state.Pin();
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
int lastError = Marshal.GetLastWin32Error();
Debug.Assert((unchecked((int)lastError) != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER &&
unchecked((int)lastError) != unchecked((int)0x80090321)), // SEC_E_BUFFER_TOO_SMALL
$"Unexpected async error in WinHttpRequestCallback: {unchecked((int)lastError)}");
// Dispose (which will unpin) the state object. Since this failed, WinHTTP won't associate
// our context value (state object) to the request handle. And thus we won't get HANDLE_CLOSING
// notifications which would normally cause the state object to be unpinned and disposed.
state.Dispose();
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
return state.LifecycleAwaitable;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private RendezvousAwaitable<int> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.LifecycleAwaitable;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Collections;
using DataDictionaryCreator.Properties;
using System.Deployment.Application;
namespace DataDictionaryCreator
{
public partial class Main : Form
{
#region - Internal properties -
private string sqlConnectionString
{
get { return Properties.Settings.Default.SQL_CONNECTION_STRING; }
set
{
Properties.Settings.Default.SQL_CONNECTION_STRING = value;
Properties.Settings.Default.Save();
//TODO: Review this code. Why can't the connectionstring == value? Does it make a difference to setup again?
if (connection != null) //&& connection.ConnectionString != value)
{
DocumentationSetup(value);
btnConnect.Visible = false;
}
}
}
private string additionalProperties
{
get { return Properties.Settings.Default.ADDITIONAL_PROPERTIES; }
set
{
Properties.Settings.Default.ADDITIONAL_PROPERTIES = value.TrimEnd(',');
Properties.Settings.Default.Save();
FillSelectedTableToDocument();
}
}
private string foreignKeyDescription
{
get { return Properties.Settings.Default.FOREIGN_KEY_DESCRIPTION; }
set
{
Properties.Settings.Default.FOREIGN_KEY_DESCRIPTION = value;
Properties.Settings.Default.Save();
}
}
private string primaryKeyDescription
{
get { return Properties.Settings.Default.PRIMARY_KEY_DESCRIPTION; }
set
{
Properties.Settings.Default.PRIMARY_KEY_DESCRIPTION = value;
Properties.Settings.Default.Save();
}
}
private string[] additionalPropertiesArray
{
get
{
if (additionalProperties.Length == 0)
{
return new string[0];
}
else
{
string[] items = additionalProperties.Split(',');
List<string> reservedProperties = new List<string>();
reservedProperties.Add("Column");
reservedProperties.Add("Datatype");
reservedProperties.Add("Description");
reservedProperties.Add("Number");
reservedProperties.Add("Size");
reservedProperties.Add("Nullable");
reservedProperties.Add("InPrimaryKey");
reservedProperties.Add("IsForeignKey");
List<string> noDups = new List<string>();
for (int i = 0; i < items.Length; i++)
{
//Not Empty AND Not already in the list AND Not reserved
if (items[i].Trim().Length > 0
&& !noDups.Exists(obj => string.Compare(obj, items[i].Trim(), true) == 0)
&& !reservedProperties.Exists(obj => string.Compare(obj, items[i].Trim(), true) == 0)
)
{
noDups.Add(items[i].Trim());
}
}
return noDups.ToArray();
}
}
}
private bool allowOverwrite
{
get { return Properties.Settings.Default.ALLOW_OVERWRITE; }
set
{
Properties.Settings.Default.ALLOW_OVERWRITE = value;
Properties.Settings.Default.Save();
}
}
private string connectionStatusDetails = string.Empty;
private string connectionExceptionDetails = string.Empty;
SqlConnection connection;
Server server;
Database db;
Table table;
private enum tabpages
{
tabPageConnect, tabPageAdvancedSettings, tabPageDocumentDatabase, tabPageImportDocumentation,
tabPageExportDocumentation
, tabPageTables, tabPageViews
}
#endregion
#region - Public -
public Main()
{
//System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("fr-fr");
Application.EnableVisualStyles();
Application.DoEvents();
InitializeComponent();
}
#endregion
#region - Private -
/// <summary>
/// Application Launch Point
/// </summary>
private void MainForm_Load(object sender, EventArgs e)
{
//Hide the "Update Available!" menu item until we can verify
updateAvailableToolStripMenuItem.Visible = false;
bgwUpdater.RunWorkerAsync();
//Remove view tp for release.
tabContainerObjects.TabPages.Remove(tabPageViews);
ApplicationSetup();
DocumentationSetup(sqlConnectionString);
}
/// <summary>
/// Set form field values based on established user settings
/// </summary>
private void ApplicationSetup()
{
txtPrimaryKeyDescription.Text = primaryKeyDescription;
txtForeignKeyDescription.Text = foreignKeyDescription;
chkOverwriteDescriptions.Checked = allowOverwrite;
txtAdditionalProperties.Text = additionalProperties;
Properties.Settings.Default.ExcludedObjects = Properties.Settings.Default.ExcludedObjects ?? new ExcludedObjectList();
}
/// <summary>
/// Using the current database connection, load the tables to be documented.
/// </summary>
/// <param name="sqlConnectionString">SQL Connection String</param>
private void DocumentationSetup(string sqlConnectionString)
{
BeginAction(Resources.DocumentationSetupBeginAction, 100);
try
{
connection = new SqlConnection(sqlConnectionString);
server = new Server(new ServerConnection(connection));
//server.SetDefaultInitFields(typeof(Table), "IsSystemObject");
db = server.Databases[connection.Database];
//Preload all table information, this is stop SMO from making unnecessary round trips. Increasing performance X 9000
db.PrefetchObjects(typeof(Table));
// Check role. Without DBO (or greater) priveledges, SMO can not be used.
if (!db.IsDbOwner)
{
SetConnectionState(false, Resources.ConnectionErrorDBORequired, Resources.ConnectionErrorDBORequired, Color.Orange);
}
else
{
// Get fields (in addition to description) the user wishes to document.
// These will be displayed in the grid
if (string.IsNullOrEmpty(additionalProperties))
QueryForAdditionalProperties();
else
txtAdditionalProperties.Text = additionalProperties;
//Default
SetupTableDocumentation();
// Brag out your success
SetConnectionState(true, string.Format(Resources.ConnectionSuccessGeneric, server.Name, db.Name), string.Empty, Color.Green);
}
}
catch (Exception ex)
{
SetConnectionState(false, Resources.ConnectionErrorGeneric, ex.GetBaseException().Message, Color.Red);
}
finally
{
EndAction(Resources.DocumentSetupEndAction);
}
}
/// <summary>
/// Toggle control visibility and set text based on connection state
/// </summary>
/// <param name="isConnected">true if connected, otherwise false</param>
/// <param name="statusMessage">message to be displayed on connection tab and status bar</param>
/// <param name="exceptionMessage">used to identify error condition and used for detail error message</param>
/// <param name="statusColor">green for success, red for failure</param>
private void SetConnectionState(bool isConnected, string statusMessage, string exceptionMessage, Color statusColor)
{
// Success or failed status to user
if (isConnected)
{
connectionStatusDetails = statusMessage; // You are connected. Congratulations!
this.Text = String.Format(Resources.ApplicationTitle, " - " + server.ToString() + "." + db.ToString());
}
else if (!string.IsNullOrEmpty(exceptionMessage))
{
connectionStatusDetails = Resources.ConnectionErrorGenericDetailed; // Not connected due to error
}
else
{
connectionStatusDetails = Resources.ConnectionNotConnected; // You didn't even try.
}
// Connect tab settings
lblConnectionSuccess.Text = connectionStatusDetails;
lblConnectionSuccess.ForeColor = statusColor;
btnAdvancedSettings.Visible = isConnected;
btnDocumentDatabase.Visible = isConnected;
// Document tab values
lnkException.Visible = !isConnected;
// Status bar text
toolStripStatusLabel.Text = statusMessage;
// Not-so-friend error message to be displayed only when asked for...
connectionExceptionDetails = exceptionMessage;
// Enable/Disable tabs based on connection status
foreach (TabPage tp in tabContainerMain.TabPages)
{
if (tp.Name != tabpages.tabPageConnect.ToString())
{
tp.Enabled = isConnected;
}
}
foreach (TabPage tp in tabContainerObjects.TabPages)
{
tp.Enabled = isConnected;
}
}
/// <summary>
/// If Additonal Properties aren't stored in user settings, try to determine which properties were previously used.
/// TODO: Ask Jon what the heck this is all about.
/// </summary>
private void QueryForAdditionalProperties()
{
SqlDataReader dr;
string previousAdditionalProperties = string.Empty;
try
{
string sqlCommand = GetSql("sql.read_previous_properties.sql");
dr = server.ConnectionContext.ExecuteReader(sqlCommand);
while (dr.Read())
{
previousAdditionalProperties += dr["name"].ToString() + ",";
}
// We're going to explicitly close the reader here.
dr.Close();
if (!string.IsNullOrEmpty(previousAdditionalProperties))
{
previousAdditionalProperties.TrimEnd(',');
// We've identified additional properties so set the private variable, the settings as well as the form field.
additionalProperties = previousAdditionalProperties;
txtAdditionalProperties.Text = previousAdditionalProperties;
}
#region "Code Jon Is Afraid To Throw Away"
////This was the previous code using SMO. My hunch is that it's slower.
////If possible, the SMO code should be used since it doesn't require database version logic.
//ArrayList extProperties = new ArrayList();
//foreach (ExtendedProperty ep in db.Tables[0].Columns[0].ExtendedProperties)
//{
// if (ep.Name != SmoUtil.DESCRIPTION_PROPERTY)
// extProperties.Add(ep.Name);
//}
//string determinedProperties = string.Join(",", (String[])extProperties.ToArray(typeof(string)));
//if (!string.IsNullOrEmpty(determinedProperties))
// this.additionalProperties = determinedProperties;
#endregion
}
catch (SqlException sqlEx)
{
this.connectionStatusDetails = sqlEx.Message;
}
finally
{
dr = null;
}
}
/// <summary>
/// Populate the select table fields to be documented
/// </summary>
private void FillSelectedTableToDocument()
{
BeginAction(Resources.DocumentLoadTableBeginAction, 100);
if (ddlTables.SelectedIndex >= 0)
{
// Select by index rather than name since names aren't consistently populated in SQL2K with a user account
table = SmoUtil.GetTableByName(db, ddlTables.SelectedItem.ToString());
if (table.ExtendedProperties.Contains(SmoUtil.DESCRIPTION_PROPERTY))
txtTableDescription.Text = table.ExtendedProperties[SmoUtil.DESCRIPTION_PROPERTY].Value.ToString();
else
txtTableDescription.Text = string.Empty;
chkExcludedTable.Checked = Properties.Settings.Default.ExcludedObjects.Exists(obj => obj == new ExcludedObject(table));
DataTable columnList = new DataTable();
columnList.Columns.Add("Number");
columnList.Columns.Add("Column");
columnList.Columns.Add("Datatype");
columnList.Columns.Add("Size");
columnList.Columns.Add("Nullable");
columnList.Columns.Add("InPrimaryKey");
columnList.Columns.Add("IsForeignKey");
columnList.Columns.Add("Description");
foreach (string property in additionalPropertiesArray)
columnList.Columns.Add(property);
foreach (Column column in table.Columns)
{
DataRow row = columnList.NewRow();
row["Number"] = column.ID;
row["Column"] = column.Name;
row["Datatype"] = SmoUtil.GetDatatypeString(column);
row["Size"] = column.DataType.MaximumLength;
row["Nullable"] = column.Nullable == true ? "Y" : "N";
row["InPrimaryKey"] = column.InPrimaryKey == true ? "Y" : "N";
row["IsForeignKey"] = column.IsForeignKey == true ? "Y" : "N";
AddColumnToGrid(column, row, "Description", SmoUtil.DESCRIPTION_PROPERTY);
foreach (string property in additionalPropertiesArray)
AddColumnToGrid(column, row, property, property);
columnList.Rows.Add(row);
}
dgvColumns.DataSource = columnList;
FormatReadonlyColumn(dgvColumns.Columns["Number"]);
FormatReadonlyColumn(dgvColumns.Columns["Column"]);
FormatReadonlyColumn(dgvColumns.Columns["Datatype"]);
FormatReadonlyColumn(dgvColumns.Columns["Size"]);
FormatReadonlyColumn(dgvColumns.Columns["Nullable"]);
FormatReadonlyColumn(dgvColumns.Columns["InPrimaryKey"]);
FormatReadonlyColumn(dgvColumns.Columns["IsForeignKey"]);
}
// This is Ben's silly way of trying to make the document grid look pretty:
// Set the height of the grid to the same height as the included rows or set to a max height
int RequiredGridHeight = dgvColumns.Rows.GetRowsHeight(DataGridViewElementStates.None) + dgvColumns.ColumnHeadersHeight;
if (RequiredGridHeight > Convert.ToInt32(Resources.DocumentMaxGridHeight))
dgvColumns.Height = Convert.ToInt32(Resources.DocumentMaxGridHeight);
else
dgvColumns.Height = RequiredGridHeight;
EndAction(Resources.DocumentLoadTableEndAction);
}
/// <summary>
/// Format readonly fields
/// </summary>
/// <param name="column">column</param>
private void FormatReadonlyColumn(DataGridViewColumn column)
{
column.ReadOnly = true;
column.DefaultCellStyle.BackColor = Color.AliceBlue;
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
}
/// <summary>
/// Add extended properties columns to grid
/// </summary>
/// <param name="column">column</param>
/// <param name="row">row</param>
/// <param name="gridName">grid name</param>
/// <param name="propertyName">extended property name</param>
private void AddColumnToGrid(Column column, DataRow row, string gridName, string propertyName)
{
ExtendedPropertyCollection extendedProperties = column.ExtendedProperties;
if (extendedProperties.Contains(propertyName))
row[gridName] = column.ExtendedProperties[propertyName].Value;
else
row[gridName] = null;
}
/// <summary>
/// Begin action manages progress bar and mousepointers
/// </summary>
/// <param name="message">status message</param>
/// <param name="progressMax">int representing max progress value</param>
private void BeginAction(string message, int progressMax)
{
Cursor.Current = Cursors.WaitCursor;
btnExport.Enabled = false;
btnSetKeyDescriptions.Enabled = false;
toolStripProgressBar.Maximum = progressMax;
toolStripProgressBar.Visible = true;
toolStripStatusLabel.Text = message;
statusStrip.Refresh();
}
/// <summary>
/// End action manages progress bar and mousepointers
/// </summary>
/// <param name="message">final status message</param>
private void EndAction(string message)
{
toolStripProgressBar.Visible = false;
toolStripProgressBar.Value = 0;
toolStripStatusLabel.Text = message;
Cursor.Current = Cursors.Default;
btnExport.Enabled = true;
btnSetKeyDescriptions.Enabled = true;
}
/// <summary>
/// Establish the extended property and associated value
/// </summary>
/// <param name="table">table to be updated</param>
/// <param name="databasePropertyName">extended property</param>
/// <param name="value">value</param>
/// <param name="columnName">column</param>
/// <param name="overwrite">overwrite</param>
private void SetPropertyValue(Table table, string databasePropertyName, string value, string columnName, bool overwrite)
{
Column column = table.Columns[columnName];
if (column == null)
{
throw new Exception(string.Format(Resources.MissingColumnException, table.ToString(), columnName));
}
SetPropertyValue(table, databasePropertyName, value, column, overwrite);
}
/// <summary>
/// Establish the extended property and associated value
/// </summary>
/// <param name="table">table to be updated</param>
/// <param name="databasePropertyName">extended property</param>
/// <param name="value">value</param>
/// <param name="column">column</param>
/// <param name="overwrite">overwrite</param>
private void SetPropertyValue(Table table, string databasePropertyName, string value, Column column, bool overwrite)
{
if (!column.ExtendedProperties.Contains(databasePropertyName))
{
column.ExtendedProperties.Add(new ExtendedProperty(column, databasePropertyName, value));
}
else
{
if (overwrite || string.IsNullOrEmpty(column.ExtendedProperties[databasePropertyName].Value.ToString()))
{
column.ExtendedProperties[databasePropertyName].Value = value;
column.ExtendedProperties[databasePropertyName].Alter();
}
}
column.Alter();
}
/// <summary>
/// Increment the progress bar
/// </summary>
/// <param name="Sender"></param>
/// <param name="e"></param>
private void ProgressUpdate(object Sender, EventArgs e)
{
toolStripProgressBar.Value++;
}
/// <summary>
/// Establish a description for the currently documented table
/// </summary>
/// <param name="description"></param>
private void SetTableDescription(string description)
{
SetTableDescription(table, description);
}
/// Establish a description for table provided
private void SetTableDescription(Table updateTable, string description)
{
BeginAction(Resources.TableDescriptionBeginAction, 100);
if (!updateTable.ExtendedProperties.Contains(SmoUtil.DESCRIPTION_PROPERTY))
{
updateTable.ExtendedProperties.Add(new ExtendedProperty(updateTable, SmoUtil.DESCRIPTION_PROPERTY, description));
}
else
{
updateTable.ExtendedProperties[SmoUtil.DESCRIPTION_PROPERTY].Value = description;
updateTable.ExtendedProperties[SmoUtil.DESCRIPTION_PROPERTY].Alter();
}
updateTable.Alter();
EndAction(Resources.TableDescriptionEndAction);
}
/// <summary>
/// Displays a Connection String Builder (DataLinks) dialog.
///
/// Credits:
/// http://www.codeproject.com/cs/database/DataLinks.asp
/// http://www.codeproject.com/cs/database/DataLinks.asp?df=100&forumid=33457&select=1560237#xx1560237xx
///
/// Required COM references:
/// %PROGRAMFILES%\Microsoft.NET\Primary Interop Assemblies\adodb.dll
/// %PROGRAMFILES%\Common Files\System\Ole DB\OLEDB32.DLL
/// </summary>
/// <param name="currentConnectionString">Previous database connection string</param>
/// <returns>Selected connection string</returns>
private string PromptForConnectionString(string currentConnectionString)
{
MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
ADODB.Connection dialogConnection;
string generatedConnectionString = string.Empty;
if (currentConnectionString == String.Empty)
{
dialogConnection = (ADODB.Connection)dataLinks.PromptNew();
generatedConnectionString = dialogConnection.ConnectionString.ToString();
}
else
{
dialogConnection = new ADODB.Connection();
dialogConnection.Provider = "SQLOLEDB.1";
ADODB.Property persistProperty = dialogConnection.Properties["Persist Security Info"];
persistProperty.Value = true;
dialogConnection.ConnectionString = currentConnectionString;
dataLinks = new MSDASC.DataLinks();
object objConn = dialogConnection;
if (dataLinks.PromptEdit(ref objConn))
{
generatedConnectionString = dialogConnection.ConnectionString.ToString();
}
}
generatedConnectionString = generatedConnectionString.Replace("Provider=SQLOLEDB.1;", string.Empty);
if
(
!generatedConnectionString.Contains("Integrated Security=SSPI")
&& !generatedConnectionString.Contains("Trusted_Connection=True")
&& !generatedConnectionString.Contains("Password=")
&& !generatedConnectionString.Contains("Pwd=")
)
// BSG: Updated for null check on Value not only Password Property.
if (dialogConnection.Properties["Password"].Value != null)
generatedConnectionString += ";Password=" + dialogConnection.Properties["Password"].Value.ToString();
return generatedConnectionString;
}
/// <summary>
///
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
internal static string GetSql(string Name)
{
// Gets the current assembly.
System.Reflection.Assembly Asm = System.Reflection.Assembly.GetExecutingAssembly();
// Resources are named using a fully qualified name.
Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);
// Reads the contents of the embedded file.
StreamReader reader = new StreamReader(strm);
return reader.ReadToEnd();
}
/// <summary>
/// Prompt the user to build a connection string and then set the connection
/// </summary>
private void SetConnectionString()
{
// Build the connection string
string newConnectionString = PromptForConnectionString(this.txtConnectionString.Text);
this.Refresh(); //Need to repaint form after dialog goes away.
//TODO: Review this code
// We may need to check the new and old value of the connection string but I'm commenting it out now because it is causing issues and no one is here to stop me
// if (!string.IsNullOrEmpty(newConnectionString) && newConnectionString != sqlConnectionString)
if (!string.IsNullOrEmpty(newConnectionString))
{
sqlConnectionString = newConnectionString;
}
}
#endregion
#region - Connect Database Tab Events -
private void txtConnectionString_Leave(object sender, EventArgs e)
{
//Underlying setting will be automatically updated, but need to trigger refresh
sqlConnectionString = txtConnectionString.Text;
}
private void txtConnectionString_DoubleClick(object sender, EventArgs e)
{
SetConnectionString();
}
private void btnSetConnectionString_Click(object sender, EventArgs e)
{
SetConnectionString();
}
private void btnAdvancedSettings_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageAdvancedSettings.ToString());
}
private void btnDocumentDatabase_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageDocumentDatabase.ToString());
}
#endregion
#region - Advanced Settings Tab Events -
private void txtAdditionalProperties_Leave(object sender, EventArgs e)
{
additionalProperties = txtAdditionalProperties.Text;
}
private void txtPrimaryKeyDescription_Leave(object sender, EventArgs e)
{
primaryKeyDescription = txtPrimaryKeyDescription.Text;
}
private void txtForeignKeyDescription_Leave(object sender, EventArgs e)
{
foreignKeyDescription = txtForeignKeyDescription.Text;
}
private void chkOverwriteDescriptions_CheckStateChanged(object sender, EventArgs e)
{
allowOverwrite = chkOverwriteDescriptions.Checked;
}
#endregion
#region - Document Tab Events -
private void txtConnectionString_TextChanged(object sender, EventArgs e)
{
btnConnect.Visible = true;
}
private void btnConnect_Click(object sender, EventArgs e)
{
//Underlying setting will be automatically updated, but need to trigger refresh
sqlConnectionString = txtConnectionString.Text;
btnConnect.Visible = false;
}
private void btnSetKeyDescriptions_Click(object sender, EventArgs e)
{
bool overwrite = chkOverwriteDescriptions.Checked;
BeginAction(Resources.AdvanceSettingsKeyDescriptionsBeginAction, db.Tables.Count);
foreach (Table table in db.Tables)
{
toolStripProgressBar.Value++;
foreach (Column column in table.Columns)
{
if (column.InPrimaryKey)
SetPropertyValue(table, SmoUtil.DESCRIPTION_PROPERTY, primaryKeyDescription, column, overwrite);
if (column.IsForeignKey)
{
foreach (ForeignKey fk in table.ForeignKeys)
{
if (fk.Columns.Contains(column.Name))
{
SetPropertyValue(table, SmoUtil.DESCRIPTION_PROPERTY, string.Format(foreignKeyDescription, fk.ReferencedTable), column, overwrite);
break;
}
}
}
}
}
EndAction(Resources.AdvancedSettingsKeyDescriptonsEndAction);
}
#endregion
#region - Export Tab Events --
private void btnExport_Click(object sender, EventArgs e)
{
saveFileDialogExport.FileName = db.Name;
saveFileDialogExport.Filter = "Excel (*.xls)|*.xls" +
"|Excel Grouped (*.xls)|*.xls" +
"|HTML (*.htm)|*.htm" +
"|HTML Grouped (.htm)|.htm" +
"|Word (*.doc)|*.doc" +
"|Word Grouped (*.doc)|*.doc" +
"|XML (*.xml)|*.xml" +
"|T-SQL (*.sql)|*.sql";
saveFileDialogExport.ShowDialog();
if (!string.IsNullOrEmpty(saveFileDialogExport.FileName))
{
try
{
FileInfo fileInfo = new FileInfo(saveFileDialogExport.FileName);
//Allow a little extra space on the progress bar for the XSL transform
BeginAction("Exporting to " + fileInfo.Name, (int)(db.Tables.Count * 1.1));
this.Refresh();
Exporter exporter;
switch (fileInfo.Extension)
{
case ".sql":
exporter = Exporter.SqlScriptExporter(server.Information);
break;
case ".doc":
if (saveFileDialogExport.FilterIndex == 6)
{
exporter = Exporter.WordExporter(true);
}
else
{
exporter = Exporter.WordExporter(false);
}
break;
case ".xls":
if (saveFileDialogExport.FilterIndex == 2)
{
exporter = Exporter.ExcelExporter(true);
}
else
{
exporter = Exporter.ExcelExporter(false);
}
break;
case ".htm":
case ".html":
if (saveFileDialogExport.FilterIndex == 4)
{
exporter = Exporter.HtmlExporter(true);
}
else
{
exporter = Exporter.HtmlExporter(false);
}
break;
case ".xml":
exporter = Exporter.XmlExporter();
break;
case "":
return;
default:
//Could move this check before exporting to XML.
MessageBox.Show(
"Export isn't supported for this filetype: " + fileInfo.Extension,
"Unsupported File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
exporter.Progressed += new EventHandler(ProgressUpdate);
exporter.Export(db, additionalPropertiesArray, fileInfo);
try
{
if (chkOpenFile.Checked)
System.Diagnostics.Process.Start(fileInfo.FullName);
}
catch (Exception)
{
MessageBox.Show(Resources.ExportErrorGeneric);
}
}
finally
{
EndAction(Resources.ExportEndAction);
}
}
}
#endregion
#region - Import Tab Events -
private void btnImport_Click(object sender, EventArgs e)
{
openFileDialogImport.ShowDialog();
if (!string.IsNullOrEmpty(openFileDialogImport.FileName))
{
try
{
FileInfo fileInfo = new FileInfo(openFileDialogImport.FileName);
//Allow a little extra space on the progress bar for the XSL transform
BeginAction("Importing from " + fileInfo.Name, (int)(db.Tables.Count * 1.1));
this.Refresh();
switch (fileInfo.Extension)
{
case ".sql":
//Check script contains correct DDC tag
string script = fileInfo.OpenText().ReadToEnd();
if (script.IndexOf(Exporter.Identifier, StringComparison.InvariantCultureIgnoreCase) == -1)
throw new System.Exception(Resources.ImportErrorCanNotValidateScript);
//Execute SQL script - this command knows how to deal with GO separators
server.ConnectionContext.ExecuteNonQuery(script);
break;
case ".xml":
//Check doctype and tags to ensure DDC type
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileInfo.FullName);
if (!xmlDoc.DocumentType.Name.Equals(XmlExporter.Identifier, StringComparison.InvariantCultureIgnoreCase))
throw new System.Exception(Resources.ImportErrorUnsupportedVersion);
//Iterate and import
foreach (XmlNode tableNode in xmlDoc.SelectNodes("//documentation/tables/table"))
{
string tbl = "[" + tableNode.Attributes["schema"].Value + "].[" + tableNode.Attributes["name"].Value + "]";
Table currentTable = SmoUtil.GetTableByName(db, tbl);
SetTableDescription(currentTable, tableNode.Attributes["description"].Value);
foreach (XmlNode columnNode in tableNode.SelectNodes("column"))
{
SetPropertyValue(currentTable, SmoUtil.DESCRIPTION_PROPERTY, columnNode.Attributes["description"].Value, columnNode.Attributes["name"].Value, true);
foreach (XmlNode columnPropertyNode in columnNode.SelectNodes("property"))
{
SetPropertyValue(currentTable, columnPropertyNode.Attributes["name"].Value, columnPropertyNode.Attributes["value"].Value, columnNode.Attributes["name"].Value, true);
}
}
}
break;
}
DocumentationSetup(sqlConnectionString);
EndAction(Resources.ImportEndAction);
}
catch (Exception ex)
{
EndAction("ERROR: " + ex.Message);
}
finally
{
}
}
}
#endregion
#region - Status Bar Events -
private void lnkException_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MessageBox.Show(connectionExceptionDetails);
}
#endregion
#region - Menu Events -
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
About frmAbout = new About();
frmAbout.Show();
}
private void connectToDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageConnect.ToString());
}
private void setAdditionalPropertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageAdvancedSettings.ToString());
}
private void importDocumentationToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageImportDocumentation.ToString());
}
private void documentDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageDocumentDatabase.ToString());
}
private void exportDocumentationToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageExportDocumentation.ToString());
}
private void additionalPropertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageAdvancedSettings.ToString());
}
private void autoFillKeysToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageAdvancedSettings.ToString());
}
private void tablesToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageDocumentDatabase.ToString());
tabContainerObjects.SelectTab(tabpages.tabPageTables.ToString());
}
private void viewsToolStripMenuItem_Click(object sender, EventArgs e)
{
tabContainerMain.SelectTab(tabpages.tabPageDocumentDatabase.ToString());
tabContainerObjects.SelectTab(tabpages.tabPageViews.ToString());
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Dispose();
}
#endregion
#region - Tab Navigation -
private void btnNext_Click(object sender, EventArgs e)
{
int curIndex = tabContainerMain.SelectedIndex;
tabContainerMain.SelectTab(curIndex + 1);
}
private void btnBack_Click(object sender, EventArgs e)
{
int curIndex = tabContainerMain.SelectedIndex;
tabContainerMain.SelectTab(curIndex - 1);
}
private void tabContainerMain_SelectedIndexChanged(object sender, EventArgs e)
{
btnBack.Visible = !(tabContainerMain.SelectedIndex == 0);
btnNext.Visible = !(tabContainerMain.SelectedIndex == (tabContainerMain.TabCount - 1));
}
#endregion
#region - Tables Documentation -
private void SetupTableDocumentation()
{
ddlTables.Items.Clear();
dgvColumns.DataSource = null;
// Display all non-sysobject tables to be documented
foreach (Table table in db.Tables)
{
if (!table.IsSystemObject)
{
ddlTables.Items.Add(table.ToString());
}
}
// Ultimately, display the selected table fields in the grid
if (ddlTables.Items.Count > 0)
{
if (ddlTables.SelectedIndex == 0)
FillSelectedTableToDocument();
else
ddlTables.SelectedIndex = 0;
}
}
private void ddlTables_SelectedIndexChanged(object sender, EventArgs e)
{
FillSelectedTableToDocument();
}
private void txtTableDescription_Leave(object sender, EventArgs e)
{
SetTableDescription(txtTableDescription.Text);
}
private void dgvColumns_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
string tableColumnName = dgvColumns["Column", e.RowIndex].Value.ToString();
string gridPropertyName = dgvColumns.Columns[e.ColumnIndex].Name;
string databasePropertyName = (gridPropertyName == "Description") ? SmoUtil.DESCRIPTION_PROPERTY : gridPropertyName;
string value = dgvColumns[e.ColumnIndex, e.RowIndex].Value.ToString();
SetPropertyValue(this.table, databasePropertyName, value, tableColumnName, true);
}
private void chkExcludedTable_Click(object sender, EventArgs e)
{
ExcludedObject eo = new ExcludedObject(this.table);
bool exists = Properties.Settings.Default.ExcludedObjects.Exists(obj => obj == eo);
if (chkExcludedTable.Checked)
{
if (!exists)
{
Properties.Settings.Default.ExcludedObjects.Add(eo);
Properties.Settings.Default.Save();
}
}
else
{
if (exists)
{
Properties.Settings.Default.ExcludedObjects.Remove(eo);
Properties.Settings.Default.Save();
}
}
}
#endregion
#region - Views Documentation -
private void SetupViewDocumentation()
{
ddlViews.Items.Clear();
//dgvColumns.DataSource = null;
// Display all non-sysobject tables to be documented
foreach (Microsoft.SqlServer.Management.Smo.View view in db.Views)
{
if (!view.IsSystemObject)
{
ddlViews.Items.Add(view.ToString());
}
}
// Ultimately, display the selected table fields in the grid
if (ddlViews.Items.Count > 0)
{
if (ddlViews.SelectedIndex == 0)
{
;//FillSelectedTableToDocument();
}
else
{
ddlViews.SelectedIndex = 0;
}
}
}
#endregion
#region Updater
private bool UpdateAvailable()
{
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment updateCheck = ApplicationDeployment.CurrentDeployment;
UpdateCheckInfo info = updateCheck.CheckForDetailedUpdate();
return info.UpdateAvailable;
}
return false;
}
#endregion
#region Update Checker
private enum UpdateStatuses
{
NoUpdateAvailable,
UpdateAvailable,
UpdateRequired,
NotDeployedViaClickOnce,
DeploymentDownloadException,
InvalidDeploymentException,
InvalidOperationException
}
private void bgwUpdater_DoWork(object sender, DoWorkEventArgs e)
{
UpdateCheckInfo info = null;
// Check if the application was deployed via ClickOnce.
if (!ApplicationDeployment.IsNetworkDeployed)
{
e.Result = UpdateStatuses.NotDeployedViaClickOnce;
return;
}
ApplicationDeployment updateCheck = ApplicationDeployment.CurrentDeployment;
try
{
info = updateCheck.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException)
{
e.Result = UpdateStatuses.DeploymentDownloadException;
return;
}
catch (InvalidDeploymentException)
{
e.Result = UpdateStatuses.InvalidDeploymentException;
return;
}
catch (InvalidOperationException)
{
e.Result = UpdateStatuses.InvalidOperationException;
return;
}
if (info.UpdateAvailable)
{
if (info.IsUpdateRequired)
{
e.Result = UpdateStatuses.UpdateRequired;
}
else
{
e.Result = UpdateStatuses.UpdateAvailable;
}
}
else
{
e.Result = UpdateStatuses.NoUpdateAvailable;
}
}
private void bgwUpdater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
switch ((UpdateStatuses)e.Result)
{
case UpdateStatuses.UpdateAvailable:
updateAvailableToolStripMenuItem.Visible = true;
break;
case UpdateStatuses.UpdateRequired:
updateAvailableToolStripMenuItem.Visible = true;
MessageBox.Show(Resources.RequiredUpdateAvailable, Resources.UpdateAvailable, MessageBoxButtons.OK);
UpdateApplication();
break;
}
}
private void updateAvailableToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show(Resources.UpdateApplicationNow, Resources.UpdateAvailable, MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.OK)
{
UpdateApplication();
}
}
private void UpdateApplication()
{
try
{
ApplicationDeployment updateCheck = ApplicationDeployment.CurrentDeployment;
updateCheck.Update();
MessageBox.Show(Resources.ApplicationUpdated);
Application.Restart();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show(string.Format(Resources.DeploymentDownloadExceptionMessage, dde));
return;
}
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Globalization;
// external references
using Mono.Unix;
using ServiceStack.Text;
using System.Threading;
namespace LogstashPurge
{
class MainClass
{
public static void Main(string[] args)
{
bool _shutDown = false;
bool _isMono;
Thread signal_thread = null;
_isMono = Type.GetType("Mono.Runtime") != null;
if (_isMono)
{
//http://unixhelp.ed.ac.uk/CGI/man-cgi?signal+7
UnixSignal[] signals;
signals = new UnixSignal[] {
//new UnixSignal (Mono.Unix.Native.Signum.SIGHUP),
new UnixSignal (Mono.Unix.Native.Signum.SIGINT),
//new UnixSignal (Mono.Unix.Native.Signum.SIGQUIT),
new UnixSignal (Mono.Unix.Native.Signum.SIGABRT),
//new UnixSignal (Mono.Unix.Native.Signum.SIGKILL),
new UnixSignal (Mono.Unix.Native.Signum.SIGTERM),
//new UnixSignal (Mono.Unix.Native.Signum.SIGSTOP),
new UnixSignal (Mono.Unix.Native.Signum.SIGTSTP)
};
signal_thread = new Thread(delegate()
{
while (!_shutDown)
{
// Wait for a signal to be delivered
int index = UnixSignal.WaitAny(signals, -1);
Mono.Unix.Native.Signum signal = signals[index].Signum;
Console.WriteLine("shutdown signal recieved {0}" + signal.ToString());
_shutDown = true;
}
});
}
Uri elasticSearchUrl;
int daysToKeep = 30;
if (args.Length == 0)
{
elasticSearchUrl = new Uri(Environment.GetEnvironmentVariable("elasticSearchUrl"));
string environmentVariable = Environment.GetEnvironmentVariable("daysToKeep");
if (environmentVariable != null)
{
daysToKeep = int.Parse(environmentVariable);
}
}
else
{
elasticSearchUrl = new Uri(args[0]);
if (args.Length > 1)
{
daysToKeep = int.Parse(args[1]);
}
}
IPAddress ip = GetExternalIP();
TimeSpan wait;
while (!_shutDown)
{
Console.WriteLine("\n\nstarting purge from IP {0} at {1}", ip, DateTime.UtcNow);
try
{
var mapping = GetMappings(elasticSearchUrl);
var toDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day).Subtract(TimeSpan.FromDays(daysToKeep));
var toDateString = GetDayOnlyString(toDate);
mapping.Indices.Sort();
foreach (var i in mapping.Indices)
{
Console.WriteLine("checking index {0}", i);
if (IndexExists(elasticSearchUrl, i))
{
var count = GetCount(elasticSearchUrl, i, toDateString);
if (count != 0)
{
Console.WriteLine("deleting {0} records", count);
Uri uri = new Uri(elasticSearchUrl, i + "/_query");
string range = GetRangeString(toDateString);
var queryBytes = Encoding.UTF8.GetBytes(range);
/*string responseText = */
Console.WriteLine("delete query: {0}", range);
GetResponseText(uri, "DELETE", queryBytes);
//{"ok":true,"_indices":{"logstash-2013.07.21":{"_shards":{"total":4,"successful":4,"failed":0}}}}
}
else
{
Console.WriteLine("index {0} has no matching records", i);
}
// then clean it up if empty
if (DeleteIndexIfEmpty(elasticSearchUrl, i))
{
Console.WriteLine("deleted emtpy index {0}", i);
}
}
else
{
Console.WriteLine("index {0} does not exist", i);
}
}
wait = TimeSpan.FromDays(1);
}
catch (Exception ex)
{
Console.WriteLine("ERROR:" + ex.ToString());
wait = TimeSpan.FromMinutes(1);
}
Console.WriteLine("\n\nwaiting {0} minutes until next purge", wait.TotalMinutes);
Thread.Sleep(wait);
}
Console.WriteLine("shutting down");
if (_isMono)
{
signal_thread.Join();
}
Console.WriteLine("shut down complete.");
}
public static bool DeleteIndexIfEmpty(Uri baseUri, string index)
{
var count = GetCount(baseUri, index, null);
if (count == 0)
{
Uri uri = new Uri(baseUri, index);
/*string responseText = */
GetResponseText(uri, "DELETE", null);
// {"ok":true,"acknowledged":true}
return true;
}
else
{
return false;
}
}
public static int GetCount(Uri baseUri, string index, string toDateString)
{
Uri uri = new Uri(baseUri, index + "/_count");
byte[] queryBytes = null;
if (!string.IsNullOrEmpty(toDateString))
{
string range = GetRangeString(toDateString);
queryBytes = Encoding.UTF8.GetBytes(range);
}
string responseText = GetResponseText(uri, "POST", queryBytes);
Dictionary<string, object> responseObject = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(responseText);
return int.Parse(responseObject["count"].ToString());
}
public static string GetRangeString(string toDateString)
{
return "{" +
" \"range\": {" +
" \"@timestamp\": {" +
" \"to\": \"" + toDateString + "\"" +
" }" +
" }" +
"}";
}
public static string GetQueryString(string toDateString)
{
return "{" + GetRangeString(toDateString) + "}";
}
public static bool IndexExists(Uri uri, string index)
{
string method = "HEAD";
var u = new Uri(uri, index + "/");
try
{
GetResponseText(u, method, null);
return true;
}
catch
{
return false;
}
}
public static string GetResponseText(Uri uri, string method, byte[] queryBytes)
{
string responseText;
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = method;
if (method.ToLower() == "post" || method.ToLower() == "delete")
{
if (queryBytes != null)
{
using (var reqStream = req.GetRequestStream())
{
reqStream.Write(queryBytes, 0, queryBytes.Length);
}
}
}
using (var response = (HttpWebResponse)req.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(string.Format("status {0}", response.StatusCode));
}
using (var resStream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(resStream))
{
responseText = streamReader.ReadToEnd();
}
}
}
return responseText;
}
public static Mapping GetMappings(Uri uri)
{
string json = GetResponseText(new Uri(uri, "/_mapping?pretty"), "GET", null);
Dictionary<string, Dictionary<string, object>> obj = JsonSerializer.DeserializeFromString<Dictionary<string, Dictionary<string, object>>>(json);
var mapping = new Mapping();
foreach (string k in obj.Keys)
{
if (!string.IsNullOrEmpty(k))
{
if (k.StartsWith("logstash-"))
{
mapping.Indices.Add(k);
var index = (Dictionary<string, object>)obj[k];
foreach (string t in index.Keys)
{
if (!mapping.Types.Contains(t))
{
mapping.Types.Add(t);
}
}
}
}
}
mapping.Types.Sort();
return mapping;
}
public static string GetDayOnlyString(DateTime toDate)
{
//2013-09-06T00:00:00
var date1 = new DateTime(toDate.Year, toDate.Month, toDate.Day);
var ci = CultureInfo.InvariantCulture;
var toDateString = date1.ToString("yyyy-MM-dd", ci) + "T00:00:00";
return toDateString;
}
public static IPAddress GetExternalIP()
{
IPAddress ip = IPAddress.Parse(GetResponseText(new Uri("http://api.externalip.net/ip"), "GET", null));
return ip;
}
}
public class Mapping
{
public Mapping()
{
Indices = new List<string>();
Types = new List<string>();
}
public List<string> Indices { get; set; }
public List<string> Types { get; set; }
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: A1025Response.txt
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace DolphinServer.ProtoEntity {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class A1025Response {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_A1025Response__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1025Response, global::DolphinServer.ProtoEntity.A1025Response.Builder> internal__static_A1025Response__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static A1025Response() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFBMTAyNVJlc3BvbnNlLnR4dCJqCg1BMTAyNVJlc3BvbnNlEhEKCUVycm9y",
"SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSCwoDVWlkGAMgASgJEhAK",
"CFJvb21DYXJkGAQgASgFEhQKDEZyaWVuZE51bWJlchgFIAEoBUIcqgIZRG9s",
"cGhpblNlcnZlci5Qcm90b0VudGl0eQ=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_A1025Response__Descriptor = Descriptor.MessageTypes[0];
internal__static_A1025Response__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1025Response, global::DolphinServer.ProtoEntity.A1025Response.Builder>(internal__static_A1025Response__Descriptor,
new string[] { "ErrorInfo", "ErrorCode", "Uid", "RoomCard", "FriendNumber", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class A1025Response : pb::GeneratedMessage<A1025Response, A1025Response.Builder> {
private A1025Response() { }
private static readonly A1025Response defaultInstance = new A1025Response().MakeReadOnly();
private static readonly string[] _a1025ResponseFieldNames = new string[] { "ErrorCode", "ErrorInfo", "FriendNumber", "RoomCard", "Uid" };
private static readonly uint[] _a1025ResponseFieldTags = new uint[] { 16, 10, 40, 32, 26 };
public static A1025Response DefaultInstance {
get { return defaultInstance; }
}
public override A1025Response DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override A1025Response ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DolphinServer.ProtoEntity.Proto.A1025Response.internal__static_A1025Response__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<A1025Response, A1025Response.Builder> InternalFieldAccessors {
get { return global::DolphinServer.ProtoEntity.Proto.A1025Response.internal__static_A1025Response__FieldAccessorTable; }
}
public const int ErrorInfoFieldNumber = 1;
private bool hasErrorInfo;
private string errorInfo_ = "";
public bool HasErrorInfo {
get { return hasErrorInfo; }
}
public string ErrorInfo {
get { return errorInfo_; }
}
public const int ErrorCodeFieldNumber = 2;
private bool hasErrorCode;
private int errorCode_;
public bool HasErrorCode {
get { return hasErrorCode; }
}
public int ErrorCode {
get { return errorCode_; }
}
public const int UidFieldNumber = 3;
private bool hasUid;
private string uid_ = "";
public bool HasUid {
get { return hasUid; }
}
public string Uid {
get { return uid_; }
}
public const int RoomCardFieldNumber = 4;
private bool hasRoomCard;
private int roomCard_;
public bool HasRoomCard {
get { return hasRoomCard; }
}
public int RoomCard {
get { return roomCard_; }
}
public const int FriendNumberFieldNumber = 5;
private bool hasFriendNumber;
private int friendNumber_;
public bool HasFriendNumber {
get { return hasFriendNumber; }
}
public int FriendNumber {
get { return friendNumber_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _a1025ResponseFieldNames;
if (hasErrorInfo) {
output.WriteString(1, field_names[1], ErrorInfo);
}
if (hasErrorCode) {
output.WriteInt32(2, field_names[0], ErrorCode);
}
if (hasUid) {
output.WriteString(3, field_names[4], Uid);
}
if (hasRoomCard) {
output.WriteInt32(4, field_names[3], RoomCard);
}
if (hasFriendNumber) {
output.WriteInt32(5, field_names[2], FriendNumber);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasErrorInfo) {
size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo);
}
if (hasErrorCode) {
size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode);
}
if (hasUid) {
size += pb::CodedOutputStream.ComputeStringSize(3, Uid);
}
if (hasRoomCard) {
size += pb::CodedOutputStream.ComputeInt32Size(4, RoomCard);
}
if (hasFriendNumber) {
size += pb::CodedOutputStream.ComputeInt32Size(5, FriendNumber);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static A1025Response ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A1025Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A1025Response ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A1025Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A1025Response ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A1025Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static A1025Response ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static A1025Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static A1025Response ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A1025Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private A1025Response MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(A1025Response prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<A1025Response, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(A1025Response cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private A1025Response result;
private A1025Response PrepareBuilder() {
if (resultIsReadOnly) {
A1025Response original = result;
result = new A1025Response();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override A1025Response MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DolphinServer.ProtoEntity.A1025Response.Descriptor; }
}
public override A1025Response DefaultInstanceForType {
get { return global::DolphinServer.ProtoEntity.A1025Response.DefaultInstance; }
}
public override A1025Response BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is A1025Response) {
return MergeFrom((A1025Response) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(A1025Response other) {
if (other == global::DolphinServer.ProtoEntity.A1025Response.DefaultInstance) return this;
PrepareBuilder();
if (other.HasErrorInfo) {
ErrorInfo = other.ErrorInfo;
}
if (other.HasErrorCode) {
ErrorCode = other.ErrorCode;
}
if (other.HasUid) {
Uid = other.Uid;
}
if (other.HasRoomCard) {
RoomCard = other.RoomCard;
}
if (other.HasFriendNumber) {
FriendNumber = other.FriendNumber;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_a1025ResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _a1025ResponseFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasErrorInfo = input.ReadString(ref result.errorInfo_);
break;
}
case 16: {
result.hasErrorCode = input.ReadInt32(ref result.errorCode_);
break;
}
case 26: {
result.hasUid = input.ReadString(ref result.uid_);
break;
}
case 32: {
result.hasRoomCard = input.ReadInt32(ref result.roomCard_);
break;
}
case 40: {
result.hasFriendNumber = input.ReadInt32(ref result.friendNumber_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasErrorInfo {
get { return result.hasErrorInfo; }
}
public string ErrorInfo {
get { return result.ErrorInfo; }
set { SetErrorInfo(value); }
}
public Builder SetErrorInfo(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasErrorInfo = true;
result.errorInfo_ = value;
return this;
}
public Builder ClearErrorInfo() {
PrepareBuilder();
result.hasErrorInfo = false;
result.errorInfo_ = "";
return this;
}
public bool HasErrorCode {
get { return result.hasErrorCode; }
}
public int ErrorCode {
get { return result.ErrorCode; }
set { SetErrorCode(value); }
}
public Builder SetErrorCode(int value) {
PrepareBuilder();
result.hasErrorCode = true;
result.errorCode_ = value;
return this;
}
public Builder ClearErrorCode() {
PrepareBuilder();
result.hasErrorCode = false;
result.errorCode_ = 0;
return this;
}
public bool HasUid {
get { return result.hasUid; }
}
public string Uid {
get { return result.Uid; }
set { SetUid(value); }
}
public Builder SetUid(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasUid = true;
result.uid_ = value;
return this;
}
public Builder ClearUid() {
PrepareBuilder();
result.hasUid = false;
result.uid_ = "";
return this;
}
public bool HasRoomCard {
get { return result.hasRoomCard; }
}
public int RoomCard {
get { return result.RoomCard; }
set { SetRoomCard(value); }
}
public Builder SetRoomCard(int value) {
PrepareBuilder();
result.hasRoomCard = true;
result.roomCard_ = value;
return this;
}
public Builder ClearRoomCard() {
PrepareBuilder();
result.hasRoomCard = false;
result.roomCard_ = 0;
return this;
}
public bool HasFriendNumber {
get { return result.hasFriendNumber; }
}
public int FriendNumber {
get { return result.FriendNumber; }
set { SetFriendNumber(value); }
}
public Builder SetFriendNumber(int value) {
PrepareBuilder();
result.hasFriendNumber = true;
result.friendNumber_ = value;
return this;
}
public Builder ClearFriendNumber() {
PrepareBuilder();
result.hasFriendNumber = false;
result.friendNumber_ = 0;
return this;
}
}
static A1025Response() {
object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1025Response.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Initial
{
/// <summary>
/// Represents the initial database schema creation by running CreateTable for all DTOs against the db.
/// </summary>
internal class DatabaseSchemaCreation
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="database"></param>
/// <param name="logger"></param>
/// <param name="sqlSyntaxProvider"></param>
public DatabaseSchemaCreation(Database database, ILogger logger, ISqlSyntaxProvider sqlSyntaxProvider)
{
_database = database;
_logger = logger;
_sqlSyntaxProvider = sqlSyntaxProvider;
_schemaHelper = new DatabaseSchemaHelper(database, logger, sqlSyntaxProvider);
}
#region Private Members
private readonly DatabaseSchemaHelper _schemaHelper;
private readonly Database _database;
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _sqlSyntaxProvider;
private static readonly Dictionary<int, Type> OrderedTables = new Dictionary<int, Type>
{
{0, typeof (NodeDto)},
{1, typeof (ContentTypeDto)},
{2, typeof (TemplateDto)},
{3, typeof (ContentDto)},
{4, typeof (ContentVersionDto)},
{5, typeof (DocumentDto)},
{6, typeof (DocumentTypeDto)},
{7, typeof (DataTypeDto)},
{8, typeof (DataTypePreValueDto)},
{9, typeof (DictionaryDto)},
{10, typeof (LanguageTextDto)},
{11, typeof (LanguageDto)},
{12, typeof (DomainDto)},
{13, typeof (LogDto)},
{14, typeof (MacroDto)},
{15, typeof (MacroPropertyDto)},
{16, typeof (MemberTypeDto)},
{17, typeof (MemberDto)},
{18, typeof (Member2MemberGroupDto)},
{19, typeof (ContentXmlDto)},
{20, typeof (PreviewXmlDto)},
{21, typeof (PropertyTypeGroupDto)},
{22, typeof (PropertyTypeDto)},
{23, typeof (PropertyDataDto)},
{24, typeof (RelationTypeDto)},
{25, typeof (RelationDto)},
{26, typeof (StylesheetDto)},
{27, typeof (StylesheetPropertyDto)},
{28, typeof (TagDto)},
{29, typeof (TagRelationshipDto)},
{30, typeof (UserLoginDto)},
{31, typeof (UserTypeDto)},
{32, typeof (UserDto)},
{33, typeof (TaskTypeDto)},
{34, typeof (TaskDto)},
{35, typeof (ContentType2ContentTypeDto)},
{36, typeof (ContentTypeAllowedContentTypeDto)},
{37, typeof (User2AppDto)},
{38, typeof (User2NodeNotifyDto)},
{39, typeof (User2NodePermissionDto)},
{40, typeof (ServerRegistrationDto)},
{41, typeof (AccessDto)},
{42, typeof (AccessRuleDto)},
{43, typeof(CacheInstructionDto)},
{44, typeof (ExternalLoginDto)},
{45, typeof (MigrationDto)}
};
#endregion
/// <summary>
/// Drops all Umbraco tables in the db
/// </summary>
internal void UninstallDatabaseSchema()
{
_logger.Info<DatabaseSchemaCreation>("Start UninstallDatabaseSchema");
foreach (var item in OrderedTables.OrderByDescending(x => x.Key))
{
var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>();
string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value;
_logger.Info<DatabaseSchemaCreation>("Uninstall" + tableName);
try
{
if (_schemaHelper.TableExist(tableName))
{
_schemaHelper.DropTable(tableName);
}
}
catch (Exception ex)
{
//swallow this for now, not sure how best to handle this with diff databases... though this is internal
// and only used for unit tests. If this fails its because the table doesn't exist... generally!
_logger.Error<DatabaseSchemaCreation>("Could not drop table " + tableName, ex);
}
}
}
/// <summary>
/// Initialize the database by creating the umbraco db schema
/// </summary>
public void InitializeDatabaseSchema()
{
var e = new DatabaseCreationEventArgs();
FireBeforeCreation(e);
if (!e.Cancel)
{
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
_schemaHelper.CreateTable(false, item.Value);
}
}
FireAfterCreation(e);
}
/// <summary>
/// Validates the schema of the current database
/// </summary>
public DatabaseSchemaResult ValidateSchema()
{
var result = new DatabaseSchemaResult();
//get the db index defs
result.DbIndexDefinitions = _sqlSyntaxProvider.GetDefinedIndexes(_database)
.Select(x => new DbIndexDefinition()
{
TableName = x.Item1,
IndexName = x.Item2,
ColumnName = x.Item3,
IsUnique = x.Item4
}).ToArray();
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
var tableDefinition = DefinitionFactory.GetTableDefinition(item.Value);
result.TableDefinitions.Add(tableDefinition);
}
ValidateDbTables(result);
ValidateDbColumns(result);
ValidateDbIndexes(result);
ValidateDbConstraints(result);
return result;
}
private void ValidateDbConstraints(DatabaseSchemaResult result)
{
//MySql doesn't conform to the "normal" naming of constraints, so there is currently no point in doing these checks.
//TODO: At a later point we do other checks for MySql, but ideally it should be necessary to do special checks for different providers.
// ALso note that to get the constraints for MySql we have to open a connection which we currently have not.
if (_sqlSyntaxProvider is MySqlSyntaxProvider)
return;
//Check constraints in configured database against constraints in schema
var constraintsInDatabase = _sqlSyntaxProvider.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList();
var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")).Select(x => x.Item3).ToList();
var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")).Select(x => x.Item3).ToList();
var indexesInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("IX_")).Select(x => x.Item3).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
var unknownConstraintsInDatabase =
constraintsInDatabase.Where(
x =>
x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false &&
x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList();
var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList();
var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName))
.Where(x => x.IsNullOrWhiteSpace() == false).ToList();
//Add valid and invalid foreign key differences to the result object
// We'll need to do invariant contains with case insensitivity because foreign key, primary key, and even index naming w/ MySQL is not standardized
// In theory you could have: FK_ or fk_ ...or really any standard that your development department (or developer) chooses to use.
foreach (var unknown in unknownConstraintsInDatabase)
{
if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown) || indexesInSchema.InvariantContains(unknown))
{
result.ValidConstraints.Add(unknown);
}
else
{
result.Errors.Add(new Tuple<string, string>("Unknown", unknown));
}
}
//Foreign keys:
var validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var foreignKey in validForeignKeyDifferences)
{
result.ValidConstraints.Add(foreignKey);
}
var invalidForeignKeyDifferences =
foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var foreignKey in invalidForeignKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey));
}
//Primary keys:
//Add valid and invalid primary key differences to the result object
var validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var primaryKey in validPrimaryKeyDifferences)
{
result.ValidConstraints.Add(primaryKey);
}
var invalidPrimaryKeyDifferences =
primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var primaryKey in invalidPrimaryKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey));
}
//Constaints:
//NOTE: SD: The colIndex checks above should really take care of this but I need to keep this here because it was here before
// and some schema validation checks might rely on this data remaining here!
//Add valid and invalid index differences to the result object
var validIndexDifferences = indexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validIndexDifferences)
{
result.ValidConstraints.Add(index);
}
var invalidIndexDifferences =
indexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(indexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", index));
}
}
private void ValidateDbColumns(DatabaseSchemaResult result)
{
//Check columns in configured database against columns in schema
var columnsInDatabase = _sqlSyntaxProvider.GetColumnsInSchema(_database);
var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList();
var columnsPerTableInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList();
//Add valid and invalid column differences to the result object
var validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var column in validColumnDifferences)
{
result.ValidColumns.Add(column);
}
var invalidColumnDifferences =
columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var column in invalidColumnDifferences)
{
result.Errors.Add(new Tuple<string, string>("Column", column));
}
}
private void ValidateDbTables(DatabaseSchemaResult result)
{
//Check tables in configured database against tables in schema
var tablesInDatabase = _sqlSyntaxProvider.GetTablesInSchema(_database).ToList();
var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList();
//Add valid and invalid table differences to the result object
var validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var tableName in validTableDifferences)
{
result.ValidTables.Add(tableName);
}
var invalidTableDifferences =
tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var tableName in invalidTableDifferences)
{
result.Errors.Add(new Tuple<string, string>("Table", tableName));
}
}
private void ValidateDbIndexes(DatabaseSchemaResult result)
{
//These are just column indexes NOT constraints or Keys
//var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList();
var colIndexesInDatabase = result.DbIndexDefinitions.Select(x => x.IndexName).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
//Add valid and invalid index differences to the result object
var validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validColIndexDifferences)
{
result.ValidIndexes.Add(index);
}
var invalidColIndexDifferences =
colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidColIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Index", index));
}
}
#region Events
/// <summary>
/// The save event handler
/// </summary>
internal delegate void DatabaseEventHandler(DatabaseCreationEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
internal static event DatabaseEventHandler BeforeCreation;
/// <summary>
/// Raises the <see cref="BeforeCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected internal virtual void FireBeforeCreation(DatabaseCreationEventArgs e)
{
if (BeforeCreation != null)
{
BeforeCreation(e);
}
}
/// <summary>
/// Occurs when [after save].
/// </summary>
internal static event DatabaseEventHandler AfterCreation;
/// <summary>
/// Raises the <see cref="AfterCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterCreation(DatabaseCreationEventArgs e)
{
if (AfterCreation != null)
{
AfterCreation(e);
}
}
#endregion
}
}
| |
/*
* Reactor 3D MIT License
*
* Copyright (c) 2010 Reiser Games
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#region Using
using System;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
#endregion
namespace Reactor.Content.Importer
{
/// <summary>
/// Custom content processor adds randomly positioned billboards on the
/// surface of the input mesh. This technique can be used to scatter
/// grass billboards across a landscape model.
/// </summary>
[ContentProcessor]
public class RGrassProcessor : ModelProcessor
{
#region Processor Parameters
int billboardsPerTriangle = 23;
[DisplayName("Billboards per Triangle")]
[DefaultValue(23)]
[Description("Amount of vegetation per triangle in the landscape geometry.")]
public int BillboardsPerTriangle
{
get { return billboardsPerTriangle; }
set { billboardsPerTriangle = value; }
}
double treeProbability = 0.002;
[DisplayName("Tree Probability")]
[DefaultValue(0.002)]
[Description("The chance that a given piece of vegetation is actually a tree.")]
public double TreeProbability
{
get { return treeProbability; }
set { treeProbability = value; }
}
double grassWidth = 2.0;
[DisplayName("Grass Width")]
[DefaultValue(2.0)]
[Description("The Width of the Grass Billboards.")]
public double GrassWidth
{
get { return grassWidth; }
set { grassWidth = value; }
}
double grassHeight = 2.0;
[DisplayName("Grass Height")]
[DefaultValue(2.0)]
[Description("The Height of the Grass Billboards.")]
public double GrassHeight
{
get { return grassHeight; }
set { grassHeight = value; }
}
double treeWidth = 2.0;
[DisplayName("Tree Width")]
[DefaultValue(2.0)]
[Description("The Width of the Tree Billboards.")]
public double TreeWidth
{
get { return treeWidth; }
set { treeWidth = value; }
}
double treeHeight = 2.0;
[DisplayName("Tree Height")]
[DefaultValue(2.0)]
[Description("The Height of the Tree Billboards.")]
public double TreeHeight
{
get { return treeHeight; }
set { treeHeight = value; }
}
#endregion
Random random = new Random();
/// <summary>
/// Override the main Process method.
/// </summary>
public override ModelContent Process(NodeContent input,
ContentProcessorContext context)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
// Create vegetation billboards.
GenerateVegetation(input, input.Identity);
// Chain to the standard ModelProcessor.
return base.Process(input, context);
}
/// <summary>
/// Recursive function adds vegetation billboards to all meshes.
/// </summary>
void GenerateVegetation(NodeContent node, ContentIdentity identity)
{
// First, recurse over any child nodes.
foreach (NodeContent child in node.Children)
{
GenerateVegetation(child, identity);
}
// Check whether this node is in fact a mesh.
MeshContent mesh = node as MeshContent;
if (mesh != null)
{
// Create three new geometry objects, one for each type
// of billboard that we are going to create. Set different
// effect parameters to control the size and wind sensitivity
// for each type of billboard.
GeometryContent grass = CreateVegetationGeometry((float)grassWidth, (float)grassHeight, 1.0f, identity);
GeometryContent trees = CreateVegetationGeometry((float)treeWidth, (float)treeHeight, 0.5f, identity);
// Loop over all the existing geometry in this mesh.
foreach (GeometryContent geometry in mesh.Geometry)
{
IList<int> indices = geometry.Indices;
IList<Vector3> positions = geometry.Vertices.Positions;
IList<Vector3> normals = geometry.Vertices.Channels.Get<Vector3>(
VertexChannelNames.Normal());
// Loop over all the triangles in this piece of geometry.
for (int triangle = 0; triangle < indices.Count; triangle += 3)
{
// Look up the three indices for this triangle.
int i1 = indices[triangle];
int i2 = indices[triangle + 1];
int i3 = indices[triangle + 2];
// Create vegetation billboards to cover this triangle.
// A more sophisticated implementation would measure the
// size of the triangle to work out how many to create,
// but we don't bother since we happen to know that all
// our triangles are roughly the same size.
for (int count = 0; count < BillboardsPerTriangle; count++)
{
Vector3 position, normal;
// Choose a random location on the triangle.
PickRandomPoint(positions[i1], positions[i2], positions[i3],
normals[i1], normals[i2], normals[i3],
out position, out normal);
// Randomly choose what type of billboard to create.
GeometryContent billboardType;
if (random.NextDouble() < TreeProbability)
{
billboardType = trees;
// As a special case, force trees to point straight
// upward, even if they are growing on a slope.
// That's what trees do in real life, after all!
normal = Vector3.Up;
}
else
{
billboardType = grass;
}
// Add a new billboard to the output geometry.
GenerateBillboard(mesh, billboardType, position, normal);
}
}
}
// Add our new billboard geometry to the main mesh.
mesh.Geometry.Add(grass);
mesh.Geometry.Add(trees);
}
}
/// <summary>
/// Helper function creates a new geometry object,
/// and sets it to use our billboard effect.
/// </summary>
static GeometryContent CreateVegetationGeometry(float width, float height,
float windAmount,
ContentIdentity identity)
{
GeometryContent geometry = new GeometryContent();
// Add the vertex channels needed for our billboard geometry.
VertexChannelCollection channels = geometry.Vertices.Channels;
// Add a vertex channel holding normal vectors.
channels.Add<Vector3>(VertexChannelNames.Normal(), null);
// Add a vertex channel holding texture coordinates.
channels.Add<Vector2>(VertexChannelNames.TextureCoordinate(0), null);
// Add a second texture coordinate channel, holding a per-billboard
// random number. This is used to make each billboard come out a
// slightly different size, and to animate at different speeds.
channels.Add<float>(VertexChannelNames.TextureCoordinate(1), null);
// Create a material for rendering the billboards.
//EffectMaterialContent material = new EffectMaterialContent();
// Point the material at our custom billboard effect.
//string directory = Path.GetDirectoryName(identity.SourceFilename);
//string effectFilename = Path.Combine(directory, "Billboard.fx");
//material.Effect = new ExternalReference<EffectContent>(effectFilename);
// Set the texture to be used by these billboards.
//textureFilename = Path.Combine(directory, textureFilename);
//material.Textures.Add("Texture",
//new ExternalReference<TextureContent>(textureFilename));
// Set effect parameters describing the size and
// wind sensitivity of these billboards.
//material.OpaqueData.Add("BillboardWidth", width);
//material.OpaqueData.Add("BillboardHeight", height);
//material.OpaqueData.Add("WindAmount", windAmount);
geometry.OpaqueData.Add("Grass", true);
geometry.Material = null;
return geometry;
}
/// <summary>
/// Helper function chooses a random location on a triangle.
/// </summary>
void PickRandomPoint(Vector3 position1, Vector3 position2, Vector3 position3,
Vector3 normal1, Vector3 normal2, Vector3 normal3,
out Vector3 randomPosition, out Vector3 randomNormal)
{
float a = (float)random.NextDouble();
float b = (float)random.NextDouble();
if (a + b > 1)
{
a = 1 - a;
b = 1 - b;
}
randomPosition = Vector3.Barycentric(position1, position2, position3, a, b);
randomNormal = Vector3.Barycentric(normal1, normal2, normal3, a, b);
randomNormal.Normalize();
}
/// <summary>
/// Helper function adds a single new billboard sprite to the output geometry.
/// </summary>
private void GenerateBillboard(MeshContent mesh, GeometryContent geometry,
Vector3 position, Vector3 normal)
{
VertexContent vertices = geometry.Vertices;
VertexChannelCollection channels = vertices.Channels;
// First, create a vertex position entry for this billboard. Each
// billboard is going to be rendered a quad, so we need to create four
// vertices, but at this point we only have a single position that is
// shared by all the vertices. The real position of each vertex will be
// computed on the fly in the vertex shader, thus allowing us to
// implement effects like making the billboard rotate to always face the
// camera, and sway in the wind. As input the vertex shader only wants to
// know the center point of the billboard, and that is the same for all
// the vertices, so only a single position is needed here.
int positionIndex = mesh.Positions.Count;
mesh.Positions.Add(position);
// Second, create the four vertices, all referencing the same position.
int index = vertices.PositionIndices.Count;
for (int i = 0; i < 4; i++)
{
vertices.Add(positionIndex);
}
// Third, add normal data for each of the four vertices. A normal for a
// billboard is kind of a silly thing to define, since we are using a
// 2D sprite to fake a complex 3D object that would in reality have many
// different normals across its surface. Here we are just using a copy
// of the normal from the ground underneath the billboard, which can be
// used in our lighting computation to make the vegetation darker or
// lighter depending on the lighting of the underlying landscape.
VertexChannel<Vector3> normals;
normals = channels.Get<Vector3>(VertexChannelNames.Normal());
for (int i = 0; i < 4; i++)
{
normals[index + i] = normal;
}
// Fourth, add texture coordinates.
VertexChannel<Vector2> texCoords;
texCoords = channels.Get<Vector2>(VertexChannelNames.TextureCoordinate(0));
texCoords[index + 0] = new Vector2(0, 0);
texCoords[index + 1] = new Vector2(1, 0);
texCoords[index + 2] = new Vector2(1, 1);
texCoords[index + 3] = new Vector2(0, 1);
// Fifth, add a per-billboard random value, which is the same for
// all four vertices. This is used in the vertex shader to make
// each billboard a slightly different size, and to be affected
// differently by the wind animation.
float randomValue = (float)random.NextDouble() * 2 - 1;
VertexChannel<float> randomValues;
randomValues = channels.Get<float>(VertexChannelNames.TextureCoordinate(1));
for (int i = 0; i < 4; i++)
{
randomValues[index + i] = randomValue;
}
// Sixth and finally, add indices defining the pair of
// triangles that will be used to render the billboard.
geometry.Indices.Add(index + 0);
geometry.Indices.Add(index + 1);
geometry.Indices.Add(index + 2);
geometry.Indices.Add(index + 0);
geometry.Indices.Add(index + 2);
geometry.Indices.Add(index + 3);
}
}
/// <summary>
/// Custom processor extends the builtin framework ModelProcessor class,
/// adding animation support.
/// </summary>
[ContentProcessor(DisplayName = "Reactor 3D Mesh")]
public class RMeshProcessor : ModelProcessor
{
/// <summary>
/// The main Process method converts an intermediate format content pipeline
/// NodeContent tree to a ModelContent object with embedded tangent data.
/// </summary>
public override ModelContent Process(NodeContent input,
ContentProcessorContext context)
{
GenerateTangents(input, context);
return base.Process(input, context);
}
static IList<string> acceptableVertexChannelNames =
new string[]
{
VertexChannelNames.TextureCoordinate(0),
VertexChannelNames.Normal(0),
VertexChannelNames.Binormal(0),
VertexChannelNames.Tangent(0)
};
protected override void ProcessVertexChannel(GeometryContent geometry, int vertexChannelIndex, ContentProcessorContext context)
{
String vertexChannelName =
geometry.Vertices.Channels[vertexChannelIndex].Name;
// if this vertex channel has an acceptable names, process it as normal.
if (acceptableVertexChannelNames.Contains(vertexChannelName))
{
base.ProcessVertexChannel(geometry, vertexChannelIndex, context);
}
// otherwise, remove it from the vertex channels; it's just extra data
// we don't need.
else
{
geometry.Vertices.Channels.Remove(vertexChannelName);
}
}
/// <summary>
/// Generates Tangent Data for a Mesh
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
static void GenerateTangents(NodeContent input, ContentProcessorContext context)
{
MeshContent mesh = input as MeshContent;
if (mesh != null)
{
MeshHelper.CalculateTangentFrames(mesh, VertexChannelNames.TextureCoordinate(0), VertexChannelNames.Tangent(0), VertexChannelNames.Binormal(0));
foreach (NodeContent child in input.Children)
{
GenerateTangents(child, context);
}
}
}
/// <summary>
/// We override this property from the base processor and force it to always
/// return true: tangent frames are required for normal mapping, so they should
/// not be optional.
/// </summary>
public override bool GenerateTangentFrames
{
get { return true; }
set { }
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// SOURCECODE IS MODIFIED FROM ANOTHER WORK AND IS ORIGINALLY BASED ON GeoTools.NET:
/*
* Copyright (C) 2002 Urban Science Applications, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
using System;
using System.Globalization;
using System.IO;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
namespace SharpMap.Converters.WellKnownText
{
/// <summary>
/// Outputs the textual representation of a <see cref="NetTopologySuite.Geometries.Geometry"/> instance.
/// </summary>
/// <remarks>
/// <para>The Well-Known Text (WKT) representation of Geometry is designed to exchange geometry data in ASCII form.</para>
/// Examples of WKT representations of geometry objects are:
/// <list type="table">
/// <listheader><term>Geometry </term><description>WKT Representation</description></listheader>
/// <item><term>A Point</term>
/// <description>POINT(15 20)<br/> Note that point coordinates are specified with no separating comma.</description></item>
/// <item><term>A LineString with four points:</term>
/// <description>LINESTRING(0 0, 10 10, 20 25, 50 60)</description></item>
/// <item><term>A Polygon with one exterior ring and one interior ring:</term>
/// <description>POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))</description></item>
/// <item><term>A MultiPoint with three Point values:</term>
/// <description>MultiPoint(0 0, 20 20, 60 60)</description></item>
/// <item><term>A MultiLineString with two LineString values:</term>
/// <description>MultiLineString((10 10, 20 20), (15 15, 30 15))</description></item>
/// <item><term>A MultiPolygon with two Polygon values:</term>
/// <description>MultiPolygon(((0 0,10 0,10 10,0 10,0 0)),((5 5,7 5,7 7,5 7, 5 5)))</description></item>
/// <item><term>A GeometryCollection consisting of two Point values and one LineString:</term>
/// <description>GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), LINESTRING(15 15, 20 20))</description></item>
/// </list>
/// </remarks>
public class GeometryToWKT
{
/// <summary>
/// Converts a Geometry to its Well-known Text representation.
/// </summary>
/// <param name="geometry">A Geometry to write.</param>
/// <returns>A <Geometry Tagged Text> string (see the OpenGIS Simple
/// Features Specification)</returns>
public static string Write(Geometry geometry)
{
StringWriter sw = new StringWriter();
Write(geometry, sw);
return sw.ToString();
}
/// <summary>
/// Converts a Geometry to its Well-known Text representation.
/// </summary>
/// <param name="geometry">A geometry to process.</param>
/// <param name="writer">Stream to write out the geometry's text representation.</param>
/// <remarks>
/// Geometry is written to the output stream as <Geometry Tagged Text> string (see the OpenGIS
/// Simple Features Specification).
/// </remarks>
public static void Write(Geometry geometry, StringWriter writer)
{
WKTWriter wkt = new WKTWriter();
wkt.Write(geometry, writer);
//AppendGeometryTaggedText(geometry, writer);
}
/// <summary>
/// Converts a Geometry to <Geometry Tagged Text > format, then Appends it to the writer.
/// </summary>
/// <param name="geometry">The Geometry to process.</param>
/// <param name="writer">The output stream to Append to.</param>
private static void AppendGeometryTaggedText(Geometry geometry, StringWriter writer)
{
if (geometry == null)
throw new NullReferenceException("Cannot write Well-Known Text: geometry was null");
if (geometry is Point)
{
var point = geometry as Point;
AppendPointTaggedText(point, writer);
}
else if (geometry is LineString)
AppendLineStringTaggedText(geometry as LineString, writer);
else if (geometry is Polygon)
AppendPolygonTaggedText(geometry as Polygon, writer);
else if (geometry is MultiPoint)
AppendMultiPointTaggedText(geometry as MultiPoint, writer);
else if (geometry is MultiLineString)
AppendMultiLineStringTaggedText(geometry as MultiLineString, writer);
else if (geometry is MultiPolygon)
AppendMultiPolygonTaggedText(geometry as MultiPolygon, writer);
else if (geometry is GeometryCollection)
AppendGeometryCollectionTaggedText(geometry as GeometryCollection, writer);
else
throw new NotSupportedException("Unsupported Geometry implementation:" + geometry.GetType().Name);
}
/// <summary>
/// Converts a Coordinate to <Point Tagged Text> format,
/// then Appends it to the writer.
/// </summary>
/// <param name="coordinate">the <code>Coordinate</code> to process</param>
/// <param name="writer">the output writer to Append to</param>
private static void AppendPointTaggedText(Point coordinate, StringWriter writer)
{
writer.Write("POINT ");
AppendPointText(coordinate, writer);
}
/// <summary>
/// Converts a LineString to LineString tagged text format,
/// </summary>
/// <param name="lineString">The LineString to process.</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendLineStringTaggedText(LineString lineString, StringWriter writer)
{
writer.Write("LINESTRING ");
AppendLineStringText(lineString, writer);
}
/// <summary>
/// Converts a Polygon to <Polygon Tagged Text> format,
/// then Appends it to the writer.
/// </summary>
/// <param name="polygon">Th Polygon to process.</param>
/// <param name="writer">The stream writer to Append to.</param>
private static void AppendPolygonTaggedText(Polygon polygon, StringWriter writer)
{
writer.Write("POLYGON ");
AppendPolygonText(polygon, writer);
}
/// <summary>
/// Converts a MultiPoint to <MultiPoint Tagged Text>
/// format, then Appends it to the writer.
/// </summary>
/// <param name="MultiPoint">The MultiPoint to process.</param>
/// <param name="writer">The output writer to Append to.</param>
private static void AppendMultiPointTaggedText(MultiPoint MultiPoint, StringWriter writer)
{
writer.Write("MultiPoint ");
AppendMultiPointText(MultiPoint, writer);
}
/// <summary>
/// Converts a MultiLineString to <MultiLineString Tagged
/// Text> format, then Appends it to the writer.
/// </summary>
/// <param name="MultiLineString">The MultiLineString to process</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendMultiLineStringTaggedText(MultiLineString MultiLineString, StringWriter writer)
{
writer.Write("MultiLineString ");
AppendMultiLineStringText(MultiLineString, writer);
}
/// <summary>
/// Converts a MultiPolygon to <MultiPolygon Tagged
/// Text> format, then Appends it to the writer.
/// </summary>
/// <param name="MultiPolygon">The MultiPolygon to process</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendMultiPolygonTaggedText(MultiPolygon MultiPolygon, StringWriter writer)
{
writer.Write("MultiPolygon ");
AppendMultiPolygonText(MultiPolygon, writer);
}
/// <summary>
/// Converts a GeometryCollection to <GeometryCollection Tagged
/// Text> format, then Appends it to the writer.
/// </summary>
/// <param name="geometryCollection">The GeometryCollection to process</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendGeometryCollectionTaggedText(GeometryCollection geometryCollection,
StringWriter writer)
{
writer.Write("GEOMETRYCOLLECTION ");
AppendGeometryCollectionText(geometryCollection, writer);
}
/// <summary>
/// Converts a Coordinate to Point Text format then Appends it to the writer.
/// </summary>
/// <param name="coordinate">The Coordinate to process.</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendPointText(Point coordinate, StringWriter writer)
{
if (coordinate == null || coordinate.IsEmpty)
writer.Write("EMPTY");
else
{
writer.Write("(");
AppendCoordinate(coordinate.Coordinate, writer);
writer.Write(")");
}
}
/// <summary>
/// Converts a Coordinate to <Point> format, then Appends
/// it to the writer.
/// </summary>
/// <param name="coordinate">The Coordinate to process.</param>
/// <param name="writer">The output writer to Append to.</param>
private static void AppendCoordinate(Coordinate coordinate, StringWriter writer)
{
writer.Write(WriteNumber(coordinate[Ordinate.X]));
writer.Write(' ');
writer.Write(WriteNumber(coordinate[Ordinate.Y]));
if (!double.IsNaN(coordinate.Z))
{
writer.Write(' ');
writer.Write(WriteNumber(coordinate[Ordinate.Y]));
}
}
/// <summary>
/// Converts a double to a string, not in scientific notation.
/// </summary>
/// <param name="d">The double to convert.</param>
/// <returns>The double as a string, not in scientific notation.</returns>
private static string WriteNumber(double d)
{
return d.ToString(NumberFormatInfo.InvariantInfo);
}
/// <summary>
/// Converts a LineString to <LineString Text> format, then
/// Appends it to the writer.
/// </summary>
/// <param name="lineString">The LineString to process.</param>
/// <param name="writer">The output stream to Append to.</param>
private static void AppendLineStringText(LineString lineString, StringWriter writer)
{
if (lineString == null || lineString.IsEmpty)
writer.Write("EMPTY");
else
{
var vertices = lineString.Coordinates;
writer.Write("(");
for (int i = 0; i < vertices.Length; i++)
{
if (i > 0)
writer.Write(", ");
AppendCoordinate(vertices[i], writer);
}
writer.Write(")");
}
}
/// <summary>
/// Converts a Polygon to <Polygon Text> format, then
/// Appends it to the writer.
/// </summary>
/// <param name="polygon">The Polygon to process.</param>
/// <param name="writer"></param>
private static void AppendPolygonText(Polygon polygon, StringWriter writer)
{
if (polygon == null || polygon.IsEmpty)
writer.Write("EMPTY");
else
{
writer.Write("(");
AppendLineStringText(polygon.ExteriorRing, writer);
if (polygon.NumInteriorRings > 0)
{
foreach (var ring in polygon.InteriorRings)
{
writer.Write(", ");
AppendLineStringText(ring, writer);
}
}
writer.Write(")");
}
}
/// <summary>
/// Converts a MultiPoint to <MultiPoint Text> format, then
/// Appends it to the writer.
/// </summary>
/// <param name="MultiPoint">The MultiPoint to process.</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendMultiPointText(MultiPoint MultiPoint, StringWriter writer)
{
if (MultiPoint == null || MultiPoint.IsEmpty)
writer.Write("EMPTY");
else
{
var vertices = MultiPoint.Coordinates;
writer.Write("(");
for (var i = 0; i < vertices.Length; i++)
{
if (i > 0)
writer.Write(", ");
AppendCoordinate(vertices[i], writer);
}
writer.Write(")");
}
}
/// <summary>
/// Converts a MultiLineString to <MultiLineString Text>
/// format, then Appends it to the writer.
/// </summary>
/// <param name="MultiLineString">The MultiLineString to process.</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendMultiLineStringText(MultiLineString MultiLineString, StringWriter writer)
{
if (MultiLineString == null || MultiLineString.IsEmpty)
writer.Write("EMPTY");
else
{
writer.Write("(");
for (var i = 0; i < MultiLineString.NumGeometries; i++)
{
if (i > 0)
writer.Write(", ");
AppendLineStringText((LineString)MultiLineString.GetGeometryN(i), writer);
}
writer.Write(")");
}
}
/// <summary>
/// Converts a MultiPolygon to <MultiPolygon Text> format, then Appends to it to the writer.
/// </summary>
/// <param name="MultiPolygon">The MultiPolygon to process.</param>
/// <param name="writer">The output stream to Append to.</param>
private static void AppendMultiPolygonText(MultiPolygon MultiPolygon, StringWriter writer)
{
if (MultiPolygon == null || MultiPolygon.IsEmpty)
writer.Write("EMPTY");
else
{
writer.Write("(");
for (int i = 0; i < MultiPolygon.NumGeometries; i++)
{
if (i > 0)
writer.Write(", ");
AppendPolygonText((Polygon)MultiPolygon.GetGeometryN(i), writer);
}
writer.Write(")");
}
}
/// <summary>
/// Converts a GeometryCollection to <GeometryCollection Text > format, then Appends it to the writer.
/// </summary>
/// <param name="geometryCollection">The GeometryCollection to process.</param>
/// <param name="writer">The output stream writer to Append to.</param>
private static void AppendGeometryCollectionText(GeometryCollection geometryCollection, StringWriter writer)
{
if (geometryCollection == null || geometryCollection.IsEmpty)
writer.Write("EMPTY");
else
{
writer.Write("(");
for (var i = 0; i < geometryCollection.NumGeometries; i++)
{
if (i > 0)
writer.Write(", ");
AppendGeometryTaggedText(geometryCollection[i], writer);
}
writer.Write(")");
}
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.Bugs;
using StructureMap.Testing.GenericWidgets;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class GenericsPluginGraphTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
}
#endregion
private void assertCanBeCast(Type pluginType, Type pluggedType)
{
Assert.IsTrue(GenericsPluginGraph.CanBeCast(pluginType, pluggedType));
}
private void assertCanNotBeCast(Type pluginType, Type pluggedType)
{
Assert.IsFalse(GenericsPluginGraph.CanBeCast(pluginType, pluggedType));
}
[Test]
public void BuildAnInstanceManagerFromTemplatedPluginFamily()
{
var pluginGraph = new PluginGraph();
PluginFamily family = pluginGraph.FindFamily(typeof (IGenericService<>));
family.DefaultInstanceKey = "Default";
family.AddPlugin(typeof (GenericService<>), "Default");
family.AddPlugin(typeof (SecondGenericService<>), "Second");
family.AddPlugin(typeof (ThirdGenericService<>), "Third");
var manager = new Container(pluginGraph);
var intService = (GenericService<int>) manager.GetInstance<IGenericService<int>>();
Assert.AreEqual(typeof (int), intService.GetT());
Assert.IsInstanceOfType(typeof (SecondGenericService<int>),
manager.GetInstance<IGenericService<int>>("Second"));
var stringService =
(GenericService<string>) manager.GetInstance<IGenericService<string>>();
Assert.AreEqual(typeof (string), stringService.GetT());
}
[Test]
public void BuildTemplatedFamilyWithOnlyOneTemplateParameter()
{
var pluginGraph = new PluginGraph();
PluginFamily family = pluginGraph.FindFamily(typeof (IGenericService<>));
family.AddPlugin(typeof (GenericService<>), "Default");
family.AddPlugin(typeof (SecondGenericService<>), "Second");
family.AddPlugin(typeof (ThirdGenericService<>), "Third");
PluginFamily templatedFamily1 = family.CreateTemplatedClone(new[] {typeof (int)});
PluginFamily templatedFamily = templatedFamily1;
Assert.IsNotNull(templatedFamily);
Assert.AreEqual(typeof (IGenericService<int>), templatedFamily.PluginType);
}
[Test]
public void can_iterate_through_families()
{
var graph = new GenericsPluginGraph();
graph.FindFamily(typeof (IGenericService<>)).AddType(typeof (GenericService<>));
graph.FindFamily(typeof (IService<>)).AddType(typeof (Service<>));
graph.Families.Count().ShouldEqual(2);
}
[Test]
public void Check_the_generic_plugin_family_expression()
{
var container =
new Container(
r =>
{
r.ForRequestedType(typeof (IGenericService<>)).TheDefaultIsConcreteType(
typeof (GenericService<>));
});
container.GetInstance<IGenericService<string>>().ShouldBeOfType(typeof (GenericService<string>));
}
[Test]
public void checking_can_be_cast()
{
assertCanBeCast(typeof (IOpenType<>), typeof (OpenType<>));
}
[Test]
public void DirectImplementationOfInterfaceCanBeCast()
{
assertCanBeCast(typeof (IGenericService<>), typeof (GenericService<>));
assertCanNotBeCast(typeof (IGenericService<>), typeof (SpecificService<>));
}
[Test]
public void DirectInheritanceOfAbstractClassCanBeCast()
{
assertCanBeCast(typeof (BaseSpecificService<>), typeof (SpecificService<>));
}
[Test]
public void GetTemplatedFamily()
{
var pluginGraph = new PluginGraph();
PluginFamily family = pluginGraph.FindFamily(typeof (IGenericService<>));
family.AddPlugin(typeof (GenericService<>), "Default");
family.AddPlugin(typeof (SecondGenericService<>), "Second");
family.AddPlugin(typeof (ThirdGenericService<>), "Third");
var genericsGraph = new GenericsPluginGraph();
genericsGraph.AddFamily(family);
PluginFamily templatedFamily = genericsGraph.CreateTemplatedFamily(typeof (IGenericService<int>),
new ProfileManager());
Assert.IsNotNull(templatedFamily);
Assert.AreEqual(typeof (IGenericService<int>), templatedFamily.PluginType);
}
[Test]
public void ImplementationOfInterfaceFromBaseType()
{
assertCanBeCast(typeof (ISomething<>), typeof (SpecificService<>));
}
[Test]
public void Import_from_adds_all_new_PluginFamily_from_source()
{
var sourceFamily = new PluginFamily(typeof (ISomething<>));
var sourceFamily2 = new PluginFamily(typeof (ISomething2<>));
var sourceFamily3 = new PluginFamily(typeof (ISomething3<>));
var source = new GenericsPluginGraph();
source.AddFamily(sourceFamily);
source.AddFamily(sourceFamily2);
source.AddFamily(sourceFamily3);
var destination = new GenericsPluginGraph();
destination.ImportFrom(source);
Assert.AreEqual(3, destination.FamilyCount);
Assert.AreNotSame(sourceFamily, destination.FindFamily(typeof (ISomething<>)));
}
[Test]
public void RecursiveImplementation()
{
assertCanBeCast(typeof (ISomething<>), typeof (SpecificService<>));
assertCanBeCast(typeof (ISomething<>), typeof (GrandChildSpecificService<>));
}
[Test]
public void RecursiveInheritance()
{
assertCanBeCast(typeof (BaseSpecificService<>), typeof (ChildSpecificService<>));
assertCanBeCast(typeof (BaseSpecificService<>), typeof (GrandChildSpecificService<>));
}
}
public interface IGenericService<T>
{
}
public class GenericService<T> : IGenericService<T>
{
public Type GetT()
{
return typeof (T);
}
}
public class SecondGenericService<T> : IGenericService<T>
{
}
public class ThirdGenericService<T> : IGenericService<T>
{
}
public interface ISomething<T>
{
}
public interface ISomething2<T>
{
}
public interface ISomething3<T>
{
}
public abstract class BaseSpecificService<T> : ISomething<T>
{
}
public class SpecificService<T> : BaseSpecificService<T>
{
}
public class ChildSpecificService<T> : SpecificService<T>
{
}
public class GrandChildSpecificService<T> : ChildSpecificService<T>
{
}
public interface IGenericService3<T, U, V>
{
}
public class GenericService3<T, U, V> : IGenericService3<T, U, V>
{
public Type GetT()
{
return typeof (T);
}
}
public class SecondGenericService3<T, U, V> : IGenericService3<T, U, V>
{
}
public class ThirdGenericService3<T, U, V> : IGenericService3<T, U, V>
{
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
/// <summary>
/// Loads the Configuration files into nIni
/// </summary>
public class ConfigurationLoader
{
/// <summary>
/// Various Config settings the region needs to start
/// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
/// StorageDLL, Storage Connection String, Estate connection String, Client Stack
/// Standalone settings.
/// </summary>
protected ConfigSettings m_configSettings;
/// <summary>
/// A source of Configuration data
/// </summary>
protected OpenSimConfigSource m_config;
/// <summary>
/// Grid Service Information. This refers to classes and addresses of the grid service
/// </summary>
protected NetworkServersInfo m_networkServersInfo;
/// <summary>
/// Console logger
/// </summary>
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public ConfigurationLoader()
{
}
/// <summary>
/// Loads the region configuration
/// </summary>
/// <param name="argvSource">Parameters passed into the process when started</param>
/// <param name="configSettings"></param>
/// <param name="networkInfo"></param>
/// <returns>A configuration that gets passed to modules</returns>
public OpenSimConfigSource LoadConfigSettings(
IConfigSource argvSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = argvSource.Configs["Startup"];
List<string> sources = new List<string>();
string masterFileName =
startupConfig.GetString("inimaster", String.Empty);
if (IsUri(masterFileName))
{
if (!sources.Contains(masterFileName))
sources.Add(masterFileName);
}
else
{
string masterFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), masterFileName));
if (masterFileName != String.Empty &&
File.Exists(masterFilePath) &&
(!sources.Contains(masterFilePath)))
sources.Add(masterFilePath);
}
string iniFileName =
startupConfig.GetString("inifile", "OpenSim.ini");
if (IsUri(iniFileName))
{
if (!sources.Contains(iniFileName))
sources.Add(iniFileName);
Application.iniFilePath = iniFileName;
}
else
{
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
if (!File.Exists(Application.iniFilePath))
{
iniFileName = "OpenSim.xml";
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
}
if (File.Exists(Application.iniFilePath))
{
if (!sources.Contains(Application.iniFilePath))
sources.Add(Application.iniFilePath);
}
}
string iniDirName =
startupConfig.GetString("inidirectory", "config");
string iniDirPath =
Path.Combine(Util.configDir(), iniDirName);
if (Directory.Exists(iniDirPath))
{
m_log.InfoFormat("Searching folder {0} for config ini files",
iniDirPath);
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
if (!sources.Contains(Path.GetFullPath(filePath)))
sources.Add(Path.GetFullPath(filePath));
}
}
}
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG] Reading configuration settings");
if (sources.Count == 0)
{
m_log.FatalFormat("[CONFIG] Could not load any configuration");
m_log.FatalFormat("[CONFIG] Did you copy the OpenSim.ini.example file to OpenSim.ini?");
Environment.Exit(1);
}
for (int i = 0 ; i < sources.Count ; i++)
{
if (ReadConfig(sources[i]))
iniFileExists = true;
AddIncludes(sources);
}
if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG] Could not load any configuration");
m_log.FatalFormat("[CONFIG] Configuration exists, but there was an error loading it!");
Environment.Exit(1);
}
// Make sure command line options take precedence
//
m_config.Source.Merge(argvSource);
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Adds the included files as ini configuration files
/// </summary>
/// <param name="sources">List of URL strings or filename strings</param>
private void AddIncludes(List<string> sources)
{
//loop over config sources
foreach (IConfig config in m_config.Source.Configs)
{
// Look for Include-* in the key name
string[] keys = config.GetKeys();
foreach (string k in keys)
{
if (k.StartsWith("Include-"))
{
// read the config file to be included.
string file = config.GetString(k);
if (IsUri(file))
{
if (!sources.Contains(file))
sources.Add(file);
}
else
{
string basepath = Path.GetFullPath(Util.configDir());
string path = Path.Combine(basepath, file);
string[] paths = Util.Glob(path);
foreach (string p in paths)
{
if (!sources.Contains(p))
sources.Add(p);
}
}
}
}
}
}
/// <summary>
/// Check if we can convert the string to a URI
/// </summary>
/// <param name="file">String uri to the remote resource</param>
/// <returns>true if we can convert the string to a Uri object</returns>
bool IsUri(string file)
{
Uri configUri;
return Uri.TryCreate(file, UriKind.Absolute,
out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniPath">Full path to the ini</param>
/// <returns></returns>
private bool ReadConfig(string iniPath)
{
bool success = false;
if (!IsUri(iniPath))
{
m_log.InfoFormat("[CONFIG] Reading configuration file {0}",
Path.GetFullPath(iniPath));
m_config.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
m_log.InfoFormat("[CONFIG] {0} is a http:// URI, fetching ...",
iniPath);
// The ini file path is a http URI
// Try to read it
//
try
{
XmlReader r = XmlReader.Create(iniPath);
XmlConfigSource cs = new XmlConfigSource(r);
m_config.Source.Merge(cs);
success = true;
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG] Exception reading config from URI {0}\n" + e.ToString(), iniPath);
Environment.Exit(1);
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns>A Configuration source containing the default configuration</returns>
private static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("gridmode", false);
config.Set("physics", "OpenDynamicsEngine");
config.Set("meshing", "Meshmerizer");
config.Set("physical_prim", true);
config.Set("see_into_this_sim_from_neighbor", true);
config.Set("serverside_object_permissions", false);
config.Set("storage_plugin", "OpenSim.Data.SQLite.dll");
config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3");
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["StandAlone"];
if (null == config)
config = defaultConfig.AddConfig("StandAlone");
config.Set("accounts_authenticate", true);
config.Set("welcome_message", "Welcome to OpenSimulator");
config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll");
config.Set("inventory_source", "");
config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll");
config.Set("user_source", "");
config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar));
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("default_location_x", 1000);
config.Set("default_location_y", 1000);
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
config.Set("remoting_listener_port", ConfigSettings.DefaultRegionRemotingPort);
config.Set("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString());
config.Set("grid_send_key", "null");
config.Set("grid_recv_key", "null");
config.Set("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
config.Set("user_send_key", "null");
config.Set("user_recv_key", "null");
config.Set("asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString());
config.Set("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString());
config.Set("secure_inventory_server", "true");
}
return defaultConfig;
}
/// <summary>
/// Read initial region settings from the ConfigSource
/// </summary>
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
m_configSettings.Standalone = !startupConfig.GetBoolean("gridmode", false);
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll")
{
m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll";
m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll.");
Thread.Sleep(3000);
}
m_configSettings.StorageConnectionString
= startupConfig.GetString("storage_connection_string");
m_configSettings.EstateConnectionString
= startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString);
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
IConfig standaloneConfig = m_config.Source.Configs["StandAlone"];
if (standaloneConfig != null)
{
m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message");
m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin");
m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source");
m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin");
m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source");
m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Input;
using Reflectable_v2;
using System.ServiceModel;
using System.IO;
using System.Threading;
using System.ComponentModel;
using System.ServiceModel.Channels;
using System.Diagnostics;
using System.Windows.Threading;
namespace Tablet
{
public partial class MainWindow : SurfaceWindow, ICallbackContract
{
private ITableService proxy;
private IFileDownloadService fileProxy;
private Round currentRound;
private User currentUser;
private int panopticonPercentage;
private Stage2UI.PanopticonState panopticonState;
private string videoFile;
private string panopticonFile;
private PanopticonInfo panopticonInfo;
private List<Press> presses;
private TimeSpan length;
private long toDownload;
private long downloaded;
public MainWindow()
{
InitializeComponent();
currentUser = new User(Properties.Settings.Default.UserId, null);
panopticonPercentage = 0;
panopticonState = Stage2UI.PanopticonState.PROCESSING;
toDownload = 0;
downloaded = 0;
Stage2Control.AnnotationMade += new Stage2UI.AnnotationMadeEventHandler(Stage2Control_AnnotationMade);
Stage2Control.ResearchQuestionSubmitted += new Stage2UI.ResearchQuestionSubmittedEventHandler(Stage2Control_ResearchQuestionSubmitted);
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Window w = App.Current.MainWindow;
#if DEBUG
w.WindowState = WindowState.Normal;
w.WindowStyle = WindowStyle.ThreeDBorderWindow;
#else
w.WindowStyle = WindowStyle.None;
w.WindowState = WindowState.Maximized;
w.ResizeMode = ResizeMode.NoResize;
w.Topmost = true;
#endif
}
private void Stage2Control_ResearchQuestionSubmitted(object sender, string question)
{
proxy.SetResearchQuestion(question);
}
private void Stage2Control_AnnotationMade(object sender, Tablet.PopupPlayer.AnnotationMadeEventArgs e)
{
proxy.MakeAnnotation(new Annotation(e.User, e.Comment, e.Press));
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
}
private void HideAll()
{
RegisterControl.Visibility = Visibility.Hidden;
Stage1Control.Visibility = Visibility.Hidden;
Stage2Control.Visibility = Visibility.Hidden;
}
private void Register_RegisterClicked(object sender, RoutedEventArgs e)
{
NetTcpBinding serviceBinding = new NetTcpBinding(SecurityMode.None);
serviceBinding.ReceiveTimeout = TimeSpan.MaxValue;
serviceBinding.SendTimeout = TimeSpan.MaxValue;
proxy = DuplexChannelFactory<ITableService>.CreateChannel(this, serviceBinding, new EndpointAddress(Properties.Settings.Default.ServerAddress));
TcpTransportBindingElement transport = new TcpTransportBindingElement();
transport.MaxReceivedMessageSize = long.MaxValue;
transport.MaxBufferSize = int.MaxValue;
transport.MaxBufferPoolSize = long.MaxValue;
transport.TransferMode = TransferMode.Streamed;
BinaryMessageEncodingBindingElement encoder = new BinaryMessageEncodingBindingElement();
CustomBinding fileBinding = new CustomBinding(encoder, transport);
fileBinding.ReceiveTimeout = TimeSpan.MaxValue;
fileBinding.SendTimeout = TimeSpan.MaxValue;
fileProxy = ChannelFactory<IFileDownloadService>.CreateChannel(fileBinding, new EndpointAddress(Properties.Settings.Default.FileServerAddress));
try
{
DateTime serverTime = proxy.GetTime();
OffsetDateTime.Difference = serverTime - DateTime.UtcNow;
proxy.Register(currentUser);
}
catch (FaultException ex)
{
MessageBox.Show(ex.Message);
}
catch (EndpointNotFoundException)
{
MessageBox.Show("Could not connect to the table");
}
finally
{
Register r = (Register)sender;
r.RegisterButton.Visibility = Visibility.Visible;
r.Spinner.Visibility = Visibility.Collapsed;
}
}
private void StageControl_RoundComplete(object sender, RoutedEventArgs e)
{
proxy.RoundComplete(currentRound);
}
private void Stage1Control_ButtonPressed(object sender, RoutedEventArgs e)
{
proxy.ButtonPress(currentUser);
}
private void StageControl_StartRequested(object sender, RoutedEventArgs e)
{
proxy.RequestStartRound();
}
private void DownloadData()
{
panopticonState = Stage2UI.PanopticonState.DOWNLOADING;
panopticonPercentage = 0;
UpdatePanopticonState();
UpdatePanopticonPercentage();
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((s, e) =>
{
videoFile = proxy.GetVideoFilename();
panopticonFile = proxy.GetPanopticonFilename();
panopticonInfo = proxy.GetPanopticonInfo();
presses = proxy.GetPresses();
length = proxy.GetStudyLength();
toDownload = proxy.GetVideoSize() + proxy.GetPanopticonSize();
downloaded = 0;
Thread t1 = new Thread(() =>
{
if (!File.Exists(videoFile))
{
Stream videoStream = fileProxy.DownloadVideo();
DownloadFile(videoStream, videoFile);
}
});
Thread t2 = new Thread(() =>
{
if (!File.Exists(panopticonFile))
{
Stream panopticonStream = fileProxy.DownloadPanopticonVideo();
DownloadFile(panopticonStream, panopticonFile);
}
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
panopticonState = Stage2UI.PanopticonState.READY;
UpdatePanopticonState();
});
worker.RunWorkerAsync();
}
private void DownloadFile(Stream source, string file)
{
byte[] buffer = new byte[4096];
int position = 0;
FileStream fStream = File.OpenWrite(FileLocationUtility.GetPathInVideoFolderLocation(file));
do
{
position = source.Read(buffer, 0, buffer.Length);
fStream.Write(buffer, 0, position);
downloaded += buffer.Length;
double percentage = (double)downloaded / (double)toDownload;
panopticonPercentage = (int)(percentage * 100.0);
if (panopticonPercentage > 100)
{
panopticonPercentage = 100;
}
UpdatePanopticonPercentage();
}
while (position != 0);
fStream.Close();
}
private void UpdatePanopticonState()
{
Dispatcher.BeginInvoke(new Action(() =>
{
Stage2Control.PanopticonVideoState = panopticonState;
if (panopticonState == Stage2UI.PanopticonState.READY)
{
Stage2Control.PanopticonVideoFile = FileLocationUtility.GetPathInVideoFolderLocation(panopticonFile);
Stage2Control.VideoFile = FileLocationUtility.GetPathInVideoFolderLocation(videoFile);
Stage2Control.Presses = presses;
Stage2Control.Length = length;
Stage2Control.PanopticonVideoInfo = panopticonInfo;
}
}));
}
private void UpdatePanopticonPercentage()
{
Dispatcher.BeginInvoke(new Action(() =>
{
Stage2Control.PanopticonPercentage = panopticonPercentage;
}));
}
#region WebService
public void SetRound(Round r)
{
this.currentRound = r;
HideAll();
switch (r.Id)
{
case Round.RoundId.PAPER_DIVERGE:
case Round.RoundId.PAPER_CONVERGE:
case Round.RoundId.PAPER_TRANSCEND:
Stage1Control.Visibility = Visibility.Visible;
Stage1Control.Round = r;
break;
case Round.RoundId.VIDEO_BROWSE:
case Round.RoundId.RESEARCH_QUESTION:
case Round.RoundId.VIDEO_DIVERGE:
case Round.RoundId.VIDEO_CONVERGE:
Stage2Control.Visibility = Visibility.Visible;
Stage2Control.PanopticonVideoState = panopticonState;
Stage2Control.PanopticonPercentage = panopticonPercentage;
Stage2Control.Round = r;
if (panopticonState == Stage2UI.PanopticonState.PROCESSING)
{
Thread t = new Thread(() =>
{
if (proxy.IsPanopticonProcessingComplete())
{
DownloadData();
}
});
t.Start();
}
break;
case Round.RoundId.COMPLETE:
App.Restart();
break;
}
}
public void StartRound(DateTime startTime)
{
switch (currentRound.Id)
{
case Round.RoundId.PAPER_DIVERGE:
case Round.RoundId.PAPER_CONVERGE:
case Round.RoundId.PAPER_TRANSCEND:
Stage1Control.Start(startTime);
break;
case Round.RoundId.VIDEO_BROWSE:
case Round.RoundId.VIDEO_DIVERGE:
case Round.RoundId.VIDEO_CONVERGE:
Stage2Control.Start(startTime);
break;
}
}
public void PanopticonCompleted()
{
if (panopticonState == Stage2UI.PanopticonState.PROCESSING)
{
DownloadData();
}
}
public void PanopticonPercentageChanged(int percentage)
{
this.panopticonPercentage = percentage;
UpdatePanopticonPercentage();
}
public void SetUserColor(Color c)
{
currentUser.Color = c;
Stage1Control.UserColor = c;
Stage2Control.UserColor = c;
}
#endregion
}
}
| |
//
// Mono.Cairo.Cairo.cs
//
// Author: Duncan Mak (duncan@ximian.com)
//
// (C) Ximian, Inc. 2003
//
// This is a simplistic binding of the Cairo API to C#. All functions
// in cairo.h are transcribed into their C# equivelants and all
// enumerations are also listed here.
//
// Copyright (C) 2004 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.Drawing;
using System.Runtime.InteropServices;
namespace Cairo {
public class CairoAPI
{
internal const string CairoImp = "cairo";
//
// Manipulating state objects
//
[DllImport (CairoImp)]
public static extern IntPtr cairo_create ();
[DllImport (CairoImp)]
public static extern void cairo_reference (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_destroy (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_save (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_restore (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_copy (out IntPtr dest, IntPtr src);
//
// Modify state
//
[DllImport (CairoImp)]
public static extern void cairo_set_target_surface (IntPtr cr, IntPtr surface);
[DllImport (CairoImp)]
public static extern void cairo_set_target_image (
IntPtr cr, string data, Cairo.Format format, int width, int height, int stride);
[DllImport (CairoImp)]
public static extern void cairo_set_target_drawable (
IntPtr ct, IntPtr display, IntPtr drawable);
[DllImport (CairoImp)]
public static extern void cairo_set_operator (IntPtr cr, Cairo.Operator op);
[DllImport (CairoImp)]
public static extern void cairo_set_rgb_color (IntPtr cr, double red, double green, double blue);
[DllImport (CairoImp)]
public static extern void cairo_set_alpha (IntPtr cr, double alpha);
[DllImport (CairoImp)]
public static extern void cairo_set_pattern (IntPtr cr, IntPtr pattern);
[DllImport (CairoImp)]
public static extern void cairo_set_tolerance (IntPtr cr, double tolerance);
[DllImport (CairoImp)]
public static extern void cairo_set_fill_rule (IntPtr cr, Cairo.FillRule fill_rule);
[DllImport (CairoImp)]
public static extern void cairo_set_line_width (IntPtr cr, double width);
[DllImport (CairoImp)]
public static extern void cairo_set_line_cap (IntPtr cr, Cairo.LineCap line_cap);
[DllImport (CairoImp)]
public static extern void cairo_set_line_join (IntPtr cr, Cairo.LineJoin line_join);
[DllImport (CairoImp)]
public static extern void cairo_set_dash (IntPtr cr, double [] dashes, int ndash, double offset);
[DllImport (CairoImp)]
public static extern void cairo_set_miter_limit (IntPtr cr, double limit);
[DllImport (CairoImp)]
public static extern void cairo_translate (IntPtr cr, double tx, double ty);
[DllImport (CairoImp)]
public static extern void cairo_scale (IntPtr cr, double sx, double sy);
[DllImport (CairoImp)]
public static extern void cairo_rotate (IntPtr cr, double angle);
[DllImport (CairoImp)]
public static extern void cairo_concat_matrix (IntPtr cr, IntPtr matrix);
[DllImport (CairoImp)]
public static extern void cairo_set_matrix (IntPtr cr, IntPtr matrix);
[DllImport (CairoImp)]
public static extern void cairo_default_matrix (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_identity_matrix (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_transform_point (IntPtr cr, ref double x, ref double y);
[DllImport (CairoImp)]
public static extern void cairo_transform_distance (IntPtr cr, ref double dx, ref double dy);
[DllImport (CairoImp)]
public static extern void cairo_inverse_transform_point (IntPtr cr, ref double x, ref double y);
[DllImport (CairoImp)]
public static extern void cairo_inverse_transform_distance (IntPtr cr, ref double dx, ref double dy);
//
// Path creation
//
[DllImport (CairoImp)]
public static extern void cairo_new_path (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_move_to (IntPtr cr, double x, double y);
[DllImport (CairoImp)]
public static extern void cairo_line_to (IntPtr cr, double x, double y);
[DllImport (CairoImp)]
public static extern void cairo_curve_to (
IntPtr cr, double x1, double y1, double x2, double y2, double x3, double y3);
[DllImport (CairoImp)]
public static extern void cairo_arc (
IntPtr cr, double xc, double yc, double radius, double angel1, double angel2);
[DllImport (CairoImp)]
public static extern void cairo_arc_negative (
IntPtr cr, double xc, double yc, double radius, double angel1, double angel2);
[DllImport (CairoImp)]
public static extern void cairo_rel_move_to (IntPtr cr, double dx, double dy);
[DllImport (CairoImp)]
public static extern void cairo_rel_line_to (IntPtr cr, double dx, double dy);
[DllImport (CairoImp)]
public static extern void cairo_rel_curve_to (
IntPtr cr, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3);
[DllImport (CairoImp)]
public static extern void cairo_rectangle (IntPtr cr, double x, double y, double width, double height);
[DllImport (CairoImp)]
public static extern void cairo_close_path (IntPtr cr);
//
// Painting
//
[DllImport (CairoImp)]
public static extern void cairo_stroke (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_fill (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_clip (IntPtr cr);
//
// Font / Text
//
[DllImport (CairoImp)]
public static extern void cairo_select_font (IntPtr cr, string key, FontSlant slant, FontWeight weight);
[DllImport (CairoImp)]
public static extern void cairo_scale_font (IntPtr cr, double scale);
[DllImport (CairoImp)]
public static extern void cairo_transform_font (IntPtr cr, IntPtr matrix);
[DllImport (CairoImp)]
public static extern void cairo_show_text (IntPtr cr, string utf8);
[DllImport (CairoImp)]
public static extern void cairo_font_set_transform (IntPtr font, IntPtr matrix);
[DllImport (CairoImp)]
public static extern void cairo_font_current_transform (IntPtr font, IntPtr matrix);
[DllImport (CairoImp)]
public static extern void cairo_font_reference (IntPtr font);
[DllImport (CairoImp)]
public static extern void cairo_font_destroy (IntPtr font);
[DllImport (CairoImp)]
public static extern void cairo_current_font_extents (IntPtr source, ref Extents extents);
[DllImport (CairoImp)]
public static extern void cairo_show_glyphs (IntPtr ct, IntPtr glyphs, int num_glyphs);
[DllImport (CairoImp)]
public static extern void cairo_text_path (IntPtr ct, string utf8);
[DllImport (CairoImp)]
public static extern void cairo_glyph_path (IntPtr ct, IntPtr glyphs, int num_glyphs);
// Cairo's font manipulation platform-specific Unix Fontconfig/Freetype interface
[DllImport (CairoImp)]
public static extern IntPtr cairo_ft_font_create (IntPtr ft_library, IntPtr ft_pattern);
//
// Image
//
[DllImport (CairoImp)]
public static extern void cairo_show_surface (IntPtr cr, IntPtr surface, int width, int height);
//
// query
//
[DllImport (CairoImp)]
public static extern Cairo.Operator cairo_current_operator (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_current_rgb_color (
IntPtr cr, out double red, out double green, out double blue);
[DllImport (CairoImp)]
public static extern double cairo_current_alpha (IntPtr cr);
[DllImport (CairoImp)]
public static extern bool cairo_in_stroke (IntPtr cr, double x, double y);
[DllImport (CairoImp)]
public static extern bool cairo_in_fill (IntPtr cr, double x, double y);
[DllImport (CairoImp)]
public static extern double cairo_current_tolerance (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_current_point (
IntPtr cr, out double x, out double y);
[DllImport (CairoImp)]
public static extern Cairo.FillRule cairo_current_fill_rule (IntPtr cr);
[DllImport (CairoImp)]
public static extern double cairo_current_line_width (IntPtr cr);
[DllImport (CairoImp)]
public static extern LineCap cairo_current_line_cap (IntPtr cr);
[DllImport (CairoImp)]
public static extern LineJoin cairo_current_line_join (IntPtr cr);
[DllImport (CairoImp)]
public static extern double cairo_current_miter_limit (IntPtr cr);
[DllImport (CairoImp)]
public static extern void cairo_current_matrix (IntPtr cr, IntPtr matrix);
[DllImport (CairoImp)]
public static extern IntPtr cairo_current_target_surface (IntPtr cr);
//
// Error status queries
//
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_status (IntPtr cr);
[DllImport (CairoImp, EntryPoint="cairo_status_string")]
static extern IntPtr _cairo_status_string (IntPtr cr);
public static string cairo_status_string (IntPtr cr)
{
return Marshal.PtrToStringAnsi (_cairo_status_string (cr));
}
//
// Surface Manipulation
//
[DllImport (CairoImp)]
public static extern IntPtr cairo_surface_create_for_image (
string data, Cairo.Format format, int width, int height, int stride);
[DllImport (CairoImp)]
public static extern IntPtr cairo_image_surface_create (Cairo.Format format, int width,
int height);
[DllImport (CairoImp)]
public static extern IntPtr cairo_surface_create_similar (
IntPtr surface, Cairo.Format format, int width, int height);
[DllImport (CairoImp)]
public static extern IntPtr cairo_surface_create_similar_solid (
IntPtr surface, Cairo.Format format,
int width, int height, double red, double green, double blue, double alpha);
[DllImport (CairoImp)]
public static extern void cairo_surface_reference (IntPtr surface);
[DllImport (CairoImp)]
public static extern void cairo_surface_destroy (IntPtr surface);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_surface_set_repeat (
IntPtr surface, int repeat);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_surface_set_matrix (
IntPtr surface, IntPtr matrix);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_surface_get_matrix (
IntPtr surface, out IntPtr matrix);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_surface_set_filter (
IntPtr surface, Cairo.Filter filter);
//
// Matrix
//
[DllImport (CairoImp)]
public static extern IntPtr cairo_matrix_create ();
[DllImport (CairoImp)]
public static extern void cairo_matrix_destroy (IntPtr matrix);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_copy (
IntPtr matrix, out IntPtr other);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_set_identity (IntPtr matrix);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_set_affine (
IntPtr matrix,
double a, double b, double c, double d, double tx, double ty);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_get_affine (
IntPtr matrix,
out double a, out double b, out double c,
out double d, out double tx, out double ty);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_translate (
IntPtr matrix, double tx, double ty);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_scale (
IntPtr matrix, double sx, double sy);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_rotate (
IntPtr matrix, double radians);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_invert (IntPtr matrix);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_multiply (
out IntPtr result, IntPtr a, IntPtr b);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_transform_distance (
IntPtr matrix, ref double dx, ref double dy);
[DllImport (CairoImp)]
public static extern Cairo.Status cairo_matrix_transform_point (
IntPtr matrix, ref double x, ref double y);
[DllImport (CairoImp)]
public static extern void cairo_set_font (IntPtr ct, IntPtr font);
[DllImport (CairoImp)]
public static extern IntPtr cairo_current_font (IntPtr ct);
//
// Pattern functions
//
[DllImport (CairoImp)]
public static extern IntPtr cairo_pattern_create_for_surface (IntPtr surface);
[DllImport (CairoImp)]
public static extern IntPtr cairo_pattern_create_linear (double x0, double y0,
double x1, double y1);
[DllImport (CairoImp)]
public static extern IntPtr cairo_pattern_create_radial (double cx0, double cy0,
double radius0, double cx1, double cy1, double radius1);
[DllImport (CairoImp)]
public static extern void cairo_pattern_reference (IntPtr pattern);
[DllImport (CairoImp)]
public static extern void cairo_pattern_destroy (IntPtr pattern);
[DllImport (CairoImp)]
public static extern Status cairo_pattern_add_color_stop (IntPtr pattern,
double offset, double red, double green, double blue, double alpha);
[DllImport (CairoImp)]
public static extern Status cairo_pattern_set_matrix (IntPtr pattern, IntPtr matrix);
[DllImport (CairoImp)]
public static extern Status cairo_pattern_get_matrix (IntPtr pattern, out IntPtr matrix);
[DllImport (CairoImp)]
public static extern Status cairo_pattern_set_extend (IntPtr pattern, Extend extend);
[DllImport (CairoImp)]
public static extern Extend cairo_pattern_get_extend (IntPtr pattern);
[DllImport (CairoImp)]
public static extern Status cairo_pattern_set_filter (IntPtr pattern, Filter filter);
[DllImport (CairoImp)]
public static extern Filter cairo_pattern_get_filter (IntPtr pattern);
}
//
// Freetype interface need it by cairo_ft interface calls
//
public class FreeType
{
internal const string FreeTypeImp = "freetype";
[DllImport (FreeTypeImp)]
public static extern int FT_Init_FreeType (out IntPtr library);
[DllImport (FreeTypeImp)]
public static extern int FT_Set_Char_Size (IntPtr face, long width, long height, uint horz_res, uint vert_res);
}
//
// Fontconfig interface need it by cairo_ft interface calls
//
public class FontConfig
{
internal const string FontConfigImp = "fontconfig";
public const string FC_FAMILY = "family";
public const string FC_STYLE = "style";
public const string FC_SLANT = "slant";
public const string FC_WEIGHT = "weight";
[DllImport (FontConfigImp)]
public static extern bool FcPatternAddString (IntPtr pattern, string obj, string value);
[DllImport (FontConfigImp)]
public static extern bool FcPatternAddInteger (IntPtr pattern, string obj, int value);
[DllImport (FontConfigImp)]
public static extern IntPtr FcPatternCreate ();
[DllImport (FontConfigImp)]
public static extern bool FcPatternDestroy (IntPtr pattern);
}
//
// Enumerations
//
public enum Format {
ARGB32 = 0,
RGB24 = 1,
A8 = 2,
A1 = 4
}
public enum Operator {
Clear = 0,
Src = 1,
Dst = 2,
Over = 3,
OverReverse = 4,
In = 5,
InReverse = 6,
Out = 7,
OutReverse = 8,
Atop = 9,
AtopReverse = 10,
Xor = 11,
Add = 12,
Saturate = 13,
DisjointClear = 16,
DisjointSrc = 17,
DisjointDst = 18,
DisjointOver = 19,
DisjointOverReverse = 20,
DisjointIn = 21,
DisjointInReverse = 22,
DisjointOut = 23,
DisjointOutReverse = 24,
DisjointAtop = 25,
DisjointAtopReverse = 26,
DisjointXor = 27,
ConjointClear = 32,
ConjointSrc = 33,
ConjointDst = 34,
ConjointOver = 35,
ConjointOverReverse = 36,
ConjointIn = 37,
ConjointInReverse = 38,
ConjointOut = 39,
ConjointOutReverse = 40,
ConjointAtop = 41,
ConjointAtopReverse = 42,
ConjointXor = 43
}
public enum FillRule {
Winding,
EvenOdd
}
public enum LineCap {
Butt, Round, Square
}
public enum LineJoin {
Miter, Round, Bevel
}
public enum Status {
Success = 0,
NoMemory,
InvalidRestore,
InvalidPopGroup,
NoCurrentPoint,
InvalidMatrix
}
public enum Filter {
Fast,
Good,
Best,
Nearest,
Bilinear,
Gaussian,
}
public enum FontSlant {
Normal = 0,
Italic = 1,
Oblique = 2
}
public enum FontWeight {
Normal = 0,
Bold = 1,
}
public enum Extend {
None,
Repetat,
Reflect,
}
[StructLayout(LayoutKind.Sequential)]
public struct Extents
{
public double x_bearing;
public double y_bearing;
public double width;
public double height;
public double x_advance;
public double y_advance;
}
[StructLayout(LayoutKind.Sequential)]
public struct Glyph
{
public long index;
public double x;
public double y;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RecoveryPointsOperations operations.
/// </summary>
internal partial class RecoveryPointsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IRecoveryPointsOperations
{
/// <summary>
/// Initializes a new instance of the RecoveryPointsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RecoveryPointsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides the information of the backed up data identified using
/// RecoveryPointID. This is an asynchronous operation. To know the status of
/// the operation, call the GetProtectedItemOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose backup data needs to be fetched.
/// </param>
/// <param name='recoveryPointId'>
/// RecoveryPointID represents the backed up data to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RecoveryPointResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName");
}
if (recoveryPointId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("recoveryPointId", recoveryPointId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
_url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<RecoveryPointResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RecoveryPointResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the backup copies for the backed up item.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item whose backup copies are to be fetched.
/// </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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<RecoveryPointResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, Microsoft.Rest.Azure.OData.ODataQuery<BMSRPQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<BMSRPQueryObject>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RecoveryPointResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the backup copies for the backed up item.
/// </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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<RecoveryPointResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<RecoveryPointResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RecoveryPointResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using umbraco.editorControls.tinyMCE3;
using umbraco.interfaces;
namespace Umbraco.Tests.Services
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture, RequiresSTA]
public class ThreadSafetyServiceTest : BaseDatabaseFactoryTest
{
private PerThreadPetaPocoUnitOfWorkProvider _uowProvider;
private PerThreadDatabaseFactory _dbFactory;
[SetUp]
public override void Initialize()
{
base.Initialize();
//we need to use our own custom IDatabaseFactory for the DatabaseContext because we MUST ensure that
//a Database instance is created per thread, whereas the default implementation which will work in an HttpContext
//threading environment, or a single apartment threading environment will not work for this test because
//it is multi-threaded.
_dbFactory = new PerThreadDatabaseFactory(Logger);
//overwrite the local object
ApplicationContext.DatabaseContext = new DatabaseContext(_dbFactory, Logger, new SqlCeSyntaxProvider(), "System.Data.SqlServerCe.4.0");
//disable cache
var cacheHelper = CacheHelper.CreateDisabledCacheHelper();
//here we are going to override the ServiceContext because normally with our test cases we use a
//global Database object but this is NOT how it should work in the web world or in any multi threaded scenario.
//we need a new Database object for each thread.
var repositoryFactory = new RepositoryFactory(cacheHelper, Logger, SqlSyntax, SettingsForTests.GenerateMockSettings());
_uowProvider = new PerThreadPetaPocoUnitOfWorkProvider(_dbFactory);
ApplicationContext.Services = new ServiceContext(
repositoryFactory,
_uowProvider,
new FileUnitOfWorkProvider(),
new PublishingStrategy(),
cacheHelper,
Logger);
CreateTestData();
}
[TearDown]
public override void TearDown()
{
_error = null;
//dispose!
_dbFactory.Dispose();
_uowProvider.Dispose();
base.TearDown();
}
/// <summary>
/// Used to track exceptions during multi-threaded tests, volatile so that it is not locked in CPU registers.
/// </summary>
private volatile Exception _error = null;
private const int MaxThreadCount = 20;
[Test]
public void Ensure_All_Threads_Execute_Successfully_Content_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var contentService = (ContentService)ServiceContext.ContentService;
var threads = new List<Thread>();
Debug.WriteLine("Starting test...");
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
{
try
{
Debug.WriteLine("Created content on thread: " + Thread.CurrentThread.ManagedThreadId);
//create 2 content items
string name1 = "test" + Guid.NewGuid();
var content1 = contentService.CreateContent(name1, -1, "umbTextpage", 0);
Debug.WriteLine("Saving content1 on thread: " + Thread.CurrentThread.ManagedThreadId);
contentService.Save(content1);
Thread.Sleep(100); //quick pause for maximum overlap!
string name2 = "test" + Guid.NewGuid();
var content2 = contentService.CreateContent(name2, -1, "umbTextpage", 0);
Debug.WriteLine("Saving content2 on thread: " + Thread.CurrentThread.ManagedThreadId);
contentService.Save(content2);
}
catch(Exception e)
{
_error = e;
}
});
threads.Add(t);
}
//start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
if (_error == null)
{
//now look up all items, there should be 40!
var items = contentService.GetRootContent();
Assert.AreEqual(40, items.Count());
}
else
{
throw new Exception("Error!", _error);
}
}
[Test]
public void Ensure_All_Threads_Execute_Successfully_Media_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var mediaService = (MediaService)ServiceContext.MediaService;
var threads = new List<Thread>();
Debug.WriteLine("Starting test...");
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
{
try
{
Debug.WriteLine("Created content on thread: " + Thread.CurrentThread.ManagedThreadId);
//create 2 content items
string name1 = "test" + Guid.NewGuid();
var folder1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("Saving folder1 on thread: " + Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder1, 0);
Thread.Sleep(100); //quick pause for maximum overlap!
string name = "test" + Guid.NewGuid();
var folder2 = mediaService.CreateMedia(name, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("Saving folder2 on thread: " + Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder2, 0);
}
catch (Exception e)
{
_error = e;
}
});
threads.Add(t);
}
//start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
if (_error == null)
{
//now look up all items, there should be 40!
var items = mediaService.GetRootMedia();
Assert.AreEqual(40, items.Count());
}
else
{
Assert.Fail("ERROR! " + _error);
}
}
public void CreateTestData()
{
//Create and Save ContentType "umbTextpage" -> 1045
ContentType contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage", "Textpage");
contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522");
ServiceContext.ContentTypeService.Save(contentType);
}
/// <summary>
/// Creates a Database object per thread, this mimics the web context which is per HttpContext and is required for the multi-threaded test
/// </summary>
internal class PerThreadDatabaseFactory : DisposableObject, IDatabaseFactory
{
private readonly ILogger _logger;
public PerThreadDatabaseFactory(ILogger logger)
{
_logger = logger;
}
private readonly ConcurrentDictionary<int, UmbracoDatabase> _databases = new ConcurrentDictionary<int, UmbracoDatabase>();
public UmbracoDatabase CreateDatabase()
{
var db = _databases.GetOrAdd(
Thread.CurrentThread.ManagedThreadId,
i => new UmbracoDatabase(Umbraco.Core.Configuration.GlobalSettings.UmbracoConnectionName, _logger));
return db;
}
protected override void DisposeResources()
{
//dispose the databases
_databases.ForEach(x => x.Value.Dispose());
}
}
/// <summary>
/// Creates a UOW with a Database object per thread
/// </summary>
internal class PerThreadPetaPocoUnitOfWorkProvider : DisposableObject, IDatabaseUnitOfWorkProvider
{
private readonly PerThreadDatabaseFactory _dbFactory;
public PerThreadPetaPocoUnitOfWorkProvider(PerThreadDatabaseFactory dbFactory)
{
_dbFactory = dbFactory;
}
public IDatabaseUnitOfWork GetUnitOfWork()
{
//Create or get a database instance for this thread.
var db = _dbFactory.CreateDatabase();
return new PetaPocoUnitOfWork(db);
}
protected override void DisposeResources()
{
//dispose the databases
_dbFactory.Dispose();
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Management.Automation.Interpreter
{
/// <summary>
/// Contains compiler state corresponding to a LabelTarget
/// See also LabelScopeInfo.
/// </summary>
internal sealed class LabelInfo
{
// The tree node representing this label
private readonly LabelTarget _node;
// The BranchLabel label, will be mutated if Node is redefined
private BranchLabel _label;
// The blocks where this label is defined. If it has more than one item,
// the blocks can't be jumped to except from a child block
// If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored
// as a HashSet<LabelScopeInfo>
private object _definitions;
// Blocks that jump to this block
private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>();
// True if at least one jump is across blocks
// If we have any jump across blocks to this label, then the
// LabelTarget can only be defined in one place
private bool _acrossBlockJump;
internal LabelInfo(LabelTarget node)
{
_node = node;
}
internal BranchLabel GetLabel(LightCompiler compiler)
{
EnsureLabel(compiler);
return _label;
}
internal void Reference(LabelScopeInfo block)
{
_references.Add(block);
if (HasDefinitions)
{
ValidateJump(block);
}
}
internal void Define(LabelScopeInfo block)
{
// Prevent the label from being shadowed, which enforces cleaner
// trees. Also we depend on this for simplicity (keeping only one
// active IL Label per LabelInfo)
for (LabelScopeInfo j = block; j != null; j = j.Parent)
{
if (j.ContainsTarget(_node))
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name));
}
}
AddDefinition(block);
block.AddLabelInfo(_node, this);
// Once defined, validate all jumps
if (HasDefinitions && !HasMultipleDefinitions)
{
foreach (var r in _references)
{
ValidateJump(r);
}
}
else
{
// Was just redefined, if we had any across block jumps, they're
// now invalid
if (_acrossBlockJump)
{
throw new InvalidOperationException("Ambiguous jump");
}
// For local jumps, we need a new IL label
// This is okay because:
// 1. no across block jumps have been made or will be made
// 2. we don't allow the label to be shadowed
_label = null;
}
}
private void ValidateJump(LabelScopeInfo reference)
{
// look for a simple jump out
for (LabelScopeInfo j = reference; j != null; j = j.Parent)
{
if (DefinedIn(j))
{
// found it, jump is valid!
return;
}
if (j.Kind == LabelScopeKind.Filter)
{
break;
}
}
_acrossBlockJump = true;
if (HasMultipleDefinitions)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name));
}
// We didn't find an outward jump. Look for a jump across blocks
LabelScopeInfo def = FirstDefinition();
LabelScopeInfo common = CommonNode(def, reference, static b => b.Parent);
// Validate that we aren't jumping across a finally
for (LabelScopeInfo j = reference; j != common; j = j.Parent)
{
if (j.Kind == LabelScopeKind.Filter)
{
throw new InvalidOperationException("Control cannot leave filter test");
}
}
// Validate that we aren't jumping into a catch or an expression
for (LabelScopeInfo j = def; j != common; j = j.Parent)
{
if (!j.CanJumpInto)
{
if (j.Kind == LabelScopeKind.Expression)
{
throw new InvalidOperationException("Control cannot enter an expression");
}
else
{
throw new InvalidOperationException("Control cannot enter try");
}
}
}
}
internal void ValidateFinish()
{
// Make sure that if this label was jumped to, it is also defined
if (_references.Count > 0 && !HasDefinitions)
{
throw new InvalidOperationException("label target undefined");
}
}
private void EnsureLabel(LightCompiler compiler)
{
if (_label == null)
{
_label = compiler.Instructions.MakeLabel();
}
}
private bool DefinedIn(LabelScopeInfo scope)
{
if (_definitions == scope)
{
return true;
}
HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>;
if (definitions != null)
{
return definitions.Contains(scope);
}
return false;
}
private bool HasDefinitions
{
get
{
return _definitions != null;
}
}
private LabelScopeInfo FirstDefinition()
{
LabelScopeInfo scope = _definitions as LabelScopeInfo;
if (scope != null)
{
return scope;
}
return ((HashSet<LabelScopeInfo>)_definitions).First();
}
private void AddDefinition(LabelScopeInfo scope)
{
if (_definitions == null)
{
_definitions = scope;
}
else
{
HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>;
if (set == null)
{
_definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions };
}
set.Add(scope);
}
}
private bool HasMultipleDefinitions
{
get
{
return _definitions is HashSet<LabelScopeInfo>;
}
}
internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class
{
var cmp = EqualityComparer<T>.Default;
if (cmp.Equals(first, second))
{
return first;
}
var set = new HashSet<T>(cmp);
for (T t = first; t != null; t = parent(t))
{
set.Add(t);
}
for (T t = second; t != null; t = parent(t))
{
if (set.Contains(t))
{
return t;
}
}
return null;
}
}
internal enum LabelScopeKind
{
// any "statement like" node that can be jumped into
Statement,
// these correspond to the node of the same name
Block,
Switch,
Lambda,
Try,
// these correspond to the part of the try block we're in
Catch,
Finally,
Filter,
// the catch-all value for any other expression type
// (means we can't jump into it)
Expression,
}
//
// Tracks scoping information for LabelTargets. Logically corresponds to a
// "label scope". Even though we have arbitrary goto support, we still need
// to track what kinds of nodes that gotos are jumping through, both to
// emit property IL ("leave" out of a try block), and for validation, and
// to allow labels to be duplicated in the tree, as long as the jumps are
// considered "up only" jumps.
//
// We create one of these for every Expression that can be jumped into, as
// well as creating them for the first expression we can't jump into. The
// "Kind" property indicates what kind of scope this is.
//
internal sealed class LabelScopeInfo
{
private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block
internal readonly LabelScopeKind Kind;
internal readonly LabelScopeInfo Parent;
internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind)
{
Parent = parent;
Kind = kind;
}
/// <summary>
/// Returns true if we can jump into this node.
/// </summary>
internal bool CanJumpInto
{
get
{
switch (Kind)
{
case LabelScopeKind.Block:
case LabelScopeKind.Statement:
case LabelScopeKind.Switch:
case LabelScopeKind.Lambda:
return true;
}
return false;
}
}
internal bool ContainsTarget(LabelTarget target)
{
if (_labels == null)
{
return false;
}
return _labels.ContainsKey(target);
}
internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info)
{
if (_labels == null)
{
info = null;
return false;
}
return _labels.TryGetValue(target, out info);
}
internal void AddLabelInfo(LabelTarget target, LabelInfo info)
{
Debug.Assert(CanJumpInto);
if (_labels == null)
{
_labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
}
_labels[target] = info;
}
}
}
| |
// 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.Threading;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>Provides an <see langword='abstract '/>base class to
/// create new debugging and tracing switches.</para>
/// </devdoc>
public abstract class Switch
{
private readonly string _description;
private readonly string _displayName;
private int _switchSetting = 0;
private volatile bool _initialized = false;
private bool _initializing = false;
private volatile string _switchValueString = String.Empty;
private string _defaultValue;
private object _intializedLock;
private static List<WeakReference> s_switches = new List<WeakReference>();
private static int s_LastCollectionCount;
private object IntializedLock
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
get
{
if (_intializedLock == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref _intializedLock, o, null);
}
return _intializedLock;
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.Switch'/>
/// class.</para>
/// </devdoc>
protected Switch(string displayName, string description) : this(displayName, description, "0")
{
}
protected Switch(string displayName, string description, string defaultSwitchValue)
{
// displayName is used as a hashtable key, so it can never
// be null.
if (displayName == null) displayName = string.Empty;
_displayName = displayName;
_description = description;
// Add a weakreference to this switch and cleanup invalid references
lock (s_switches)
{
_pruneCachedSwitches();
s_switches.Add(new WeakReference(this));
}
_defaultValue = defaultSwitchValue;
}
private static void _pruneCachedSwitches()
{
lock (s_switches)
{
if (s_LastCollectionCount != GC.CollectionCount(2))
{
List<WeakReference> buffer = new List<WeakReference>(s_switches.Count);
for (int i = 0; i < s_switches.Count; i++)
{
Switch s = ((Switch)s_switches[i].Target);
if (s != null)
{
buffer.Add(s_switches[i]);
}
}
if (buffer.Count < s_switches.Count)
{
s_switches.Clear();
s_switches.AddRange(buffer);
s_switches.TrimExcess();
}
s_LastCollectionCount = GC.CollectionCount(2);
}
}
}
/// <devdoc>
/// <para>Gets a name used to identify the switch.</para>
/// </devdoc>
public string DisplayName
{
get
{
return _displayName;
}
}
/// <devdoc>
/// <para>Gets a description of the switch.</para>
/// </devdoc>
public string Description
{
get
{
return (_description == null) ? string.Empty : _description;
}
}
/// <devdoc>
/// <para>
/// Indicates the current setting for this switch.
/// </para>
/// </devdoc>
protected int SwitchSetting
{
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "reviewed for thread-safety")]
get
{
if (!_initialized)
{
if (InitializeWithStatus())
OnSwitchSettingChanged();
}
return _switchSetting;
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "reviewed for thread-safety")]
set
{
bool didUpdate = false;
lock (IntializedLock)
{
_initialized = true;
if (_switchSetting != value)
{
_switchSetting = value;
didUpdate = true;
}
}
if (didUpdate)
{
OnSwitchSettingChanged();
}
}
}
protected string Value
{
get
{
Initialize();
return _switchValueString;
}
set
{
Initialize();
_switchValueString = value;
OnValueChanged();
}
}
private void Initialize()
{
InitializeWithStatus();
}
private bool InitializeWithStatus()
{
if (!_initialized)
{
lock (IntializedLock)
{
if (_initialized || _initializing)
{
return false;
}
// This method is re-entrent during initialization, since calls to OnValueChanged() in subclasses could end up having InitializeWithStatus()
// called again, we don't want to get caught in an infinite loop.
_initializing = true;
_switchValueString = _defaultValue;
OnValueChanged();
_initialized = true;
_initializing = false;
}
}
return true;
}
/// <devdoc>
/// This method is invoked when a switch setting has been changed. It will
/// be invoked the first time a switch reads its value from the registry
/// or environment, and then it will be invoked each time the switch's
/// value is changed.
/// </devdoc>
protected virtual void OnSwitchSettingChanged()
{
}
protected virtual void OnValueChanged()
{
SwitchSetting = Int32.Parse(Value, CultureInfo.InvariantCulture);
}
internal static void RefreshAll()
{
lock (s_switches)
{
_pruneCachedSwitches();
for (int i = 0; i < s_switches.Count; i++)
{
Switch swtch = ((Switch)s_switches[i].Target);
if (swtch != null)
{
swtch.Refresh();
}
}
}
}
internal void Refresh()
{
lock (IntializedLock)
{
_initialized = false;
Initialize();
}
}
}
}
| |
// 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.Text;
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Globalization;
namespace System
{
// TimeSpan represents a duration of time. A TimeSpan can be negative
// or positive.
//
// TimeSpan is internally represented as a number of milliseconds. While
// this maps well into units of time such as hours and days, any
// periods longer than that aren't representable in a nice fashion.
// For instance, a month can be between 28 and 31 days, while a year
// can contain 365 or 364 days. A decade can have between 1 and 3 leapyears,
// depending on when you map the TimeSpan into the calendar. This is why
// we do not provide Years() or Months().
//
// Note: System.TimeSpan needs to interop with the WinRT structure
// type Windows::Foundation:TimeSpan. These types are currently binary-compatible in
// memory so no custom marshalling is required. If at any point the implementation
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
[Serializable]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
public const long TicksPerMillisecond = 10000;
private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond;
public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000
private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000
private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9
public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000
private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11
public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000
private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60; // 60,000
private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000
private const int MillisPerDay = MillisPerHour * 24; // 86,400,000
internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond;
internal const long MinSeconds = Int64.MinValue / TicksPerSecond;
internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond;
internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond;
internal const long TicksPerTenthSecond = TicksPerMillisecond * 100;
public static readonly TimeSpan Zero = new TimeSpan(0);
public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue);
public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue);
// internal so that DateTime doesn't have to call an extra get
// method for some arithmetic operations.
internal long _ticks; // Do not rename (binary serialization)
public TimeSpan(long ticks)
{
this._ticks = ticks;
}
public TimeSpan(int hours, int minutes, int seconds)
{
_ticks = TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
: this(days, hours, minutes, seconds, 0)
{
}
public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
{
Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds;
if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds)
throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
_ticks = (long)totalMilliSeconds * TicksPerMillisecond;
}
public long Ticks
{
get { return _ticks; }
}
public int Days
{
get { return (int)(_ticks / TicksPerDay); }
}
public int Hours
{
get { return (int)((_ticks / TicksPerHour) % 24); }
}
public int Milliseconds
{
get { return (int)((_ticks / TicksPerMillisecond) % 1000); }
}
public int Minutes
{
get { return (int)((_ticks / TicksPerMinute) % 60); }
}
public int Seconds
{
get { return (int)((_ticks / TicksPerSecond) % 60); }
}
public double TotalDays
{
get { return ((double)_ticks) * DaysPerTick; }
}
public double TotalHours
{
get { return (double)_ticks * HoursPerTick; }
}
public double TotalMilliseconds
{
get
{
double temp = (double)_ticks * MillisecondsPerTick;
if (temp > MaxMilliSeconds)
return (double)MaxMilliSeconds;
if (temp < MinMilliSeconds)
return (double)MinMilliSeconds;
return temp;
}
}
public double TotalMinutes
{
get { return (double)_ticks * MinutesPerTick; }
}
public double TotalSeconds
{
get { return (double)_ticks * SecondsPerTick; }
}
public TimeSpan Add(TimeSpan ts)
{
long result = _ticks + ts._ticks;
// Overflow if signs of operands was identical and result's
// sign was opposite.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
// Compares two TimeSpan values, returning an integer that indicates their
// relationship.
//
public static int Compare(TimeSpan t1, TimeSpan t2)
{
if (t1._ticks > t2._ticks) return 1;
if (t1._ticks < t2._ticks) return -1;
return 0;
}
// Returns a value less than zero if this object
public int CompareTo(Object value)
{
if (value == null) return 1;
if (!(value is TimeSpan))
throw new ArgumentException(SR.Arg_MustBeTimeSpan);
long t = ((TimeSpan)value)._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public int CompareTo(TimeSpan value)
{
long t = value._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
public static TimeSpan FromDays(double value)
{
return Interval(value, MillisPerDay);
}
public TimeSpan Duration()
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_Duration);
return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks);
}
public override bool Equals(Object value)
{
if (value is TimeSpan)
{
return _ticks == ((TimeSpan)value)._ticks;
}
return false;
}
public bool Equals(TimeSpan obj)
{
return _ticks == obj._ticks;
}
public static bool Equals(TimeSpan t1, TimeSpan t2)
{
return t1._ticks == t2._ticks;
}
public override int GetHashCode()
{
return (int)_ticks ^ (int)(_ticks >> 32);
}
public static TimeSpan FromHours(double value)
{
return Interval(value, MillisPerHour);
}
private static TimeSpan Interval(double value, int scale)
{
if (Double.IsNaN(value))
throw new ArgumentException(SR.Arg_CannotBeNaN);
double tmp = value * scale;
double millis = tmp + (value >= 0 ? 0.5 : -0.5);
if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan((long)millis * TicksPerMillisecond);
}
public static TimeSpan FromMilliseconds(double value)
{
return Interval(value, 1);
}
public static TimeSpan FromMinutes(double value)
{
return Interval(value, MillisPerMinute);
}
public TimeSpan Negate()
{
if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
return new TimeSpan(-_ticks);
}
public static TimeSpan FromSeconds(double value)
{
return Interval(value, MillisPerSecond);
}
public TimeSpan Subtract(TimeSpan ts)
{
long result = _ticks - ts._ticks;
// Overflow if signs of operands was different and result's
// sign was opposite from the first argument's sign.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
public TimeSpan Multiply(double factor) => this * factor;
public TimeSpan Divide(double divisor) => this / divisor;
public double Divide(TimeSpan ts) => this / ts;
public static TimeSpan FromTicks(long value)
{
return new TimeSpan(value);
}
internal static long TimeToTicks(int hour, int minute, int second)
{
// totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31,
// which is less than 2^44, meaning we won't overflow totalSeconds.
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
return totalSeconds * TicksPerSecond;
}
// See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat
#region ParseAndFormat
private static void ValidateStyles(TimeSpanStyles style, String parameterName)
{
if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative)
throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName);
}
public static TimeSpan Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
return TimeSpanParse.Parse(s.AsReadOnlySpan(), null);
}
public static TimeSpan Parse(String input, IFormatProvider formatProvider)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
return TimeSpanParse.Parse(input.AsReadOnlySpan(), formatProvider);
}
public static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null)
{
return TimeSpanParse.Parse(input, formatProvider);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
return TimeSpanParse.ParseExact(input.AsReadOnlySpan(), format, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider)
{
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
return TimeSpanParse.ParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, nameof(styles));
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
return TimeSpanParse.ParseExact(input.AsReadOnlySpan(), format, formatProvider, styles);
}
public static TimeSpan ParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None)
{
ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, nameof(styles));
if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
return TimeSpanParse.ParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, styles);
}
public static TimeSpan ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None)
{
ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result)
{
if (s == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParse(s.AsReadOnlySpan(), null, out result);
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result)
{
if (input == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParse(input.AsReadOnlySpan(), formatProvider, out result);
}
public static bool TryParse(ReadOnlySpan<char> input, out TimeSpan result, IFormatProvider formatProvider = null)
{
return TimeSpanParse.TryParse(input, formatProvider, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result)
{
if (input == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParseExact(input.AsReadOnlySpan(), format, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result)
{
if (input == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, nameof(styles));
if (input == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParseExact(input.AsReadOnlySpan(), format, formatProvider, styles, out result);
}
public static bool TryParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, out TimeSpan result, TimeSpanStyles styles = TimeSpanStyles.None)
{
ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, nameof(styles));
if (input == null)
{
result = default(TimeSpan);
return false;
}
return TimeSpanParse.TryParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, styles, out result);
}
public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, out TimeSpan result, TimeSpanStyles styles = TimeSpanStyles.None)
{
ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString()
{
return TimeSpanFormat.Format(this, null, null);
}
public String ToString(String format)
{
return TimeSpanFormat.Format(this, format, null);
}
public String ToString(String format, IFormatProvider formatProvider)
{
return TimeSpanFormat.Format(this, format, formatProvider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, string format = null, IFormatProvider formatProvider = null)
{
return TimeSpanFormat.TryFormat(this, destination, out charsWritten, format, formatProvider);
}
#endregion
public static TimeSpan operator -(TimeSpan t)
{
if (t._ticks == TimeSpan.MinValue._ticks)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
return new TimeSpan(-t._ticks);
}
public static TimeSpan operator -(TimeSpan t1, TimeSpan t2)
{
return t1.Subtract(t2);
}
public static TimeSpan operator +(TimeSpan t)
{
return t;
}
public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)
{
return t1.Add(t2);
}
public static TimeSpan operator *(TimeSpan timeSpan, double factor)
{
if (double.IsNaN(factor))
{
throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(factor));
}
// Rounding to the nearest tick is as close to the result we would have with unlimited
// precision as possible, and so likely to have the least potential to surprise.
double ticks = Math.Round(timeSpan.Ticks * factor);
if (ticks > long.MaxValue | ticks < long.MinValue)
{
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
}
return FromTicks((long)ticks);
}
public static TimeSpan operator *(double factor, TimeSpan timeSpan) => timeSpan * factor;
public static TimeSpan operator /(TimeSpan timeSpan, double divisor)
{
if (double.IsNaN(divisor))
{
throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(divisor));
}
double ticks = Math.Round(timeSpan.Ticks / divisor);
if (ticks > long.MaxValue | ticks < long.MinValue || double.IsNaN(ticks))
{
throw new OverflowException(SR.Overflow_TimeSpanTooLong);
}
return FromTicks((long)ticks);
}
// Using floating-point arithmetic directly means that infinities can be returned, which is reasonable
// if we consider TimeSpan.FromHours(1) / TimeSpan.Zero asks how many zero-second intervals there are in
// an hour for which infinity is the mathematic correct answer. Having TimeSpan.Zero / TimeSpan.Zero return NaN
// is perhaps less useful, but no less useful than an exception.
public static double operator /(TimeSpan t1, TimeSpan t2) => t1.Ticks / (double)t2.Ticks;
public static bool operator ==(TimeSpan t1, TimeSpan t2)
{
return t1._ticks == t2._ticks;
}
public static bool operator !=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks != t2._ticks;
}
public static bool operator <(TimeSpan t1, TimeSpan t2)
{
return t1._ticks < t2._ticks;
}
public static bool operator <=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks <= t2._ticks;
}
public static bool operator >(TimeSpan t1, TimeSpan t2)
{
return t1._ticks > t2._ticks;
}
public static bool operator >=(TimeSpan t1, TimeSpan t2)
{
return t1._ticks >= t2._ticks;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.Xunit;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Pomelo.EntityFrameworkCore.MySql.Internal;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore
{
// Tests are split into classes to enable parallel execution
// Some combinations are skipped to reduce run time
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorExistsTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, true, false)]
[InlineData(false, false, false)]
[InlineData(true, true, true)]
[InlineData(false, false, true)]
public Task Returns_false_when_database_does_not_exist(bool async, bool ambientTransaction, bool useCanConnect)
{
return Returns_false_when_database_does_not_exist_test(async, ambientTransaction, useCanConnect, file: false);
}
[ConditionalTheory]
[InlineData(true, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, true)]
[InlineData(false, true, true)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Returns_false_when_database_with_filename_does_not_exist(bool async, bool ambientTransaction, bool useCanConnect)
{
return Returns_false_when_database_does_not_exist_test(async, ambientTransaction, useCanConnect, file: true);
}
private static async Task Returns_false_when_database_does_not_exist_test(bool async, bool ambientTransaction, bool useCanConnect, bool file)
{
using (var testDatabase = MySqlTestStore.Create("NonExisting", file))
{
using (var context = new BloggingContext(testDatabase))
{
var creator = GetDatabaseCreator(context);
using (CreateTransactionScope(ambientTransaction))
{
if (useCanConnect)
{
Assert.False(async ? await creator.CanConnectAsync() : creator.CanConnect());
}
else
{
Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
}
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
}
}
}
[ConditionalTheory]
[InlineData(true, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, true)]
[InlineData(false, true, true)]
public Task Returns_true_when_database_exists(bool async, bool ambientTransaction, bool useCanConnect)
{
return Returns_true_when_database_exists_test(async, ambientTransaction, useCanConnect, file: false);
}
[ConditionalTheory]
[InlineData(true, true, false)]
[InlineData(false, false, false)]
[InlineData(true, true, true)]
[InlineData(false, false, true)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Returns_true_when_database_with_filename_exists(bool async, bool ambientTransaction, bool useCanConnect)
{
return Returns_true_when_database_exists_test(async, ambientTransaction, useCanConnect, file: true);
}
private static async Task Returns_true_when_database_exists_test(bool async, bool ambientTransaction, bool useCanConnect, bool file)
{
using (var testDatabase = file
? MySqlTestStore.CreateInitialized("ExistingBloggingFile", useFileName: true)
: MySqlTestStore.GetOrCreateInitialized("ExistingBlogging"))
{
using (var context = new BloggingContext(testDatabase))
{
var creator = GetDatabaseCreator(context);
using (CreateTransactionScope(ambientTransaction))
{
if (useCanConnect)
{
Assert.True(async ? await creator.CanConnectAsync() : creator.CanConnect());
}
else
{
Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
}
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
}
}
}
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorEnsureDeletedTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, true, true)]
[InlineData(false, false, true)]
[InlineData(true, false, false)]
[InlineData(false, true, false)]
public Task Deletes_database(bool async, bool open, bool ambientTransaction)
{
return Delete_database_test(async, open, ambientTransaction, file: false);
}
[ConditionalTheory]
[InlineData(true, true, false)]
[InlineData(true, false, true)]
[InlineData(false, true, true)]
[InlineData(false, false, false)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Deletes_database_with_filename(bool async, bool open, bool ambientTransaction)
{
return Delete_database_test(async, open, ambientTransaction, file: true);
}
private static async Task Delete_database_test(bool async, bool open, bool ambientTransaction, bool file)
{
using (var testDatabase = MySqlTestStore.CreateInitialized("EnsureDeleteBlogging" + (file ? "File" : ""), file))
{
if (!open)
{
testDatabase.CloseConnection();
}
using (var context = new BloggingContext(testDatabase))
{
var creator = GetDatabaseCreator(context);
Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
using (CreateTransactionScope(ambientTransaction))
{
if (async)
{
Assert.True(await context.Database.EnsureDeletedAsync());
}
else
{
Assert.True(context.Database.EnsureDeleted());
}
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
}
}
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public Task Noop_when_database_does_not_exist(bool async)
{
return Noop_when_database_does_not_exist_test(async, file: false);
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Noop_when_database_with_filename_does_not_exist(bool async)
{
return Noop_when_database_does_not_exist_test(async, file: true);
}
private static async Task Noop_when_database_does_not_exist_test(bool async, bool file)
{
using (var testDatabase = MySqlTestStore.Create("NonExisting", file))
{
using (var context = new BloggingContext(testDatabase))
{
var creator = GetDatabaseCreator(context);
Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
if (async)
{
Assert.False(await creator.EnsureDeletedAsync());
}
else
{
Assert.False(creator.EnsureDeleted());
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
}
}
}
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorEnsureCreatedTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, true)]
[InlineData(false, false)]
public Task Creates_schema_in_existing_database(bool async, bool ambientTransaction)
{
return Creates_schema_in_existing_database_test(async, ambientTransaction, file: false);
}
[ConditionalTheory]
[InlineData(true, false)]
[InlineData(false, true)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Creates_schema_in_existing_database_with_filename(bool async, bool ambientTransaction)
{
return Creates_schema_in_existing_database_test(async, ambientTransaction, file: true);
}
private static Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction, bool file)
{
return TestEnvironment.IsSqlAzure
? new TestMySqlRetryingExecutionStrategy().ExecuteAsync(
(true, async, ambientTransaction, file), Creates_physical_database_and_schema_test)
: Creates_physical_database_and_schema_test((true, async, ambientTransaction, file));
}
[ConditionalTheory]
[InlineData(true, false)]
[InlineData(false, true)]
[MySqlCondition(MySqlCondition.IsNotSqlAzure)]
public Task Creates_physical_database_and_schema(bool async, bool ambientTransaction)
{
return Creates_new_physical_database_and_schema_test(async, ambientTransaction, file: false);
}
[ConditionalTheory]
[InlineData(true, true)]
[InlineData(false, false)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Creates_physical_database_with_filename_and_schema(bool async, bool ambientTransaction)
{
return Creates_new_physical_database_and_schema_test(async, ambientTransaction, file: true);
}
private static Task Creates_new_physical_database_and_schema_test(bool async, bool ambientTransaction, bool file)
{
return TestEnvironment.IsSqlAzure
? new TestMySqlRetryingExecutionStrategy().ExecuteAsync(
(false, async, ambientTransaction, file), Creates_physical_database_and_schema_test)
: Creates_physical_database_and_schema_test((false, async, ambientTransaction, file));
}
private static async Task Creates_physical_database_and_schema_test(
(bool CreateDatabase, bool Async, bool ambientTransaction, bool File) options)
{
var (createDatabase, async, ambientTransaction, file) = options;
using (var testDatabase = MySqlTestStore.Create("EnsureCreatedTest" + (file ? "File" : ""), file))
{
using (var context = new BloggingContext(testDatabase))
{
if (createDatabase)
{
testDatabase.Initialize(null, (Func<DbContext>)null, null);
}
else
{
testDatabase.DeleteDatabase();
}
var creator = GetDatabaseCreator(context);
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
using (CreateTransactionScope(ambientTransaction))
{
if (async)
{
Assert.True(await creator.EnsureCreatedAsync());
}
else
{
Assert.True(creator.EnsureCreated());
}
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
if (testDatabase.ConnectionState != ConnectionState.Open)
{
await testDatabase.OpenConnectionAsync();
}
var tables = testDatabase.Query<string>(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'").ToList();
Assert.Equal(1, tables.Count);
Assert.Equal("Blogs", tables.Single());
var columns = testDatabase.Query<string>(
"SELECT TABLE_NAME + '.' + COLUMN_NAME + ' (' + DATA_TYPE + ')' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs' ORDER BY TABLE_NAME, COLUMN_NAME").ToArray();
Assert.Equal(14, columns.Length);
Assert.Equal(
new[]
{
"Blogs.AndChew (varbinary)",
"Blogs.AndRow (timestamp)",
"Blogs.Cheese (nvarchar)",
"Blogs.ErMilan (int)",
"Blogs.Fuse (smallint)",
"Blogs.George (bit)",
"Blogs.Key1 (nvarchar)",
"Blogs.Key2 (varbinary)",
"Blogs.NotFigTime (datetime2)",
"Blogs.On (real)",
"Blogs.OrNothing (float)",
"Blogs.TheGu (uniqueidentifier)",
"Blogs.ToEat (tinyint)",
"Blogs.WayRound (bigint)"
},
columns);
}
}
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public Task Noop_when_database_exists_and_has_schema(bool async)
{
return Noop_when_database_exists_and_has_schema_test(async, file: false);
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
[MySqlCondition(MySqlCondition.SupportsAttach)]
public Task Noop_when_database_with_filename_exists_and_has_schema(bool async)
{
return Noop_when_database_exists_and_has_schema_test(async, file: true);
}
private static async Task Noop_when_database_exists_and_has_schema_test(bool async, bool file)
{
using (var testDatabase = MySqlTestStore.CreateInitialized("InitializedBlogging" + (file ? "File" : ""), file))
{
using (var context = new BloggingContext(testDatabase))
{
context.Database.EnsureCreatedResiliently();
if (async)
{
Assert.False(await context.Database.EnsureCreatedResilientlyAsync());
}
else
{
Assert.False(context.Database.EnsureCreatedResiliently());
}
Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
}
}
}
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorHasTablesTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public async Task Throws_when_database_does_not_exist(bool async)
{
using (var testDatabase = MySqlTestStore.GetOrCreate("NonExisting"))
{
var databaseCreator = GetDatabaseCreator(testDatabase);
await databaseCreator.ExecutionStrategyFactory.Create().ExecuteAsync(
databaseCreator,
async creator =>
{
var errorNumber = async
? (await Assert.ThrowsAsync<SqlException>(() => creator.HasTablesAsyncBase())).Number
: Assert.Throws<SqlException>(() => creator.HasTablesBase()).Number;
if (errorNumber != 233) // skip if no-process transient failure
{
Assert.Equal(
4060, // Login failed error number
errorNumber);
}
});
}
}
[ConditionalTheory]
[InlineData(true, false)]
[InlineData(false, true)]
public async Task Returns_false_when_database_exists_but_has_no_tables(bool async, bool ambientTransaction)
{
using (var testDatabase = MySqlTestStore.GetOrCreateInitialized("Empty"))
{
var creator = GetDatabaseCreator(testDatabase);
using (CreateTransactionScope(ambientTransaction))
{
Assert.False(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
}
}
}
[ConditionalTheory]
[InlineData(true, true)]
[InlineData(false, false)]
public async Task Returns_true_when_database_exists_and_has_any_tables(bool async, bool ambientTransaction)
{
using (var testDatabase = MySqlTestStore.GetOrCreate("ExistingTables")
.InitializeMySql(null, t => new BloggingContext(t), null))
{
var creator = GetDatabaseCreator(testDatabase);
using (CreateTransactionScope(ambientTransaction))
{
Assert.True(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
}
}
}
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorDeleteTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, true)]
[InlineData(false, false)]
public static async Task Deletes_database(bool async, bool ambientTransaction)
{
using (var testDatabase = MySqlTestStore.CreateInitialized("DeleteBlogging"))
{
testDatabase.CloseConnection();
var creator = GetDatabaseCreator(testDatabase);
Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
using (CreateTransactionScope(ambientTransaction))
{
if (async)
{
await creator.DeleteAsync();
}
else
{
creator.Delete();
}
}
Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
}
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public async Task Throws_when_database_does_not_exist(bool async)
{
using (var testDatabase = MySqlTestStore.GetOrCreate("NonExistingBlogging"))
{
var creator = GetDatabaseCreator(testDatabase);
if (async)
{
await Assert.ThrowsAsync<SqlException>(() => creator.DeleteAsync());
}
else
{
Assert.Throws<SqlException>(() => creator.Delete());
}
}
}
[ConditionalFact]
public void Throws_when_no_initial_catalog()
{
var connectionStringBuilder = new SqlConnectionStringBuilder(TestEnvironment.DefaultConnection);
connectionStringBuilder.Remove("Initial Catalog");
var creator = GetDatabaseCreator(connectionStringBuilder.ToString());
var ex = Assert.Throws<InvalidOperationException>(() => creator.Delete());
Assert.Equal(MySqlStrings.NoInitialCatalog, ex.Message);
}
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorCreateTablesTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, true)]
[InlineData(false, false)]
public async Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction)
{
using (var testDatabase = MySqlTestStore.GetOrCreateInitialized("ExistingBlogging" + (async ? "Async" : "")))
{
using (var context = new BloggingContext(testDatabase))
{
var creator = GetDatabaseCreator(context);
using (CreateTransactionScope(ambientTransaction))
{
if (async)
{
await creator.CreateTablesAsync();
}
else
{
creator.CreateTables();
}
}
if (testDatabase.ConnectionState != ConnectionState.Open)
{
await testDatabase.OpenConnectionAsync();
}
var tables = (await testDatabase.QueryAsync<string>(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).ToList();
Assert.Equal(1, tables.Count);
Assert.Equal("Blogs", tables.Single());
var columns = (await testDatabase.QueryAsync<string>(
"SELECT TABLE_NAME + '.' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs'")).ToList();
Assert.Equal(14, columns.Count);
Assert.True(columns.Any(c => c == "Blogs.Key1"));
Assert.True(columns.Any(c => c == "Blogs.Key2"));
Assert.True(columns.Any(c => c == "Blogs.Cheese"));
Assert.True(columns.Any(c => c == "Blogs.ErMilan"));
Assert.True(columns.Any(c => c == "Blogs.George"));
Assert.True(columns.Any(c => c == "Blogs.TheGu"));
Assert.True(columns.Any(c => c == "Blogs.NotFigTime"));
Assert.True(columns.Any(c => c == "Blogs.ToEat"));
Assert.True(columns.Any(c => c == "Blogs.OrNothing"));
Assert.True(columns.Any(c => c == "Blogs.Fuse"));
Assert.True(columns.Any(c => c == "Blogs.WayRound"));
Assert.True(columns.Any(c => c == "Blogs.On"));
Assert.True(columns.Any(c => c == "Blogs.AndChew"));
Assert.True(columns.Any(c => c == "Blogs.AndRow"));
}
}
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public async Task Throws_if_database_does_not_exist(bool async)
{
using (var testDatabase = MySqlTestStore.GetOrCreate("NonExisting"))
{
var creator = GetDatabaseCreator(testDatabase);
var errorNumber
= async
? (await Assert.ThrowsAsync<SqlException>(() => creator.CreateTablesAsync())).Number
: Assert.Throws<SqlException>(() => creator.CreateTables()).Number;
if (errorNumber != 233) // skip if no-process transient failure
{
Assert.Equal(
4060, // Login failed error number
errorNumber);
}
}
}
[Fact]
public void GenerateCreateScript_works()
{
using (var context = new BloggingContext("Data Source=foo"))
{
var script = context.Database.GenerateCreateScript();
Assert.Equal(
"CREATE TABLE [Blogs] (" + _eol +
" [Key1] nvarchar(450) NOT NULL," + _eol +
" [Key2] varbinary(900) NOT NULL," + _eol +
" [Cheese] nvarchar(max) NULL," + _eol +
" [ErMilan] int NOT NULL," + _eol +
" [George] bit NOT NULL," + _eol +
" [TheGu] uniqueidentifier NOT NULL," + _eol +
" [NotFigTime] datetime2 NOT NULL," + _eol +
" [ToEat] tinyint NOT NULL," + _eol +
" [OrNothing] float NOT NULL," + _eol +
" [Fuse] smallint NOT NULL," + _eol +
" [WayRound] bigint NOT NULL," + _eol +
" [On] real NOT NULL," + _eol +
" [AndChew] varbinary(max) NULL," + _eol +
" [AndRow] rowversion NULL," + _eol +
" CONSTRAINT [PK_Blogs] PRIMARY KEY ([Key1], [Key2])" + _eol +
");" + _eol +
"GO" + _eol + _eol + _eol,
script);
}
}
private static readonly string _eol = Environment.NewLine;
}
[MySqlCondition(MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorCreateTest : MySqlDatabaseCreatorTest
{
[ConditionalTheory]
[InlineData(true, false)]
[InlineData(false, true)]
public async Task Creates_physical_database_but_not_tables(bool async, bool ambientTransaction)
{
using (var testDatabase = MySqlTestStore.GetOrCreate("CreateTest"))
{
var creator = GetDatabaseCreator(testDatabase);
creator.EnsureDeleted();
using (CreateTransactionScope(ambientTransaction))
{
if (async)
{
await creator.CreateAsync();
}
else
{
creator.Create();
}
}
Assert.True(creator.Exists());
if (testDatabase.ConnectionState != ConnectionState.Open)
{
await testDatabase.OpenConnectionAsync();
}
Assert.Equal(
0, (await testDatabase.QueryAsync<string>(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).Count());
Assert.True(
await testDatabase.ExecuteScalarAsync<bool>(
string.Concat(
"SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name='",
testDatabase.Name,
"'")));
}
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public async Task Throws_if_database_already_exists(bool async)
{
using (var testDatabase = MySqlTestStore.GetOrCreateInitialized("ExistingBlogging"))
{
var creator = GetDatabaseCreator(testDatabase);
var ex = async
? await Assert.ThrowsAsync<SqlException>(() => creator.CreateAsync())
: Assert.Throws<SqlException>(() => creator.Create());
Assert.Equal(
1801, // Database with given name already exists
ex.Number);
}
}
}
#pragma warning disable RCS1102 // Make class static.
[MySqlCondition(MySqlCondition.IsNotSqlAzure | MySqlCondition.IsNotTeamCity)]
public class MySqlDatabaseCreatorTest
{
public static IDisposable CreateTransactionScope(bool useTransaction)
{
#if NET461
return TestStore.CreateTransactionScope(useTransaction);
#else
return TestStore.CreateTransactionScope(useTransaction: false);
#endif
}
public static TestDatabaseCreator GetDatabaseCreator(MySqlTestStore testStore)
{
return GetDatabaseCreator(testStore.ConnectionString);
}
public static TestDatabaseCreator GetDatabaseCreator(string connectionString)
{
return GetDatabaseCreator(new BloggingContext(connectionString));
}
public static TestDatabaseCreator GetDatabaseCreator(BloggingContext context)
{
return (TestDatabaseCreator)context.GetService<IRelationalDatabaseCreator>();
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestMySqlExecutionStrategyFactory : MySqlExecutionStrategyFactory
{
public TestMySqlExecutionStrategyFactory(ExecutionStrategyDependencies dependencies)
: base(dependencies)
{
}
protected override IExecutionStrategy CreateDefaultStrategy(ExecutionStrategyDependencies dependencies)
{
return new NoopExecutionStrategy(dependencies);
}
}
private static IServiceProvider CreateServiceProvider()
{
return new ServiceCollection()
.AddEntityFrameworkMySql()
.AddScoped<IExecutionStrategyFactory, TestMySqlExecutionStrategyFactory>()
.AddScoped<IRelationalDatabaseCreator, TestDatabaseCreator>()
.BuildServiceProvider();
}
public class BloggingContext : DbContext
{
private readonly string _connectionString;
public BloggingContext(MySqlTestStore testStore)
: this(testStore.ConnectionString)
{
}
public BloggingContext(string connectionString)
{
_connectionString = connectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseMySql(
_connectionString,
b => b.ApplyConfiguration().CommandTimeout(MySqlTestStore.CommandTimeout))
.UseInternalServiceProvider(CreateServiceProvider());
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(
b =>
{
b.HasKey(
e => new
{
e.Key1,
e.Key2
});
b.Property(e => e.AndRow).IsConcurrencyToken().ValueGeneratedOnAddOrUpdate();
});
}
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public string Key1 { get; set; }
public byte[] Key2 { get; set; }
public string Cheese { get; set; }
public int ErMilan { get; set; }
public bool George { get; set; }
public Guid TheGu { get; set; }
public DateTime NotFigTime { get; set; }
public byte ToEat { get; set; }
public double OrNothing { get; set; }
public short Fuse { get; set; }
public long WayRound { get; set; }
public float On { get; set; }
public byte[] AndChew { get; set; }
public byte[] AndRow { get; set; }
}
public class TestDatabaseCreator : MySqlDatabaseCreator
{
public TestDatabaseCreator(
RelationalDatabaseCreatorDependencies dependencies,
IMySqlConnection connection,
IRawSqlCommandBuilder rawSqlCommandBuilder)
: base(dependencies, connection, rawSqlCommandBuilder)
{
}
public bool HasTablesBase()
{
return HasTables();
}
public Task<bool> HasTablesAsyncBase(CancellationToken cancellationToken = default)
{
return HasTablesAsync(cancellationToken);
}
public IExecutionStrategyFactory ExecutionStrategyFactory => Dependencies.ExecutionStrategyFactory;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using HtcSharp.HttpModule.Http.Abstractions.Internal;
namespace HtcSharp.HttpModule.Http.Abstractions {
// SourceTools-Start
// Remote-File C:\ASP\src\Http\Http.Abstractions\src\PathString.cs
// Start-At-Remote-Line 11
// SourceTools-End
/// <summary>
/// Provides correct escaping for Path and PathBase values when needed to reconstruct a request or redirect URI string
/// </summary>
[TypeConverter(typeof(PathStringConverter))]
public readonly struct PathString : IEquatable<PathString> {
/// <summary>
/// Represents the empty path. This field is read-only.
/// </summary>
public static readonly PathString Empty = new PathString(string.Empty);
private readonly string _value;
/// <summary>
/// Initialize the path string with a given value. This value must be in unescaped format. Use
/// PathString.FromUriComponent(value) if you have a path value which is in an escaped format.
/// </summary>
/// <param name="value">The unescaped path to be assigned to the Value property.</param>
public PathString(string value) {
if (!string.IsNullOrEmpty(value) && value[0] != '/') {
throw new ArgumentException(Resources.FormatException_PathMustStartWithSlash(nameof(value)), nameof(value));
}
_value = value;
}
/// <summary>
/// The unescaped path value
/// </summary>
public string Value {
get { return _value; }
}
/// <summary>
/// True if the path is not empty
/// </summary>
public bool HasValue {
get { return !string.IsNullOrEmpty(_value); }
}
/// <summary>
/// Provides the path string escaped in a way which is correct for combining into the URI representation.
/// </summary>
/// <returns>The escaped path value</returns>
public override string ToString() {
return ToUriComponent();
}
/// <summary>
/// Provides the path string escaped in a way which is correct for combining into the URI representation.
/// </summary>
/// <returns>The escaped path value</returns>
public string ToUriComponent() {
if (!HasValue) {
return string.Empty;
}
var value = _value;
var i = 0;
for (; i < value.Length; i++) {
if (!PathStringHelper.IsValidPathChar(value[i]) || PathStringHelper.IsPercentEncodedChar(value, i)) {
break;
}
}
if (i < value.Length) {
return ToEscapedUriComponent(value, i);
}
return value;
}
private static string ToEscapedUriComponent(string value, int i) {
StringBuilder buffer = null;
var start = 0;
var count = i;
var requiresEscaping = false;
while (i < value.Length) {
var isPercentEncodedChar = PathStringHelper.IsPercentEncodedChar(value, i);
if (PathStringHelper.IsValidPathChar(value[i]) || isPercentEncodedChar) {
if (requiresEscaping) {
// the current segment requires escape
if (buffer == null) {
buffer = new StringBuilder(value.Length * 3);
}
buffer.Append(Uri.EscapeDataString(value.Substring(start, count)));
requiresEscaping = false;
start = i;
count = 0;
}
if (isPercentEncodedChar) {
count += 3;
i += 3;
} else {
count++;
i++;
}
} else {
if (!requiresEscaping) {
// the current segment doesn't require escape
if (buffer == null) {
buffer = new StringBuilder(value.Length * 3);
}
buffer.Append(value, start, count);
requiresEscaping = true;
start = i;
count = 0;
}
count++;
i++;
}
}
if (count == value.Length && !requiresEscaping) {
return value;
} else {
if (count > 0) {
if (buffer == null) {
buffer = new StringBuilder(value.Length * 3);
}
if (requiresEscaping) {
buffer.Append(Uri.EscapeDataString(value.Substring(start, count)));
} else {
buffer.Append(value, start, count);
}
}
return buffer.ToString();
}
}
/// <summary>
/// Returns an PathString given the path as it is escaped in the URI format. The string MUST NOT contain any
/// value that is not a path.
/// </summary>
/// <param name="uriComponent">The escaped path as it appears in the URI format.</param>
/// <returns>The resulting PathString</returns>
public static PathString FromUriComponent(string uriComponent) {
// REVIEW: what is the exactly correct thing to do?
return new PathString(Uri.UnescapeDataString(uriComponent));
}
/// <summary>
/// Returns an PathString given the path as from a Uri object. Relative Uri objects are not supported.
/// </summary>
/// <param name="uri">The Uri object</param>
/// <returns>The resulting PathString</returns>
public static PathString FromUriComponent(Uri uri) {
if (uri == null) {
throw new ArgumentNullException(nameof(uri));
}
// REVIEW: what is the exactly correct thing to do?
return new PathString("/" + uri.GetComponents(UriComponents.Path, UriFormat.Unescaped));
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/>.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other) {
return StartsWithSegments(other, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/> when compared
/// using the specified comparison option.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <param name="comparisonType">One of the enumeration values that determines how this <see cref="PathString"/> and value are compared.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other, StringComparison comparisonType) {
var value1 = Value ?? string.Empty;
var value2 = other.Value ?? string.Empty;
if (value1.StartsWith(value2, comparisonType)) {
return value1.Length == value2.Length || value1[value2.Length] == '/';
}
return false;
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/> and returns
/// the remaining segments.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <param name="remaining">The remaining segments after the match.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other, out PathString remaining) {
return StartsWithSegments(other, StringComparison.OrdinalIgnoreCase, out remaining);
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/> when compared
/// using the specified comparison option and returns the remaining segments.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <param name="comparisonType">One of the enumeration values that determines how this <see cref="PathString"/> and value are compared.</param>
/// <param name="remaining">The remaining segments after the match.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other, StringComparison comparisonType, out PathString remaining) {
var value1 = Value ?? string.Empty;
var value2 = other.Value ?? string.Empty;
if (value1.StartsWith(value2, comparisonType)) {
if (value1.Length == value2.Length || value1[value2.Length] == '/') {
remaining = new PathString(value1.Substring(value2.Length));
return true;
}
}
remaining = Empty;
return false;
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/> and returns
/// the matched and remaining segments.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <param name="matched">The matched segments with the original casing in the source value.</param>
/// <param name="remaining">The remaining segments after the match.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other, out PathString matched, out PathString remaining) {
return StartsWithSegments(other, StringComparison.OrdinalIgnoreCase, out matched, out remaining);
}
/// <summary>
/// Determines whether the beginning of this <see cref="PathString"/> instance matches the specified <see cref="PathString"/> when compared
/// using the specified comparison option and returns the matched and remaining segments.
/// </summary>
/// <param name="other">The <see cref="PathString"/> to compare.</param>
/// <param name="comparisonType">One of the enumeration values that determines how this <see cref="PathString"/> and value are compared.</param>
/// <param name="matched">The matched segments with the original casing in the source value.</param>
/// <param name="remaining">The remaining segments after the match.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public bool StartsWithSegments(PathString other, StringComparison comparisonType, out PathString matched, out PathString remaining) {
var value1 = Value ?? string.Empty;
var value2 = other.Value ?? string.Empty;
if (value1.StartsWith(value2, comparisonType)) {
if (value1.Length == value2.Length || value1[value2.Length] == '/') {
matched = new PathString(value1.Substring(0, value2.Length));
remaining = new PathString(value1.Substring(value2.Length));
return true;
}
}
remaining = Empty;
matched = Empty;
return false;
}
/// <summary>
/// Adds two PathString instances into a combined PathString value.
/// </summary>
/// <returns>The combined PathString value</returns>
public PathString Add(PathString other) {
if (HasValue &&
other.HasValue &&
Value[Value.Length - 1] == '/') {
// If the path string has a trailing slash and the other string has a leading slash, we need
// to trim one of them.
return new PathString(Value + other.Value.Substring(1));
}
return new PathString(Value + other.Value);
}
/// <summary>
/// Combines a PathString and QueryString into the joined URI formatted string value.
/// </summary>
/// <returns>The joined URI formatted string value</returns>
public string Add(QueryString other) {
return ToUriComponent() + other.ToUriComponent();
}
/// <summary>
/// Compares this PathString value to another value. The default comparison is StringComparison.OrdinalIgnoreCase.
/// </summary>
/// <param name="other">The second PathString for comparison.</param>
/// <returns>True if both PathString values are equal</returns>
public bool Equals(PathString other) {
return Equals(other, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Compares this PathString value to another value using a specific StringComparison type
/// </summary>
/// <param name="other">The second PathString for comparison</param>
/// <param name="comparisonType">The StringComparison type to use</param>
/// <returns>True if both PathString values are equal</returns>
public bool Equals(PathString other, StringComparison comparisonType) {
if (!HasValue && !other.HasValue) {
return true;
}
return string.Equals(_value, other._value, comparisonType);
}
/// <summary>
/// Compares this PathString value to another value. The default comparison is StringComparison.OrdinalIgnoreCase.
/// </summary>
/// <param name="obj">The second PathString for comparison.</param>
/// <returns>True if both PathString values are equal</returns>
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj)) {
return !HasValue;
}
return obj is PathString && Equals((PathString)obj);
}
/// <summary>
/// Returns the hash code for the PathString value. The hash code is provided by the OrdinalIgnoreCase implementation.
/// </summary>
/// <returns>The hash code</returns>
public override int GetHashCode() {
return (HasValue ? StringComparer.OrdinalIgnoreCase.GetHashCode(_value) : 0);
}
/// <summary>
/// Operator call through to Equals
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>True if both PathString values are equal</returns>
public static bool operator ==(PathString left, PathString right) {
return left.Equals(right);
}
/// <summary>
/// Operator call through to Equals
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>True if both PathString values are not equal</returns>
public static bool operator !=(PathString left, PathString right) {
return !left.Equals(right);
}
/// <summary>
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>The ToString combination of both values</returns>
public static string operator +(string left, PathString right) {
// This overload exists to prevent the implicit string<->PathString converter from
// trying to call the PathString+PathString operator for things that are not path strings.
return string.Concat(left, right.ToString());
}
/// <summary>
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>The ToString combination of both values</returns>
public static string operator +(PathString left, string right) {
// This overload exists to prevent the implicit string<->PathString converter from
// trying to call the PathString+PathString operator for things that are not path strings.
return string.Concat(left.ToString(), right);
}
/// <summary>
/// Operator call through to Add
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>The PathString combination of both values</returns>
public static PathString operator +(PathString left, PathString right) {
return left.Add(right);
}
/// <summary>
/// Operator call through to Add
/// </summary>
/// <param name="left">The left parameter</param>
/// <param name="right">The right parameter</param>
/// <returns>The PathString combination of both values</returns>
public static string operator +(PathString left, QueryString right) {
return left.Add(right);
}
/// <summary>
/// Implicitly creates a new PathString from the given string.
/// </summary>
/// <param name="s"></param>
public static implicit operator PathString(string s)
=> ConvertFromString(s);
/// <summary>
/// Implicitly calls ToString().
/// </summary>
/// <param name="path"></param>
public static implicit operator string(PathString path)
=> path.ToString();
internal static PathString ConvertFromString(string s)
=> string.IsNullOrEmpty(s) ? new PathString(s) : FromUriComponent(s);
}
internal sealed class PathStringConverter : TypeConverter {
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string)
? true
: base.CanConvertFrom(context, sourceType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
=> value is string
? PathString.ConvertFromString((string)value)
: base.ConvertFrom(context, culture, value);
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
=> destinationType == typeof(string)
? value.ToString()
: base.ConvertTo(context, culture, value, destinationType);
}
}
| |
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using Decal.Filters;
using Decal.Interop.Core;
//using Decal.Interop.Inject;
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Zegeger.Data;
using Zegeger.Decal;
using Zegeger.Diagnostics;
using Zegeger.Decal.Chat;
using Zegeger.Decal.Data;
using Zegeger.Decal.VVS;
using Zegeger.Versioning;
using Zegeger.Decal.Hotkey;
using Zegeger.Decal.Spells;
namespace Zegeger.Decal.Plugins.AgentU
{
public enum PluginState
{
Init,
Starting,
Running,
ShuttingDown,
ShutDown,
Unknown
}
public partial class PluginCore : PluginBase
{
internal static PluginHost MyHost;
internal static IView View;
internal static FileService fileService;
List<Component> ComponentList;
SettingsComponent settingsComp;
PluginState State;
EchoFilter Echo;
Updater UpdateChecker;
internal static ChatType NormalType;
internal static ChatType ErrorType;
internal const string PluginName = "AgentU";
internal const string ShortPluginName = "AU";
internal const string PluginVersion = "1.0.0.0";
internal const string PluginAuthor = "Zegeger of Harvestgain";
internal const string CommandPrefix = "au";
private int filesUpdated;
private VersionNumber latestVersion;
protected override void Startup()
{
try
{
State = PluginState.Init;
MyHost = Host;
fileService = Core.FileService as FileService;
ComponentList = new List<Component>();
string dllPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6) + @"\";
string profilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\Decal Plugins\Zegeger\" + PluginName + @"\";
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Zegeger\" + PluginName + @"\";
TraceLogger.StartUp(appDataPath + @"Logs");
TraceLogger.LoggingLevel = TraceLevel.Noise;
TraceLogger.AutoFlush = true;
TraceLogger.Write("START");
TraceLogger.Write("dllPath: " + dllPath, TraceLevel.Verbose);
TraceLogger.Write("profilePath: " + profilePath, TraceLevel.Verbose);
TraceLogger.Write("appDataPath: " + appDataPath, TraceLevel.Verbose);
Constants.StartUp(appDataPath + @"RefData\");
if (Constants.AutoUpdate)
{
//Update(appDataPath);
}
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Zegeger.Decal.Plugins." + PluginName + ".ViewXML.mainView.xml"))
{
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
View = Zegeger.Decal.VVS.ViewSystemSelector.CreateViewResource(PluginCore.MyHost, result);
}
}
ZTimer.StartUp(Core);
Action.StartUp(Core);
Enchantments.Initialize(Core);
DataHandler.StartUp(profilePath + @"Data\");
SettingsProfileHandler.StartUp(profilePath + @"Settings\");
Core.PluginInitComplete += new EventHandler<EventArgs>(Core_PluginInitComplete);
Core.CharacterFilter.LoginComplete += new EventHandler(CharacterFilter_LoginComplete);
CommandHandler.StartUp(Core, CommandPrefix, new string[] { PluginName + " " + PluginVersion, "By " + PluginAuthor }, WriteToChat);
Echo = new EchoFilter(Core);
settingsComp = new SettingsComponent(Core, View);
RegisterComponent(settingsComp);
RegisterComponent(new Items(Core, View));
RegisterComponent(new Util(Core, Host, View, dllPath));
RegisterComponent(new OneTouch(Core, View));
State = PluginState.Starting;
TraceLogger.Write("Startup End");
}
catch (Exception ex)
{
TraceLogger.Write(ex);
WriteToChat(ex.ToString());
}
}
private void RegisterComponent(Component c)
{
c.ComponentStateChange += new ComponentStateChangeEvent(ComponentStateChange);
ComponentList.Add(c);
}
void Update(string appDataPath)
{
TraceLogger.Write("Enter. Beginning up check to " + Constants.UpdateURL);
try
{
UpdateChecker = new Updater(Constants.UpdateURL);
UpdateChecker.BeginCheckVersions(PluginName, PluginVersion, ir =>
{
try
{
TraceLogger.Write("Check Versions Complete");
UpdateCheckResults results = UpdateChecker.EndCheckVersions(ir);
TraceLogger.Write("Check Versions result: " + results.Status);
if (results.Status == ResultStatus.Success)
{
List<UpdateResult> removalList = new List<UpdateResult>();
foreach (UpdateResult result in results.Results)
{
if (result.action == UpdateAction.Application)
{
TraceLogger.Write("Current application version: " + result.newVersion);
latestVersion = new VersionNumber(result.newVersion);
removalList.Add(result);
}
else
{
if (Constants.FileInfo.ContainsKey(result.fileName))
{
if (result.action == UpdateAction.CreateUpdate)
{
if (new VersionNumber(Constants.FileInfo[result.fileName]) >= new VersionNumber(result.newVersion))
{
TraceLogger.Write("Existing file is up-to-date: " + result.fileName);
removalList.Add(result);
}
}
else if (result.action == UpdateAction.Delete)
{
TraceLogger.Write("Existing file should be removed: " + result.fileName);
File.Move(appDataPath + @"RefData\" + result.fileName, appDataPath + @"RefData\" + result.fileName + ".bak");
removalList.Add(result);
}
}
}
}
foreach (UpdateResult file in removalList)
{
results.Results.Remove(file);
}
filesUpdated = results.Results.Count;
if (results.Results.Count > 0)
{
TraceLogger.Write("Beginning to fetch files, count: " + results.Results.Count);
UpdateChecker.BeginFetchFiles(results.Results, ir2 =>
{
try
{
TraceLogger.Write("Fetch Files Complete");
FilesFetchedResults fileResult = UpdateChecker.EndFetchFiles(ir2);
TraceLogger.Write("Fetch Files result: " + fileResult.Status);
if (fileResult.Status == ResultStatus.Success)
{
bool restart = false;
foreach (FetchedFile file in fileResult.Files)
{
if (file.fileName != "Application" && file.file.Length > 0)
{
TraceLogger.Write("Deleting existing backup file: " + appDataPath + @"RefData\" + file.fileName + ".bak");
File.Delete(appDataPath + @"RefData\" + file.fileName + ".bak");
TraceLogger.Write("Backing up existing file: " + appDataPath + @"RefData\" + file.fileName);
File.Move(appDataPath + @"RefData\" + file.fileName, appDataPath + @"RefData\" + file.fileName + ".bak");
TraceLogger.Write("Writing new file: " + appDataPath + @"RefData\" + file.fileName);
using (FileStream fileStream = new FileStream(appDataPath + @"RefData\" + file.fileName, FileMode.Create))
{
fileStream.Write(file.file, 0, file.file.Length);
fileStream.Close();
TraceLogger.Write("File written");
restart = true;
}
}
}
if (restart)
{
TraceLogger.Write("Restarting plugin after updating data files.", TraceLevel.Warning);
Shutdown();
Startup();
}
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}, null);
}
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}, null);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
void ComponentStateChange(object sender, ComponentStateChangeEventArgs e)
{
Component component = (Component)sender;
TraceLogger.Write("Enter Component: " + component.ComponentName + ", State: " + e.NewState.ToString());
if (State == PluginState.Running && e.NewState != ComponentState.Running && component.Critical == true)
{
TraceLogger.Write("Critical component in incorrect state! Shutting down plugin!", TraceLevel.Fatal);
Termiante("Critical component transitioned to an incorrect state " + component.ComponentName);
}
TraceLogger.Write("Exit");
}
void Core_PluginInitComplete(object sender, EventArgs e)
{
TraceLogger.Write("Enter");
try
{
ZChatWrapper.Initialize(Core, PluginName);
TraceLogger.Write("ChatMode: " + ZChatWrapper.ChatMode.ToString());
NormalType = ZChatWrapper.CreateChatType(Constants.ChatColors("Purple"), true, false, false, false, false);
ErrorType = ZChatWrapper.CreateChatType(Constants.ChatColors("DarkRed"), true, false, false, false, false);
foreach (Component c in ComponentList)
{
c.PostPluginInit();
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
void CharacterFilter_LoginComplete(object sender, EventArgs e)
{
TraceLogger.Write("Enter");
try
{
ZHotkeyWrapper.Initialize(PluginName, ShortPluginName, Core);
DataHandler.PostLogin(Core.CharacterFilter.Name, Core.CharacterFilter.Server);
SettingsProfileHandler.PostLogin(settingsComp.SettingId);
foreach (Component c in ComponentList)
{
c.PostLogin();
}
foreach (Component c in ComponentList)
{
if (c.Critical && c.State != ComponentState.Running)
{
TraceLogger.Write("Critical component in incorrect state! Shutting down plugin!", TraceLevel.Fatal);
Termiante("Critical component failed to load properly " + c.ComponentName);
return;
}
}
State = PluginState.Running;
WriteToChat("Plugin Loaded! Type /" + CommandPrefix + " help for commands.");
if (latestVersion != null)
{
if (new VersionNumber(PluginVersion) < latestVersion)
{
WriteToChat("There is a newer version (" + latestVersion.ToString() + ") available. Please download it from " + Constants.DownloadURL);
}
}
if (filesUpdated > 0)
{
WriteToChat(filesUpdated.ToString() + " files updated.");
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit");
}
private void Termiante(string error = "")
{
WriteToChatError("An error occured: " + error + ". Terminating plugin operation...");
Shutdown();
}
protected override void Shutdown()
{
TraceLogger.Write("Shutdown Start");
try
{
if (State != PluginState.ShutDown && State != PluginState.ShuttingDown)
{
State = PluginState.ShuttingDown;
foreach (Component c in ComponentList)
{
c.Shutdown();
}
ComponentList.Clear();
SettingsProfileHandler.Shutdown();
DataHandler.Shutdown();
Enchantments.Shutdown();
ZHotkeyWrapper.Shutdown();
CommandHandler.Shutdown();
Core.PluginInitComplete -= new EventHandler<EventArgs>(Core_PluginInitComplete);
Core.CharacterFilter.LoginComplete -= new EventHandler(CharacterFilter_LoginComplete);
ZChatWrapper.Dispose();
Constants.Shutdown();
MyHost = null;
TraceLogger.Write("Shutdown End");
TraceLogger.ShutDown();
State = PluginState.ShutDown;
}
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
}
internal static void WriteToChat(string message)
{
TraceLogger.Write("Enter message: " + message, TraceLevel.Verbose);
try
{
ZChatWrapper.WriteToChat("<" + PluginName + "> " + message, NormalType);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit", TraceLevel.Verbose);
}
internal static void WriteToChatError(string message)
{
TraceLogger.Write("Enter message: " + message, TraceLevel.Error);
try
{
ZChatWrapper.WriteToChat("<" + PluginName + "> " + message, ErrorType);
}
catch (Exception ex)
{
TraceLogger.Write(ex);
}
TraceLogger.Write("Exit", TraceLevel.Verbose);
}
}
}
| |
using System.Collections.Generic;
using System.Text;
using Box2D.Collision;
using Box2D.Common;
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
internal static class b2VecHelper
{
public static CCVector2 ToCCVector2(this b2Vec2 vec)
{
return new CCVector2(vec.x, vec.y);
}
internal static Color ToColor(this b2Color color)
{
return new Color(color.r, color.g, color.b);
}
internal static CCColor4B ToCCColor4B(this b2Color color)
{
return new CCColor4B (color.r, color.g, color.b, 255);
}
}
public class CCBox2dDraw : b2Draw
{
#if WINDOWS_PHONE || OUYA
public const int CircleSegments = 16;
#else
public const int CircleSegments = 32;
#endif
internal Color TextColor = Color.White;
CCPrimitiveBatch primitiveBatch;
SpriteFont spriteFont;
List<StringData> stringData;
StringBuilder stringBuilder;
#region Structs
struct StringData
{
public object[] Args;
public Color Color;
public string S;
public int X, Y;
public StringData(int x, int y, string s, object[] args, Color color)
{
X = x;
Y = y;
S = s;
Args = args;
Color = color;
}
}
#endregion Structs
#region Constructors
public CCBox2dDraw(string spriteFontName, int ptmRatio) : base(ptmRatio)
{
primitiveBatch = new CCPrimitiveBatch(5000);
spriteFont = CCContentManager.SharedContentManager.Load<SpriteFont>(spriteFontName);
stringData = new List<StringData>();
stringBuilder = new StringBuilder();
}
#endregion Constructors
public override void DrawPolygon(b2Vec2[] vertices, int vertexCount, b2Color color)
{
if (!primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
for (int i = 0; i < vertexCount - 1; i++)
{
primitiveBatch.AddVertex(vertices[i].ToCCVector2() * PTMRatio, color.ToCCColor4B(), PrimitiveType.LineList);
primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2() * PTMRatio, color.ToCCColor4B(), PrimitiveType.LineList);
}
primitiveBatch.AddVertex(vertices[vertexCount - 1].ToCCVector2() * PTMRatio, color.ToCCColor4B(), PrimitiveType.LineList);
primitiveBatch.AddVertex(vertices[0].ToCCVector2() * PTMRatio, color.ToCCColor4B(), PrimitiveType.LineList);
}
public override void DrawSolidPolygon(b2Vec2[] vertices, int vertexCount, b2Color color)
{
if (!primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
if (vertexCount == 2)
{
DrawPolygon(vertices, vertexCount, color);
return;
}
var colorFill = color.ToCCColor4B() * 0.5f;
for (int i = 1; i < vertexCount - 1; i++)
{
primitiveBatch.AddVertex(vertices[0].ToCCVector2() * PTMRatio, colorFill, PrimitiveType.TriangleList);
primitiveBatch.AddVertex(vertices[i].ToCCVector2() * PTMRatio, colorFill, PrimitiveType.TriangleList);
primitiveBatch.AddVertex(vertices[i + 1].ToCCVector2() * PTMRatio, colorFill, PrimitiveType.TriangleList);
}
DrawPolygon(vertices, vertexCount, color);
}
public override void DrawCircle(b2Vec2 center, float radius, b2Color color)
{
if (!primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
const double increment = Math.PI * 2.0 / CircleSegments;
double theta = 0.0;
var col = color.ToCCColor4B();
CCVector2 centr = center.ToCCVector2();
for (int i = 0, count = CircleSegments; i < count; i++)
{
CCVector2 v1 = (centr + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta))) * PTMRatio;
CCVector2 v2 = (centr +
radius *
new CCVector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment))) * PTMRatio;
primitiveBatch.AddVertex(ref v1, col, PrimitiveType.LineList);
primitiveBatch.AddVertex(ref v2, col, PrimitiveType.LineList);
theta += increment;
}
}
public override void DrawSolidCircle(b2Vec2 center, float radius, b2Vec2 axis, b2Color color)
{
if (!primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
const double increment = Math.PI * 2.0 / CircleSegments;
double theta = 0.0;
var colorFill = color.ToCCColor4B() * 0.5f;
var centr = center.ToCCVector2();
CCVector2 v0 = center.ToCCVector2() + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta));
theta += increment;
v0 *= PTMRatio;
for (int i = 1; i < CircleSegments - 1; i++)
{
var v1 = centr + radius * new CCVector2((float) Math.Cos(theta), (float) Math.Sin(theta));
v1 *= PTMRatio;
var v2 = centr +
radius * new CCVector2((float) Math.Cos(theta + increment), (float) Math.Sin(theta + increment));
v2 *= PTMRatio;
primitiveBatch.AddVertex(ref v0, colorFill, PrimitiveType.TriangleList);
primitiveBatch.AddVertex(ref v1, colorFill, PrimitiveType.TriangleList);
primitiveBatch.AddVertex(ref v2, colorFill, PrimitiveType.TriangleList);
theta += increment;
}
DrawCircle(center, radius, color);
DrawSegment(center, center + axis * radius, color);
}
public override void DrawSegment(b2Vec2 p1, b2Vec2 p2, b2Color color)
{
if (!primitiveBatch.IsReady())
{
throw new InvalidOperationException("BeginCustomDraw must be called before drawing anything.");
}
primitiveBatch.AddVertex(p1.ToCCVector2() * PTMRatio , color.ToCCColor4B(), PrimitiveType.LineList);
primitiveBatch.AddVertex(p2.ToCCVector2() * PTMRatio, color.ToCCColor4B(), PrimitiveType.LineList);
}
public override void DrawTransform(b2Transform xf)
{
const float axisScale = 0.4f;
b2Vec2 p1 = xf.p;
b2Vec2 p2 = p1 + axisScale * xf.q.GetXAxis();
DrawSegment(p1, p2, new b2Color(1, 0, 0));
p2 = p1 + axisScale * xf.q.GetYAxis();
DrawSegment(p1, p2, new b2Color(0, 1, 0));
}
public void DrawString(int x, int y, string format, params object[] objects)
{
stringData.Add(new StringData(x, y, format, objects, Color.White));
}
public void DrawPoint(b2Vec2 p, float size, b2Color color)
{
b2Vec2[] verts = new b2Vec2[4];
float hs = size / 2.0f;
verts[0] = p + new b2Vec2(-hs, -hs);
verts[1] = p + new b2Vec2(hs, -hs);
verts[2] = p + new b2Vec2(hs, hs);
verts[3] = p + new b2Vec2(-hs, hs);
DrawSolidPolygon(verts, 4, color);
}
public void DrawAABB(b2AABB aabb, b2Color p1)
{
b2Vec2[] verts = new b2Vec2[4];
verts[0] = new b2Vec2(aabb.LowerBound.x, aabb.LowerBound.y);
verts[1] = new b2Vec2(aabb.UpperBound.x, aabb.LowerBound.y);
verts[2] = new b2Vec2(aabb.UpperBound.x, aabb.UpperBound.y);
verts[3] = new b2Vec2(aabb.LowerBound.x, aabb.UpperBound.y);
DrawPolygon(verts, 4, p1);
}
public void Begin()
{
primitiveBatch.Begin();
}
public void End()
{
primitiveBatch.End();
// var _batch = CCDrawManager.SharedDrawManager.SpriteBatch;
//
// _batch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
//
// for (int i = 0; i < stringData.Count; i++)
// {
// stringBuilder.Length = 0;
// stringBuilder.AppendFormat(stringData[i].S, stringData[i].Args);
// _batch.DrawString(spriteFont, stringBuilder, new Vector2(stringData[i].X, stringData[i].Y),
// stringData[i].Color);
// }
//
// _batch.End();
stringData.Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using BTDB.Collections;
using BTDB.FieldHandler;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
using Xunit;
namespace BTDBTest
{
public class ObjectDbTableUpgradeTest : IDisposable
{
readonly IKeyValueDB _lowDb;
IObjectDB _db;
StructList<string> _fieldHandlerLoggerMessages;
public ObjectDbTableUpgradeTest()
{
_lowDb = new InMemoryKeyValueDB();
OpenDb();
}
public void Dispose()
{
Assert.Empty(_fieldHandlerLoggerMessages);
_db.Dispose();
_lowDb.Dispose();
}
void ApproveFieldHandlerLoggerMessages([CallerMemberName] string? testName = null)
{
Assent.Extensions.Assent(this, string.Join('\n', _fieldHandlerLoggerMessages) + "\n", null, testName);
_fieldHandlerLoggerMessages.Clear();
}
void ReopenDb()
{
_db.Dispose();
OpenDb();
}
void OpenDb()
{
_db = new ObjectDB();
_db.Open(_lowDb, false,
new DBOptions().WithoutAutoRegistration()
.WithFieldHandlerLogger(new DefaultFieldHandlerLogger(s => _fieldHandlerLoggerMessages.Add(s))));
}
public class JobV1
{
[PrimaryKey(1)] public ulong Id { get; set; }
public string? Name { get; set; }
}
public interface IJobTable1 : IRelation<JobV1>
{
void Insert(JobV1 job);
}
public class JobV2
{
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Name")] public string Name { get; set; }
[SecondaryKey("Cost", IncludePrimaryKeyOrder = 1)]
public uint Cost { get; set; }
}
public interface IJobTable2 : IRelation<JobV2>
{
void Insert(JobV2 job);
JobV2 FindByNameOrDefault(string name);
JobV2 FindByCostOrDefault(ulong id, uint cost);
IEnumerator<JobV2> ListByCost(AdvancedEnumeratorParam<uint> param);
}
public class JobIncompatible
{
[PrimaryKey(1)] public Guid Id { get; set; }
}
public interface IJobTableIncompatible : IRelation<JobIncompatible>
{
void Insert(JobIncompatible job);
}
[Fact]
public void ChangeOfPrimaryKeyIsNotSupported()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1>("Job");
var jobTable = creator(tr);
var job = new JobV1 { Id = 11, Name = "Code" };
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
Assert.Throws<BTDBException>(() => tr.InitRelation<IJobTableIncompatible>("Job"));
}
}
[Fact]
public void NewIndexesAreAutomaticallyGenerated()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1>("Job");
var jobTable = creator(tr);
var job = new JobV1 { Id = 11, Name = "Code" };
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 { Id = 21, Name = "Build", Cost = 42 };
jobTable.Insert(job);
var j = jobTable.FindByNameOrDefault("Code");
Assert.Equal("Code", j.Name);
j = jobTable.FindByCostOrDefault(21, 42);
Assert.Equal("Build", j.Name);
var en = jobTable.ListByCost(new AdvancedEnumeratorParam<uint>(EnumerationOrder.Ascending));
Assert.True(en.MoveNext());
Assert.Equal(0u, en.Current.Cost);
Assert.True(en.MoveNext());
Assert.Equal(42u, en.Current.Cost);
tr.Commit();
}
}
public class Car
{
[PrimaryKey(1)] public ulong CompanyId { get; set; }
[PrimaryKey(2)] public ulong Id { get; set; }
public string Name { get; set; }
}
public interface ICarTable : IRelation<Car>
{
void Insert(Car car);
Car FindById(ulong companyId, ulong id);
}
public enum SimpleEnum
{
One = 1,
Two = 2
}
public enum SimpleEnumV2
{
Eins = 1,
Zwei = 2,
Drei = 3
}
public enum SimpleEnumV3
{
Two = 2,
Three = 3,
Four = 4
}
public class ItemWithEnumInKey
{
[PrimaryKey] public SimpleEnum Key { get; set; }
public string Value { get; set; }
}
public class ItemWithEnumInKeyV2
{
[PrimaryKey] public SimpleEnumV2 Key { get; set; }
public string Value { get; set; }
}
public class ItemWithEnumInKeyV3
{
[PrimaryKey] public SimpleEnumV3 Key { get; set; }
public string Value { get; set; }
}
public interface ITableWithEnumInKey : IRelation<ItemWithEnumInKey>
{
void Insert(ItemWithEnumInKey person);
}
public interface ITableWithEnumInKeyV2 : IRelation<ItemWithEnumInKeyV2>
{
ItemWithEnumInKeyV2 FindById(SimpleEnumV2 key);
}
public interface ITableWithEnumInKeyV3 : IRelation<ItemWithEnumInKeyV3>
{
}
[Fact]
public void UpgradePrimaryKeyWithEnumWorks()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKey>("EnumWithItemInKey");
var table = creator(tr);
table.Insert(new ItemWithEnumInKey { Key = SimpleEnum.One, Value = "A" });
table.Insert(new ItemWithEnumInKey { Key = SimpleEnum.Two, Value = "B" });
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKeyV2>("EnumWithItemInKey");
var table = creator(tr);
Assert.Equal("A", table.FindById(SimpleEnumV2.Eins).Value);
Assert.False(table.Upsert(new ItemWithEnumInKeyV2 { Key = SimpleEnumV2.Zwei, Value = "B2" }));
Assert.True(table.Upsert(new ItemWithEnumInKeyV2 { Key = SimpleEnumV2.Drei, Value = "C" }));
Assert.Equal(3, table.Count);
}
}
[Fact]
public void UpgradePrimaryKeyWithIncompatibleEnumNotWork()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKey>("EnumWithItemInKeyIncompatible");
var table = creator(tr);
table.Insert(new ItemWithEnumInKey { Key = SimpleEnum.One, Value = "A" });
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var ex = Assert.Throws<BTDBException>(() =>
tr.InitRelation<ITableWithEnumInKeyV3>("EnumWithItemInKeyIncompatible"));
Assert.Contains("Field 'Key'", ex.Message);
}
}
public class JobV21
{
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Name", Order = 2)] public string Name { get; set; }
[SecondaryKey("Name", Order = 1)]
[SecondaryKey("Cost", IncludePrimaryKeyOrder = 1)]
public uint Cost { get; set; }
}
public interface IJobTable21 : IRelation<JobV21>
{
void Insert(JobV21 job);
JobV21 FindByNameOrDefault(uint cost, string name);
}
[Fact]
public void ModifiedIndexesAreRecalculated()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 { Id = 11, Name = "Code", Cost = 1000 };
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable21>("Job");
var jobTable = creator(tr);
var j = jobTable.FindByNameOrDefault(1000, "Code");
Assert.NotNull(j);
Assert.Equal("Code", j.Name);
tr.Commit();
}
}
public class JobV3
{
public JobV3()
{
Status = 100;
}
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Status")] public int Status { get; set; }
}
public interface IJobTable3 : IRelation<JobV3>
{
void Insert(JobV3 job);
void RemoveById(ulong id);
}
[Fact]
public void AddedFieldIsInsertedFromDefaultObject()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 { Id = 11, Name = "Code" };
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable3>("Job");
var jobTable = creator(tr);
jobTable.RemoveById(11);
Assert.Equal(0, jobTable.Count);
}
}
public class JobV31
{
public JobV31()
{
Status = 100;
}
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Status")]
[SecondaryKey("ExpiredStatus", Order = 2)]
public int Status { get; set; }
[SecondaryKey("ExpiredStatus", Order = 1)]
public bool IsExpired { get; set; }
}
public interface IJobTable31 : IRelation<JobV31>
{
void Insert(JobV31 job);
void RemoveById(ulong id);
JobV31? FindByExpiredStatusOrDefault(bool isExpired, int status);
}
[Fact]
public void NewIndexesOnNewFieldAreDeletedWhenItemWasDeleted()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable3>("Job");
var jobTable = creator(tr);
var job1 = new JobV3 { Id = 11, Status = 300 };
jobTable.Insert(job1);
var job2 = new JobV3 { Id = 12, Status = 200 };
jobTable.Insert(job2);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable31>("Job");
var jobTable = creator(tr);
jobTable.RemoveById(11);
Assert.Equal(1, jobTable.Count);
Assert.Null(jobTable.FindByExpiredStatusOrDefault(false, 300));
var item = jobTable.FindByExpiredStatusOrDefault(false, 200);
Assert.Equal(12ul, item.Id);
tr.Commit();
}
}
public class JobV1s
{
[PrimaryKey(1)] public ulong Id { get; set; }
[PersistedName("Name")] public List<string> Names { get; set; }
}
public interface IJobTable1s : IRelation<JobV1s>
{
}
[Fact]
public void ConvertsSingularToList()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1>("Job");
var jobTable = creator(tr);
var job1 = new JobV1 { Id = 11, Name = "A" };
jobTable.Insert(job1);
var job2 = new JobV1 { Id = 12, Name = null };
jobTable.Insert(job2);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1s>("Job");
var jobTable = creator(tr);
Assert.Equal(2, jobTable.Count);
Assert.Equal(new[] { "A" }, jobTable.First().Names);
Assert.Equal(Array.Empty<string>(), jobTable.Last().Names);
}
}
public class EnumsInKeys1
{
[PrimaryKey(1)] public ulong Id { get; set; }
public Dictionary<SimpleEnum, int>? E { get; set; }
}
public interface IEnumsInKeys1Table : IRelation<EnumsInKeys1>
{
}
public class EnumsInKeys2
{
[PrimaryKey(1)] public ulong Id { get; set; }
public Dictionary<SimpleEnumV2, int>? E { get; set; }
}
public interface IEnumsInKeys2Table : IRelation<EnumsInKeys2>
{
}
[Fact]
public void EnumsInDictionaryKeysIncompatibleUpgradeDoesNotWorkButAtLeastReportProblem()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IEnumsInKeys1Table>("Enums");
var eTable = creator(tr);
var e = new EnumsInKeys1 { Id = 1, E = new Dictionary<SimpleEnum, int> { { SimpleEnum.One, 1 } } };
eTable.Upsert(e);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IEnumsInKeys2Table>("Enums");
var eTable = creator(tr);
Assert.Null(eTable.First().E);
Assert.Equal(1, eTable.Count);
var e = new EnumsInKeys2 { Id = 1, E = new Dictionary<SimpleEnumV2, int> { { SimpleEnumV2.Drei, 1 } } };
eTable.Upsert(e);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IEnumsInKeys1Table>("Enums");
var eTable = creator(tr);
Assert.Equal(1, eTable.Count);
}
ApproveFieldHandlerLoggerMessages();
}
}
}
| |
// F#: changed multiplication from decimal*int to int*int
// unfortunately this fails because the following code doesn't compile
// (type arguments 'k and 'v are restricted to values from use in the 'Test' class)
// otherwise it should be correct
/*
#light
open System.Collections.Generic
type MyDictionary<'K, 'V> =
class
inherit Dictionary<'K, 'V> as base
new() = {}
end
and Test =
class
member this.MyMethod() =
let d = new MyDictionary<string, List<string>>()
0
end
*/
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Globalization;
using Microsoft.Samples.CodeDomTestSuite;
public class GenericsTest : CodeDomTestTree {
public override string Comment
{
get
{
return "F# doesn't permit Dictionary<_,_>() to be called without an equality constraint";
}
}
public override TestTypes TestType
{
get {
return TestTypes.Whidbey;
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override string Name {
get {
return "GenericsTest";
}
}
public override string Description {
get {
return "Tests generating generics from CodeDom.";
}
}
public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
// GENERATES (C#):
// namespace TestNamespace {
// using System;
// using System.Collections.Generic;
//
//
// public class MyDictionary<K, V> : Dictionary<K, V>
// where K : System.IComparable, IComparable<K>, new ()
// where V : IList<string> {
//
// public virtual int Calculate<S, T>(int value1, int value2)
// where S : new()
// {
// return (value1 * value2);
// }
// }
//
// public class Test {
//
// public virtual int MyMethod() {
// int dReturn;
// MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>();
// dReturn = dict.Calculate<int, int>(2.5, 11);
// return dReturn;
// }
// }
// }
if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) {
return;
}
CodeNamespace ns = new CodeNamespace("TestNamespace");
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
cu.Namespaces.Add (ns);
// Declare a generic class
CodeTypeDeclaration class1 = new CodeTypeDeclaration();
class1.Name = "MyDictionary";
class1.BaseTypes.Add( new CodeTypeReference("Dictionary",
new CodeTypeReference[] { new CodeTypeReference("K"), new CodeTypeReference("V"),}));
CodeTypeParameter kType = new CodeTypeParameter("K");
kType.HasConstructorConstraint= true;
kType.Constraints.Add( new CodeTypeReference(typeof(IComparable)));
kType.CustomAttributes.Add(new CodeAttributeDeclaration(
"System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));
CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
iComparableT.TypeArguments.Add(new CodeTypeReference(kType));
kType.Constraints.Add(iComparableT);
CodeTypeParameter vType = new CodeTypeParameter("V");
vType.Constraints.Add(new CodeTypeReference("IList[System.String]"));
class1.TypeParameters.Add(kType);
class1.TypeParameters.Add(vType);
ns.Types.Add(class1);
// declare a generic method
CodeMemberMethod method = new CodeMemberMethod();
CodeTypeParameter sType = new CodeTypeParameter("S");
sType.HasConstructorConstraint = true;
CodeTypeParameter tType = new CodeTypeParameter("T");
sType.HasConstructorConstraint = true;
method.Name = "Calculate";
method.TypeParameters.Add(sType);
method.TypeParameters.Add(tType);
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value1"));
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value2"));
method.ReturnType = new CodeTypeReference(typeof(int));
method.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new
CodeVariableReferenceExpression("value1"), CodeBinaryOperatorType.Multiply, new
CodeVariableReferenceExpression("value2"))));
method.Attributes = MemberAttributes.Public;
class1.Members.Add(method);
CodeTypeDeclaration class2 = new CodeTypeDeclaration();
class2.Name = "Test";
AddScenario ("CheckMyMethod");
CodeMemberMethod method2 = new CodeMemberMethod();
method2.Name = "MyMethod";
method2.Attributes = MemberAttributes.Public;
method2.ReturnType = new CodeTypeReference(typeof(int));
method2.Statements.Add( new CodeVariableDeclarationStatement(typeof(int), "dReturn"));
CodeTypeReference myClass = new CodeTypeReference( "MyDictionary",
new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List",
new CodeTypeReference[] {new CodeTypeReference("System.String") })} );
method2.Statements.Add( new CodeVariableDeclarationStatement( myClass, "dict", new CodeObjectCreateExpression(myClass) ));
method2.Statements.Add(new CodeAssignStatement( new CodeVariableReferenceExpression("dReturn"),
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("dict"), "Calculate",
new CodeTypeReference[] {
new CodeTypeReference("System.Int32"),
new CodeTypeReference("System.Int32"),}),
new CodeExpression[]{new CodePrimitiveExpression(25), new CodePrimitiveExpression(11)})));
method2.Statements.Add (new CodeMethodReturnStatement(new CodeVariableReferenceExpression("dReturn")));
class2.Members.Add(method2);
ns.Types.Add(class2);
#endif
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
#if WHIDBEY
if (provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) {
object genObject;
Type genType;
AddScenario ("InstantiateTest");
if (!FindAndInstantiate ("TestNamespace.Test", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTest");
// verify scenario with 'new' attribute
if (VerifyMethod(genType, genObject, "MyMethod", null, 275)) {
VerifyScenario ("CheckMyMethod");
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using Imported.PeanutButter.Utils;
using NExpect.Implementations;
using NExpect.Interfaces;
using NExpect.MatcherLogic;
using static NExpect.Implementations.MessageHelpers;
// ReSharper disable MemberCanBePrivate.Global
namespace NExpect
{
/// <summary>
/// Provides matchers for testing equality
/// </summary>
public static class EqualityProviderMatchers
{
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this ITo<T> be,
object expected)
{
return be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this ITo<T> be,
object expected,
string customMessage)
{
return be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this ITo<T> be,
object expected,
Func<string> customMessageGenerator)
{
return be.AddMatcher(
CreateRefEqualMatcherFor<T>(
expected,
customMessageGenerator
)
);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(this IToAfterNot<T> be, object expected)
{
return be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this IToAfterNot<T> be,
object expected,
string customMessage)
{
return be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this IToAfterNot<T> be,
object expected,
Func<string> customMessageGenerator)
{
return be.AddMatcher(
CreateRefEqualMatcherFor<T>(
expected,
customMessageGenerator
)
);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(this INotAfterTo<T> be, object expected)
{
return be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this INotAfterTo<T> be,
object expected,
string customMessage)
{
return be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static IMore<T> Be<T>(
this INotAfterTo<T> be,
object expected,
Func<string> customMessageGenerator)
{
return be.AddMatcher(
CreateRefEqualMatcherFor<T>(
expected,
customMessageGenerator
)
);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static void Be<T>(
this ICollectionTo<T> be,
object expected)
{
be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage"></param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static void Be<T>(
this ICollectionTo<T> be,
object expected,
string customMessage)
{
be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between your actual and the provided expected value
/// </summary>
/// <param name="be">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator"></param>
/// <typeparam name="T">Type of the object being tested</typeparam>
public static void Be<T>(
this ICollectionTo<T> be,
object expected,
Func<string> customMessageGenerator)
{
be.AddMatcher(CreateCollectionRefEqualMatcherFor<T>(expected, customMessageGenerator));
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionToAfterNot<T> be,
object expected
)
{
be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <param name="customMessage"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionToAfterNot<T> be,
object expected,
string customMessage
)
{
be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <param name="customMessageGenerator"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionToAfterNot<T> be,
object expected,
Func<string> customMessageGenerator
)
{
be.AddMatcher(CreateCollectionRefEqualMatcherFor<T>(expected, customMessageGenerator));
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionNotAfterTo<T> be,
object expected
)
{
be.Be(expected, NULL_STRING);
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <param name="customMessage"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionNotAfterTo<T> be,
object expected,
string customMessage
)
{
be.Be(expected, () => customMessage);
}
/// <summary>
/// Performs reference equality checking between actual and expected values
/// </summary>
/// <param name="be"></param>
/// <param name="expected"></param>
/// <param name="customMessageGenerator"></param>
/// <typeparam name="T"></typeparam>
public static void Be<T>(
this ICollectionNotAfterTo<T> be,
object expected,
Func<string> customMessageGenerator
)
{
be.AddMatcher(CreateCollectionRefEqualMatcherFor<T>(expected, customMessageGenerator));
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T expected
)
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T expected,
string customMessage
)
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T? expected
) where T : struct
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add into failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T? expected,
string customMessage
) where T : struct
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Custom message to add into failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T? expected,
Func<string> customMessageGenerator
) where T : struct
{
return continuation.AddMatcher(
GenerateNullableEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T expected
)
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T expected,
string customMessage
)
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T expected,
Func<string> customMessageGenerator
)
{
return continuation.AddMatcher(
GenerateEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T? expected
) where T : struct
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T? expected,
string customMessage
) where T : struct
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this IToAfterNot<T> continuation,
T? expected,
Func<string> customMessageGenerator
) where T : struct
{
return continuation.AddMatcher(
GenerateNullableEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T expected
)
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T expected,
string customMessage
)
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T expected,
Func<string> customMessageGenerator
)
{
return continuation.AddMatcher(
GenerateEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T? expected
) where T : struct
{
return continuation.Equal(expected, NULL_STRING);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T? expected,
string customMessage
) where T : struct
{
return continuation.Equal(expected, () => customMessage);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to add to failure messages</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this INotAfterTo<T> continuation,
T? expected,
Func<string> customMessageGenerator
) where T : struct
{
return continuation.AddMatcher(
GenerateNullableEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Performs equality checking -- the end of .To.Equal()
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Custom message to include when failing</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Equal<T>(
this ITo<T> continuation,
T expected,
Func<string> customMessageGenerator
)
{
return continuation.AddMatcher(
GenerateEqualityMatcherFor(expected, customMessageGenerator)
);
}
/// <summary>
/// Tests if a value is null
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="customMessage">Custom message to include when failing</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Null<T>(
this IBe<T> continuation,
string customMessage
)
{
return continuation.Null(() => customMessage);
}
/// <summary>
/// Tests if a value is null
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="customMessageGenerator">Generates a custom message to include when failing</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Null<T>(
this IBe<T> continuation,
Func<string> customMessageGenerator
)
{
continuation.AddMatcher(
actual =>
{
var passed = actual == null;
return new MatcherResult(
passed,
FinalMessageFor(
() => passed
? new[] { "Expected not to get null" }
: new[] { "Expected null but got", Quote(actual) },
customMessageGenerator)
);
});
return continuation.More();
}
/// <summary>
/// Tests if a value is null
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <typeparam name="T">Type of object being tested</typeparam>
public static IMore<T> Null<T>(this IBe<T> continuation)
{
return continuation.Null(NULL_STRING);
}
/// <summary>
/// Last part of the .To.Be.Equal.To() chain
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <typeparam name="T">Object type being tested</typeparam>
public static IMore<T> To<T>(
this IEqualityContinuation<T> continuation,
T expected
)
{
return continuation.To(expected, NULL_STRING);
}
/// <summary>
/// Last part of the .To.Be.Equal.To() chain
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessage">Custom message to include when failing</param>
/// <typeparam name="T">Object type being tested</typeparam>
public static IMore<T> To<T>(
this IEqualityContinuation<T> continuation,
T expected,
string customMessage
)
{
return continuation.To(expected, () => customMessage);
}
/// <summary>
/// Last part of the .To.Be.Equal.To() chain
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="expected">Expected value</param>
/// <param name="customMessageGenerator">Generates a custom message to include when failing</param>
/// <typeparam name="T">Object type being tested</typeparam>
public static IMore<T> To<T>(
this IEqualityContinuation<T> continuation,
T expected,
Func<string> customMessageGenerator
)
{
return continuation.AddMatcher(
actual =>
{
var passed = (actual == null && expected == null) ||
(actual?.Equals(expected) ?? false);
return new MatcherResult(
passed,
FinalMessageFor(
() => new[]
{
"Expected",
Quote(actual),
$"{passed.AsNot()}to equal",
Quote(expected)
},
customMessageGenerator
));
});
}
/// <summary>
/// Tests if a string is empty, with a provided custom error message
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="customMessage">Custom message to include when failing</param>
public static void Empty(
this IBe<string> continuation,
string customMessage)
{
continuation.Empty(() => customMessage);
}
/// <summary>
/// Tests if a string is empty, with a provided custom error message
/// </summary>
/// <param name="continuation">Continuation to operate on</param>
/// <param name="customMessageGenerator">Generates a custom message to include when failing</param>
public static void Empty(
this IBe<string> continuation,
Func<string> customMessageGenerator)
{
continuation.AddMatcher(
actual =>
{
var passed = actual == "";
return new MatcherResult(
passed,
FinalMessageFor(
() => passed
? new[] { "Expected not to be empty" }
: new[] { "Expected empty string but got", Quote(actual) },
customMessageGenerator)
);
});
}
/// <summary>
/// Tests if a string is empty
/// </summary>
/// <param name="continuation"></param>
public static void Empty(this IBe<string> continuation)
{
continuation.Empty(NULL_STRING);
}
/// <summary>
/// Tests if a string is null or empty
/// </summary>
/// <param name="nullOr"></param>
public static void Empty(
this INullOr<string> nullOr
)
{
nullOr.Empty(NULL_STRING);
}
/// <summary>
/// Tests if a string is null or empty
/// </summary>
/// <param name="nullOr"></param>
/// <param name="customMessage">Custom message to add to the final failure message</param>
public static void Empty(
this INullOr<string> nullOr,
string customMessage
)
{
nullOr.Empty(() => customMessage);
}
/// <summary>
/// Tests if a string is null or empty
/// </summary>
/// <param name="nullOr"></param>
/// <param name="customMessageGenerator">Generates a custom message to add to the final failure message</param>
public static void Empty(
this INullOr<string> nullOr,
Func<string> customMessageGenerator
)
{
nullOr.AddMatcher(
actual =>
{
var passed = string.IsNullOrEmpty(actual);
return new MatcherResult(
passed,
FinalMessageFor(
() => $"Expected {actual} {passed.AsNot()}to be null or empty",
customMessageGenerator
)
);
});
}
/// <summary>
/// Test if string is null or whitespace
/// </summary>
/// <param name="nullOr"></param>
public static void Whitespace(
this INullOr<string> nullOr
)
{
nullOr.Whitespace(NULL_STRING);
}
/// <summary>
/// Test if string is null or whitespace
/// </summary>
/// <param name="nullOr"></param>
/// <param name="customMessage">Custom message to add to the final failure message</param>
public static void Whitespace(
this INullOr<string> nullOr,
string customMessage
)
{
nullOr.Whitespace(() => customMessage);
}
/// <summary>
/// Test if string is null or whitespace
/// </summary>
/// <param name="nullOr"></param>
/// <param name="customMessageGenerator">Generates a custom message to add to the final failure message</param>
public static void Whitespace(
this INullOr<string> nullOr,
Func<string> customMessageGenerator
)
{
nullOr.AddMatcher(
actual =>
{
var passed = string.IsNullOrWhiteSpace(actual);
return new MatcherResult(
passed,
FinalMessageFor(
() => $"Expected {actual} {passed.AsNot()}to be null or whitespace",
customMessageGenerator
)
);
});
}
private static Func<T, IMatcherResult> CreateRefEqualMatcherFor<T>(
object other,
Func<string> customMessageGenerator)
{
return actual => RefCompare(actual, other, customMessageGenerator);
}
private static Func<IEnumerable<T>, IMatcherResult> CreateCollectionRefEqualMatcherFor<T>(
object other,
Func<string> customMessageGenerator)
{
return actual => RefCompare(actual, other, customMessageGenerator);
}
private static IMatcherResult RefCompare(object actual,
object other,
Func<string> customMessageGenerator)
{
var passed = ReferenceEquals(actual, other);
return new MatcherResult(
passed,
() => FinalMessageFor(
$"Expected {actual?.ToString() ?? NULL_REPLACER} {passed.AsNot()}to be the same reference as {other?.ToString() ?? NULL_REPLACER}",
customMessageGenerator()
)
);
}
private static Func<T, IMatcherResult> GenerateNullableEqualityMatcherFor<T>(
T? expected,
Func<string> customMessage
) where T : struct
{
return actual =>
{
var nullableActual = actual as T?;
return CompareForEquality(nullableActual, expected, customMessage);
};
}
internal static Func<T, IMatcherResult> GenerateEqualityMatcherFor<T>(
T expected,
Func<string> customMessageGenerator
)
{
return actual => CompareForEquality(
actual,
expected,
customMessageGenerator);
}
private static IMatcherResult CompareForEquality<T>(
T actual,
T expected,
Func<string> customMessageGenerator)
{
if (BothAreNull(actual, expected) ||
ValuesAreEqual(actual, expected))
{
return new MatcherResult(
true,
FinalMessageFor(
() => new[]
{
"Did not expect",
Quote(expected),
"but got exactly that"
},
customMessageGenerator)
);
}
var extraMessage = DifferenceHighlighting.ProvideMoreInfoFor(
actual,
expected
);
var message = new List<string>(new[]
{
"Expected",
Quote(expected),
"but got",
Quote(actual)
});
if (!string.IsNullOrWhiteSpace(extraMessage))
{
message.Add(extraMessage);
}
return new MatcherResult(
false,
FinalMessageFor(
() => message.ToArray(),
customMessageGenerator
));
}
private static bool ValuesAreEqual<T>(
T actual,
T expected)
{
if (actual == null &&
expected == null)
{
return true;
}
if (actual == null ||
expected == null)
{
return false;
}
var result = (actual.Equals(expected) ||
CollectionsAreEqual(actual, expected));
if (!result)
return false;
if (expected is DateTime expectedDateTime &&
actual is DateTime actualDateTime)
{
return expectedDateTime.Kind == actualDateTime.Kind;
}
return true;
}
private static bool CollectionsAreEqual<T>(
T actual,
T expected)
{
var actualEnumerable = new EnumerableWrapper(actual);
if (!actualEnumerable.IsValid)
{
return false;
}
var expectedEnumerable = new EnumerableWrapper(expected);
if (!expectedEnumerable.IsValid)
{
return false;
}
var actualEnumerator = actualEnumerable.GetEnumerator();
var expectedEnumerator = expectedEnumerable.GetEnumerator();
var actualHasNext = actualEnumerator.MoveNext();
var expectedHasNext = expectedEnumerator.MoveNext();
while (actualHasNext && expectedHasNext)
{
if (!ValuesAreEqual(
actualEnumerator.Current,
expectedEnumerator.Current))
{
return false;
}
actualHasNext = actualEnumerator.MoveNext();
expectedHasNext = expectedEnumerator.MoveNext();
}
return actualHasNext == expectedHasNext;
}
private static bool BothAreNull<T>(T expected, T actual)
{
return actual == null && expected == null;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type MailFolderChildFoldersCollectionRequest.
/// </summary>
public partial class MailFolderChildFoldersCollectionRequest : BaseRequest, IMailFolderChildFoldersCollectionRequest
{
/// <summary>
/// Constructs a new MailFolderChildFoldersCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public MailFolderChildFoldersCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified MailFolder to the collection via POST.
/// </summary>
/// <param name="mailFolder">The MailFolder to add.</param>
/// <returns>The created MailFolder.</returns>
public System.Threading.Tasks.Task<MailFolder> AddAsync(MailFolder mailFolder)
{
return this.AddAsync(mailFolder, CancellationToken.None);
}
/// <summary>
/// Adds the specified MailFolder to the collection via POST.
/// </summary>
/// <param name="mailFolder">The MailFolder to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created MailFolder.</returns>
public System.Threading.Tasks.Task<MailFolder> AddAsync(MailFolder mailFolder, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<MailFolder>(mailFolder, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IMailFolderChildFoldersCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IMailFolderChildFoldersCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<MailFolderChildFoldersCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Expand(Expression<Func<MailFolder, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Select(Expression<Func<MailFolder, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderChildFoldersCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;
using CppSharp.Generators.CLI;
using CppSharp.Passes;
namespace CppSharp
{
// This pass adds Equals and GetHashCode methods to classes.
// It will also add a ToString method if the insertion operator (<<)
// of the class is overloaded.
// Note that the OperatorToClassPass needs to run first in order for
// this to work.
public class ObjectOverridesPass : TranslationUnitPass
{
private Generator Generator { get; set; }
public ObjectOverridesPass(Generator generator)
{
Generator = generator;
}
private bool needsStreamInclude;
private void OnUnitGenerated(GeneratorOutput output)
{
needsStreamInclude = false;
foreach (var template in output.Outputs)
{
foreach (var block in template.FindBlocks(BlockKind.MethodBody))
{
var method = block.Object as Method;
VisitMethod(method, block);
}
if (needsStreamInclude)
{
var sourcesTemplate = template as CLISources;
if (sourcesTemplate != null)
{
foreach (var block in sourcesTemplate.FindBlocks(BlockKind.Includes))
{
block.WriteLine("#include <sstream>");
block.WriteLine("");
break;
}
break;
}
}
}
}
private void VisitMethod(Method method, Block block)
{
if (!method.IsSynthetized)
return;
var @class = (Class)method.Namespace;
if (method.Name == "GetHashCode" && method.Parameters.Count == 0)
GenerateGetHashCode(block);
if (method.Name == "Equals" && method.Parameters.Count == 1)
GenerateEquals(@class, block, method);
if (method.Name == "ToString" && method.Parameters.Count == 0)
GenerateToString(block);
}
void GenerateGetHashCode(Block block)
{
block.Write("return (int)NativePtr;");
}
void GenerateEquals(Class @class, Block block, Method method)
{
var cliTypePrinter = new CLITypePrinter(Context);
var classCliType = @class.Visit(cliTypePrinter);
block.WriteLine("if (!object) return false;");
block.WriteLine("auto obj = dynamic_cast<{0}>({1});",
classCliType, method.Parameters[0].Name);
block.NewLine();
block.WriteLine("if (!obj) return false;");
block.Write("return __Instance == obj->__Instance;");
}
void GenerateToString(Block block)
{
needsStreamInclude = true;
block.WriteLine("std::ostringstream os;");
block.WriteLine("os << *NativePtr;");
block.Write("return clix::marshalString<clix::E_UTF8>(os.str());");
}
private bool isHooked;
public override bool VisitClassDecl(Class @class)
{
// FIXME: Add a better way to hook the event
if (!isHooked)
{
Generator.OnUnitGenerated += OnUnitGenerated;
isHooked = true;
}
if (!VisitDeclaration(@class))
return false;
// We can't handle value types yet
// The generated code assumes that a NativePtr is available
if (@class.IsValueType)
return false;
foreach (var method in @class.Methods)
{
if (!IsInsertionOperator(method))
continue;
// Create the ToString method
var stringType = GetType("std::string");
if (stringType == null)
stringType = new CILType(typeof(string));
var toStringMethod = new Method()
{
Name = "ToString",
Namespace = @class,
ReturnType = new QualifiedType(stringType),
SynthKind = FunctionSynthKind.ComplementOperator,
IsProxy = true
};
toStringMethod.OverriddenMethods.Add(new Method { Name = "ToString" });
@class.Methods.Add(toStringMethod);
Diagnostics.Debug("Function converted to ToString: {0}::{1}",
@class.Name, method.Name);
break;
}
var methodEqualsParam = new Parameter
{
Name = "object",
QualifiedType = new QualifiedType(new CILType(typeof(Object)))
};
var methodEquals = new Method
{
Name = "Equals",
Namespace = @class,
ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
Parameters = new List<Parameter> { methodEqualsParam },
SynthKind = FunctionSynthKind.ComplementOperator,
IsProxy = true
};
methodEquals.OverriddenMethods.Add(new Method { Name = "Equals" });
@class.Methods.Add(methodEquals);
var methodHashCode = new Method
{
Name = "GetHashCode",
Namespace = @class,
ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Int)),
SynthKind = FunctionSynthKind.ComplementOperator,
IsProxy = true
};
methodHashCode.OverriddenMethods.Add(new Method { Name = "GetHashCode" });
@class.Methods.Add(methodHashCode);
return true;
}
private Dictionary<string, AST.Type> typeCache;
protected AST.Type GetType(string typeName)
{
if (typeCache == null)
typeCache = new Dictionary<string, AST.Type>();
AST.Type result;
if (!typeCache.TryGetValue(typeName, out result))
{
var typeDef = ASTContext.FindTypedef(typeName)
.FirstOrDefault();
if (typeDef != null)
result = new TypedefType() { Declaration = typeDef };
typeCache.Add(typeName, result);
}
return result;
}
private bool IsInsertionOperator(Method method)
{
// Do some basic check
if (!method.IsOperator)
return false;
if (method.OperatorKind != CXXOperatorKind.LessLess)
return false;
if (method.Parameters.Count != 2)
return false;
// Check that first parameter is a std::ostream&
var fstType = method.Parameters[0].Type as PointerType;
if (fstType == null)
return false;
var oStreamType = GetType("std::ostream");
if (oStreamType == null)
return false;
if (!oStreamType.Equals(fstType.Pointee))
return false;
// Check that second parameter is a const CLASS&
var sndType = method.Parameters[1].Type as PointerType;
if (sndType == null)
return false;
if (!sndType.QualifiedPointee.Qualifiers.IsConst)
return false;
var @class = method.Namespace as Class;
var classType = new TagType(@class);
if (!classType.Equals(sndType.Pointee))
return false;
return true;
}
}
}
| |
//
// Rect.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Hyena.Gui.Canvas
{
public struct Rect
{
private double x, y, w, h;
public Rect (double x, double y, double width, double height) : this ()
{
X = x;
Y = y;
Width = width;
Height = height;
}
public Rect (Point point1, Point point2) : this ()
{
X = Math.Min (point1.X, point2.X);
Y = Math.Min (point1.Y, point2.Y);
Width = Math.Abs (point2.X - point1.X);
Height = Math.Abs (point2.Y - point1.Y);
}
public Rect (Point location, Size size) : this ()
{
X = location.X;
Y = location.Y;
Width = size.Width;
Height = size.Height;
}
public override string ToString ()
{
if (IsEmpty) {
return "Empty";
}
return String.Format ("{0}+{1},{2}x{3}", x, y, w, h);
}
public double X {
get { return x; }
set { x = value; }
}
public double Y {
get { return y; }
set { y = value; }
}
public double Width {
get { return w; }
set {
if (value < 0) {
Log.Exception (String.Format ("Width value to set: {0}", value),
new ArgumentException ("Width setter should not receive negative values", nameof (value)));
value = 0;
}
w = value;
}
}
public double Height {
get { return h; }
set {
if (value < 0) {
Log.Exception (String.Format ("Height value to set: {0}", value),
new ArgumentException ("Height setter should not receive negative values", nameof (value)));
value = 0;
}
h = value;
}
}
public bool Contains (double px, double py)
{
return !(px < x || px > x + w || py < y || py > y + h);
}
public bool Contains (Point point)
{
return Contains (point.X, point.Y);
}
public bool IntersectsWith (Rect rect)
{
return !(Left > rect.Right ||
Right < rect.Left ||
Top > rect.Bottom ||
Bottom < rect.Top);
}
public static Rect Empty {
get {
var empty = new Rect (Double.PositiveInfinity, Double.PositiveInfinity, 0, 0);
empty.w = empty.h = Double.NegativeInfinity;
return empty;
}
}
public bool IsEmpty {
get { return w < 0 && h < 0; }
}
public double Left {
get { return x; }
}
public double Top {
get { return y; }
}
public double Right {
get { return IsEmpty ? Double.NegativeInfinity : x + w; }
}
public double Bottom {
get { return IsEmpty ? Double.NegativeInfinity : y + h; }
}
public Size Size {
get { return new Size (Width, Height); }
}
public Point Point {
get { return new Point (X, Y); }
}
public void Intersect (Rect rect)
{
if (IsEmpty || rect.IsEmpty) {
this = Rect.Empty;
return;
}
double new_x = Math.Max (x, rect.x);
double new_y = Math.Max (y, rect.y);
double new_w = Math.Min (Right, rect.Right) - new_x;
double new_h = Math.Min (Bottom, rect.Bottom) - new_y;
x = new_x;
y = new_y;
w = new_w;
h = new_h;
if (w < 0 || h < 0) {
this = Rect.Empty;
}
}
public void Union (Rect rect)
{
if (IsEmpty) {
x = rect.x;
y = rect.y;
h = rect.h;
w = rect.w;
} else if (!rect.IsEmpty) {
double new_x = Math.Min (Left, rect.Left);
double new_y = Math.Min (Top, rect.Top);
double new_w = Math.Max (Right, rect.Right) - new_x;
double new_h = Math.Max (Bottom, rect.Bottom) - new_y;
x = new_x;
y = new_y;
w = new_w;
h = new_h;
}
}
public void Union (Point point)
{
Union (new Rect (point, point));
}
public void Offset (Rect rect)
{
x += rect.X;
y += rect.Y;
}
public void Offset (Point point)
{
x += point.X;
y += point.Y;
}
public void Offset (double dx, double dy)
{
x += dx;
y += dy;
}
public static bool operator == (Rect rect1, Rect rect2)
{
return rect1.x == rect2.x && rect1.y == rect2.y && rect1.w == rect2.w && rect1.h == rect2.h;
}
public static bool operator != (Rect rect1, Rect rect2)
{
return !(rect1 == rect2);
}
public override bool Equals (object o)
{
if (o is Rect) {
return this == (Rect)o;
}
return false;
}
public bool Equals (Rect value)
{
return this == value;
}
public override int GetHashCode ()
{
return x.GetHashCode () ^ y.GetHashCode () ^ w.GetHashCode () ^ h.GetHashCode ();
}
#region GDK/Cairo extensions
public static explicit operator Rect (Gdk.Rectangle rect)
{
return new Rect () {
X = rect.X,
Y = rect.Y,
Width = rect.Width,
Height = rect.Height
};
}
public static explicit operator Gdk.Rectangle (Rect rect)
{
return new Gdk.Rectangle () {
X = (int)Math.Floor (rect.X),
Y = (int)Math.Floor (rect.Y),
Width = (int)Math.Ceiling (rect.Width),
Height = (int)Math.Ceiling (rect.Height)
};
}
public static explicit operator Rect (Cairo.Rectangle rect)
{
return new Rect (rect.X, rect.Y, rect.Width, rect.Height);
}
public static explicit operator Cairo.Rectangle (Rect rect)
{
return new Cairo.Rectangle (rect.X, rect.Y, rect.Width, rect.Height);
}
#endregion
}
}
| |
/*****************************************************************************
*
* Copyright(c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution.If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com.By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
****************************************************************************/
/*****************************************************************************
* XSharp.BV
* Based on IronStudio/IronPythonTools/IronPythonTools/Navigation
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using XSharpModel;
namespace XSharp.LanguageService
{
/// <summary>
/// Single node inside the tree of the libraries in the object browser or class view.
/// </summary>
internal class LibraryNode : IVsSimpleObjectList2, IVsNavInfoNode
{
public const uint NullIndex = (uint)0xFFFFFFFF;
/// <summary>
/// Enumeration of the capabilities of a node. It is possible to combine different values
/// to support more capabilities.
/// This enumeration is a copy of _LIB_LISTCAPABILITIES with the Flags attribute set.
/// </summary>
[Flags()]
public enum LibraryNodeCapabilities
{
None = _LIB_LISTCAPABILITIES.LLC_NONE,
HasBrowseObject = _LIB_LISTCAPABILITIES.LLC_HASBROWSEOBJ,
HasDescriptionPane = _LIB_LISTCAPABILITIES.LLC_HASDESCPANE,
HasSourceContext = _LIB_LISTCAPABILITIES.LLC_HASSOURCECONTEXT,
HasCommands = _LIB_LISTCAPABILITIES.LLC_HASCOMMANDS,
AllowDragDrop = _LIB_LISTCAPABILITIES.LLC_ALLOWDRAGDROP,
AllowRename = _LIB_LISTCAPABILITIES.LLC_ALLOWRENAME,
AllowDelete = _LIB_LISTCAPABILITIES.LLC_ALLOWDELETE,
AllowSourceControl = _LIB_LISTCAPABILITIES.LLC_ALLOWSCCOPS,
}
/// <summary>
/// Enumeration of the possible types of node. The type of a node can be the combination
/// of one of more of these values.
/// This is actually a copy of the _LIB_LISTTYPE enumeration with the difference that the
/// Flags attribute is set so that it is possible to specify more than one value.
/// </summary>
[Flags()]
public enum LibraryNodeType
{
None = 0,
Hierarchy = _LIB_LISTTYPE.LLT_HIERARCHY,
Namespaces = _LIB_LISTTYPE.LLT_NAMESPACES,
Classes = _LIB_LISTTYPE.LLT_CLASSES,
Members = _LIB_LISTTYPE.LLT_MEMBERS,
Package = _LIB_LISTTYPE.LLT_PACKAGE,
PhysicalContainer = _LIB_LISTTYPE.LLT_PHYSICALCONTAINERS,
Containment = _LIB_LISTTYPE.LLT_CONTAINMENT,
ContainedBy = _LIB_LISTTYPE.LLT_CONTAINEDBY,
UsesClasses = _LIB_LISTTYPE.LLT_USESCLASSES,
UsedByClasses = _LIB_LISTTYPE.LLT_USEDBYCLASSES,
NestedClasses = _LIB_LISTTYPE.LLT_NESTEDCLASSES,
InheritedInterface = _LIB_LISTTYPE.LLT_INHERITEDINTERFACES,
InterfaceUsedByClasses = _LIB_LISTTYPE.LLT_INTERFACEUSEDBYCLASSES,
Definitions = _LIB_LISTTYPE.LLT_DEFINITIONS,
References = _LIB_LISTTYPE.LLT_REFERENCES,
DeferExpansion = _LIB_LISTTYPE.LLT_DEFEREXPANSION,
}
private string name;
private LibraryNodeType type;
internal List<LibraryNode> children;
internal LibraryNode parent;
private LibraryNodeCapabilities capabilities;
private List<VSOBJCLIPFORMAT> clipboardFormats;
public VSTREEDISPLAYDATA displayData;
private _VSTREEFLAGS flags;
private CommandID contextMenuID;
private string tooltip;
internal uint updateCount;
private Dictionary<LibraryNodeType, LibraryNode> filteredView;
public LibraryNode(string name)
: this(name, LibraryNodeType.None, LibraryNodeCapabilities.None, null)
{ }
public LibraryNode(string name, LibraryNodeType type)
: this(name, type, LibraryNodeCapabilities.None, null)
{ }
public LibraryNode(string name, LibraryNodeType type, LibraryNodeCapabilities capabilities, CommandID contextMenuID)
{
this.capabilities = capabilities;
this.contextMenuID = contextMenuID;
this.name = name;
this.tooltip = name;
this.type = type;
children = new List<LibraryNode>();
clipboardFormats = new List<VSOBJCLIPFORMAT>();
filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
}
public LibraryNode(LibraryNode node)
{
this.capabilities = node.capabilities;
this.contextMenuID = node.contextMenuID;
this.displayData = node.displayData;
this.name = node.name;
this.tooltip = node.tooltip;
this.type = node.type;
this.children = new List<LibraryNode>();
foreach (LibraryNode child in node.children)
{
children.Add(child);
}
this.clipboardFormats = new List<VSOBJCLIPFORMAT>();
foreach (VSOBJCLIPFORMAT format in node.clipboardFormats)
{
clipboardFormats.Add(format);
}
this.filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
this.updateCount = node.updateCount;
}
protected void SetCapabilityFlag(LibraryNodeCapabilities flag, bool value)
{
if (value)
{
capabilities |= flag;
}
else
{
capabilities &= ~flag;
}
}
internal IList<LibraryNode> Children => children;
/// <summary>
/// Get or Set if the node can be deleted.
/// </summary>
public bool CanDelete
{
get { return (0 != (capabilities & LibraryNodeCapabilities.AllowDelete)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.AllowDelete, value); }
}
/// <summary>
/// Get or Set if the node can be associated with some source code.
/// </summary>
public bool CanGoToSource
{
get { return (0 != (capabilities & LibraryNodeCapabilities.HasSourceContext)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.HasSourceContext, value); }
}
/// <summary>
/// Get or Set if the node can be renamed.
/// </summary>
public bool CanRename
{
get { return (0 != (capabilities & LibraryNodeCapabilities.AllowRename)); }
set { SetCapabilityFlag(LibraryNodeCapabilities.AllowRename, value); }
}
public LibraryNodeCapabilities Capabilities
{
get { return capabilities; }
set { capabilities = value; }
}
public _VSTREEFLAGS Flags
{
get { return flags; }
set { flags = value; }
}
public string TooltipText
{
get { return tooltip; }
set { tooltip = value; }
}
internal void AddNode(LibraryNode node)
{
lock (children)
{
children.Add(node);
}
filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
updateCount += 1;
}
internal void RemoveNode(LibraryNode node)
{
lock (children)
{
children.Remove(node);
}
filteredView = new Dictionary<LibraryNodeType, LibraryNode>();
updateCount += 1;
}
protected virtual object BrowseObject
{
get { return null; }
}
protected virtual uint CategoryField(LIB_CATEGORY category)
{
uint fieldValue = 0;
switch (category)
{
case LIB_CATEGORY.LC_LISTTYPE:
{
LibraryNodeType subTypes = LibraryNodeType.None;
foreach (LibraryNode node in children)
{
subTypes |= node.type;
}
fieldValue = (uint)subTypes;
}
break;
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_HIERARCHYTYPE:
fieldValue = (uint)_LIBCAT_HIERARCHYTYPE.LCHT_UNKNOWN;
break;
case LIB_CATEGORY.LC_VISIBILITY:
case LIB_CATEGORY.LC_NODETYPE:
case LIB_CATEGORY.LC_MODIFIER:
case LIB_CATEGORY.LC_CLASSTYPE:
case LIB_CATEGORY.LC_CLASSACCESS:
case LIB_CATEGORY.LC_MEMBERACCESS:
case LIB_CATEGORY.LC_MEMBERTYPE:
default:
break;
}
return fieldValue;
}
internal virtual LibraryNode Clone()
{
return new LibraryNode(this);
}
/// <summary>
/// Performs the operations needed to delete this node.
/// </summary>
protected virtual void Delete()
{
}
/// <summary>
/// Perform a Drag and Drop operation on this node.
/// </summary>
protected virtual void DoDragDrop(OleDataObject dataObject, uint keyState, uint effect)
{
}
protected virtual uint EnumClipboardFormats(_VSOBJCFFLAGS flags, VSOBJCLIPFORMAT[] formats)
{
if ((null == formats) || (formats.Length == 0))
{
return (uint)clipboardFormats.Count;
}
uint itemsToCopy = (uint)clipboardFormats.Count;
if (itemsToCopy > (uint)formats.Length)
{
itemsToCopy = (uint)formats.Length;
}
Array.Copy(clipboardFormats.ToArray(), formats, (int)itemsToCopy);
return itemsToCopy;
}
protected virtual void buildDescription(_VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 description)
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
description.ClearDescriptionText();
description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_NAME, null);
});
}
protected IVsSimpleObjectList2 FilterView(LibraryNodeType filterType)
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
LibraryNode filtered = null;
if (filteredView.TryGetValue(filterType, out filtered))
{
return filtered as IVsSimpleObjectList2;
}
filtered = this.Clone();
for (int i = 0; i < filtered.children.Count; )
{
if (0 == (filtered.children[i].type & filterType))
{
filtered.children.RemoveAt(i);
}
else
{
i += 1;
}
}
filteredView.Add(filterType, filtered);
return filtered as IVsSimpleObjectList2;
});
}
protected virtual void GotoSource(VSOBJGOTOSRCTYPE gotoType)
{
// Do nothing.
}
public string Name
{
get { return name; }
set { name = value; }
}
public LibraryNodeType NodeType
{
get { return type; }
set { type = value; }
}
/// <summary>
/// Finds the source files associated with this node.
/// </summary>
/// <param name="hierarchy">The hierarchy containing the items.</param>
/// <param name="itemId">The item id of the item.</param>
/// <param name="itemsCount">Number of items.</param>
protected virtual void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount)
{
hierarchy = null;
itemId = 0;
itemsCount = 0;
}
protected virtual void SourceContext(out string pbstrFilename, out uint pulLineNum)
{
pbstrFilename = null;
pulLineNum = 0;
}
protected virtual void Text(VSTREETEXTOPTIONS tto, out string pbstrText)
{
pbstrText = this.name;
}
protected virtual void Rename(string newName, uint flags)
{
this.name = newName;
}
public virtual string UniqueName
{
get { return Name; }
}
#region IVsSimpleObjectList2 Members
int IVsSimpleObjectList2.CanDelete(uint index, out int pfOK)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
pfOK = children[(int)index].CanDelete ? 1 : 0;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.CanGoToSource(uint index, VSOBJGOTOSRCTYPE SrcType, out int pfOK)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
pfOK = children[(int)index].CanGoToSource ? 1 : 0;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.CanRename(uint index, string pszNewName, out int pfOK)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
pfOK = children[(int)index].CanRename ? 1 : 0;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.CountSourceItems(uint index, out IVsHierarchy ppHier, out uint pItemid, out uint pcItems)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].SourceItems(out ppHier, out pItemid, out pcItems);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.DoDelete(uint index, uint grfFlags)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].Delete();
children.RemoveAt((int)index);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.DoDragDrop(uint index, IDataObject pDataObject, uint grfKeyState, ref uint pdwEffect)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
OleDataObject dataObject = new OleDataObject(pDataObject);
children[(int)index].DoDragDrop(dataObject, grfKeyState, pdwEffect);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.DoRename(uint index, string pszNewName, uint grfFlags)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].Rename(pszNewName, grfFlags);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.EnumClipboardFormats(uint index, uint grfFlags, uint celt, VSOBJCLIPFORMAT[] rgcfFormats, uint[] pcActual)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
uint copied = children[(int)index].EnumClipboardFormats((_VSOBJCFFLAGS)grfFlags, rgcfFormats);
if ((null != pcActual) && (pcActual.Length > 0))
{
pcActual[0] = copied;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.FillDescription2(uint index, uint grfOptions, IVsObjectBrowserDescription3 pobDesc)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].buildDescription((_VSOBJDESCOPTIONS)grfOptions, pobDesc);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetBrowseObject(uint index, out object ppdispBrowseObj)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
ppdispBrowseObj = children[(int)index].BrowseObject;
if (null == ppdispBrowseObj)
{
return VSConstants.E_NOTIMPL;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetCapabilities2(out uint pgrfCapabilities)
{
pgrfCapabilities = (uint)Capabilities;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetCategoryField2(uint index, int Category, out uint pfCatField)
{
LibraryNode node;
pfCatField = 0u;
if ( !XSolution.IsClosing)
{
if (NullIndex == index)
{
node = this;
}
else if (index < (uint)children.Count)
{
node = children[(int)index];
}
else
{
throw new ArgumentOutOfRangeException("index");
}
pfCatField = node.CategoryField((LIB_CATEGORY)Category);
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetClipboardFormat(uint index, uint grfFlags, FORMATETC[] pFormatetc, STGMEDIUM[] pMedium)
{
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetContextMenu(uint index, out Guid pclsidActive, out int pnMenuId, out IOleCommandTarget ppCmdTrgtActive)
{
ppCmdTrgtActive = null;
pnMenuId = 0;
pclsidActive = Guid.Empty;
if (!XSolution.IsClosing)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
CommandID commandId = children[(int)index].contextMenuID;
if (null == commandId)
{
pclsidActive = Guid.Empty;
pnMenuId = 0;
ppCmdTrgtActive = null;
return VSConstants.E_NOTIMPL;
}
pclsidActive = commandId.Guid;
pnMenuId = commandId.ID;
IOleCommandTarget target = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
target = children[(int)index] as IOleCommandTarget;
});
ppCmdTrgtActive = target;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData)
{
if (!XSolution.IsClosing)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
pData[0] = children[(int)index].displayData;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetExpandable3(uint index, uint ListTypeExcluded, out int pfExpandable)
{
// There is a not empty implementation of GetCategoryField2, so this method should
// return E_NOTIMPL.
pfExpandable = 0;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetExtendedClipboardVariant(uint index, uint grfFlags, VSOBJCLIPFORMAT[] pcfFormat, out object pvarFormat)
{
pvarFormat = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetFlags(out uint pFlags)
{
pFlags = (uint)Flags;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetItemCount(out uint pCount)
{
pCount = 0;
if (!XSolution.IsClosing)
{
pCount = (uint)children.Count;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetList2(uint index, uint ListType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2)
{
// TODO: Use the flags and list type to actually filter the result.
ppIVsSimpleObjectList2 = null;
if (!XSolution.IsClosing)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
ppIVsSimpleObjectList2 = children[(int)index].FilterView((LibraryNodeType)ListType);
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetMultipleSourceItems(uint index, uint grfGSI, uint cItems, VSITEMSELECTION[] rgItemSel)
{
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetNavInfo(uint index, out IVsNavInfo ppNavInfo)
{
ppNavInfo = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetNavInfoNode(uint index, out IVsNavInfoNode ppNavInfoNode)
{
ppNavInfoNode = null;
if (!XSolution.IsClosing)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
IVsNavInfoNode navinfo = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
navinfo = children[(int)index] as IVsNavInfoNode;
});
ppNavInfoNode = navinfo;
}
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetProperty(uint index, int propid, out object pvar)
{
pvar = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GetSourceContextWithOwnership(uint index, out string pbstrFilename, out uint pulLineNum)
{
// Return the source filename and linenumber for that Item
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].SourceContext(out pbstrFilename, out pulLineNum);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetTextWithOwnership(uint index, VSTREETEXTOPTIONS tto, out string pbstrText)
{
// TODO: make use of the text option.
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].Text( tto, out pbstrText);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetTipTextWithOwnership(uint index, VSTREETOOLTIPTYPE eTipType, out string pbstrText)
{
// TODO: Make use of the tooltip type.
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
pbstrText = children[(int)index].TooltipText;
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.GetUserContext(uint index, out object ppunkUserCtx)
{
ppunkUserCtx = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.GoToSource(uint index, VSOBJGOTOSRCTYPE SrcType)
{
if (index >= (uint)children.Count)
{
throw new ArgumentOutOfRangeException("index");
}
children[(int)index].GotoSource(SrcType);
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.LocateNavInfoNode(IVsNavInfoNode pNavInfoNode, out uint pulIndex)
{
if (null == pNavInfoNode)
{
throw new ArgumentNullException("pNavInfoNode");
}
pulIndex = NullIndex;
string nodeName = null;
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
ErrorHandler.ThrowOnFailure(pNavInfoNode.get_Name(out nodeName));
});
try
{
for (int i = 0; i < children.Count; i++)
{
if (0 == string.Compare(children[i].UniqueName, nodeName, StringComparison.OrdinalIgnoreCase))
{
pulIndex = (uint)i;
return VSConstants.S_OK;
}
}
}
catch (Exception)
{
}
return VSConstants.S_FALSE;
}
int IVsSimpleObjectList2.OnClose(VSTREECLOSEACTIONS[] ptca)
{
// Do Nothing.
return VSConstants.S_OK;
}
int IVsSimpleObjectList2.QueryDragDrop(uint index, IDataObject pDataObject, uint grfKeyState, ref uint pdwEffect)
{
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.ShowHelp(uint index)
{
return VSConstants.E_NOTIMPL;
}
int IVsSimpleObjectList2.UpdateCounter(out uint pCurUpdate)
{
pCurUpdate = updateCount;
return VSConstants.S_OK;
}
#endregion
#region IVsNavInfoNode Members
int IVsNavInfoNode.get_Name(out string pbstrName)
{
pbstrName = UniqueName;
return VSConstants.S_OK;
}
int IVsNavInfoNode.get_Type(out uint pllt)
{
pllt = (uint)type;
return VSConstants.S_OK;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Utilities;
using Avalonia.Visuals.Media.Imaging;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.Mathematics.Interop;
using BitmapInterpolationMode = Avalonia.Visuals.Media.Imaging.BitmapInterpolationMode;
namespace Avalonia.Direct2D1.Media
{
/// <summary>
/// Draws using Direct2D1.
/// </summary>
public class DrawingContextImpl : IDrawingContextImpl
{
private readonly IVisualBrushRenderer _visualBrushRenderer;
private readonly ILayerFactory _layerFactory;
private readonly SharpDX.Direct2D1.RenderTarget _renderTarget;
private readonly DeviceContext _deviceContext;
private readonly bool _ownsDeviceContext;
private readonly SharpDX.DXGI.SwapChain1 _swapChain;
private readonly Action _finishedCallback;
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContextImpl"/> class.
/// </summary>
/// <param name="visualBrushRenderer">The visual brush renderer.</param>
/// <param name="renderTarget">The render target to draw to.</param>
/// <param name="layerFactory">
/// An object to use to create layers. May be null, in which case a
/// <see cref="WicRenderTargetBitmapImpl"/> will created when a new layer is requested.
/// </param>
/// <param name="swapChain">An optional swap chain associated with this drawing context.</param>
/// <param name="finishedCallback">An optional delegate to be called when context is disposed.</param>
public DrawingContextImpl(
IVisualBrushRenderer visualBrushRenderer,
ILayerFactory layerFactory,
SharpDX.Direct2D1.RenderTarget renderTarget,
SharpDX.DXGI.SwapChain1 swapChain = null,
Action finishedCallback = null)
{
_visualBrushRenderer = visualBrushRenderer;
_layerFactory = layerFactory;
_renderTarget = renderTarget;
_swapChain = swapChain;
_finishedCallback = finishedCallback;
if (_renderTarget is DeviceContext deviceContext)
{
_deviceContext = deviceContext;
_ownsDeviceContext = false;
}
else
{
_deviceContext = _renderTarget.QueryInterface<DeviceContext>();
_ownsDeviceContext = true;
}
_deviceContext.BeginDraw();
}
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix Transform
{
get { return _deviceContext.Transform.ToAvalonia(); }
set { _deviceContext.Transform = value.ToDirect2D(); }
}
/// <inheritdoc/>
public void Clear(Color color)
{
_deviceContext.Clear(color.ToDirect2D());
}
/// <summary>
/// Ends a draw operation.
/// </summary>
public void Dispose()
{
foreach (var layer in _layerPool)
{
layer.Dispose();
}
try
{
_deviceContext.EndDraw();
_swapChain?.Present(1, SharpDX.DXGI.PresentFlags.None);
_finishedCallback?.Invoke();
}
catch (SharpDXException ex) when ((uint)ex.HResult == 0x8899000C) // D2DERR_RECREATE_TARGET
{
throw new RenderTargetCorruptedException(ex);
}
finally
{
if (_ownsDeviceContext)
{
_deviceContext.Dispose();
}
}
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacity">The opacity to draw with.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
/// <param name="bitmapInterpolationMode">The bitmap interpolation mode.</param>
public void DrawBitmap(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode)
{
using (var d2d = ((BitmapImpl)source.Item).GetDirect2DBitmap(_deviceContext))
{
var interpolationMode = GetInterpolationMode(bitmapInterpolationMode);
// TODO: How to implement CompositeMode here?
_deviceContext.DrawBitmap(
d2d.Value,
destRect.ToSharpDX(),
(float)opacity,
interpolationMode,
sourceRect.ToSharpDX(),
null);
}
}
private static InterpolationMode GetInterpolationMode(BitmapInterpolationMode interpolationMode)
{
switch (interpolationMode)
{
case BitmapInterpolationMode.LowQuality:
return InterpolationMode.NearestNeighbor;
case BitmapInterpolationMode.MediumQuality:
return InterpolationMode.Linear;
case BitmapInterpolationMode.HighQuality:
return InterpolationMode.HighQualityCubic;
case BitmapInterpolationMode.Default:
return InterpolationMode.Linear;
default:
throw new ArgumentOutOfRangeException(nameof(interpolationMode), interpolationMode, null);
}
}
public static CompositeMode GetCompositeMode(BitmapBlendingMode blendingMode)
{
switch (blendingMode)
{
case BitmapBlendingMode.SourceIn:
return CompositeMode.SourceIn;
case BitmapBlendingMode.SourceOut:
return CompositeMode.SourceOut;
case BitmapBlendingMode.SourceOver:
return CompositeMode.SourceOver;
case BitmapBlendingMode.SourceAtop:
return CompositeMode.SourceAtop;
case BitmapBlendingMode.DestinationIn:
return CompositeMode.DestinationIn;
case BitmapBlendingMode.DestinationOut:
return CompositeMode.DestinationOut;
case BitmapBlendingMode.DestinationOver:
return CompositeMode.DestinationOver;
case BitmapBlendingMode.DestinationAtop:
return CompositeMode.DestinationAtop;
case BitmapBlendingMode.Xor:
return CompositeMode.Xor;
case BitmapBlendingMode.Plus:
return CompositeMode.Plus;
default:
throw new ArgumentOutOfRangeException(nameof(blendingMode), blendingMode, null);
}
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacityMask">The opacity mask to draw with.</param>
/// <param name="opacityMaskRect">The destination rect for the opacity mask.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
public void DrawBitmap(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
{
using (var d2dSource = ((BitmapImpl)source.Item).GetDirect2DBitmap(_deviceContext))
using (var sourceBrush = new BitmapBrush(_deviceContext, d2dSource.Value))
using (var d2dOpacityMask = CreateBrush(opacityMask, opacityMaskRect.Size))
using (var geometry = new SharpDX.Direct2D1.RectangleGeometry(Direct2D1Platform.Direct2D1Factory, destRect.ToDirect2D()))
{
if (d2dOpacityMask.PlatformBrush != null)
{
d2dOpacityMask.PlatformBrush.Transform = Matrix.CreateTranslation(opacityMaskRect.Position).ToDirect2D();
}
_deviceContext.FillGeometry(
geometry,
sourceBrush,
d2dOpacityMask.PlatformBrush);
}
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p2">The second point of the line.</param>
public void DrawLine(IPen pen, Point p1, Point p2)
{
if (pen != null)
{
var size = new Rect(p1, p2).Size;
using (var d2dBrush = CreateBrush(pen.Brush, size))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (d2dBrush.PlatformBrush != null)
{
_deviceContext.DrawLine(
p1.ToSharpDX(),
p2.ToSharpDX(),
d2dBrush.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
}
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush brush, IPen pen, IGeometryImpl geometry)
{
if (brush != null)
{
using (var d2dBrush = CreateBrush(brush, geometry.Bounds.Size))
{
if (d2dBrush.PlatformBrush != null)
{
var impl = (GeometryImpl)geometry;
_deviceContext.FillGeometry(impl.Geometry, d2dBrush.PlatformBrush);
}
}
}
if (pen != null)
{
using (var d2dBrush = CreateBrush(pen.Brush, geometry.GetRenderBounds(pen).Size))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (d2dBrush.PlatformBrush != null)
{
var impl = (GeometryImpl)geometry;
_deviceContext.DrawGeometry(impl.Geometry, d2dBrush.PlatformBrush, (float)pen.Thickness, d2dStroke);
}
}
}
}
/// <inheritdoc />
public void DrawRectangle(IBrush brush, IPen pen, RoundedRect rrect, BoxShadows boxShadow = default)
{
var rc = rrect.Rect.ToDirect2D();
var rect = rrect.Rect;
var radiusX = Math.Max(rrect.RadiiTopLeft.X,
Math.Max(rrect.RadiiTopRight.X, Math.Max(rrect.RadiiBottomRight.X, rrect.RadiiBottomLeft.X)));
var radiusY = Math.Max(rrect.RadiiTopLeft.Y,
Math.Max(rrect.RadiiTopRight.Y, Math.Max(rrect.RadiiBottomRight.Y, rrect.RadiiBottomLeft.Y)));
var isRounded = !MathUtilities.IsZero(radiusX) || !MathUtilities.IsZero(radiusY);
if (brush != null)
{
using (var b = CreateBrush(brush, rect.Size))
{
if (b.PlatformBrush != null)
{
if (isRounded)
{
_deviceContext.FillRoundedRectangle(
new RoundedRectangle
{
Rect = new RawRectangleF(
(float)rect.X,
(float)rect.Y,
(float)rect.Right,
(float)rect.Bottom),
RadiusX = (float)radiusX,
RadiusY = (float)radiusY
},
b.PlatformBrush);
}
else
{
_deviceContext.FillRectangle(rc, b.PlatformBrush);
}
}
}
}
if (pen?.Brush != null)
{
using (var wrapper = CreateBrush(pen.Brush, rect.Size))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (wrapper.PlatformBrush != null)
{
if (isRounded)
{
_deviceContext.DrawRoundedRectangle(
new RoundedRectangle { Rect = rc, RadiusX = (float)radiusX, RadiusY = (float)radiusY },
wrapper.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
else
{
_deviceContext.DrawRectangle(
rc,
wrapper.PlatformBrush,
(float)pen.Thickness,
d2dStroke);
}
}
}
}
}
/// <inheritdoc />
public void DrawEllipse(IBrush brush, IPen pen, Rect rect)
{
var rc = rect.ToDirect2D();
if (brush != null)
{
using (var b = CreateBrush(brush, rect.Size))
{
if (b.PlatformBrush != null)
{
_deviceContext.FillEllipse(new Ellipse
{
Point = rect.Center.ToSharpDX(),
RadiusX = (float)(rect.Width / 2),
RadiusY = (float)(rect.Height / 2)
}, b.PlatformBrush);
}
}
}
if (pen?.Brush != null)
{
using (var wrapper = CreateBrush(pen.Brush, rect.Size))
using (var d2dStroke = pen.ToDirect2DStrokeStyle(_deviceContext))
{
if (wrapper.PlatformBrush != null)
{
_deviceContext.DrawEllipse(new Ellipse
{
Point = rect.Center.ToSharpDX(),
RadiusX = (float)(rect.Width / 2),
RadiusY = (float)(rect.Height / 2)
}, wrapper.PlatformBrush, (float)pen.Thickness, d2dStroke);
}
}
}
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text)
{
if (!string.IsNullOrEmpty(text.Text))
{
var impl = (FormattedTextImpl)text;
using (var brush = CreateBrush(foreground, impl.Bounds.Size))
using (var renderer = new AvaloniaTextRenderer(this, _deviceContext, brush.PlatformBrush))
{
if (brush.PlatformBrush != null)
{
impl.TextLayout.Draw(renderer, (float)origin.X, (float)origin.Y);
}
}
}
}
/// <summary>
/// Draws a glyph run.
/// </summary>
/// <param name="foreground">The foreground.</param>
/// <param name="glyphRun">The glyph run.</param>
public void DrawGlyphRun(IBrush foreground, GlyphRun glyphRun)
{
using (var brush = CreateBrush(foreground, glyphRun.Size))
{
var glyphRunImpl = (GlyphRunImpl)glyphRun.GlyphRunImpl;
_renderTarget.DrawGlyphRun(glyphRun.BaselineOrigin.ToSharpDX(), glyphRunImpl.GlyphRun,
brush.PlatformBrush, MeasuringMode.Natural);
}
}
public IDrawingContextLayerImpl CreateLayer(Size size)
{
if (_layerFactory != null)
{
return _layerFactory.CreateLayer(size);
}
else
{
var platform = AvaloniaLocator.Current.GetService<IPlatformRenderInterface>();
var dpi = new Vector(_deviceContext.DotsPerInch.Width, _deviceContext.DotsPerInch.Height);
var pixelSize = PixelSize.FromSizeWithDpi(size, dpi);
return (IDrawingContextLayerImpl)platform.CreateRenderTargetBitmap(pixelSize, dpi);
}
}
/// <summary>
/// Pushes a clip rectange.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public void PushClip(Rect clip)
{
_deviceContext.PushAxisAlignedClip(clip.ToSharpDX(), AntialiasMode.PerPrimitive);
}
public void PushClip(RoundedRect clip)
{
//TODO: radius
_deviceContext.PushAxisAlignedClip(clip.Rect.ToDirect2D(), AntialiasMode.PerPrimitive);
}
public void PopClip()
{
_deviceContext.PopAxisAlignedClip();
}
readonly Stack<Layer> _layers = new Stack<Layer>();
private readonly Stack<Layer> _layerPool = new Stack<Layer>();
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public void PushOpacity(double opacity)
{
if (opacity < 1)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = (float)opacity,
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
else
_layers.Push(null);
}
public void PopOpacity()
{
PopLayer();
}
private void PopLayer()
{
var layer = _layers.Pop();
if (layer != null)
{
_deviceContext.PopLayer();
_layerPool.Push(layer);
}
}
/// <summary>
/// Creates a Direct2D brush wrapper for a Avalonia brush.
/// </summary>
/// <param name="brush">The avalonia brush.</param>
/// <param name="destinationSize">The size of the brush's target area.</param>
/// <returns>The Direct2D brush wrapper.</returns>
public BrushImpl CreateBrush(IBrush brush, Size destinationSize)
{
var solidColorBrush = brush as ISolidColorBrush;
var linearGradientBrush = brush as ILinearGradientBrush;
var radialGradientBrush = brush as IRadialGradientBrush;
var conicGradientBrush = brush as IConicGradientBrush;
var imageBrush = brush as IImageBrush;
var visualBrush = brush as IVisualBrush;
if (solidColorBrush != null)
{
return new SolidColorBrushImpl(solidColorBrush, _deviceContext);
}
else if (linearGradientBrush != null)
{
return new LinearGradientBrushImpl(linearGradientBrush, _deviceContext, destinationSize);
}
else if (radialGradientBrush != null)
{
return new RadialGradientBrushImpl(radialGradientBrush, _deviceContext, destinationSize);
}
else if (conicGradientBrush != null)
{
// there is no Direct2D implementation of Conic Gradients so use Radial as a stand-in
return new SolidColorBrushImpl(conicGradientBrush, _deviceContext);
}
else if (imageBrush?.Source != null)
{
return new ImageBrushImpl(
imageBrush,
_deviceContext,
(BitmapImpl)imageBrush.Source.PlatformImpl.Item,
destinationSize);
}
else if (visualBrush != null)
{
if (_visualBrushRenderer != null)
{
var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush);
if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1)
{
// We need to ensure the size we're requesting is an integer pixel size, otherwise
// D2D alters the DPI of the render target, which messes stuff up. PixelSize.FromSize
// will do the rounding for us.
var dpi = new Vector(_deviceContext.DotsPerInch.Width, _deviceContext.DotsPerInch.Height);
var pixelSize = PixelSize.FromSizeWithDpi(intermediateSize, dpi);
using (var intermediate = new BitmapRenderTarget(
_deviceContext,
CompatibleRenderTargetOptions.None,
pixelSize.ToSizeWithDpi(dpi).ToSharpDX()))
{
using (var ctx = new RenderTarget(intermediate).CreateDrawingContext(_visualBrushRenderer))
{
intermediate.Clear(null);
_visualBrushRenderer.RenderVisualBrush(ctx, visualBrush);
}
return new ImageBrushImpl(
visualBrush,
_deviceContext,
new D2DBitmapImpl(intermediate.Bitmap),
destinationSize);
}
}
}
else
{
throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl.");
}
}
return new SolidColorBrushImpl(null, _deviceContext);
}
public void PushGeometryClip(IGeometryImpl clip)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = 1,
GeometricMask = ((GeometryImpl)clip).Geometry,
MaskAntialiasMode = AntialiasMode.PerPrimitive
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
public void PopGeometryClip()
{
PopLayer();
}
public void PushBitmapBlendMode(BitmapBlendingMode blendingMode)
{
// TODO: Stubs for now
}
public void PopBitmapBlendMode()
{
// TODO: Stubs for now
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
var parameters = new LayerParameters
{
ContentBounds = PrimitiveExtensions.RectangleInfinite,
MaskTransform = PrimitiveExtensions.Matrix3x2Identity,
Opacity = 1,
OpacityBrush = CreateBrush(mask, bounds.Size).PlatformBrush
};
var layer = _layerPool.Count != 0 ? _layerPool.Pop() : new Layer(_deviceContext);
_deviceContext.PushLayer(ref parameters, layer);
_layers.Push(layer);
}
public void PopOpacityMask()
{
PopLayer();
}
public void Custom(ICustomDrawOperation custom) => custom.Render(this);
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[System.Serializable]
[NodeAttributes( "Vector2", "Constants", "Vector2 property", null, KeyCode.Alpha2 )]
public sealed class Vector2Node : PropertyNode
{
[SerializeField]
private Vector2 m_defaultValue = Vector2.zero;
[SerializeField]
private Vector2 m_materialValue = Vector2.zero;
private const float LabelWidth = 8;
private int m_cachedPropertyId = -1;
public Vector2Node() : base() { }
public Vector2Node( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_insideSize.Set(50,20);
m_selectedLocation = PreviewLocation.BottomCenter;
AddOutputVectorPorts( WirePortDataType.FLOAT2, "XY" );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
m_previewShaderGUID = "88b4191eb06084d4da85d1dd2f984085";
}
public override void CopyDefaultsToMaterial()
{
m_materialValue = m_defaultValue;
}
public override void DrawSubProperties()
{
m_defaultValue = EditorGUILayoutVector2Field( Constants.DefaultValueLabel, m_defaultValue );
}
public override void DrawMaterialProperties()
{
if ( m_materialMode )
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutVector2Field( Constants.MaterialValueLabel, m_materialValue );
if ( m_materialMode && EditorGUI.EndChangeCheck() )
m_requireMaterialUpdate = true;
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_InputVector" );
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_materialValue[ 0 ], m_materialValue[ 1 ], 0, 0 ) );
else
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_defaultValue[ 0 ], m_defaultValue[ 1 ], 0, 0 ) );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isVisible )
{
m_propertyDrawPos = m_remainingBox;
m_propertyDrawPos.x = m_remainingBox.x - LabelWidth * drawInfo.InvertedZoom;
m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE;
m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE;
EditorGUI.BeginChangeCheck();
for ( int i = 0; i < 2; i++ )
{
m_propertyDrawPos.y = m_outputPorts[ i + 1 ].Position.y - 2 * drawInfo.InvertedZoom;
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
float val = m_materialValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_materialValue[ i ] = val;
}
else
{
float val = m_defaultValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_defaultValue[ i ] = val;
}
}
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = m_materialMode;
//MarkForPreviewUpdate();
BeginDelayedDirtyProperty();
}
}
}
public override void ConfigureLocalVariable( ref MasterNodeDataCollector dataCollector )
{
Vector2 value = m_defaultValue;
dataCollector.AddLocalVariable( m_uniqueId, CreateLocalVarDec( value.x + "," + value.y ) );
m_outputPorts[ 0 ].SetLocalValue( m_propertyName );
m_outputPorts[ 1 ].SetLocalValue( m_propertyName + ".x" );
m_outputPorts[ 2 ].SetLocalValue( m_propertyName + ".y" );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId,ref dataCollector, ignoreLocalvar );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
if ( m_currentParameterType != PropertyType.Constant )
return GetOutputVectorItem( 0, outputId, PropertyData );
if ( m_outputPorts[ outputId ].IsLocalValue )
{
return m_outputPorts[ outputId ].LocalValue;
}
if ( CheckLocalVariable( ref dataCollector ) )
{
return m_outputPorts[ outputId ].LocalValue;
}
Vector2 value = m_defaultValue;
string result = string.Empty;
switch ( outputId )
{
case 0:
{
result = m_precisionString+"( " + value.x + "," + value.y + " )";
}
break;
case 1:
{
result = value.x.ToString();
}
break;
case 2:
{
result = value.y.ToString();
}
break;
}
if ( result.Equals( string.Empty ) )
{
UIUtils.ShowMessage( "Vector2Node generating empty code", MessageSeverity.Warning );
}
return result;
}
public override string GetPropertyValue()
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Vector) = (" + m_defaultValue.x + "," + m_defaultValue.y + ",0,0)";
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
mat.SetVector( m_propertyName, m_materialValue );
}
}
public override void SetMaterialMode( Material mat )
{
base.SetMaterialMode( mat );
if ( m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) )
{
m_materialValue = mat.GetVector( m_propertyName );
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
m_materialValue = material.GetVector( m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string[] components = GetCurrentParam( ref nodeParams ).Split( IOUtils.VECTOR_SEPARATOR );
if ( components.Length == 2 )
{
m_defaultValue.x = Convert.ToSingle( components[ 0 ] );
m_defaultValue.y = Convert.ToSingle( components[ 1 ] );
}
else
{
UIUtils.ShowMessage( "Incorrect number of float2 values", MessageSeverity.Error );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString() );
}
public override string GetPropertyValStr()
{
return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue.x.ToString( Mathf.Abs( m_materialValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.y.ToString( Mathf.Abs( m_materialValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) :
m_defaultValue.x.ToString( Mathf.Abs( m_defaultValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString( Mathf.Abs( m_defaultValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel );
}
public Vector2 Value
{
get { return m_defaultValue; }
set { m_defaultValue = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddInt64()
{
var test = new SimpleBinaryOpTest__AddInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddInt64
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[ElementCount];
private static Int64[] _data2 = new Int64[ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64> _dataTable;
static SimpleBinaryOpTest__AddInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Add(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Add(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Add(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddInt64();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
if ((long)(left[0] + right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((long)(left[i] + right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Add)}<Int64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Reactive.Linq;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Layout;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.Utilities;
using Avalonia.VisualTree;
using JetBrains.Annotations;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for top-level widgets.
/// </summary>
/// <remarks>
/// This class acts as a base for top level widget.
/// It handles scheduling layout, styling and rendering as well as
/// tracking the widget's <see cref="ClientSize"/>.
/// </remarks>
public abstract class TopLevel : ContentControl,
IInputRoot,
ILayoutRoot,
IRenderRoot,
ICloseable,
IStyleHost,
ILogicalRoot,
IWeakSubscriber<ResourcesChangedEventArgs>
{
/// <summary>
/// Defines the <see cref="ClientSize"/> property.
/// </summary>
public static readonly DirectProperty<TopLevel, Size> ClientSizeProperty =
AvaloniaProperty.RegisterDirect<TopLevel, Size>(nameof(ClientSize), o => o.ClientSize);
/// <summary>
/// Defines the <see cref="IInputRoot.PointerOverElement"/> property.
/// </summary>
public static readonly StyledProperty<IInputElement> PointerOverElementProperty =
AvaloniaProperty.Register<TopLevel, IInputElement>(nameof(IInputRoot.PointerOverElement));
/// <summary>
/// Defines the <see cref="TransparencyLevelHint"/> property.
/// </summary>
public static readonly StyledProperty<WindowTransparencyLevel> TransparencyLevelHintProperty =
AvaloniaProperty.Register<TopLevel, WindowTransparencyLevel>(nameof(TransparencyLevelHint), WindowTransparencyLevel.None);
/// <summary>
/// Defines the <see cref="ActualTransparencyLevel"/> property.
/// </summary>
public static readonly DirectProperty<TopLevel, WindowTransparencyLevel> ActualTransparencyLevelProperty =
AvaloniaProperty.RegisterDirect<TopLevel, WindowTransparencyLevel>(nameof(ActualTransparencyLevel),
o => o.ActualTransparencyLevel,
unsetValue: WindowTransparencyLevel.None);
/// <summary>
/// Defines the <see cref="TransparencyBackgroundFallbackProperty"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> TransparencyBackgroundFallbackProperty =
AvaloniaProperty.Register<TopLevel, IBrush>(nameof(TransparencyBackgroundFallback), Brushes.White);
private readonly IInputManager _inputManager;
private readonly IAccessKeyHandler _accessKeyHandler;
private readonly IKeyboardNavigationHandler _keyboardNavigationHandler;
private readonly IPlatformRenderInterface _renderInterface;
private readonly IGlobalStyles _globalStyles;
private Size _clientSize;
private WindowTransparencyLevel _actualTransparencyLevel;
private ILayoutManager _layoutManager;
private Border _transparencyFallbackBorder;
/// <summary>
/// Initializes static members of the <see cref="TopLevel"/> class.
/// </summary>
static TopLevel()
{
AffectsMeasure<TopLevel>(ClientSizeProperty);
TransparencyLevelHintProperty.Changed.AddClassHandler<TopLevel>(
(tl, e) =>
{
if (tl.PlatformImpl != null)
{
tl.PlatformImpl.SetTransparencyLevelHint((WindowTransparencyLevel)e.NewValue);
tl.HandleTransparencyLevelChanged(tl.PlatformImpl.TransparencyLevel);
}
});
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
public TopLevel(ITopLevelImpl impl)
: this(impl, AvaloniaLocator.Current)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
/// <param name="dependencyResolver">
/// The dependency resolver to use. If null the default dependency resolver will be used.
/// </param>
public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver dependencyResolver)
{
if (impl == null)
{
throw new InvalidOperationException(
"Could not create window implementation: maybe no windowing subsystem was initialized?");
}
PlatformImpl = impl;
_actualTransparencyLevel = PlatformImpl.TransparencyLevel;
dependencyResolver = dependencyResolver ?? AvaloniaLocator.Current;
var styler = TryGetService<IStyler>(dependencyResolver);
_accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver);
_inputManager = TryGetService<IInputManager>(dependencyResolver);
_keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver);
_renderInterface = TryGetService<IPlatformRenderInterface>(dependencyResolver);
_globalStyles = TryGetService<IGlobalStyles>(dependencyResolver);
Renderer = impl.CreateRenderer(this);
if (Renderer != null)
{
Renderer.SceneInvalidated += SceneInvalidated;
}
impl.SetInputRoot(this);
impl.Closed = HandleClosed;
impl.Input = HandleInput;
impl.Paint = HandlePaint;
impl.Resized = HandleResized;
impl.ScalingChanged = HandleScalingChanged;
impl.TransparencyLevelChanged = HandleTransparencyLevelChanged;
_keyboardNavigationHandler?.SetOwner(this);
_accessKeyHandler?.SetOwner(this);
if (_globalStyles is object)
{
_globalStyles.GlobalStylesAdded += ((IStyleHost)this).StylesAdded;
_globalStyles.GlobalStylesRemoved += ((IStyleHost)this).StylesRemoved;
}
styler?.ApplyStyles(this);
ClientSize = impl.ClientSize;
this.GetObservable(PointerOverElementProperty)
.Select(
x => (x as InputElement)?.GetObservable(CursorProperty) ?? Observable.Empty<Cursor>())
.Switch().Subscribe(cursor => PlatformImpl?.SetCursor(cursor?.PlatformCursor));
if (((IStyleHost)this).StylingParent is IResourceHost applicationResources)
{
WeakSubscriptionManager.Subscribe(
applicationResources,
nameof(IResourceHost.ResourcesChanged),
this);
}
impl.LostFocus += PlatformImpl_LostFocus;
}
/// <summary>
/// Fired when the window is opened.
/// </summary>
public event EventHandler Opened;
/// <summary>
/// Fired when the window is closed.
/// </summary>
public event EventHandler Closed;
/// <summary>
/// Gets or sets the client size of the window.
/// </summary>
public Size ClientSize
{
get { return _clientSize; }
protected set { SetAndRaise(ClientSizeProperty, ref _clientSize, value); }
}
/// <summary>
/// Gets or sets the <see cref="WindowTransparencyLevel"/> that the TopLevel should use when possible.
/// </summary>
public WindowTransparencyLevel TransparencyLevelHint
{
get { return GetValue(TransparencyLevelHintProperty); }
set { SetValue(TransparencyLevelHintProperty, value); }
}
/// <summary>
/// Gets the acheived <see cref="WindowTransparencyLevel"/> that the platform was able to provide.
/// </summary>
public WindowTransparencyLevel ActualTransparencyLevel
{
get => _actualTransparencyLevel;
private set => SetAndRaise(ActualTransparencyLevelProperty, ref _actualTransparencyLevel, value);
}
/// <summary>
/// Gets or sets the <see cref="IBrush"/> that transparency will blend with when transparency is not supported.
/// By default this is a solid white brush.
/// </summary>
public IBrush TransparencyBackgroundFallback
{
get => GetValue(TransparencyBackgroundFallbackProperty);
set => SetValue(TransparencyBackgroundFallbackProperty, value);
}
public ILayoutManager LayoutManager
{
get
{
if (_layoutManager == null)
_layoutManager = CreateLayoutManager();
return _layoutManager;
}
}
/// <summary>
/// Gets the platform-specific window implementation.
/// </summary>
[CanBeNull]
public ITopLevelImpl PlatformImpl { get; private set; }
/// <summary>
/// Gets the renderer for the window.
/// </summary>
public IRenderer Renderer { get; private set; }
/// <summary>
/// Gets the access key handler for the window.
/// </summary>
IAccessKeyHandler IInputRoot.AccessKeyHandler => _accessKeyHandler;
/// <summary>
/// Gets or sets the keyboard navigation handler for the window.
/// </summary>
IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler;
/// <summary>
/// Gets or sets the input element that the pointer is currently over.
/// </summary>
IInputElement IInputRoot.PointerOverElement
{
get { return GetValue(PointerOverElementProperty); }
set { SetValue(PointerOverElementProperty, value); }
}
/// <inheritdoc/>
IMouseDevice IInputRoot.MouseDevice => PlatformImpl?.MouseDevice;
void IWeakSubscriber<ResourcesChangedEventArgs>.OnEvent(object sender, ResourcesChangedEventArgs e)
{
((ILogical)this).NotifyResourcesChanged(e);
}
/// <summary>
/// Gets or sets a value indicating whether access keys are shown in the window.
/// </summary>
bool IInputRoot.ShowAccessKeys
{
get { return GetValue(AccessText.ShowAccessKeyProperty); }
set { SetValue(AccessText.ShowAccessKeyProperty, value); }
}
/// <inheritdoc/>
double ILayoutRoot.LayoutScaling => PlatformImpl?.RenderScaling ?? 1;
/// <inheritdoc/>
double IRenderRoot.RenderScaling => PlatformImpl?.RenderScaling ?? 1;
IStyleHost IStyleHost.StylingParent => _globalStyles;
IRenderTarget IRenderRoot.CreateRenderTarget() => CreateRenderTarget();
/// <inheritdoc/>
protected virtual IRenderTarget CreateRenderTarget()
{
if(PlatformImpl == null)
throw new InvalidOperationException("Can't create render target, PlatformImpl is null (might be already disposed)");
return _renderInterface.CreateRenderTarget(PlatformImpl.Surfaces);
}
/// <inheritdoc/>
void IRenderRoot.Invalidate(Rect rect)
{
PlatformImpl?.Invalidate(rect);
}
/// <inheritdoc/>
Point IRenderRoot.PointToClient(PixelPoint p)
{
return PlatformImpl?.PointToClient(p) ?? default;
}
/// <inheritdoc/>
PixelPoint IRenderRoot.PointToScreen(Point p)
{
return PlatformImpl?.PointToScreen(p) ?? default;
}
/// <summary>
/// Creates the layout manager for this <see cref="TopLevel" />.
/// </summary>
protected virtual ILayoutManager CreateLayoutManager() => new LayoutManager(this);
/// <summary>
/// Handles a paint notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="rect">The dirty area.</param>
protected virtual void HandlePaint(Rect rect)
{
Renderer?.Paint(rect);
}
/// <summary>
/// Handles a closed notification from <see cref="ITopLevelImpl.Closed"/>.
/// </summary>
protected virtual void HandleClosed()
{
if (_globalStyles is object)
{
_globalStyles.GlobalStylesAdded -= ((IStyleHost)this).StylesAdded;
_globalStyles.GlobalStylesRemoved -= ((IStyleHost)this).StylesRemoved;
}
Renderer?.Dispose();
Renderer = null;
var logicalArgs = new LogicalTreeAttachmentEventArgs(this, this, null);
((ILogical)this).NotifyDetachedFromLogicalTree(logicalArgs);
var visualArgs = new VisualTreeAttachmentEventArgs(this, this);
OnDetachedFromVisualTreeCore(visualArgs);
(this as IInputRoot).MouseDevice?.TopLevelClosed(this);
PlatformImpl = null;
OnClosed(EventArgs.Empty);
LayoutManager?.Dispose();
}
/// <summary>
/// Handles a resize notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="clientSize">The new client size.</param>
protected virtual void HandleResized(Size clientSize)
{
ClientSize = clientSize;
Width = clientSize.Width;
Height = clientSize.Height;
LayoutManager.ExecuteLayoutPass();
Renderer?.Resized(clientSize);
}
/// <summary>
/// Handles a window scaling change notification from
/// <see cref="ITopLevelImpl.ScalingChanged"/>.
/// </summary>
/// <param name="scaling">The window scaling.</param>
protected virtual void HandleScalingChanged(double scaling)
{
LayoutHelper.InvalidateSelfAndChildrenMeasure(this);
}
private bool TransparencyLevelsMatch (WindowTransparencyLevel requested, WindowTransparencyLevel received)
{
if(requested == received)
{
return true;
}
else if(requested >= WindowTransparencyLevel.Blur && received >= WindowTransparencyLevel.Blur)
{
return true;
}
return false;
}
protected virtual void HandleTransparencyLevelChanged(WindowTransparencyLevel transparencyLevel)
{
if(_transparencyFallbackBorder != null)
{
if(transparencyLevel == WindowTransparencyLevel.None ||
TransparencyLevelHint == WindowTransparencyLevel.None ||
!TransparencyLevelsMatch(TransparencyLevelHint, transparencyLevel))
{
_transparencyFallbackBorder.Background = TransparencyBackgroundFallback;
}
else
{
_transparencyFallbackBorder.Background = null;
}
}
ActualTransparencyLevel = transparencyLevel;
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
throw new InvalidOperationException(
$"Control '{GetType().Name}' is a top level control and cannot be added as a child.");
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_transparencyFallbackBorder = e.NameScope.Find<Border>("PART_TransparencyFallback");
HandleTransparencyLevelChanged(PlatformImpl.TransparencyLevel);
}
/// <summary>
/// Raises the <see cref="Opened"/> event.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnOpened(EventArgs e) => Opened?.Invoke(this, e);
/// <summary>
/// Raises the <see cref="Closed"/> event.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnClosed(EventArgs e) => Closed?.Invoke(this, e);
/// <summary>
/// Tries to get a service from an <see cref="IAvaloniaDependencyResolver"/>, logging a
/// warning if not found.
/// </summary>
/// <typeparam name="T">The service type.</typeparam>
/// <param name="resolver">The resolver.</param>
/// <returns>The service.</returns>
private T TryGetService<T>(IAvaloniaDependencyResolver resolver) where T : class
{
var result = resolver.GetService<T>();
if (result == null)
{
Logger.TryGet(LogEventLevel.Warning, LogArea.Control)?.Log(
this,
"Could not create {Service} : maybe Application.RegisterServices() wasn't called?",
typeof(T));
}
return result;
}
/// <summary>
/// Handles input from <see cref="ITopLevelImpl.Input"/>.
/// </summary>
/// <param name="e">The event args.</param>
private void HandleInput(RawInputEventArgs e)
{
_inputManager.ProcessInput(e);
}
private void SceneInvalidated(object sender, SceneInvalidatedEventArgs e)
{
(this as IInputRoot).MouseDevice.SceneInvalidated(this, e.DirtyRect);
}
void PlatformImpl_LostFocus()
{
var focused = (IVisual)FocusManager.Instance.Current;
if (focused == null)
return;
while (focused.VisualParent != null)
focused = focused.VisualParent;
if (focused == this)
KeyboardDevice.Instance.SetFocusedElement(null, NavigationMethod.Unspecified, KeyModifiers.None);
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DbParameterHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.EntityClient {
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
public sealed partial class EntityParameter : DbParameter {
private object _value;
private object _parent;
private ParameterDirection _direction;
private int? _size;
private string _sourceColumn;
private DataRowVersion _sourceVersion;
private bool _sourceColumnNullMapping;
private bool? _isNullable;
private object _coercedValue;
private EntityParameter(EntityParameter source) : this() {
EntityUtil.CheckArgumentNull(source, "source");
source.CloneHelper(this);
ICloneable cloneable = (_value as ICloneable);
if (null != cloneable) {
_value = cloneable.Clone();
}
}
private object CoercedValue {
get {
return _coercedValue;
}
set {
_coercedValue = value;
}
}
[
RefreshProperties(RefreshProperties.All),
EntityResCategoryAttribute(EntityRes.DataCategory_Data),
EntityResDescriptionAttribute(EntityRes.DbParameter_Direction),
]
override public ParameterDirection Direction {
get {
ParameterDirection direction = _direction;
return ((0 != direction) ? direction : ParameterDirection.Input);
}
set {
if (_direction != value) {
switch (value) {
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
PropertyChanging();
_direction = value;
break;
default:
throw EntityUtil.InvalidParameterDirection(value);
}
}
}
}
override public bool IsNullable {
get {
bool result = this._isNullable.HasValue ? this._isNullable.Value : true;
return result;
}
set {
_isNullable = value;
}
}
internal int Offset {
get {
return 0;
}
}
[
EntityResCategoryAttribute(EntityRes.DataCategory_Data),
EntityResDescriptionAttribute(EntityRes.DbParameter_Size),
]
override public int Size {
get {
int size = _size.HasValue ? _size.Value : 0;
if (0 == size) {
size = ValueSize(Value);
}
return size;
}
set {
if (!_size.HasValue || _size.Value != value) {
if (value < -1) {
throw EntityUtil.InvalidSizeValue(value);
}
PropertyChanging();
if (0 == value) {
_size = null;
}
else {
_size = value;
}
}
}
}
private void ResetSize() {
if (_size.HasValue) {
PropertyChanging();
_size = null;
}
}
private bool ShouldSerializeSize() {
return (_size.HasValue && _size.Value != 0);
}
[
EntityResCategoryAttribute(EntityRes.DataCategory_Update),
EntityResDescriptionAttribute(EntityRes.DbParameter_SourceColumn),
]
override public string SourceColumn {
get {
string sourceColumn = _sourceColumn;
return ((null != sourceColumn) ? sourceColumn : string.Empty);
}
set {
_sourceColumn = value;
}
}
public override bool SourceColumnNullMapping {
get {
return _sourceColumnNullMapping;
}
set {
_sourceColumnNullMapping = value;
}
}
[
EntityResCategoryAttribute(EntityRes.DataCategory_Update),
EntityResDescriptionAttribute(EntityRes.DbParameter_SourceVersion),
]
override public DataRowVersion SourceVersion {
get {
DataRowVersion sourceVersion = _sourceVersion;
return ((0 != sourceVersion) ? sourceVersion : DataRowVersion.Current);
}
set {
switch(value) {
case DataRowVersion.Original:
case DataRowVersion.Current:
case DataRowVersion.Proposed:
case DataRowVersion.Default:
_sourceVersion = value;
break;
default:
throw EntityUtil.InvalidDataRowVersion(value);
}
}
}
private void CloneHelperCore(EntityParameter destination) {
destination._value = _value;
destination._direction = _direction;
destination._size = _size;
destination._sourceColumn = _sourceColumn;
destination._sourceVersion = _sourceVersion;
destination._sourceColumnNullMapping = _sourceColumnNullMapping;
destination._isNullable = _isNullable;
}
internal void CopyTo(DbParameter destination) {
EntityUtil.CheckArgumentNull(destination, "destination");
CloneHelper((EntityParameter)destination);
}
internal object CompareExchangeParent(object value, object comparand) {
object parent = _parent;
if (comparand == parent) {
_parent = value;
}
return parent;
}
internal void ResetParent() {
_parent = null;
}
override public string ToString() {
return ParameterName;
}
private byte ValuePrecisionCore(object value) {
if (value is Decimal) {
return ((System.Data.SqlTypes.SqlDecimal)(Decimal) value).Precision;
}
return 0;
}
private byte ValueScaleCore(object value) {
if (value is Decimal) {
return (byte)((Decimal.GetBits((Decimal)value)[3] & 0x00ff0000) >> 0x10);
}
return 0;
}
private int ValueSizeCore(object value) {
if (!EntityUtil.IsNull(value)) {
string svalue = (value as string);
if (null != svalue) {
return svalue.Length;
}
byte[] bvalue = (value as byte[]);
if (null != bvalue) {
return bvalue.Length;
}
char[] cvalue = (value as char[]);
if (null != cvalue) {
return cvalue.Length;
}
if ((value is byte) || (value is char)) {
return 1;
}
}
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Diagnostics;
namespace System.Reflection.Emit
{
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type)
{
return new MethodOnTypeBuilderInstantiation(method, type);
}
#endregion
#region Private Data Members
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
public override MemberTypes MemberType => m_method.MemberType;
public override string Name => m_method.Name;
public override Type? DeclaringType => m_type;
public override Type? ReflectedType => m_type;
public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override Module Module => m_method.Module;
#endregion
#region MethodBase Members
public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle => m_method.MethodHandle;
public override MethodAttributes Attributes => m_method.Attributes;
public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention => m_method.CallingConvention;
public override Type[] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition => m_method.IsGenericMethodDefinition;
public override bool ContainsGenericParameters => m_method.ContainsGenericParameters;
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this));
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod => m_method.IsGenericMethod;
#endregion
#region Public Abstract\Virtual Members
public override Type ReturnType => m_method.ReturnType;
public override ParameterInfo ReturnParameter => throw new NotSupportedException();
public override ICustomAttributeProvider ReturnTypeCustomAttributes => throw new NotSupportedException();
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
{
#region Private Static Members
internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type)
{
return new ConstructorOnTypeBuilderInstantiation(Constructor, type);
}
#endregion
#region Private Data Members
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
}
internal override Type GetReturnType()
{
return m_type;
}
#region MemberInfo Overrides
public override MemberTypes MemberType => m_ctor.MemberType;
public override string Name => m_ctor.Name;
public override Type? DeclaringType => m_type;
public override Type? ReflectedType => m_type;
public override object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
ConstructorBuilder? cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
else
{
Debug.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
}
public override Module Module => m_ctor.Module;
#endregion
#region MethodBase Members
public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle => m_ctor.MethodHandle;
public override MethodAttributes Attributes => m_ctor.Attributes;
public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention => m_ctor.CallingConvention;
public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); }
public override bool IsGenericMethodDefinition => false;
public override bool ContainsGenericParameters => false;
public override bool IsGenericMethod => false;
#endregion
#region ConstructorInfo Members
public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new InvalidOperationException();
}
#endregion
}
internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo
{
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
FieldInfo m;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
// that the second thread's value clobbers the first in the hashtable. This is
// an acceptable race condition since we make no guarantees that this will return the
// same object.
//
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field))
{
m = (type.m_hashtable[Field] as FieldInfo)!;
}
else
{
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
return m;
}
#endregion
#region Private Data Members
private FieldInfo m_field;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
}
#endregion
internal FieldInfo FieldInfo => m_field;
#region MemberInfo Overrides
public override MemberTypes MemberType => System.Reflection.MemberTypes.Field;
public override string Name => m_field.Name;
public override Type? DeclaringType => m_type;
public override Type? ReflectedType => m_type;
public override object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
FieldBuilder? fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
else
{
Debug.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
}
public override Module Module => m_field.Module;
#endregion
#region Public Abstract\Virtual Members
public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); }
public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); }
public override void SetValueDirect(TypedReference obj, object value)
{
throw new NotImplementedException();
}
public override object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
}
public override RuntimeFieldHandle FieldHandle => throw new NotImplementedException();
public override Type FieldType => throw new NotImplementedException();
public override object GetValue(object? obj) { throw new InvalidOperationException(); }
public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes => m_field.Attributes;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace DPStressHarness
{
public class Program
{
public static void Main(string[] args)
{
Init(args);
Run();
}
public enum RunMode
{
RunAll,
RunVerify,
Help,
ExitWithError
};
private static RunMode s_mode = RunMode.RunAll;
private static IEnumerable<TestBase> s_tests;
private static StressEngine s_eng;
private static string s_error;
public static void Init(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "-a":
string assemblyName = args[++i];
TestFinder.AssemblyName = new AssemblyName(assemblyName);
break;
case "-all":
s_mode = RunMode.RunAll;
break;
case "-override":
TestMetrics.Overrides.Add(args[++i], args[++i]);
break;
case "-variation":
TestMetrics.Variations.Add(args[++i]);
break;
case "-test":
TestMetrics.SelectedTests.Add(args[++i]);
break;
case "-duration":
TestMetrics.StressDuration = Int32.Parse(args[++i]);
break;
case "-threads":
TestMetrics.StressThreads = Int32.Parse(args[++i]);
break;
case "-verify":
s_mode = RunMode.RunVerify;
break;
case "-debug":
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
else
{
Console.WriteLine("Current PID: {0}, attach the debugger and press Enter to continue the execution...", System.Diagnostics.Process.GetCurrentProcess().Id);
Console.ReadLine();
}
break;
case "-exceptionThreshold":
TestMetrics.ExceptionThreshold = Int32.Parse(args[++i]);
break;
case "-monitorenabled":
TestMetrics.MonitorEnabled = bool.Parse(args[++i]);
break;
case "-randomSeed":
TestMetrics.RandomSeed = Int32.Parse(args[++i]);
break;
case "-filter":
TestMetrics.Filter = args[++i];
break;
case "-printMethodName":
TestMetrics.PrintMethodName = true;
break;
case "-deadlockdetection":
if (bool.Parse(args[++i]))
{
DeadlockDetection.Enable();
}
break;
default:
s_mode = RunMode.Help;
break;
}
}
if (TestFinder.AssemblyName != null)
{
Console.WriteLine("Assembly Found for the Assembly Name " + TestFinder.AssemblyName);
if (TestFinder.AssemblyName != null)
{
// get and load all the tests
s_tests = TestFinder.GetTests(Assembly.Load(TestFinder.AssemblyName));
// instantiate the stress engine
s_eng = new StressEngine(TestMetrics.StressThreads, TestMetrics.StressDuration, s_tests, TestMetrics.RandomSeed);
}
else
{
Program.s_error = string.Format("Assembly {0} cannot be found.", TestFinder.AssemblyName);
s_mode = RunMode.ExitWithError;
}
}
}
public static void TestCase(Assembly assembly,
RunMode mode,
int duration,
int threads,
int? exceptionThreshold = null,
bool printMethodName = false,
bool deadlockDetection = false,
int randomSeed = 0,
string[] selectedTests = null,
string[] overrides = null,
string[] variations = null,
string filter = null,
bool monitorEnabled = false,
string monitorMachineName = "localhost")
{
TestMetrics.Reset();
TestFinder.AssemblyName = assembly.GetName();
mode = RunMode.RunAll;
for (int i = 0; overrides != null && i < overrides.Length; i++)
{
TestMetrics.Overrides.Add(overrides[i], overrides[++i]);
}
for (int i = 0; variations != null && i < variations.Length; i++)
{
TestMetrics.Variations.Add(variations[i]);
}
for (int i = 0; selectedTests != null && i < selectedTests.Length; i++)
{
TestMetrics.SelectedTests.Add(selectedTests[i]);
}
TestMetrics.StressDuration = duration;
TestMetrics.StressThreads = threads;
TestMetrics.ExceptionThreshold = exceptionThreshold;
TestMetrics.MonitorEnabled = monitorEnabled;
TestMetrics.MonitorMachineName = monitorMachineName;
TestMetrics.RandomSeed = randomSeed;
TestMetrics.Filter = filter;
TestMetrics.PrintMethodName = printMethodName;
if (deadlockDetection)
{
DeadlockDetection.Enable();
}
// get and load all the tests
s_tests = TestFinder.GetTests(assembly);
// instantiate the stress engine
s_eng = new StressEngine(TestMetrics.StressThreads, TestMetrics.StressDuration, s_tests, TestMetrics.RandomSeed);
}
public static void Run()
{
if (TestFinder.AssemblyName == null)
{
s_mode = RunMode.Help;
}
switch (s_mode)
{
case RunMode.RunAll:
RunStress();
break;
case RunMode.RunVerify:
RunVerify();
break;
case RunMode.ExitWithError:
ExitWithError();
break;
case RunMode.Help:
PrintHelp();
break;
}
}
private static void PrintHelp()
{
Console.WriteLine("stresstest.exe [-a <module name>] <arguments>");
Console.WriteLine();
Console.WriteLine(" -a <module name> should specify path to the assembly containing the tests.");
Console.WriteLine();
Console.WriteLine("Supported options are:");
Console.WriteLine();
Console.WriteLine(" -all Run all tests - best for debugging, not perf measurements.");
Console.WriteLine();
Console.WriteLine(" -verify Run in functional verification mode.");
Console.WriteLine();
Console.WriteLine(" -duration <n> Duration of the test in seconds.");
Console.WriteLine();
Console.WriteLine(" -threads <n> Number of threads to use.");
Console.WriteLine();
Console.WriteLine(" -override <name> <value> Override the value of a test property.");
Console.WriteLine();
Console.WriteLine(" -test <name> Run specific test(s) using their name.");
Console.WriteLine();
Console.WriteLine(" -debug Print process ID in the beginning and wait for Enter (to give your time to attach the debugger).");
Console.WriteLine();
Console.WriteLine(" -exceptionThreshold <n> An optional limit on exceptions which will be caught. When reached, test will halt.");
Console.WriteLine();
Console.WriteLine(" -monitorenabled True or False to enable monitoring. Default is false");
Console.WriteLine();
Console.WriteLine(" -randomSeed Enables setting of the random number generator used internally. This serves both the purpose");
Console.WriteLine(" of helping to improve reproducibility and making it deterministic from Chess's perspective");
Console.WriteLine(" for a given schedule. Default is " + TestMetrics.RandomSeed + ".");
Console.WriteLine();
Console.WriteLine(" -filter Run tests whose stress test attributes match the given filter. Filter is not applied if attribute");
Console.WriteLine(" does not implement ITestAttributeFilter. Example: -filter TestType=Query,Update;IsServerTest=True ");
Console.WriteLine();
Console.WriteLine(" -printMethodName Print tests' title in console window");
Console.WriteLine();
Console.WriteLine(" -deadlockdetection True or False to enable deadlock detection. Default is false");
Console.WriteLine();
}
private static int ExitWithError()
{
Environment.FailFast("Exit with error(s).");
return 1;
}
private static int RunVerify()
{
throw new NotImplementedException();
}
private static int RunStress()
{
return s_eng.Run();
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentBag.cs
//
// An unordered collection that allows duplicates and that provides add and get operations.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents an thread-safe, unordered collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the bag.</typeparam>
/// <remarks>
/// <para>
/// Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support
/// duplicates. <see cref="ConcurrentBag{T}"/> is a thread-safe bag implementation, optimized for
/// scenarios where the same thread will be both producing and consuming data stored in the bag.
/// </para>
/// <para>
/// <see cref="ConcurrentBag{T}"/> accepts null reference (Nothing in Visual Basic) as a valid
/// value for reference types.
/// </para>
/// <para>
/// All public and protected members of <see cref="ConcurrentBag{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
// ThreadLocalList object that contains the data per thread
[NonSerialized]
private ThreadLocal<ThreadLocalList> _locals;
// This head and tail pointers points to the first and last local lists, to allow enumeration on the thread locals objects
[NonSerialized]
private volatile ThreadLocalList _headList, _tailList;
// A flag used to tell the operations thread that it must synchronize the operation, this flag is set/unset within
// GlobalListsLock lock
[NonSerialized]
private bool _needSync;
// Used for custom serialization.
private T[] _serializationArray;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentBag{T}"/>
/// class.
/// </summary>
public ConcurrentBag()
{
Initialize(null);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentBag{T}"/>
/// class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentBag{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public ConcurrentBag(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection), SR.ConcurrentBag_Ctor_ArgumentNullException);
}
Initialize(collection);
}
/// <summary>
/// Local helper function to initialize a new bag object
/// </summary>
/// <param name="collection">An enumeration containing items with which to initialize this bag.</param>
private void Initialize(IEnumerable<T> collection)
{
_locals = new ThreadLocal<ThreadLocalList>();
// Copy the collection to the bag
if (collection != null)
{
ThreadLocalList list = GetThreadList(true);
foreach (T item in collection)
{
list.Add(item, false);
}
}
}
/// <summary>Get the data array to be serialized.</summary>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// save the data into the serialization array to be saved
_serializationArray = ToArray();
}
/// <summary>Clear the serialized array.</summary>
[OnSerialized]
private void OnSerialized(StreamingContext context)
{
_serializationArray = null;
}
/// <summary>Construct the stack from a previously seiralized one.</summary>
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
_locals = new ThreadLocal<ThreadLocalList>();
ThreadLocalList list = GetThreadList(true);
foreach (T item in _serializationArray)
{
list.Add(item, false);
}
_headList = list;
_tailList = list;
_serializationArray = null;
}
/// <summary>
/// Adds an object to the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="item">The object to be added to the
/// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.</param>
public void Add(T item)
{
// Get the local list for that thread, create a new list if this thread doesn't exist
//(first time to call add)
ThreadLocalList list = GetThreadList(true);
AddInternal(list, item);
}
/// <summary>
/// </summary>
/// <param name="list"></param>
/// <param name="item"></param>
private void AddInternal(ThreadLocalList list, T item)
{
bool lockTaken = false;
try
{
#pragma warning disable 0420
Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Add);
#pragma warning restore 0420
//Synchronization cases:
// if the list count is less than two to avoid conflict with any stealing thread
// if _needSync is set, this means there is a thread that needs to freeze the bag
if (list.Count < 2 || _needSync)
{
// reset it back to zero to avoid deadlock with stealing thread
list._currentOp = (int)ListOperation.None;
Monitor.Enter(list, ref lockTaken);
}
list.Add(item, lockTaken);
}
finally
{
list._currentOp = (int)ListOperation.None;
if (lockTaken)
{
Monitor.Exit(list);
}
}
}
/// <summary>
/// Attempts to add an object to the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="item">The object to be added to the
/// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.</param>
/// <returns>Always returns true</returns>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Add(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains the object
/// removed from the <see cref="ConcurrentBag{T}"/> or the default value
/// of <typeparamref name="T"/> if the operation failed.</param>
/// <returns>true if an object was removed successfully; otherwise, false.</returns>
public bool TryTake(out T result)
{
return TryTakeOrPeek(out result, true);
}
/// <summary>
/// Attempts to return an object from the <see cref="ConcurrentBag{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the <see cref="ConcurrentBag{T}"/> or the default value of
/// <typeparamref name="T"/> if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
return TryTakeOrPeek(out result, false);
}
/// <summary>
/// Local helper function to Take or Peek an item from the bag
/// </summary>
/// <param name="result">To receive the item retrieved from the bag</param>
/// <param name="take">True means Take operation, false means Peek operation</param>
/// <returns>True if succeeded, false otherwise</returns>
private bool TryTakeOrPeek(out T result, bool take)
{
// Get the local list for that thread, return null if the thread doesn't exit
//(this thread never add before)
ThreadLocalList list = GetThreadList(false);
if (list == null || list.Count == 0)
{
return Steal(out result, take);
}
bool lockTaken = false;
try
{
if (take) // Take operation
{
#pragma warning disable 0420
Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Take);
#pragma warning restore 0420
//Synchronization cases:
// if the list count is less than or equal two to avoid conflict with any stealing thread
// if _needSync is set, this means there is a thread that needs to freeze the bag
if (list.Count <= 2 || _needSync)
{
// reset it back to zero to avoid deadlock with stealing thread
list._currentOp = (int)ListOperation.None;
Monitor.Enter(list, ref lockTaken);
// Double check the count and steal if it became empty
if (list.Count == 0)
{
// Release the lock before stealing
if (lockTaken)
{
try { }
finally
{
lockTaken = false; // reset lockTaken to avoid calling Monitor.Exit again in the finally block
Monitor.Exit(list);
}
}
return Steal(out result, true);
}
}
list.Remove(out result);
}
else
{
if (!list.Peek(out result))
{
return Steal(out result, false);
}
}
}
finally
{
list._currentOp = (int)ListOperation.None;
if (lockTaken)
{
Monitor.Exit(list);
}
}
return true;
}
/// <summary>
/// Local helper function to retrieve a thread local list by a thread object
/// </summary>
/// <param name="forceCreate">Create a new list if the thread does not exist</param>
/// <returns>The local list object</returns>
private ThreadLocalList GetThreadList(bool forceCreate)
{
ThreadLocalList list = _locals.Value;
if (list != null)
{
return list;
}
else if (forceCreate)
{
// Acquire the lock to update the _tailList pointer
lock (GlobalListsLock)
{
if (_headList == null)
{
list = new ThreadLocalList(Environment.CurrentManagedThreadId);
_headList = list;
_tailList = list;
}
else
{
list = GetUnownedList();
if (list == null)
{
list = new ThreadLocalList(Environment.CurrentManagedThreadId);
_tailList._nextList = list;
_tailList = list;
}
}
_locals.Value = list;
}
}
else
{
return null;
}
Debug.Assert(list != null);
return list;
}
/// <summary>
/// Try to reuse an unowned list if exist
/// unowned lists are the lists that their owner threads are aborted or terminated
/// this is workaround to avoid memory leaks.
/// </summary>
/// <returns>The list object, null if all lists are owned</returns>
private ThreadLocalList GetUnownedList()
{
//the global lock must be held at this point
Debug.Assert(Monitor.IsEntered(GlobalListsLock));
int currentThreadId = Environment.CurrentManagedThreadId;
ThreadLocalList currentList = _headList;
while (currentList != null)
{
if (currentList._ownerThreadId == currentThreadId)
{
return currentList;
}
currentList = currentList._nextList;
}
return null;
}
/// <summary>
/// Local helper method to steal an item from any other non empty thread
/// </summary>
/// <param name="result">To receive the item retrieved from the bag</param>
/// <param name="take">Whether to remove or peek.</param>
/// <returns>True if succeeded, false otherwise.</returns>
private bool Steal(out T result, bool take)
{
#if FEATURE_TRACING
if (take)
CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryTakeSteals();
else
CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryPeekSteals();
#endif
bool loop;
List<int> versionsList = new List<int>(); // save the lists version
do
{
versionsList.Clear(); //clear the list from the previous iteration
loop = false;
ThreadLocalList currentList = _headList;
while (currentList != null)
{
versionsList.Add(currentList._version);
if (currentList._head != null && TrySteal(currentList, out result, take))
{
return true;
}
currentList = currentList._nextList;
}
// verify versioning, if other items are added to this list since we last visit it, we should retry
currentList = _headList;
foreach (int version in versionsList)
{
if (version != currentList._version) //oops state changed
{
loop = true;
if (currentList._head != null && TrySteal(currentList, out result, take))
return true;
}
currentList = currentList._nextList;
}
} while (loop);
result = default(T);
return false;
}
/// <summary>
/// local helper function tries to steal an item from given local list
/// </summary>
private bool TrySteal(ThreadLocalList list, out T result, bool take)
{
lock (list)
{
if (CanSteal(list))
{
list.Steal(out result, take);
return true;
}
result = default(T);
return false;
}
}
/// <summary>
/// Local helper function to check the list if it became empty after acquiring the lock
/// and wait if there is unsynchronized Add/Take operation in the list to be done
/// </summary>
/// <param name="list">The list to steal</param>
/// <returns>True if can steal, false otherwise</returns>
private static bool CanSteal(ThreadLocalList list)
{
if (list.Count <= 2 && list._currentOp != (int)ListOperation.None)
{
SpinWait spinner = new SpinWait();
while (list._currentOp != (int)ListOperation.None)
{
spinner.SpinOnce();
}
}
return list.Count > 0;
}
/// <summary>
/// Copies the <see cref="ConcurrentBag{T}"/> elements to an existing
/// one-dimensional <see cref="T:System.Array">Array</see>, starting at the specified array
/// index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentBag{T}"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- the number of elements in the source <see
/// cref="ConcurrentBag{T}"/> is greater than the available space from
/// <paramref name="index"/> to the end of the destination <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException
(nameof(index), SR.ConcurrentBag_CopyTo_ArgumentOutOfRangeException);
}
// Short path if the bag is empty
if (_headList == null)
return;
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
ToList().CopyTo(array, index);
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentBag{T}"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException);
}
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
((ICollection)ToList()).CopyTo(array, index);
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>
/// Copies the <see cref="ConcurrentBag{T}"/> elements to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentBag{T}"/>.</returns>
public T[] ToArray()
{
// Short path if the bag is empty
if (_headList == null)
return Array.Empty<T>();
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return ToList().ToArray();
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentBag{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentBag{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the bag.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Short path if the bag is empty
if (_headList == null)
return ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator();
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return ToList().GetEnumerator();
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentBag{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentBag{T}"/>.</returns>
/// <remarks>
/// The items enumerated represent a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any update to the collection after
/// <see cref="GetEnumerator"/> was called.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
return ((ConcurrentBag<T>)this).GetEnumerator();
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentBag{T}"/>.</value>
/// <remarks>
/// The count returned represents a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called.
/// </remarks>
public int Count
{
get
{
// Short path if the bag is empty
if (_headList == null)
return 0;
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return GetCountInternal();
}
finally
{
UnfreezeBag(lockTaken);
}
}
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentBag{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentBag{T}"/> is empty; otherwise, false.</value>
public bool IsEmpty
{
get
{
if (_headList == null)
return true;
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
ThreadLocalList currentList = _headList;
while (currentList != null)
{
if (currentList._head != null)
//at least this list is not empty, we return false
{
return false;
}
currentList = currentList._nextList;
}
return true;
}
finally
{
UnfreezeBag(lockTaken);
}
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentBag{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
}
}
/// <summary>
/// A global lock object, used in two cases:
/// 1- To maintain the _tailList pointer for each new list addition process ( first time a thread called Add )
/// 2- To freeze the bag in GetEnumerator, CopyTo, ToArray and Count members
/// </summary>
private object GlobalListsLock
{
get
{
Debug.Assert(_locals != null);
return _locals;
}
}
#region Freeze bag helper methods
/// <summary>
/// Local helper method to freeze all bag operations, it
/// 1- Acquire the global lock to prevent any other thread to freeze the bag, and also new thread can be added
/// to the dictionary
/// 2- Then Acquire all local lists locks to prevent steal and synchronized operations
/// 3- Wait for all un-synchronized operations to be done
/// </summary>
/// <param name="lockTaken">Retrieve the lock taken result for the global lock, to be passed to Unfreeze method</param>
private void FreezeBag(ref bool lockTaken)
{
Debug.Assert(!Monitor.IsEntered(GlobalListsLock));
// global lock to be safe against multi threads calls count and corrupt _needSync
Monitor.Enter(GlobalListsLock, ref lockTaken);
// This will force any future add/take operation to be synchronized
_needSync = true;
//Acquire all local lists locks
AcquireAllLocks();
// Wait for all un-synchronized operation to be done
WaitAllOperations();
}
/// <summary>
/// Local helper method to unfreeze the bag from a frozen state
/// </summary>
/// <param name="lockTaken">The lock taken result from the Freeze method</param>
private void UnfreezeBag(bool lockTaken)
{
ReleaseAllLocks();
_needSync = false;
if (lockTaken)
{
Monitor.Exit(GlobalListsLock);
}
}
/// <summary>
/// local helper method to acquire all local lists locks
/// </summary>
private void AcquireAllLocks()
{
Debug.Assert(Monitor.IsEntered(GlobalListsLock));
bool lockTaken = false;
ThreadLocalList currentList = _headList;
while (currentList != null)
{
// Try/Finally block to avoid thread abort between acquiring the lock and setting the taken flag
try
{
Monitor.Enter(currentList, ref lockTaken);
}
finally
{
if (lockTaken)
{
currentList._lockTaken = true;
lockTaken = false;
}
}
currentList = currentList._nextList;
}
}
/// <summary>
/// Local helper method to release all local lists locks
/// </summary>
private void ReleaseAllLocks()
{
ThreadLocalList currentList = _headList;
while (currentList != null)
{
if (currentList._lockTaken)
{
currentList._lockTaken = false;
Monitor.Exit(currentList);
}
currentList = currentList._nextList;
}
}
/// <summary>
/// Local helper function to wait all unsynchronized operations
/// </summary>
private void WaitAllOperations()
{
Debug.Assert(Monitor.IsEntered(GlobalListsLock));
ThreadLocalList currentList = _headList;
while (currentList != null)
{
if (currentList._currentOp != (int)ListOperation.None)
{
SpinWait spinner = new SpinWait();
while (currentList._currentOp != (int)ListOperation.None)
{
spinner.SpinOnce();
}
}
currentList = currentList._nextList;
}
}
/// <summary>
/// Local helper function to get the bag count, the caller should call it from Freeze/Unfreeze block
/// </summary>
/// <returns>The current bag count</returns>
private int GetCountInternal()
{
Debug.Assert(Monitor.IsEntered(GlobalListsLock));
int count = 0;
ThreadLocalList currentList = _headList;
while (currentList != null)
{
checked
{
count += currentList.Count;
}
currentList = currentList._nextList;
}
return count;
}
/// <summary>
/// Local helper function to return the bag item in a list, this is mainly used by CopyTo and ToArray
/// This is not thread safe, should be called in Freeze/UnFreeze bag block
/// </summary>
/// <returns>List the contains the bag items</returns>
private List<T> ToList()
{
Debug.Assert(Monitor.IsEntered(GlobalListsLock));
List<T> list = new List<T>();
ThreadLocalList currentList = _headList;
while (currentList != null)
{
Node currentNode = currentList._head;
while (currentNode != null)
{
list.Add(currentNode._value);
currentNode = currentNode._next;
}
currentList = currentList._nextList;
}
return list;
}
#endregion
#region Inner Classes
/// <summary>
/// A class that represents a node in the lock thread list
/// </summary>
internal class Node
{
public Node(T value)
{
_value = value;
}
public readonly T _value;
public Node _next;
public Node _prev;
}
/// <summary>
/// A class that represents the lock thread list
/// </summary>
internal class ThreadLocalList
{
// Head node in the list, null means the list is empty
internal volatile Node _head;
// Tail node for the list
private volatile Node _tail;
// The current list operation
internal volatile int _currentOp;
// The list count from the Add/Take perspective
private int _count;
// The stealing count
internal int _stealCount;
// Next list in the dictionary values
internal volatile ThreadLocalList _nextList;
// Set if the locl lock is taken
internal bool _lockTaken;
// The owner thread for this list
internal int _ownerThreadId;
// the version of the list, incremented only when the list changed from empty to non empty state
internal volatile int _version;
/// <summary>
/// ThreadLocalList constructor
/// </summary>
/// <param name="ownerThread">The owner thread for this list</param>
internal ThreadLocalList(int ownerThreadId)
{
_ownerThreadId = ownerThreadId;
}
/// <summary>
/// Add new item to head of the list
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="updateCount">Whether to update the count.</param>
internal void Add(T item, bool updateCount)
{
checked
{
_count++;
}
Node node = new Node(item);
if (_head == null)
{
Debug.Assert(_tail == null);
_head = node;
_tail = node;
_version++; // changing from empty state to non empty state
}
else
{
node._next = _head;
_head._prev = node;
_head = node;
}
if (updateCount) // update the count to avoid overflow if this add is synchronized
{
_count = _count - _stealCount;
_stealCount = 0;
}
}
/// <summary>
/// Remove an item from the head of the list
/// </summary>
/// <param name="result">The removed item</param>
internal void Remove(out T result)
{
Debug.Assert(_head != null);
Node head = _head;
_head = _head._next;
if (_head != null)
{
_head._prev = null;
}
else
{
_tail = null;
}
_count--;
result = head._value;
}
/// <summary>
/// Peek an item from the head of the list
/// </summary>
/// <param name="result">the peeked item</param>
/// <returns>True if succeeded, false otherwise</returns>
internal bool Peek(out T result)
{
Node head = _head;
if (head != null)
{
result = head._value;
return true;
}
result = default(T);
return false;
}
/// <summary>
/// Steal an item from the tail of the list
/// </summary>
/// <param name="result">the removed item</param>
/// <param name="remove">remove or peek flag</param>
internal void Steal(out T result, bool remove)
{
Node tail = _tail;
Debug.Assert(tail != null);
if (remove) // Take operation
{
_tail = _tail._prev;
if (_tail != null)
{
_tail._next = null;
}
else
{
_head = null;
}
// Increment the steal count
_stealCount++;
}
result = tail._value;
}
/// <summary>
/// Gets the total list count, it's not thread safe, may provide incorrect count if it is called concurrently
/// </summary>
internal int Count
{
get
{
return _count - _stealCount;
}
}
}
#endregion
}
/// <summary>
/// List operations for ConcurrentBag
/// </summary>
internal enum ListOperation
{
None,
Add,
Take
};
}
| |
using NDatabase;
using NDatabase.Api;
using NDatabase.Meta;
using NDatabase.Meta.Compare;
using NDatabase.Meta.Introspector;
using NDatabase.Oid;
using NDatabase.Tool.Wrappers;
using NDatabase.Triggers;
using NUnit.Framework;
using Test.NDatabase.Odb.Test.VO.Inheritance;
using Test.NDatabase.Odb.Test.VO.Login;
namespace Test.NDatabase.Odb.Test.Intropector
{
public class InstrospectorTest : ODBTest
{
[Test]
public void TestClassInfo()
{
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
var classInfoList = ClassIntrospector.Introspect(user.GetType(), true);
AssertEquals(OdbClassNameResolver.GetFullName(user.GetType()), classInfoList.GetMainClassInfo().FullClassName);
AssertEquals(3, classInfoList.GetMainClassInfo().Attributes.Count);
AssertEquals(3, classInfoList.GetClassInfos().Count);
}
[Test]
public void TestInstanceInfo()
{
const string dbName = "TestInstanceInfo.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
var ci = ClassIntrospector.Introspect(user.GetType(), true).GetMainClassInfo();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
AssertEquals(OdbClassNameResolver.GetFullName(user.GetType()), instanceInfo.GetClassInfo().FullClassName);
AssertEquals("olivier smadja", instanceInfo.GetAttributeValueFromId(ci.GetAttributeId("name")).ToString());
AssertEquals(typeof (AtomicNativeObjectInfo),
instanceInfo.GetAttributeValueFromId(ci.GetAttributeId("name")).GetType());
odb.Close();
}
[Test]
public void TestInstanceInfo2()
{
const string dbName = "TestInstanceInfo2.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
var ci = ClassIntrospector.Introspect(user.GetType(), true).GetMainClassInfo();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
AssertEquals(instanceInfo.GetClassInfo().FullClassName, OdbClassNameResolver.GetFullName(user.GetType()));
AssertEquals(instanceInfo.GetAttributeValueFromId(ci.GetAttributeId("name")).ToString(), "olivier smadja");
odb.Close();
}
[Test]
public void TestCompareCollection1()
{
const string dbName = "introspectortest1.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo) nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
user.SetName("Olivier Smadja");
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection11()
{
const string dbName = "introspectortest2.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
object o = instanceInfo.GetAttributeValueFromId(3);
var nnoiProfile = (NonNativeObjectInfo) o;
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
user.SetName("Olivier Smadja");
user.SetEmail("olivier@ndatabase.net");
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(2, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection2()
{
const string dbName = "introspectortest3.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net",
new Profile("operator", new VO.Login.Function("login")));
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading them from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
user.SetName(null);
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetAttributesIdentification(offsets);
instanceInfo3.GetHeader().SetAttributesIds(ids);
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection4CollectionContentChange()
{
const string dbName = "introspectortest22.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var user = new User("olivier smadja", "user@ndatabase.net", new Profile("operator", function));
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
function.SetName(null);
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetAttributesIdentification(offsets);
instanceInfo3.GetHeader().SetAttributesIds(ids);
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
IObjectInfoComparator comparator = new ObjectInfoComparator();
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(2, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection5()
{
const string dbName = "introspectortest5.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "user@ndatabase.net", profile);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
profile.GetFunctions().Add(new VO.Login.Function("logout"));
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(3, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection6()
{
const string dbName = "introspectortest6.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "user@ndatabase.net", profile);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var ci = ClassIntrospector.Introspect(user.GetType(), true).GetMainClassInfo();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
var nnoi = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(ci.GetAttributeId("profile"));
nnoi.GetHeader().SetAttributesIdentification(offsets);
nnoi.GetHeader().SetAttributesIds(ids);
profile.SetName("ope");
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection7()
{
const string dbName = "introspectortest7.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "user@ndatabase.net", profile);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
// / Set the same name
profile.SetName("operator");
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertFalse(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(0, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection8()
{
const string dbName = "introspectortest8.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "user@ndatabase.net", profile);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
user.SetProfile(null);
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCompareCollection9()
{
const string dbName = "introspectortest9.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "user@ndatabase.net", profile);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
var nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
user.SetName("Kiko");
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
nnoiFunctions = (NonNativeObjectInfo)nnoiProfile.GetAttributeValueFromId(1);
nnoiFunctions.SetOid(OIDFactory.BuildObjectOID(3));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestGetAllFields()
{
var allFields = ClassIntrospector.GetAllFieldsFrom(typeof (FootballPlayer));
AssertEquals(3, allFields.Count);
AssertEquals("groundName", (allFields[0]).Name);
AssertEquals("name", (allFields[1]).Name);
AssertEquals("role", (allFields[2]).Name);
}
[Test]
public void TestIntrospectWithNull()
{
const string dbName = "TestIntrospectWithNull.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net", null);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
object o = instanceInfo.GetAttributeValueFromId(3);
var nnoiProfile = (NonNativeObjectInfo) o;
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
user.SetName("Olivier Smadja");
user.SetEmail("olivier@ndatabase.net");
user.SetProfile(new Profile("pname"));
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(3, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestIntrospectWithNull2()
{
const string dbName = "TestIntrospectWithNull2.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var user = new User("olivier smadja", "user@ndatabase.net", null);
IObjectInfoComparator comparator = new ObjectInfoComparator();
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
// Sets attributes offsets - this is normally done by reading then from
// disk, but in this junit,
// we must set them manually
var offsets = new[] {1L, 2L, 3L};
var ids = new[] {1, 2, 3};
instanceInfo.GetHeader().SetAttributesIdentification(offsets);
instanceInfo.GetHeader().SetAttributesIds(ids);
instanceInfo.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
var nnoiProfile = (NonNativeObjectInfo) instanceInfo.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
user.SetProfile(new Profile("pname"));
var instanceInfo3 =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
instanceInfo3.GetHeader().SetAttributesIdentification(offsets);
instanceInfo3.GetHeader().SetAttributesIds(ids);
instanceInfo3.GetHeader().SetOid(OIDFactory.BuildObjectOID(1));
nnoiProfile = (NonNativeObjectInfo) instanceInfo3.GetAttributeValueFromId(3);
nnoiProfile.SetOid(OIDFactory.BuildObjectOID(2));
AssertTrue(comparator.HasChanged(instanceInfo, instanceInfo3));
AssertEquals(1, comparator.GetNbChanges());
odb.Close();
}
[Test]
public void TestCopy()
{
const string dbName = "introspectortest2.odb";
DeleteBase(dbName);
var odb = OdbFactory.Open(dbName);
var function = new VO.Login.Function("login");
var profile = new Profile("operator", function);
var user = new User("olivier smadja", "olivier@ndatabase.net", profile);
var storageEngine = ((global::NDatabase.Odb)odb).GetStorageEngine();
var instanceInfo =
(NonNativeObjectInfo)
new ObjectIntrospector(storageEngine.GetClassInfoProvider()).GetMetaRepresentation(user, true, null,
new InstrumentationCallbackForStore(null,
false));
var copy = (NonNativeObjectInfo) instanceInfo.CreateCopy(new OdbHashMap<OID, AbstractObjectInfo>(), true);
AssertEquals(3, copy.GetAttributeValues().Length);
var aois = copy.GetAttributeValues();
for (var i = 0; i < aois.Length; i++)
{
var aoi = aois[i];
AssertEquals(instanceInfo.GetAttributeValues()[i].GetOdbTypeId(), aoi.GetOdbTypeId());
}
odb.Close();
}
}
}
| |
//
// X501Name.cs: X.501 Distinguished Names stuff
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 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.
//
using System;
using System.Globalization;
using System.Text;
using Mono.Security;
namespace Mono.Security.X509 {
// References:
// 1. Information technology - Open Systems Interconnection - The Directory: Models
// http://www.itu.int/rec/recommendation.asp?type=items&lang=e&parent=T-REC-X.501-200102-I
// 2. RFC2253: Lightweight Directory Access Protocol (v3): UTF-8 String Representation of Distinguished Names
// http://www.ietf.org/rfc/rfc2253.txt
/*
* Name ::= CHOICE { RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
*/
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class X501 {
static byte[] countryName = { 0x55, 0x04, 0x06 };
static byte[] organizationName = { 0x55, 0x04, 0x0A };
static byte[] organizationalUnitName = { 0x55, 0x04, 0x0B };
static byte[] commonName = { 0x55, 0x04, 0x03 };
static byte[] localityName = { 0x55, 0x04, 0x07 };
static byte[] stateOrProvinceName = { 0x55, 0x04, 0x08 };
static byte[] streetAddress = { 0x55, 0x04, 0x09 };
//static byte[] serialNumber = { 0x55, 0x04, 0x05 };
static byte[] domainComponent = { 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x19 };
static byte[] userid = { 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01 };
static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
private X501 ()
{
}
static public string ToString (ASN1 seq)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < seq.Count; i++) {
ASN1 entry = seq [i];
// multiple entries are valid
for (int k = 0; k < entry.Count; k++) {
ASN1 pair = entry [k];
ASN1 s = pair [1];
if (s == null)
continue;
ASN1 poid = pair [0];
if (poid == null)
continue;
if (poid.CompareValue (countryName))
sb.Append ("C=");
else if (poid.CompareValue (organizationName))
sb.Append ("O=");
else if (poid.CompareValue (organizationalUnitName))
sb.Append ("OU=");
else if (poid.CompareValue (commonName))
sb.Append ("CN=");
else if (poid.CompareValue (localityName))
sb.Append ("L=");
else if (poid.CompareValue (stateOrProvinceName))
sb.Append ("S="); // NOTE: RFC2253 uses ST=
else if (poid.CompareValue (streetAddress))
sb.Append ("STREET=");
else if (poid.CompareValue (domainComponent))
sb.Append ("DC=");
else if (poid.CompareValue (userid))
sb.Append ("UID=");
else if (poid.CompareValue (email))
sb.Append ("E="); // NOTE: Not part of RFC2253
else {
// unknown OID
sb.Append ("OID."); // NOTE: Not present as RFC2253
sb.Append (ASN1Convert.ToOid (poid));
sb.Append ("=");
}
string sValue = null;
// 16bits or 8bits string ? TODO not complete (+special chars!)
if (s.Tag == 0x1E) {
// BMPSTRING
StringBuilder sb2 = new StringBuilder ();
for (int j = 1; j < s.Value.Length; j += 2)
sb2.Append ((char)s.Value[j]);
sValue = sb2.ToString ();
} else {
sValue = System.Text.Encoding.UTF8.GetString (s.Value);
// in some cases we must quote (") the value
// Note: this doesn't seems to conform to RFC2253
char[] specials = { ',', '+', '"', '\\', '<', '>', ';' };
if (sValue.IndexOfAny (specials, 0, sValue.Length) > 0)
sValue = "\"" + sValue + "\"";
else if (sValue.StartsWith (" "))
sValue = "\"" + sValue + "\"";
else if (sValue.EndsWith (" "))
sValue = "\"" + sValue + "\"";
}
sb.Append (sValue);
// separator (not on last iteration)
if (k < entry.Count - 1)
sb.Append (", ");
}
// separator (not on last iteration)
if (i < seq.Count - 1)
sb.Append (", ");
}
return sb.ToString ();
}
static private X520.AttributeTypeAndValue GetAttributeFromOid (string attributeType)
{
switch (attributeType.ToUpper (CultureInfo.InvariantCulture).Trim ()) {
case "C":
return new X520.CountryName ();
case "O":
return new X520.OrganizationName ();
case "OU":
return new X520.OrganizationalUnitName ();
case "CN":
return new X520.CommonName ();
case "L":
return new X520.LocalityName ();
case "S": // Microsoft
case "ST": // RFC2253
return new X520.StateOrProvinceName ();
case "E": // NOTE: Not part of RFC2253
return new X520.EmailAddress ();
case "DC":
// return streetAddress;
case "UID":
// return domainComponent;
default:
return null;
}
}
static public ASN1 FromString (string rdn)
{
if (rdn == null)
throw new ArgumentNullException ("rdn");
// get string from here to ',' or end of string
int start = 0;
int end = 0;
ASN1 asn1 = new ASN1 (0x30);
while (start < rdn.Length) {
end = rdn.IndexOf (',', end) + 1;
if (end == 0)
end = rdn.Length + 1;
string av = rdn.Substring (start, end - start - 1);
// get '=' position in substring
int equal = av.IndexOf ('=');
// get AttributeType
string attributeType = av.Substring (0, equal);
// get value
string attributeValue = av.Substring (equal + 1);
X520.AttributeTypeAndValue atv = GetAttributeFromOid (attributeType);
atv.Value = attributeValue;
asn1.Add (new ASN1 (0x31, atv.GetBytes ()));
// next part
start = end;
if (start != - 1) {
if (end > rdn.Length)
break;
}
}
return asn1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ILRuntime.Runtime.Stack;
namespace ILRuntime.Runtime
{
public static class Extensions
{
public static void GetClassName(this Type type, out string clsName, out string realClsName, out bool isByRef, bool simpleClassName = false)
{
isByRef = type.IsByRef;
int arrayRank = 1;
bool isArray = type.IsArray;
if (isByRef)
{
type = type.GetElementType();
}
if (isArray)
{
arrayRank = type.GetArrayRank();
type = type.GetElementType();
if (type.IsArray)
{
type.GetClassName(out clsName, out realClsName, out isByRef, simpleClassName);
clsName += "_Array";
if (!simpleClassName)
clsName += "_Binding";
if (arrayRank > 1)
clsName += arrayRank;
if (arrayRank <= 1)
realClsName += "[]";
else
{
StringBuilder sb = new StringBuilder();
sb.Append(realClsName);
sb.Append('[');
for (int i = 0; i < arrayRank - 1; i++)
{
sb.Append(',');
}
sb.Append(']');
realClsName = sb.ToString();
}
return;
}
}
string realNamespace = null;
bool isNestedGeneric = false;
if (type.IsNested)
{
string bClsName, bRealClsName;
bool tmp;
var rt = type.ReflectedType;
if(rt.IsGenericType && rt.IsGenericTypeDefinition)
{
if (type.IsGenericType)
{
rt = rt.MakeGenericType(type.GetGenericArguments());
isNestedGeneric = true;
}
}
GetClassName(rt, out bClsName, out bRealClsName, out tmp);
clsName = bClsName + "_";
realNamespace = bRealClsName + ".";
}
else
{
clsName = simpleClassName ? "" : (!string.IsNullOrEmpty(type.Namespace) ? type.Namespace.Replace(".", "_") + "_" : "");
realNamespace = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace + "." : "global::";
}
clsName = clsName + type.Name.Replace(".", "_").Replace("`", "_").Replace("<", "_").Replace(">", "_");
bool isGeneric = false;
string ga = null;
if (type.IsGenericType && !isNestedGeneric)
{
isGeneric = true;
clsName += "_";
ga = "<";
var args = type.GetGenericArguments();
bool first = true;
foreach (var j in args)
{
if (first)
first = false;
else
{
clsName += "_";
ga += ", ";
}
string a, b;
bool tmp;
GetClassName(j, out a, out b, out tmp, true);
clsName += a;
ga += b;
}
ga += ">";
}
if (isArray)
{
clsName += "_Array";
if (arrayRank > 1)
clsName += arrayRank;
}
if (!simpleClassName)
clsName += "_Binding";
realClsName = realNamespace;
if (isGeneric)
{
int idx = type.Name.IndexOf("`");
if (idx > 0)
{
realClsName += type.Name.Substring(0, idx);
realClsName += ga;
}
else
realClsName += type.Name;
}
else
realClsName += type.Name;
if (isArray)
{
if (arrayRank <= 1)
realClsName += "[]";
else
{
StringBuilder sb = new StringBuilder();
sb.Append(realClsName);
sb.Append('[');
for(int i=0;i<arrayRank - 1; i++)
{
sb.Append(',');
}
sb.Append(']');
realClsName = sb.ToString();
}
}
}
public static int ToInt32(this object obj)
{
if (obj is int)
return (int)obj;
if (obj is float)
return (int)(float)obj;
if (obj is long)
return (int)(long)obj;
if (obj is short)
return (int)(short)obj;
if (obj is double)
return (int)(double)obj;
if (obj is byte)
return (int)(byte)obj;
if (obj is Intepreter.ILEnumTypeInstance)
return (int)((Intepreter.ILEnumTypeInstance)obj)[0];
if (obj is uint)
return (int)(uint)obj;
if (obj is ushort)
return (int)(ushort)obj;
if (obj is sbyte)
return (int)(sbyte)obj;
throw new InvalidCastException();
}
public static long ToInt64(this object obj)
{
if (obj is long)
return (long)obj;
if (obj is int)
return (long)(int)obj;
if (obj is float)
return (long)(float)obj;
if (obj is short)
return (long)(short)obj;
if (obj is double)
return (long)(double)obj;
if (obj is byte)
return (long)(byte)obj;
if (obj is uint)
return (long)(uint)obj;
if (obj is ushort)
return (long)(ushort)obj;
if (obj is sbyte)
return (long)(sbyte)obj;
throw new InvalidCastException();
}
public static short ToInt16(this object obj)
{
if (obj is short)
return (short)obj;
if (obj is long)
return (short)(long)obj;
if (obj is int)
return (short)(int)obj;
if (obj is float)
return (short)(float)obj;
if (obj is double)
return (short)(double)obj;
if (obj is byte)
return (short)(byte)obj;
if (obj is uint)
return (short)(uint)obj;
if (obj is ushort)
return (short)(ushort)obj;
if (obj is sbyte)
return (short)(sbyte)obj;
throw new InvalidCastException();
}
public static float ToFloat(this object obj)
{
if (obj is float)
return (float)obj;
if (obj is int)
return (float)(int)obj;
if (obj is long)
return (float)(long)obj;
if (obj is short)
return (float)(short)obj;
if (obj is double)
return (float)(double)obj;
if (obj is byte)
return (float)(byte)obj;
if (obj is uint)
return (float)(uint)obj;
if (obj is ushort)
return (float)(ushort)obj;
if (obj is sbyte)
return (float)(sbyte)obj;
throw new InvalidCastException();
}
public static double ToDouble(this object obj)
{
if (obj is double)
return (double)obj;
if (obj is float)
return (float)obj;
if (obj is int)
return (double)(int)obj;
if (obj is long)
return (double)(long)obj;
if (obj is short)
return (double)(short)obj;
if (obj is byte)
return (double)(byte)obj;
if (obj is uint)
return (double)(uint)obj;
if (obj is ushort)
return (double)(ushort)obj;
if (obj is sbyte)
return (double)(sbyte)obj;
throw new InvalidCastException();
}
public static Type GetActualType(this object value)
{
if (value is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
return ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)value).ILInstance.Type.ReflectionType;
if (value is ILRuntime.Runtime.Intepreter.ILTypeInstance)
return ((ILRuntime.Runtime.Intepreter.ILTypeInstance)value).Type.ReflectionType;
else
return value.GetType();
}
public static bool MatchGenericParameters(this System.Reflection.MethodInfo m, Type[] genericArguments, Type returnType, params Type[] parameters)
{
var param = m.GetParameters();
if (param.Length == parameters.Length)
{
var args = m.GetGenericArguments();
if (args.MatchGenericParameters(m.ReturnType, returnType, genericArguments))
{
for (int i = 0; i < param.Length; i++)
{
if (!args.MatchGenericParameters(param[i].ParameterType, parameters[i], genericArguments))
return false;
}
return true;
}
else
return false;
}
else
return false;
}
public static bool MatchGenericParameters(this Type[] args, Type type, Type q, Type[] genericArguments)
{
if (type.IsGenericParameter)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == type)
{
return q == genericArguments[i];
}
}
throw new NotSupportedException();
}
else
{
if (type.IsArray)
{
if (q.IsArray)
{
return MatchGenericParameters(args, type.GetElementType(), q.GetElementType(), genericArguments);
}
else
return false;
}
else if (type.IsByRef)
{
if (q.IsByRef)
{
return MatchGenericParameters(args, type.GetElementType(), q.GetElementType(), genericArguments);
}
else
return false;
}
else if (type.IsGenericType)
{
if (q.IsGenericType)
{
var t1 = type.GetGenericTypeDefinition();
var t2 = type.GetGenericTypeDefinition();
if (t1 == t2)
{
var argA = type.GetGenericArguments();
var argB = q.GetGenericArguments();
if (argA.Length == argB.Length)
{
for (int i = 0; i < argA.Length; i++)
{
if (!MatchGenericParameters(args, argA[i], argB[i], genericArguments))
return false;
}
return true;
}
else
return false;
}
else
return false;
}
else
return false;
}
else
return type == q;
}
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.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;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ChargebackDispute
/// </summary>
[DataContract]
public partial class ChargebackDispute : IEquatable<ChargebackDispute>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ChargebackDispute" /> class.
/// </summary>
/// <param name="accountNumber">Account number.</param>
/// <param name="adjustmentRequestText">Adjustment request text.</param>
/// <param name="amount">Amount.</param>
/// <param name="authCode">Auth code.</param>
/// <param name="caseNumber">Case number.</param>
/// <param name="chargebackDisputeOid">Chargeback Dispute Oid.</param>
/// <param name="chargebackDts">Chargeback dts.</param>
/// <param name="currency">Currency.</param>
/// <param name="customerCareNotes">Customer care notes.</param>
/// <param name="encryptionKey">Encryption key.</param>
/// <param name="expirationDts">Expiration Dts.</param>
/// <param name="faxFailureReason">Fax failure reason.</param>
/// <param name="faxNumber">Fax number.</param>
/// <param name="faxTransactionId">Fax transaction id.</param>
/// <param name="icsid">icsid.</param>
/// <param name="merchantAccountProfileOid">Merchant account profile oid.</param>
/// <param name="order">order.</param>
/// <param name="orderId">Order Id.</param>
/// <param name="partialCardNumber">Partial card number.</param>
/// <param name="pdfFileOid">PDF file oid.</param>
/// <param name="reasonCode">Reason code.</param>
/// <param name="status">Status.</param>
/// <param name="websiteUrl">Website URL.</param>
public ChargebackDispute(string accountNumber = default(string), string adjustmentRequestText = default(string), decimal? amount = default(decimal?), string authCode = default(string), string caseNumber = default(string), int? chargebackDisputeOid = default(int?), string chargebackDts = default(string), string currency = default(string), string customerCareNotes = default(string), string encryptionKey = default(string), string expirationDts = default(string), string faxFailureReason = default(string), string faxNumber = default(string), long? faxTransactionId = default(long?), string icsid = default(string), int? merchantAccountProfileOid = default(int?), Order order = default(Order), string orderId = default(string), string partialCardNumber = default(string), string pdfFileOid = default(string), string reasonCode = default(string), string status = default(string), string websiteUrl = default(string))
{
this.AccountNumber = accountNumber;
this.AdjustmentRequestText = adjustmentRequestText;
this.Amount = amount;
this.AuthCode = authCode;
this.CaseNumber = caseNumber;
this.ChargebackDisputeOid = chargebackDisputeOid;
this.ChargebackDts = chargebackDts;
this.Currency = currency;
this.CustomerCareNotes = customerCareNotes;
this.EncryptionKey = encryptionKey;
this.ExpirationDts = expirationDts;
this.FaxFailureReason = faxFailureReason;
this.FaxNumber = faxNumber;
this.FaxTransactionId = faxTransactionId;
this.Icsid = icsid;
this.MerchantAccountProfileOid = merchantAccountProfileOid;
this.Order = order;
this.OrderId = orderId;
this.PartialCardNumber = partialCardNumber;
this.PdfFileOid = pdfFileOid;
this.ReasonCode = reasonCode;
this.Status = status;
this.WebsiteUrl = websiteUrl;
}
/// <summary>
/// Account number
/// </summary>
/// <value>Account number</value>
[DataMember(Name="account_number", EmitDefaultValue=false)]
public string AccountNumber { get; set; }
/// <summary>
/// Adjustment request text
/// </summary>
/// <value>Adjustment request text</value>
[DataMember(Name="adjustment_request_text", EmitDefaultValue=false)]
public string AdjustmentRequestText { get; set; }
/// <summary>
/// Amount
/// </summary>
/// <value>Amount</value>
[DataMember(Name="amount", EmitDefaultValue=false)]
public decimal? Amount { get; set; }
/// <summary>
/// Auth code
/// </summary>
/// <value>Auth code</value>
[DataMember(Name="auth_code", EmitDefaultValue=false)]
public string AuthCode { get; set; }
/// <summary>
/// Case number
/// </summary>
/// <value>Case number</value>
[DataMember(Name="case_number", EmitDefaultValue=false)]
public string CaseNumber { get; set; }
/// <summary>
/// Chargeback Dispute Oid
/// </summary>
/// <value>Chargeback Dispute Oid</value>
[DataMember(Name="chargeback_dispute_oid", EmitDefaultValue=false)]
public int? ChargebackDisputeOid { get; set; }
/// <summary>
/// Chargeback dts
/// </summary>
/// <value>Chargeback dts</value>
[DataMember(Name="chargeback_dts", EmitDefaultValue=false)]
public string ChargebackDts { get; set; }
/// <summary>
/// Currency
/// </summary>
/// <value>Currency</value>
[DataMember(Name="currency", EmitDefaultValue=false)]
public string Currency { get; set; }
/// <summary>
/// Customer care notes
/// </summary>
/// <value>Customer care notes</value>
[DataMember(Name="customer_care_notes", EmitDefaultValue=false)]
public string CustomerCareNotes { get; set; }
/// <summary>
/// Encryption key
/// </summary>
/// <value>Encryption key</value>
[DataMember(Name="encryption_key", EmitDefaultValue=false)]
public string EncryptionKey { get; set; }
/// <summary>
/// Expiration Dts
/// </summary>
/// <value>Expiration Dts</value>
[DataMember(Name="expiration_dts", EmitDefaultValue=false)]
public string ExpirationDts { get; set; }
/// <summary>
/// Fax failure reason
/// </summary>
/// <value>Fax failure reason</value>
[DataMember(Name="fax_failure_reason", EmitDefaultValue=false)]
public string FaxFailureReason { get; set; }
/// <summary>
/// Fax number
/// </summary>
/// <value>Fax number</value>
[DataMember(Name="fax_number", EmitDefaultValue=false)]
public string FaxNumber { get; set; }
/// <summary>
/// Fax transaction id
/// </summary>
/// <value>Fax transaction id</value>
[DataMember(Name="fax_transaction_id", EmitDefaultValue=false)]
public long? FaxTransactionId { get; set; }
/// <summary>
/// icsid
/// </summary>
/// <value>icsid</value>
[DataMember(Name="icsid", EmitDefaultValue=false)]
public string Icsid { get; set; }
/// <summary>
/// Merchant account profile oid
/// </summary>
/// <value>Merchant account profile oid</value>
[DataMember(Name="merchant_account_profile_oid", EmitDefaultValue=false)]
public int? MerchantAccountProfileOid { get; set; }
/// <summary>
/// Gets or Sets Order
/// </summary>
[DataMember(Name="order", EmitDefaultValue=false)]
public Order Order { get; set; }
/// <summary>
/// Order Id
/// </summary>
/// <value>Order Id</value>
[DataMember(Name="order_id", EmitDefaultValue=false)]
public string OrderId { get; set; }
/// <summary>
/// Partial card number
/// </summary>
/// <value>Partial card number</value>
[DataMember(Name="partial_card_number", EmitDefaultValue=false)]
public string PartialCardNumber { get; set; }
/// <summary>
/// PDF file oid
/// </summary>
/// <value>PDF file oid</value>
[DataMember(Name="pdf_file_oid", EmitDefaultValue=false)]
public string PdfFileOid { get; set; }
/// <summary>
/// Reason code
/// </summary>
/// <value>Reason code</value>
[DataMember(Name="reason_code", EmitDefaultValue=false)]
public string ReasonCode { get; set; }
/// <summary>
/// Status
/// </summary>
/// <value>Status</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Website URL
/// </summary>
/// <value>Website URL</value>
[DataMember(Name="website_url", EmitDefaultValue=false)]
public string WebsiteUrl { 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 ChargebackDispute {\n");
sb.Append(" AccountNumber: ").Append(AccountNumber).Append("\n");
sb.Append(" AdjustmentRequestText: ").Append(AdjustmentRequestText).Append("\n");
sb.Append(" Amount: ").Append(Amount).Append("\n");
sb.Append(" AuthCode: ").Append(AuthCode).Append("\n");
sb.Append(" CaseNumber: ").Append(CaseNumber).Append("\n");
sb.Append(" ChargebackDisputeOid: ").Append(ChargebackDisputeOid).Append("\n");
sb.Append(" ChargebackDts: ").Append(ChargebackDts).Append("\n");
sb.Append(" Currency: ").Append(Currency).Append("\n");
sb.Append(" CustomerCareNotes: ").Append(CustomerCareNotes).Append("\n");
sb.Append(" EncryptionKey: ").Append(EncryptionKey).Append("\n");
sb.Append(" ExpirationDts: ").Append(ExpirationDts).Append("\n");
sb.Append(" FaxFailureReason: ").Append(FaxFailureReason).Append("\n");
sb.Append(" FaxNumber: ").Append(FaxNumber).Append("\n");
sb.Append(" FaxTransactionId: ").Append(FaxTransactionId).Append("\n");
sb.Append(" Icsid: ").Append(Icsid).Append("\n");
sb.Append(" MerchantAccountProfileOid: ").Append(MerchantAccountProfileOid).Append("\n");
sb.Append(" Order: ").Append(Order).Append("\n");
sb.Append(" OrderId: ").Append(OrderId).Append("\n");
sb.Append(" PartialCardNumber: ").Append(PartialCardNumber).Append("\n");
sb.Append(" PdfFileOid: ").Append(PdfFileOid).Append("\n");
sb.Append(" ReasonCode: ").Append(ReasonCode).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" WebsiteUrl: ").Append(WebsiteUrl).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ChargebackDispute);
}
/// <summary>
/// Returns true if ChargebackDispute instances are equal
/// </summary>
/// <param name="input">Instance of ChargebackDispute to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ChargebackDispute input)
{
if (input == null)
return false;
return
(
this.AccountNumber == input.AccountNumber ||
(this.AccountNumber != null &&
this.AccountNumber.Equals(input.AccountNumber))
) &&
(
this.AdjustmentRequestText == input.AdjustmentRequestText ||
(this.AdjustmentRequestText != null &&
this.AdjustmentRequestText.Equals(input.AdjustmentRequestText))
) &&
(
this.Amount == input.Amount ||
(this.Amount != null &&
this.Amount.Equals(input.Amount))
) &&
(
this.AuthCode == input.AuthCode ||
(this.AuthCode != null &&
this.AuthCode.Equals(input.AuthCode))
) &&
(
this.CaseNumber == input.CaseNumber ||
(this.CaseNumber != null &&
this.CaseNumber.Equals(input.CaseNumber))
) &&
(
this.ChargebackDisputeOid == input.ChargebackDisputeOid ||
(this.ChargebackDisputeOid != null &&
this.ChargebackDisputeOid.Equals(input.ChargebackDisputeOid))
) &&
(
this.ChargebackDts == input.ChargebackDts ||
(this.ChargebackDts != null &&
this.ChargebackDts.Equals(input.ChargebackDts))
) &&
(
this.Currency == input.Currency ||
(this.Currency != null &&
this.Currency.Equals(input.Currency))
) &&
(
this.CustomerCareNotes == input.CustomerCareNotes ||
(this.CustomerCareNotes != null &&
this.CustomerCareNotes.Equals(input.CustomerCareNotes))
) &&
(
this.EncryptionKey == input.EncryptionKey ||
(this.EncryptionKey != null &&
this.EncryptionKey.Equals(input.EncryptionKey))
) &&
(
this.ExpirationDts == input.ExpirationDts ||
(this.ExpirationDts != null &&
this.ExpirationDts.Equals(input.ExpirationDts))
) &&
(
this.FaxFailureReason == input.FaxFailureReason ||
(this.FaxFailureReason != null &&
this.FaxFailureReason.Equals(input.FaxFailureReason))
) &&
(
this.FaxNumber == input.FaxNumber ||
(this.FaxNumber != null &&
this.FaxNumber.Equals(input.FaxNumber))
) &&
(
this.FaxTransactionId == input.FaxTransactionId ||
(this.FaxTransactionId != null &&
this.FaxTransactionId.Equals(input.FaxTransactionId))
) &&
(
this.Icsid == input.Icsid ||
(this.Icsid != null &&
this.Icsid.Equals(input.Icsid))
) &&
(
this.MerchantAccountProfileOid == input.MerchantAccountProfileOid ||
(this.MerchantAccountProfileOid != null &&
this.MerchantAccountProfileOid.Equals(input.MerchantAccountProfileOid))
) &&
(
this.Order == input.Order ||
(this.Order != null &&
this.Order.Equals(input.Order))
) &&
(
this.OrderId == input.OrderId ||
(this.OrderId != null &&
this.OrderId.Equals(input.OrderId))
) &&
(
this.PartialCardNumber == input.PartialCardNumber ||
(this.PartialCardNumber != null &&
this.PartialCardNumber.Equals(input.PartialCardNumber))
) &&
(
this.PdfFileOid == input.PdfFileOid ||
(this.PdfFileOid != null &&
this.PdfFileOid.Equals(input.PdfFileOid))
) &&
(
this.ReasonCode == input.ReasonCode ||
(this.ReasonCode != null &&
this.ReasonCode.Equals(input.ReasonCode))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.WebsiteUrl == input.WebsiteUrl ||
(this.WebsiteUrl != null &&
this.WebsiteUrl.Equals(input.WebsiteUrl))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AccountNumber != null)
hashCode = hashCode * 59 + this.AccountNumber.GetHashCode();
if (this.AdjustmentRequestText != null)
hashCode = hashCode * 59 + this.AdjustmentRequestText.GetHashCode();
if (this.Amount != null)
hashCode = hashCode * 59 + this.Amount.GetHashCode();
if (this.AuthCode != null)
hashCode = hashCode * 59 + this.AuthCode.GetHashCode();
if (this.CaseNumber != null)
hashCode = hashCode * 59 + this.CaseNumber.GetHashCode();
if (this.ChargebackDisputeOid != null)
hashCode = hashCode * 59 + this.ChargebackDisputeOid.GetHashCode();
if (this.ChargebackDts != null)
hashCode = hashCode * 59 + this.ChargebackDts.GetHashCode();
if (this.Currency != null)
hashCode = hashCode * 59 + this.Currency.GetHashCode();
if (this.CustomerCareNotes != null)
hashCode = hashCode * 59 + this.CustomerCareNotes.GetHashCode();
if (this.EncryptionKey != null)
hashCode = hashCode * 59 + this.EncryptionKey.GetHashCode();
if (this.ExpirationDts != null)
hashCode = hashCode * 59 + this.ExpirationDts.GetHashCode();
if (this.FaxFailureReason != null)
hashCode = hashCode * 59 + this.FaxFailureReason.GetHashCode();
if (this.FaxNumber != null)
hashCode = hashCode * 59 + this.FaxNumber.GetHashCode();
if (this.FaxTransactionId != null)
hashCode = hashCode * 59 + this.FaxTransactionId.GetHashCode();
if (this.Icsid != null)
hashCode = hashCode * 59 + this.Icsid.GetHashCode();
if (this.MerchantAccountProfileOid != null)
hashCode = hashCode * 59 + this.MerchantAccountProfileOid.GetHashCode();
if (this.Order != null)
hashCode = hashCode * 59 + this.Order.GetHashCode();
if (this.OrderId != null)
hashCode = hashCode * 59 + this.OrderId.GetHashCode();
if (this.PartialCardNumber != null)
hashCode = hashCode * 59 + this.PartialCardNumber.GetHashCode();
if (this.PdfFileOid != null)
hashCode = hashCode * 59 + this.PdfFileOid.GetHashCode();
if (this.ReasonCode != null)
hashCode = hashCode * 59 + this.ReasonCode.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.WebsiteUrl != null)
hashCode = hashCode * 59 + this.WebsiteUrl.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// AccountNumber (string) maxLength
if(this.AccountNumber != null && this.AccountNumber.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for AccountNumber, length must be less than 50.", new [] { "AccountNumber" });
}
// AuthCode (string) maxLength
if(this.AuthCode != null && this.AuthCode.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for AuthCode, length must be less than 20.", new [] { "AuthCode" });
}
// CaseNumber (string) maxLength
if(this.CaseNumber != null && this.CaseNumber.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CaseNumber, length must be less than 50.", new [] { "CaseNumber" });
}
// Currency (string) maxLength
if(this.Currency != null && this.Currency.Length > 10)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Currency, length must be less than 10.", new [] { "Currency" });
}
// EncryptionKey (string) maxLength
if(this.EncryptionKey != null && this.EncryptionKey.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for EncryptionKey, length must be less than 100.", new [] { "EncryptionKey" });
}
// FaxFailureReason (string) maxLength
if(this.FaxFailureReason != null && this.FaxFailureReason.Length > 250)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FaxFailureReason, length must be less than 250.", new [] { "FaxFailureReason" });
}
// FaxNumber (string) maxLength
if(this.FaxNumber != null && this.FaxNumber.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FaxNumber, length must be less than 20.", new [] { "FaxNumber" });
}
// Icsid (string) maxLength
if(this.Icsid != null && this.Icsid.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Icsid, length must be less than 50.", new [] { "Icsid" });
}
// OrderId (string) maxLength
if(this.OrderId != null && this.OrderId.Length > 30)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for OrderId, length must be less than 30.", new [] { "OrderId" });
}
// PartialCardNumber (string) maxLength
if(this.PartialCardNumber != null && this.PartialCardNumber.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PartialCardNumber, length must be less than 20.", new [] { "PartialCardNumber" });
}
// PdfFileOid (string) maxLength
if(this.PdfFileOid != null && this.PdfFileOid.Length > 32)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PdfFileOid, length must be less than 32.", new [] { "PdfFileOid" });
}
// ReasonCode (string) maxLength
if(this.ReasonCode != null && this.ReasonCode.Length > 70)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ReasonCode, length must be less than 70.", new [] { "ReasonCode" });
}
// Status (string) maxLength
if(this.Status != null && this.Status.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Status, length must be less than 20.", new [] { "Status" });
}
// WebsiteUrl (string) maxLength
if(this.WebsiteUrl != null && this.WebsiteUrl.Length > 250)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for WebsiteUrl, length must be less than 250.", new [] { "WebsiteUrl" });
}
yield break;
}
}
}
| |
// 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!
namespace Google.Cloud.Dataflow.V1Beta3.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedJobsV1Beta3ClientSnippets
{
/// <summary>Snippet for CreateJob</summary>
public void CreateJobRequestObject()
{
// Snippet: CreateJob(CreateJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
CreateJobRequest request = new CreateJobRequest
{
ProjectId = "",
Job = new Job(),
View = JobView.Unknown,
ReplaceJobId = "",
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.CreateJob(request);
// End snippet
}
/// <summary>Snippet for CreateJobAsync</summary>
public async Task CreateJobRequestObjectAsync()
{
// Snippet: CreateJobAsync(CreateJobRequest, CallSettings)
// Additional: CreateJobAsync(CreateJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
CreateJobRequest request = new CreateJobRequest
{
ProjectId = "",
Job = new Job(),
View = JobView.Unknown,
ReplaceJobId = "",
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.CreateJobAsync(request);
// End snippet
}
/// <summary>Snippet for GetJob</summary>
public void GetJobRequestObject()
{
// Snippet: GetJob(GetJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
GetJobRequest request = new GetJobRequest
{
ProjectId = "",
JobId = "",
View = JobView.Unknown,
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.GetJob(request);
// End snippet
}
/// <summary>Snippet for GetJobAsync</summary>
public async Task GetJobRequestObjectAsync()
{
// Snippet: GetJobAsync(GetJobRequest, CallSettings)
// Additional: GetJobAsync(GetJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
GetJobRequest request = new GetJobRequest
{
ProjectId = "",
JobId = "",
View = JobView.Unknown,
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.GetJobAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateJob</summary>
public void UpdateJobRequestObject()
{
// Snippet: UpdateJob(UpdateJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "",
JobId = "",
Job = new Job(),
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.UpdateJob(request);
// End snippet
}
/// <summary>Snippet for UpdateJobAsync</summary>
public async Task UpdateJobRequestObjectAsync()
{
// Snippet: UpdateJobAsync(UpdateJobRequest, CallSettings)
// Additional: UpdateJobAsync(UpdateJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "",
JobId = "",
Job = new Job(),
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.UpdateJobAsync(request);
// End snippet
}
/// <summary>Snippet for ListJobs</summary>
public void ListJobsRequestObject()
{
// Snippet: ListJobs(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Job item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListJobsAsync</summary>
public async Task ListJobsRequestObjectAsync()
{
// Snippet: ListJobsAsync(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Job item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListJobs</summary>
public void AggregatedListJobsRequestObject()
{
// Snippet: AggregatedListJobs(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Job item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListJobsAsync</summary>
public async Task AggregatedListJobsRequestObjectAsync()
{
// Snippet: AggregatedListJobsAsync(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Job item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CheckActiveJobs</summary>
public void CheckActiveJobsRequestObject()
{
// Snippet: CheckActiveJobs(CheckActiveJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", };
// Make the request
CheckActiveJobsResponse response = jobsV1Beta3Client.CheckActiveJobs(request);
// End snippet
}
/// <summary>Snippet for CheckActiveJobsAsync</summary>
public async Task CheckActiveJobsRequestObjectAsync()
{
// Snippet: CheckActiveJobsAsync(CheckActiveJobsRequest, CallSettings)
// Additional: CheckActiveJobsAsync(CheckActiveJobsRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", };
// Make the request
CheckActiveJobsResponse response = await jobsV1Beta3Client.CheckActiveJobsAsync(request);
// End snippet
}
/// <summary>Snippet for SnapshotJob</summary>
public void SnapshotJobRequestObject()
{
// Snippet: SnapshotJob(SnapshotJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
SnapshotJobRequest request = new SnapshotJobRequest
{
ProjectId = "",
JobId = "",
Ttl = new Duration(),
Location = "",
SnapshotSources = false,
Description = "",
};
// Make the request
Snapshot response = jobsV1Beta3Client.SnapshotJob(request);
// End snippet
}
/// <summary>Snippet for SnapshotJobAsync</summary>
public async Task SnapshotJobRequestObjectAsync()
{
// Snippet: SnapshotJobAsync(SnapshotJobRequest, CallSettings)
// Additional: SnapshotJobAsync(SnapshotJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
SnapshotJobRequest request = new SnapshotJobRequest
{
ProjectId = "",
JobId = "",
Ttl = new Duration(),
Location = "",
SnapshotSources = false,
Description = "",
};
// Make the request
Snapshot response = await jobsV1Beta3Client.SnapshotJobAsync(request);
// End snippet
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// EmployeeOrders Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(EmployeeOrdersConverter))]
public partial class EmployeeOrders : BusinessListBase<EmployeeOrders, EmployeeOrder>, ICustomTypeDescriptor, IVEHasBrokenRules
{
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
// One To Many
public EmployeeOrder this[Order myOrder]
{
get
{
foreach (EmployeeOrder order in this)
if (order.OrderID == myOrder.OrderID)
return order;
return null;
}
}
public new System.Collections.Generic.IList<EmployeeOrder> Items
{
get { return base.Items; }
}
public EmployeeOrder GetItem(Order myOrder)
{
foreach (EmployeeOrder order in this)
if (order.OrderID == myOrder.OrderID)
return order;
return null;
}
public EmployeeOrder Add() // One to Many
{
EmployeeOrder order = EmployeeOrder.New();
this.Add(order);
return order;
}
public void Remove(Order myOrder)
{
foreach (EmployeeOrder order in this)
{
if (order.OrderID == myOrder.OrderID)
{
Remove(order);
break;
}
}
}
public bool Contains(Order myOrder)
{
foreach (EmployeeOrder order in this)
if (order.OrderID == myOrder.OrderID)
return true;
return false;
}
public bool ContainsDeleted(Order myOrder)
{
foreach (EmployeeOrder order in DeletedList)
if (order.OrderID == myOrder.OrderID)
return true;
return false;
}
#endregion
#region ValidationRules
public IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules=null;
foreach(EmployeeOrder employeeOrder in this)
if ((hasBrokenRules = employeeOrder.HasBrokenRules) != null) return hasBrokenRules;
return hasBrokenRules;
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
#endregion
#region Factory Methods
internal static EmployeeOrders New()
{
return new EmployeeOrders();
}
internal static EmployeeOrders Get(SafeDataReader dr)
{
return new EmployeeOrders(dr);
}
public static EmployeeOrders GetByEmployeeID(int? employeeID)
{
try
{
return DataPortal.Fetch<EmployeeOrders>(new EmployeeIDCriteria(employeeID));
}
catch (Exception ex)
{
throw new DbCslaException("Error on EmployeeOrders.GetByEmployeeID", ex);
}
}
private EmployeeOrders()
{
MarkAsChild();
}
internal EmployeeOrders(SafeDataReader dr)
{
MarkAsChild();
Fetch(dr);
}
#endregion
#region Data Access Portal
// called to load data from the database
private void Fetch(SafeDataReader dr)
{
this.RaiseListChangedEvents = false;
while (dr.Read())
this.Add(EmployeeOrder.Get(dr));
this.RaiseListChangedEvents = true;
}
[Serializable()]
private class EmployeeIDCriteria
{
public EmployeeIDCriteria(int? employeeID)
{
_EmployeeID = employeeID;
}
private int? _EmployeeID;
public int? EmployeeID
{
get { return _EmployeeID; }
set { _EmployeeID = value; }
}
}
private void DataPortal_Fetch(EmployeeIDCriteria criteria)
{
this.RaiseListChangedEvents = false;
Database.LogInfo("EmployeeOrders.DataPortal_FetchEmployeeID", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getOrdersByEmployeeID";
cm.Parameters.AddWithValue("@EmployeeID", criteria.EmployeeID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read()) this.Add(new EmployeeOrder(dr));
}
}
}
}
catch (Exception ex)
{
Database.LogException("EmployeeOrders.DataPortal_FetchEmployeeID", ex);
throw new DbCslaException("EmployeeOrders.DataPortal_Fetch", ex);
}
this.RaiseListChangedEvents = true;
}
internal void Update(Employee employee)
{
this.RaiseListChangedEvents = false;
try
{
// update (thus deleting) any deleted child objects
foreach (EmployeeOrder obj in DeletedList)
obj.Delete();// TODO: Should this be SQLDelete
// now that they are deleted, remove them from memory too
DeletedList.Clear();
// add/update any current child objects
foreach (EmployeeOrder obj in this)
{
if (obj.IsNew)
obj.Insert(employee);
else
obj.Update(employee);
}
}
finally
{
this.RaiseListChangedEvents = true;
}
}
#endregion
#region ICustomTypeDescriptor impl
public String GetClassName()
{ return TypeDescriptor.GetClassName(this, true); }
public AttributeCollection GetAttributes()
{ return TypeDescriptor.GetAttributes(this, true); }
public String GetComponentName()
{ return TypeDescriptor.GetComponentName(this, true); }
public TypeConverter GetConverter()
{ return TypeDescriptor.GetConverter(this, true); }
public EventDescriptor GetDefaultEvent()
{ return TypeDescriptor.GetDefaultEvent(this, true); }
public PropertyDescriptor GetDefaultProperty()
{ return TypeDescriptor.GetDefaultProperty(this, true); }
public object GetEditor(Type editorBaseType)
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); }
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{ return TypeDescriptor.GetEvents(this, attributes, true); }
public EventDescriptorCollection GetEvents()
{ return TypeDescriptor.GetEvents(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd)
{ return this; }
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list
for (int i = 0; i < this.Items.Count; i++)
{
// Create a property descriptor for the item and add to the property descriptor collection
EmployeeOrdersPropertyDescriptor pd = new EmployeeOrdersPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
} // Class
#region Property Descriptor
/// <summary>
/// Summary description for CollectionPropertyDescriptor.
/// </summary>
public partial class EmployeeOrdersPropertyDescriptor : vlnListPropertyDescriptor
{
private EmployeeOrder Item { get { return (EmployeeOrder) _Item;} }
public EmployeeOrdersPropertyDescriptor(EmployeeOrders collection, int index):base(collection, index){;}
}
#endregion
#region Converter
internal class EmployeeOrdersConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is EmployeeOrders)
{
// Return department and department role separated by comma.
return ((EmployeeOrders) value).Items.Count.ToString() + " Orders";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Asn1;
namespace System.Security.Cryptography
{
internal static class KeyFormatHelper
{
internal delegate void KeyReader<TRet>(ReadOnlyMemory<byte> key, in AlgorithmIdentifierAsn algId, out TRet ret);
internal static unsafe void ReadSubjectPublicKeyInfo<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadSubjectPublicKeyInfo(validOids, manager.Memory, keyReader, out bytesRead, out ret);
}
}
}
internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo(
string[] validOids,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
// X.509 SubjectPublicKeyInfo is described as DER.
AsnReader reader = new AsnReader(source, AsnEncodingRules.DER);
int read = reader.PeekEncodedValue().Length;
SubjectPublicKeyInfoAsn.Decode(reader, out SubjectPublicKeyInfoAsn spki);
if (Array.IndexOf(validOids, spki.Algorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
bytesRead = read;
return spki.SubjectPublicKey;
}
private static void ReadSubjectPublicKeyInfo<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
// X.509 SubjectPublicKeyInfo is described as DER.
AsnReader reader = new AsnReader(source, AsnEncodingRules.DER);
int read = reader.PeekEncodedValue().Length;
SubjectPublicKeyInfoAsn.Decode(reader, out SubjectPublicKeyInfoAsn spki);
if (Array.IndexOf(validOids, spki.Algorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
keyReader(spki.SubjectPublicKey, spki.Algorithm, out ret);
bytesRead = read;
}
internal static unsafe void ReadPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadPkcs8(validOids, manager.Memory, keyReader, out bytesRead, out ret);
}
}
}
internal static ReadOnlyMemory<byte> ReadPkcs8(
string[] validOids,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
PrivateKeyInfoAsn.Decode(reader, out PrivateKeyInfoAsn privateKeyInfo);
if (Array.IndexOf(validOids, privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
bytesRead = read;
return privateKeyInfo.PrivateKey;
}
private static void ReadPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
PrivateKeyInfoAsn.Decode(reader, out PrivateKeyInfoAsn privateKeyInfo);
if (Array.IndexOf(validOids, privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value) < 0)
{
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);
}
// Fails if there are unconsumed bytes.
keyReader(privateKeyInfo.PrivateKey, privateKeyInfo.PrivateKeyAlgorithm, out ret);
bytesRead = read;
}
internal static unsafe void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
ReadOnlySpan<char> password,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadEncryptedPkcs8(validOids, manager.Memory, password, keyReader, out bytesRead, out ret);
}
}
}
internal static unsafe void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlySpan<byte> source,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
ReadEncryptedPkcs8(validOids, manager.Memory, passwordBytes, keyReader, out bytesRead, out ret);
}
}
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<char> password,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
ReadEncryptedPkcs8(
validOids,
source,
password,
ReadOnlySpan<byte>.Empty,
keyReader,
out bytesRead,
out ret);
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
ReadEncryptedPkcs8(
validOids,
source,
ReadOnlySpan<char>.Empty,
passwordBytes,
keyReader,
out bytesRead,
out ret);
}
private static void ReadEncryptedPkcs8<TRet>(
string[] validOids,
ReadOnlyMemory<byte> source,
ReadOnlySpan<char> password,
ReadOnlySpan<byte> passwordBytes,
KeyReader<TRet> keyReader,
out int bytesRead,
out TRet ret)
{
AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
int read = reader.PeekEncodedValue().Length;
EncryptedPrivateKeyInfoAsn.Decode(reader, out EncryptedPrivateKeyInfoAsn epki);
// No supported encryption algorithms produce more bytes of decryption output than there
// were of decryption input.
byte[] decrypted = CryptoPool.Rent(epki.EncryptedData.Length);
Memory<byte> decryptedMemory = decrypted;
try
{
int decryptedBytes = PasswordBasedEncryption.Decrypt(
epki.EncryptionAlgorithm,
password,
passwordBytes,
epki.EncryptedData.Span,
decrypted);
decryptedMemory = decryptedMemory.Slice(0, decryptedBytes);
ReadPkcs8(
validOids,
decryptedMemory,
keyReader,
out int innerRead,
out ret);
if (innerRead != decryptedMemory.Length)
{
ret = default;
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
bytesRead = read;
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decryptedMemory.Span);
CryptoPool.Return(decrypted, clearSize: 0);
}
}
internal static AsnWriter WritePkcs8(AsnWriter algorithmIdentifierWriter, AsnWriter privateKeyWriter)
{
// Ensure both input writers are balanced.
ReadOnlySpan<byte> algorithmIdentifier = algorithmIdentifierWriter.EncodeAsSpan();
ReadOnlySpan<byte> privateKey = privateKeyWriter.EncodeAsSpan();
Debug.Assert(algorithmIdentifier.Length > 0, "algorithmIdentifier was empty");
Debug.Assert(algorithmIdentifier[0] == 0x30, "algorithmIdentifier is not a constructed sequence");
Debug.Assert(privateKey.Length > 0, "privateKey was empty");
// https://tools.ietf.org/html/rfc5208#section-5
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
// PrivateKey ::= OCTET STRING
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
// PrivateKeyInfo
writer.PushSequence();
// https://tools.ietf.org/html/rfc5208#section-5 says the current version is 0.
writer.WriteInteger(0);
// PKI.Algorithm (AlgorithmIdentifier)
writer.WriteEncodedValue(algorithmIdentifier);
// PKI.privateKey
writer.WriteOctetString(privateKey);
// We don't currently accept attributes, so... done.
writer.PopSequence();
return writer;
}
internal static unsafe AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<char> password,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
return WriteEncryptedPkcs8(
password,
ReadOnlySpan<byte>.Empty,
pkcs8Writer,
pbeParameters);
}
internal static AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<byte> passwordBytes,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
return WriteEncryptedPkcs8(
ReadOnlySpan<char>.Empty,
passwordBytes,
pkcs8Writer,
pbeParameters);
}
private static unsafe AsnWriter WriteEncryptedPkcs8(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> passwordBytes,
AsnWriter pkcs8Writer,
PbeParameters pbeParameters)
{
ReadOnlySpan<byte> pkcs8Span = pkcs8Writer.EncodeAsSpan();
PasswordBasedEncryption.InitiateEncryption(
pbeParameters,
out SymmetricAlgorithm cipher,
out string hmacOid,
out string encryptionAlgorithmOid,
out bool isPkcs12);
byte[] encryptedRent = null;
Span<byte> encryptedSpan = default;
AsnWriter writer = null;
try
{
Debug.Assert(cipher.BlockSize <= 128, $"Encountered unexpected block size: {cipher.BlockSize}");
Span<byte> iv = stackalloc byte[cipher.BlockSize / 8];
Span<byte> salt = stackalloc byte[16];
// We need at least one block size beyond the input data size.
encryptedRent = CryptoPool.Rent(
checked(pkcs8Span.Length + (cipher.BlockSize / 8)));
RandomNumberGenerator.Fill(salt);
int written = PasswordBasedEncryption.Encrypt(
password,
passwordBytes,
cipher,
isPkcs12,
pkcs8Span,
pbeParameters,
salt,
encryptedRent,
iv);
encryptedSpan = encryptedRent.AsSpan(0, written);
writer = new AsnWriter(AsnEncodingRules.DER);
// PKCS8 EncryptedPrivateKeyInfo
writer.PushSequence();
// EncryptedPrivateKeyInfo.encryptionAlgorithm
PasswordBasedEncryption.WritePbeAlgorithmIdentifier(
writer,
isPkcs12,
encryptionAlgorithmOid,
salt,
pbeParameters.IterationCount,
hmacOid,
iv);
// encryptedData
writer.WriteOctetString(encryptedSpan);
writer.PopSequence();
AsnWriter ret = writer;
// Don't dispose writer on the way out.
writer = null;
return ret;
}
finally
{
CryptographicOperations.ZeroMemory(encryptedSpan);
CryptoPool.Return(encryptedRent, clearSize: 0);
writer?.Dispose();
cipher.Dispose();
}
}
internal static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return DecryptPkcs8(
inputPassword,
ReadOnlySpan<byte>.Empty,
source,
out bytesRead);
}
internal static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<byte> inputPasswordBytes,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
return DecryptPkcs8(
ReadOnlySpan<char>.Empty,
inputPasswordBytes,
source,
out bytesRead);
}
private static ArraySegment<byte> DecryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlySpan<byte> inputPasswordBytes,
ReadOnlyMemory<byte> source,
out int bytesRead)
{
AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
int localRead = reader.PeekEncodedValue().Length;
EncryptedPrivateKeyInfoAsn.Decode(reader, out EncryptedPrivateKeyInfoAsn epki);
// No supported encryption algorithms produce more bytes of decryption output than there
// were of decryption input.
byte[] decrypted = CryptoPool.Rent(epki.EncryptedData.Length);
try
{
int decryptedBytes = PasswordBasedEncryption.Decrypt(
epki.EncryptionAlgorithm,
inputPassword,
inputPasswordBytes,
epki.EncryptedData.Span,
decrypted);
bytesRead = localRead;
return new ArraySegment<byte>(decrypted, 0, decryptedBytes);
}
catch (CryptographicException e)
{
CryptoPool.Return(decrypted);
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
}
internal static AsnWriter ReencryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> current,
ReadOnlySpan<char> newPassword,
PbeParameters pbeParameters)
{
ArraySegment<byte> decrypted = DecryptPkcs8(
inputPassword,
current,
out int bytesRead);
try
{
if (bytesRead != current.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
using (AsnWriter pkcs8Writer = new AsnWriter(AsnEncodingRules.BER))
{
pkcs8Writer.WriteEncodedValue(decrypted);
return WriteEncryptedPkcs8(
newPassword,
pkcs8Writer,
pbeParameters);
}
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decrypted);
CryptoPool.Return(decrypted.Array, clearSize: 0);
}
}
internal static AsnWriter ReencryptPkcs8(
ReadOnlySpan<char> inputPassword,
ReadOnlyMemory<byte> current,
ReadOnlySpan<byte> newPasswordBytes,
PbeParameters pbeParameters)
{
ArraySegment<byte> decrypted = DecryptPkcs8(
inputPassword,
current,
out int bytesRead);
try
{
if (bytesRead != current.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
using (AsnWriter pkcs8Writer = new AsnWriter(AsnEncodingRules.BER))
{
pkcs8Writer.WriteEncodedValue(decrypted);
return WriteEncryptedPkcs8(
newPasswordBytes,
pkcs8Writer,
pbeParameters);
}
}
catch (CryptographicException e)
{
throw new CryptographicException(SR.Cryptography_Pkcs8_EncryptedReadFailed, e);
}
finally
{
CryptographicOperations.ZeroMemory(decrypted);
CryptoPool.Return(decrypted.Array, clearSize: 0);
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
#define APIHACK
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Threading;
using mshtml;
using OpenLiveWriter.BlogClient.Clients;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.CoreServices.Progress;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Localization;
using Google.Apis.Blogger.v3;
using Google.Apis.Services;
namespace OpenLiveWriter.BlogClient.Detection
{
public class BlogServiceDetector : BlogServiceDetectorBase
{
private IBlogSettingsAccessor _blogSettings;
public BlogServiceDetector(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, IBlogSettingsAccessor blogSettings, IBlogCredentialsAccessor credentials)
: base(uiContext, hiddenBrowserParentControl, blogSettings.Id, blogSettings.HomepageUrl, credentials)
{
_blogSettings = blogSettings;
}
protected override object DetectBlogService(IProgressHost progressHost)
{
using (BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode()) //supress prompting for credentials
{
try
{
// get the weblog homepage and rsd service description if available
IHTMLDocument2 weblogDOM = GetWeblogHomepageDOM(progressHost);
// while we have the DOM available, scan for a writer manifest url
if (_manifestDownloadInfo == null)
{
string manifestUrl = WriterEditingManifest.DiscoverUrl(_homepageUrl, weblogDOM);
if (manifestUrl != String.Empty)
_manifestDownloadInfo = new WriterEditingManifestDownloadInfo(manifestUrl);
}
string html = weblogDOM != null ? HTMLDocumentHelper.HTMLDocToString(weblogDOM) : null;
bool detectionSucceeded = false;
if (!detectionSucceeded)
detectionSucceeded = AttemptGenericAtomLinkDetection(_homepageUrl, html, !ApplicationDiagnostics.PreferAtom);
if (!detectionSucceeded && _blogSettings.IsGoogleBloggerBlog)
detectionSucceeded = AttemptBloggerDetection(_homepageUrl, html);
if (!detectionSucceeded)
{
RsdServiceDescription rsdServiceDescription = GetRsdServiceDescription(progressHost, weblogDOM);
// if there was no rsd service description or we fail to auto-configure from the
// rsd description then move on to other auto-detection techniques
if (!(detectionSucceeded = AttemptRsdBasedDetection(progressHost, rsdServiceDescription)))
{
// try detection by analyzing the homepage url and contents
UpdateProgress(progressHost, 75, Res.Get(StringId.ProgressAnalyzingHomepage));
if (weblogDOM != null)
detectionSucceeded = AttemptHomepageBasedDetection(_homepageUrl, html);
else
detectionSucceeded = AttemptUrlBasedDetection(_homepageUrl);
// if we successfully detected then see if we can narrow down
// to a specific weblog
if (detectionSucceeded)
{
if (!BlogProviderParameters.UrlContainsParameters(_postApiUrl))
{
// we detected the provider, now see if we can detect the weblog id
// (or at lease the list of the user's weblogs)
UpdateProgress(progressHost, 80, Res.Get(StringId.ProgressAnalyzingWeblogList));
AttemptUserBlogDetection();
}
}
}
}
if (!detectionSucceeded && html != null)
AttemptGenericAtomLinkDetection(_homepageUrl, html, false);
// finished
UpdateProgress(progressHost, 100, String.Empty);
}
catch (OperationCancelledException)
{
// WasCancelled == true
}
catch (BlogClientOperationCancelledException)
{
Cancel();
// WasCancelled == true
}
catch (BlogAccountDetectorException ex)
{
if (ApplicationDiagnostics.AutomationMode)
Trace.WriteLine(ex.ToString());
else
Trace.Fail(ex.ToString());
// ErrorOccurred == true
}
catch (Exception ex)
{
// ErrorOccurred == true
Trace.Fail(ex.Message, ex.ToString());
ReportError(MessageId.WeblogDetectionUnexpectedError, ex.Message);
}
return this;
}
}
private bool AttemptGenericAtomLinkDetection(string url, string html, bool preferredOnly)
{
const string GENERIC_ATOM_PROVIDER_ID = "D48F1B5A-06E6-4f0f-BD76-74F34F520792";
if (html == null)
return false;
HtmlExtractor ex = new HtmlExtractor(html);
if (ex
.SeekWithin("<head>", "<body>")
.SeekWithin("<link href rel='service' type='application/atomsvc+xml'>", "</head>")
.Success)
{
IBlogProvider atomProvider = BlogProviderManager.FindProvider(GENERIC_ATOM_PROVIDER_ID);
BeginTag bt = ex.Element as BeginTag;
if (preferredOnly)
{
string classes = bt.GetAttributeValue("class");
if (classes == null)
return false;
if (!Regex.IsMatch(classes, @"\bpreferred\b"))
return false;
}
string linkUrl = bt.GetAttributeValue("href");
Debug.WriteLine("Atom service link detected in the blog homepage");
_providerId = atomProvider.Id;
_serviceName = atomProvider.Name;
_clientType = atomProvider.ClientType;
_blogName = string.Empty;
_postApiUrl = linkUrl;
IBlogClient client = BlogClientManager.CreateClient(atomProvider.ClientType, _postApiUrl, _credentials);
client.VerifyCredentials();
_usersBlogs = client.GetUsersBlogs();
if (_usersBlogs.Length == 1)
{
_hostBlogId = _usersBlogs[0].Id;
_blogName = _usersBlogs[0].Name;
/*
if (_usersBlogs[0].HomepageUrl != null && _usersBlogs[0].HomepageUrl.Length > 0)
_homepageUrl = _usersBlogs[0].HomepageUrl;
*/
}
// attempt to read the blog name from the homepage title
if (_blogName == null || _blogName.Length == 0)
{
HtmlExtractor ex2 = new HtmlExtractor(html);
if (ex2.Seek("<title>").Success)
{
_blogName = ex2.CollectTextUntil("title");
}
}
return true;
}
return false;
}
private class BloggerGeneratorCriterion : IElementPredicate
{
public bool IsMatch(Element e)
{
BeginTag tag = e as BeginTag;
if (tag == null)
return false;
if (!tag.NameEquals("meta"))
return false;
if (tag.GetAttributeValue("name") != "generator")
return false;
string generator = tag.GetAttributeValue("content");
if (generator == null || CaseInsensitiveComparer.DefaultInvariant.Compare("blogger", generator) != 0)
return false;
return true;
}
}
/// <summary>
/// Do special Blogger-specific detection logic. We want to
/// use the Blogger Atom endpoints specified in the HTML, not
/// the Blogger endpoint in the RSD.
/// </summary>
private bool AttemptBloggerDetection(string homepageUrl, string html)
{
Debug.Assert(string.IsNullOrEmpty(homepageUrl), "Google Blogger blogs don't know the homepageUrl");
Debug.Assert(string.IsNullOrEmpty(html), "Google Blogger blogs don't know the homepageUrl");
const string BLOGGER_V3_PROVIDER_ID = "343F1D83-1098-43F4-AE86-93AFC7602855";
IBlogProvider bloggerProvider = BlogProviderManager.FindProvider(BLOGGER_V3_PROVIDER_ID);
if (bloggerProvider == null)
{
Trace.Fail("Couldn't retrieve Blogger provider");
return false;
}
BlogAccountDetector blogAccountDetector = new BlogAccountDetector(bloggerProvider.ClientType, bloggerProvider.PostApiUrl, _credentials);
if (blogAccountDetector.ValidateService())
{
CopySettingsFromProvider(bloggerProvider);
_usersBlogs = blogAccountDetector.UsersBlogs;
if (_usersBlogs.Length == 1)
{
_hostBlogId = _usersBlogs[0].Id;
_blogName = _usersBlogs[0].Name;
_homepageUrl = _usersBlogs[0].HomepageUrl;
}
// If we didn't find the specific blog, we'll prompt the user with the list of blogs
return true;
}
else
{
AuthenticationErrorOccurred = blogAccountDetector.Exception is BlogClientAuthenticationException;
ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams);
return false;
}
}
private bool AttemptRsdBasedDetection(IProgressHost progressHost, RsdServiceDescription rsdServiceDescription)
{
// always return alse for null description
if (rsdServiceDescription == null)
return false;
string providerId = String.Empty;
BlogAccount blogAccount = null;
// check for a match on rsd engine link
foreach (IBlogProvider provider in BlogProviderManager.Providers)
{
blogAccount = provider.DetectAccountFromRsdHomepageLink(rsdServiceDescription);
if (blogAccount != null)
{
providerId = provider.Id;
break;
}
}
// if none found on engine link, match on engine name
if (blogAccount == null)
{
foreach (IBlogProvider provider in BlogProviderManager.Providers)
{
blogAccount = provider.DetectAccountFromRsdEngineName(rsdServiceDescription);
if (blogAccount != null)
{
providerId = provider.Id;
break;
}
}
}
// No provider associated with the RSD file, try to gin one up (will only
// work if the RSD file contains an API for one of our supported client types)
if (blogAccount == null)
{
// try to create one from RSD
blogAccount = BlogAccountFromRsdServiceDescription.Create(rsdServiceDescription);
}
// if we have an rsd-detected weblog
if (blogAccount != null)
{
// confirm that the credentials are OK
UpdateProgress(progressHost, 65, Res.Get(StringId.ProgressVerifyingInterface));
BlogAccountDetector blogAccountDetector = new BlogAccountDetector(
blogAccount.ClientType, blogAccount.PostApiUrl, _credentials);
if (blogAccountDetector.ValidateService())
{
// copy basic account info
_providerId = providerId;
_serviceName = blogAccount.ServiceName;
_clientType = blogAccount.ClientType;
_hostBlogId = blogAccount.BlogId;
_postApiUrl = blogAccount.PostApiUrl;
// see if we can improve on the blog name guess we already
// have from the <title> element of the homepage
BlogInfo blogInfo = blogAccountDetector.DetectAccount(_homepageUrl, _hostBlogId);
if (blogInfo != null)
_blogName = blogInfo.Name;
}
else
{
// report user-authorization error
ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams);
}
// success!
return true;
}
else
{
// couldn't do it
return false;
}
}
private bool AttemptUrlBasedDetection(string url)
{
// matched provider
IBlogProvider blogAccountProvider = null;
// do url-based matching
foreach (IBlogProvider provider in BlogProviderManager.Providers)
{
if (provider.IsProviderForHomepageUrl(url))
{
blogAccountProvider = provider;
break;
}
}
if (blogAccountProvider != null)
{
CopySettingsFromProvider(blogAccountProvider);
return true;
}
else
{
return false;
}
}
private bool AttemptContentBasedDetection(string homepageContent)
{
// matched provider
IBlogProvider blogAccountProvider = null;
// do url-based matching
foreach (IBlogProvider provider in BlogProviderManager.Providers)
{
if (provider.IsProviderForHomepageContent(homepageContent))
{
blogAccountProvider = provider;
break;
}
}
if (blogAccountProvider != null)
{
CopySettingsFromProvider(blogAccountProvider);
return true;
}
else
{
return false;
}
}
private bool AttemptHomepageBasedDetection(string homepageUrl, string homepageContent)
{
if (AttemptUrlBasedDetection(homepageUrl))
{
return true;
}
else
{
return AttemptContentBasedDetection(homepageContent);
}
}
private RsdServiceDescription GetRsdServiceDescription(IProgressHost progressHost, IHTMLDocument2 weblogDOM)
{
if (weblogDOM != null)
{
// try to download an RSD description
UpdateProgress(progressHost, 50, Res.Get(StringId.ProgressAnalyzingInterface));
return RsdServiceDetector.DetectFromWeblog(_homepageUrl, weblogDOM);
}
else
{
return null;
}
}
private class BlogAccountFromRsdServiceDescription : BlogAccount
{
public static BlogAccount Create(RsdServiceDescription rsdServiceDescription)
{
try
{
return new BlogAccountFromRsdServiceDescription(rsdServiceDescription);
}
catch (NoSupportedRsdClientTypeException)
{
return null;
}
}
private BlogAccountFromRsdServiceDescription(RsdServiceDescription rsdServiceDescription)
{
// look for supported apis from highest fidelity to lowest
RsdApi rsdApi = rsdServiceDescription.ScanForApi("WordPress");
if (rsdApi == null)
rsdApi = rsdServiceDescription.ScanForApi("MovableType");
if (rsdApi == null)
rsdApi = rsdServiceDescription.ScanForApi("MetaWeblog");
if (rsdApi != null)
{
Init(rsdServiceDescription.EngineName, rsdApi.Name, rsdApi.ApiLink, rsdApi.BlogId);
return;
}
else
{
// couldn't find a supported api type so we fall through to here
throw new NoSupportedRsdClientTypeException();
}
}
}
private class NoSupportedRsdClientTypeException : ApplicationException
{
public NoSupportedRsdClientTypeException()
: base("No supported Rsd client-type")
{
}
}
}
/// <summary>
/// Blog settings detector for SharePoint blogs.
/// </summary>
public class SharePointBlogDetector : BlogServiceDetectorBase
{
private IBlogCredentials _blogCredentials;
public SharePointBlogDetector(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, string localBlogId, string homepageUrl, IBlogCredentialsAccessor credentials, IBlogCredentials blogCredentials)
: base(uiContext, hiddenBrowserParentControl, localBlogId, homepageUrl, credentials)
{
_blogCredentials = blogCredentials;
}
protected override object DetectBlogService(IProgressHost progressHost)
{
using (BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode()) //supress prompting for credentials
{
try
{
// copy basic account info
IBlogProvider provider = BlogProviderManager.FindProvider("4AA58E69-8C24-40b1-BACE-3BB14237E8F9");
_providerId = provider.Id;
_serviceName = provider.Name;
_clientType = provider.ClientType;
//calculate the API url based on the homepage Url.
// API URL Format: <blogurl>/_layouts/metaweblog.aspx
string homepagePath = UrlHelper.SafeToAbsoluteUri(new Uri(_homepageUrl)).Split('?')[0];
if (homepagePath == null)
homepagePath = "/";
//trim off any file information included in the URL (ex: /default.aspx)
int lastPathPartIndex = homepagePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
if (lastPathPartIndex != -1)
{
string lastPathPart = homepagePath.Substring(lastPathPartIndex);
if (lastPathPart.IndexOf('.') != -1)
{
homepagePath = homepagePath.Substring(0, lastPathPartIndex);
if (homepagePath == String.Empty)
homepagePath = "/";
}
}
if (homepagePath != "/" && homepagePath.EndsWith("/", StringComparison.OrdinalIgnoreCase)) //trim off trailing slash
homepagePath = homepagePath.Substring(0, homepagePath.Length - 1);
//Update the homepage url
_homepageUrl = homepagePath;
_postApiUrl = String.Format(CultureInfo.InvariantCulture, "{0}/_layouts/metaweblog.aspx", homepagePath);
if (VerifyCredentialsAndDetectAuthScheme(_postApiUrl, _blogCredentials, _credentials))
{
AuthenticationErrorOccurred = false;
//detect the user's blog ID.
if (!BlogProviderParameters.UrlContainsParameters(_postApiUrl))
{
// we detected the provider, now see if we can detect the weblog id
// (or at lease the list of the user's weblogs)
UpdateProgress(progressHost, 80, Res.Get(StringId.ProgressAnalyzingWeblogList));
AttemptUserBlogDetection();
}
}
else
AuthenticationErrorOccurred = true;
}
catch (OperationCancelledException)
{
// WasCancelled == true
}
catch (BlogClientOperationCancelledException)
{
Cancel();
// WasCancelled == true
}
catch (BlogAccountDetectorException)
{
// ErrorOccurred == true
}
catch (BlogClientAuthenticationException)
{
AuthenticationErrorOccurred = true;
// ErrorOccurred == true
}
catch (Exception ex)
{
// ErrorOccurred == true
ReportError(MessageId.WeblogDetectionUnexpectedError, ex.Message);
}
}
return this;
}
/*private string DiscoverPostApiUrl(string baseUrl, string blogPath)
{
}*/
/// <summary>
/// Verifies the user credentials and determines whether SharePoint is configure to use HTTP or MetaWeblog authentication
/// </summary>
/// <param name="postApiUrl"></param>
/// <param name="blogCredentials"></param>
/// <param name="credentials"></param>
/// <returns></returns>
private static bool VerifyCredentialsAndDetectAuthScheme(string postApiUrl, IBlogCredentials blogCredentials, IBlogCredentialsAccessor credentials)
{
BlogClientAttribute blogClientAttr = (BlogClientAttribute)typeof(SharePointClient).GetCustomAttributes(typeof(BlogClientAttribute), false)[0];
SharePointClient client = (SharePointClient)BlogClientManager.CreateClient(blogClientAttr.TypeName, postApiUrl, credentials);
return SharePointClient.VerifyCredentialsAndDetectAuthScheme(blogCredentials, client);
}
}
public abstract class BlogServiceDetectorBase : MultipartAsyncOperation, ITemporaryBlogSettingsDetectionContext
{
public BlogServiceDetectorBase(IBlogClientUIContext uiContext, Control hiddenBrowserParentControl, string localBlogId, string homepageUrl, IBlogCredentialsAccessor credentials)
: base(uiContext)
{
// save references
_uiContext = uiContext;
_localBlogId = localBlogId;
_homepageUrl = homepageUrl;
_credentials = credentials;
// add blog service detection
AddProgressOperation(
new ProgressOperation(DetectBlogService),
35);
// add settings downloading (note: this operation will be a no-op
// in the case where we don't succesfully detect a weblog)
AddProgressOperation(
new ProgressOperation(DetectWeblogSettings),
new ProgressOperationCompleted(DetectWeblogSettingsCompleted),
30);
// add template downloading (note: this operation will be a no-op in the
// case where we don't successfully detect a weblog)
_blogEditingTemplateDetector = new BlogEditingTemplateDetector(uiContext, hiddenBrowserParentControl);
AddProgressOperation(
new ProgressOperation(_blogEditingTemplateDetector.DetectTemplate),
35);
}
public BlogInfo[] UsersBlogs
{
get { return _usersBlogs; }
}
public string ProviderId
{
get { return _providerId; }
}
public string ServiceName
{
get { return _serviceName; }
}
public string ClientType
{
get { return _clientType; }
}
public string PostApiUrl
{
get { return _postApiUrl; }
}
public string HostBlogId
{
get { return _hostBlogId; }
}
public string BlogName
{
get { return _blogName; }
}
public IDictionary OptionOverrides
{
get { return _optionOverrides; }
}
public IDictionary HomePageOverrides
{
get { return _homePageOverrides; }
}
public IDictionary UserOptionOverrides
{
get { return null; }
}
public IBlogProviderButtonDescription[] ButtonDescriptions
{
get { return _buttonDescriptions; }
}
public BlogPostCategory[] Categories
{
get { return _categories; }
}
public BlogPostKeyword[] Keywords
{
get { return _keywords; }
}
public byte[] FavIcon
{
get { return _favIcon; }
}
public byte[] Image
{
get { return _image; }
}
public byte[] WatermarkImage
{
get { return _watermarkImage; }
}
public BlogEditingTemplateFile[] BlogTemplateFiles
{
get { return _blogEditingTemplateDetector.BlogTemplateFiles; }
}
public Color? PostBodyBackgroundColor
{
get { return _blogEditingTemplateDetector.PostBodyBackgroundColor; }
}
public bool WasCancelled
{
get { return CancelRequested; }
}
public bool ErrorOccurred
{
get { return _errorMessageType != MessageId.None; }
}
public bool AuthenticationErrorOccurred
{
get { return _authenticationErrorOccured; }
set { _authenticationErrorOccured = value; }
}
private bool _authenticationErrorOccured = false;
public bool TemplateDownloadFailed
{
get { return _blogEditingTemplateDetector.ExceptionOccurred; }
}
IBlogCredentialsAccessor IBlogSettingsDetectionContext.Credentials
{
get { return _credentials; }
}
string IBlogSettingsDetectionContext.HomepageUrl
{
get { return _homepageUrl; }
}
public WriterEditingManifestDownloadInfo ManifestDownloadInfo
{
get { return _manifestDownloadInfo; }
set { _manifestDownloadInfo = value; }
}
string IBlogSettingsDetectionContext.ClientType
{
get { return _clientType; }
set { _clientType = value; }
}
byte[] IBlogSettingsDetectionContext.FavIcon
{
get { return _favIcon; }
set { _favIcon = value; }
}
byte[] IBlogSettingsDetectionContext.Image
{
get { return _image; }
set { _image = value; }
}
byte[] IBlogSettingsDetectionContext.WatermarkImage
{
get { return _watermarkImage; }
set { _watermarkImage = value; }
}
BlogPostCategory[] IBlogSettingsDetectionContext.Categories
{
get { return _categories; }
set { _categories = value; }
}
BlogPostKeyword[] IBlogSettingsDetectionContext.Keywords
{
get { return _keywords; }
set { _keywords = value; }
}
IDictionary IBlogSettingsDetectionContext.OptionOverrides
{
get { return _optionOverrides; }
set { _optionOverrides = value; }
}
IDictionary IBlogSettingsDetectionContext.HomePageOverrides
{
get { return _homePageOverrides; }
set { _homePageOverrides = value; }
}
IBlogProviderButtonDescription[] IBlogSettingsDetectionContext.ButtonDescriptions
{
get { return _buttonDescriptions; }
set { _buttonDescriptions = value; }
}
public BlogInfo[] AvailableImageEndpoints
{
get { return availableImageEndpoints; }
set { availableImageEndpoints = value; }
}
public void ShowLastError(IWin32Window owner)
{
if (ErrorOccurred)
{
DisplayMessage.Show(_errorMessageType, owner, _errorMessageParams);
}
else
{
Trace.Fail("Called ShowLastError when no error occurred");
}
}
public static byte[] SafeDownloadFavIcon(string homepageUrl)
{
try
{
string favIconUrl = UrlHelper.UrlCombine(homepageUrl, "favicon.ico");
using (Stream favIconStream = HttpRequestHelper.SafeDownloadFile(favIconUrl))
{
using (MemoryStream memoryStream = new MemoryStream())
{
StreamHelper.Transfer(favIconStream, memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream.ToArray();
}
}
}
catch
{
return null;
}
}
protected abstract object DetectBlogService(IProgressHost progressHost);
protected void AttemptUserBlogDetection()
{
BlogAccountDetector blogAccountDetector = new BlogAccountDetector(
_clientType, _postApiUrl, _credentials);
if (blogAccountDetector.ValidateService())
{
BlogInfo blogInfo = blogAccountDetector.DetectAccount(_homepageUrl, _hostBlogId);
if (blogInfo != null)
{
// save the detected info
// TODO: Commenting out next line for Spaces demo tomorrow.
// need to decide whether to keep it commented out going forward.
// _homepageUrl = blogInfo.HomepageUrl;
_hostBlogId = blogInfo.Id;
_blogName = blogInfo.Name;
}
// always save the list of user's blogs
_usersBlogs = blogAccountDetector.UsersBlogs;
}
else
{
AuthenticationErrorOccurred = blogAccountDetector.Exception is BlogClientAuthenticationException;
ReportErrorAndFail(blogAccountDetector.ErrorMessageType, blogAccountDetector.ErrorMessageParams);
}
}
protected IHTMLDocument2 GetWeblogHomepageDOM(IProgressHost progressHost)
{
// try download the weblog home page
UpdateProgress(progressHost, 25, Res.Get(StringId.ProgressAnalyzingHomepage));
string responseUri;
IHTMLDocument2 weblogDOM = HTMLDocumentHelper.SafeGetHTMLDocumentFromUrl(_homepageUrl, out responseUri);
if (responseUri != null && responseUri != _homepageUrl)
{
_homepageUrl = responseUri;
}
if (weblogDOM != null)
{
// default the blog name to the title of the document
if (weblogDOM.title != null)
{
_blogName = weblogDOM.title;
// drop anything to the right of a "|", as it usually is a site name
int index = _blogName.IndexOf("|", StringComparison.OrdinalIgnoreCase);
if (index > 0)
{
string newname = _blogName.Substring(0, index).Trim();
if (newname != String.Empty)
_blogName = newname;
}
}
}
return weblogDOM;
}
protected void CopySettingsFromProvider(IBlogProvider blogAccountProvider)
{
_providerId = blogAccountProvider.Id;
_serviceName = blogAccountProvider.Name;
_clientType = blogAccountProvider.ClientType;
_postApiUrl = ProcessPostUrlMacros(blogAccountProvider.PostApiUrl);
}
private string ProcessPostUrlMacros(string postApiUrl)
{
return postApiUrl.Replace("<username>", _credentials.Username);
}
private object DetectWeblogSettings(IProgressHost progressHost)
{
using (BlogClientUIContextSilentMode uiContextScope = new BlogClientUIContextSilentMode()) //supress prompting for credentials
{
// no-op if we don't have a blog-id to work with
if (HostBlogId == String.Empty)
return this;
try
{
// detect settings
BlogSettingsDetector blogSettingsDetector = new BlogSettingsDetector(this);
blogSettingsDetector.DetectSettings(progressHost);
}
catch (OperationCancelledException)
{
// WasCancelled == true
}
catch (BlogClientOperationCancelledException)
{
Cancel();
// WasCancelled == true
}
catch (Exception ex)
{
Trace.Fail("Unexpected error occurred while detecting weblog settings: " + ex.ToString());
}
return this;
}
}
private void DetectWeblogSettingsCompleted(object result)
{
// no-op if we don't have a blog detected
if (HostBlogId == String.Empty)
return;
// get the editing template directory
string blogTemplateDir = BlogEditingTemplate.GetBlogTemplateDir(_localBlogId);
// set context for template detector
BlogAccount blogAccount = new BlogAccount(ServiceName, ClientType, PostApiUrl, HostBlogId);
_blogEditingTemplateDetector.SetContext(blogAccount, _credentials, _homepageUrl, blogTemplateDir, _manifestDownloadInfo, false, _providerId, _optionOverrides, null, _homePageOverrides);
}
protected void UpdateProgress(IProgressHost progressHost, int percent, string message)
{
if (CancelRequested)
throw new OperationCancelledException();
progressHost.UpdateProgress(percent, 100, message);
}
protected void ReportError(MessageId errorMessageType, params object[] errorMessageParams)
{
_errorMessageType = errorMessageType;
_errorMessageParams = errorMessageParams;
}
protected void ReportErrorAndFail(MessageId errorMessageType, params object[] errorMessageParams)
{
ReportError(errorMessageType, errorMessageParams);
throw new BlogAccountDetectorException();
}
protected class BlogAccountDetectorException : ApplicationException
{
public BlogAccountDetectorException() : base("Blog account detector did not succeed")
{
}
}
/// <summary>
/// Blog account we are scanning
/// </summary>
protected string _localBlogId;
protected string _homepageUrl;
protected WriterEditingManifestDownloadInfo _manifestDownloadInfo = null;
protected IBlogCredentialsAccessor _credentials;
// BlogTemplateDetector
private BlogEditingTemplateDetector _blogEditingTemplateDetector;
/// <summary>
/// Results of scanning
/// </summary>
protected string _providerId = String.Empty;
protected string _serviceName = String.Empty;
protected string _clientType = String.Empty;
protected string _postApiUrl = String.Empty;
protected string _hostBlogId = String.Empty;
protected string _blogName = String.Empty;
protected BlogInfo[] _usersBlogs = new BlogInfo[] { };
// if we are unable to detect these values then leave them null
// as an indicator that their values are "unknown" vs. "empty"
// callers can then choose to not overwrite any existing settings
// in this case
protected IDictionary _homePageOverrides = null;
protected IDictionary _optionOverrides = null;
private BlogPostCategory[] _categories = null;
private BlogPostKeyword[] _keywords = null;
private byte[] _favIcon = null;
private byte[] _image = null;
private byte[] _watermarkImage = null;
private IBlogProviderButtonDescription[] _buttonDescriptions = null;
// error info
private MessageId _errorMessageType;
private object[] _errorMessageParams;
protected IBlogClientUIContext _uiContext;
private BlogInfo[] availableImageEndpoints;
}
}
| |
namespace Neo4j.AspNet.Identity
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Neo4jClient;
using Neo4jClient.Cypher;
public class Neo4jUserStore<TUser> :
IUserLoginStore<TUser>,
IUserClaimStore<TUser>,
IUserRoleStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserStore<TUser>,
IUserEmailStore<TUser>,
IUserLockoutStore<TUser, object>,
IUserTwoFactorStore<TUser, string>,
IUserPhoneNumberStore<TUser>
where TUser : IdentityUser, IUser<string>, new()
{
private readonly IGraphClient _graphClient;
private bool _disposed;
public Neo4jUserStore(IGraphClient graphClient, string userLabel = null)
{
_graphClient = graphClient;
UserLabel = string.IsNullOrWhiteSpace(userLabel) ? ApplicationUser.Labels : userLabel;
}
private string UserLabel { get; }
/// <inheritdoc />
public async Task<DateTimeOffset> GetLockoutEndDateAsync(TUser user)
{
return DateTimeOffset.UtcNow;
}
/// <inheritdoc />
public async Task SetLockoutEndDateAsync(TUser user, DateTimeOffset lockoutEnd)
{
}
/// <inheritdoc />
public async Task<int> IncrementAccessFailedCountAsync(TUser user)
{
return 0;
}
/// <inheritdoc />
public async Task ResetAccessFailedCountAsync(TUser user)
{
}
/// <inheritdoc />
public async Task<int> GetAccessFailedCountAsync(TUser user)
{
return 0;
}
/// <inheritdoc />
public async Task<bool> GetLockoutEnabledAsync(TUser user)
{
return false;
}
/// <inheritdoc />
public async Task SetLockoutEnabledAsync(TUser user, bool enabled)
{
}
/// <inheritdoc />
public async Task SetPhoneNumberAsync(TUser user, string phoneNumber)
{
Throw.ArgumentException.IfNull(user, "user");
Throw.ArgumentException.IfNull(phoneNumber, "phoneNumber");
ThrowIfDisposed();
user.PhoneNumber = phoneNumber;
}
/// <inheritdoc />
public async Task<string> GetPhoneNumberAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
return user.PhoneNumber;
}
/// <inheritdoc />
public async Task<bool> GetPhoneNumberConfirmedAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
return user.PhoneNumberConfirmed;
}
/// <inheritdoc />
public async Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed)
{
Throw.ArgumentException.IfNull(user, "user");
user.PhoneNumberConfirmed = confirmed;
}
/// <inheritdoc />
public async Task SetTwoFactorEnabledAsync(TUser user, bool enabled)
{
}
/// <inheritdoc />
public async Task<bool> GetTwoFactorEnabledAsync(TUser user)
{
return false;
}
/// <summary>
/// Gets: MATCH (
/// </summary>
private ICypherFluentQuery UserMatch(string userIdentifier = "u")
{
return new CypherFluentQuery(_graphClient).Match($"({userIdentifier}:{UserLabel})");
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
#region Internal Classes for Serialization
internal class FindUserResult<T>
where T : IdentityUser, new()
{
public T User { private get; set; }
public IEnumerable<Neo4jUserLoginInfo> Logins { private get; set; }
public IEnumerable<IdentityUserClaim> Claims { private get; set; }
public T Combine()
{
var output = User;
if (Logins != null)
output.Logins = new List<UserLoginInfo>(Logins.Select(l => l.ToUserLoginInfo()));
if (Claims != null)
output.Claims = new List<IdentityUserClaim>(Claims);
return output;
}
}
// ReSharper disable once ClassNeverInstantiated.Local
internal class Role
{
public string Name { get; set; }
}
// ReSharper disable once ClassNeverInstantiated.Local
internal class Neo4jUserLoginInfo
{
/// <summary>
/// Provider for the linked login, i.e. Facebook, Google, etc.
/// </summary>
public string LoginProvider { get; set; }
/// <summary>
/// User specific key for the login provider
/// </summary>
public string ProviderKey { get; set; }
public UserLoginInfo ToUserLoginInfo()
{
return new UserLoginInfo(LoginProvider, ProviderKey);
}
}
#endregion Internal Classes for Serialization
#region IUserLoginStore
/// <inheritdoc />
public async Task AddLoginAsync(TUser user, UserLoginInfo login)
{
Throw.ArgumentException.IfNull(user, "user");
Throw.ArgumentException.IfNull(login, "login");
ThrowIfDisposed();
await Task.Run(() =>
{
if (!user.Logins.Any(x => (x.LoginProvider == login.LoginProvider) && (x.ProviderKey == login.ProviderKey)))
user.Logins.Add(login);
});
}
/// <inheritdoc />
public async Task<TUser> FindAsync(UserLoginInfo login)
{
Throw.ArgumentException.IfNull(login, "login");
ThrowIfDisposed();
var results = await _graphClient.Cypher
.Match($"(l:{Labels.Login})<-[:{Relationship.HasLogin}]-(u:{UserLabel})")
.Where((UserLoginInfo l) => l.ProviderKey == login.ProviderKey)
.AndWhere((UserLoginInfo l) => l.LoginProvider == login.LoginProvider)
.OptionalMatch($"(u)-[:{Relationship.HasClaim}]->(c:{Labels.Claim})")
.Return((u, c, l) => new FindUserResult<TUser>
{
User = u.As<TUser>(),
Logins = l.CollectAs<Neo4jUserLoginInfo>(),
Claims = c.CollectAs<IdentityUserClaim>()
}).ResultsAsync;
var result = results.SingleOrDefault();
return result?.Combine();
}
/// <inheritdoc />
public async Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
ThrowIfDisposed();
return await Task.Run(() => user.Logins as IList<UserLoginInfo>);
}
/// <inheritdoc />
public async Task RemoveLoginAsync(TUser user, UserLoginInfo login)
{
Throw.ArgumentException.IfNull(user, "user");
Throw.ArgumentException.IfNull(login, "login");
ThrowIfDisposed();
await Task.Run(() => user.Logins.RemoveAll(x => (x.LoginProvider == login.LoginProvider) && (x.ProviderKey == login.ProviderKey)));
}
/// <inheritdoc />
public async Task CreateAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
Throw.ArgumentException.IfNull(user, "user");
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(user.Id))
user.Id = Guid.NewGuid().ToString();
var query = _graphClient.Cypher
.Create("(u:User { user })")
.WithParams(new {user});
await query.ExecuteWithoutResultsAsync();
}
/// <inheritdoc />
public async Task DeleteAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
ThrowIfDisposed();
await UserMatch()
.Where((TUser u) => u.Id == user.Id)
.OptionalMatch($"(u)-[lr:{Relationship.HasLogin}]->(l)")
.OptionalMatch($"(u)-[cr:{Relationship.HasClaim}]->(c)")
.Delete("u,lr,cr,l,c")
.ExecuteWithoutResultsAsync();
}
/// <inheritdoc />
public async Task<TUser> FindByIdAsync(object userId)
{
Throw.ArgumentException.IfNull(userId, "userId");
return await FindByIdAsync(userId.ToString());
}
/// <inheritdoc />
public async Task<TUser> FindByIdAsync(string userId)
{
Throw.ArgumentException.IfNull(userId, "userId");
ThrowIfDisposed();
var query = UserMatch()
.Where((TUser u) => u.Id == userId)
.OptionalMatch($"(u)-[lr:{Relationship.HasLogin}]->(l:{Labels.Login})")
.OptionalMatch($"(u)-[cr:{Relationship.HasClaim}]->(c:{Labels.Claim})")
.Return((u, c, l) => new FindUserResult<TUser>
{
User = u.As<TUser>(),
Logins = l.CollectAs<Neo4jUserLoginInfo>(),
Claims = c.CollectAs<IdentityUserClaim>()
});
var user = (await query.ResultsAsync).SingleOrDefault();
return user?.Combine();
}
/// <inheritdoc />
public async Task<TUser> FindByNameAsync(string userName)
{
Throw.ArgumentException.IfNullOrWhiteSpace(userName, "userName");
ThrowIfDisposed();
userName = userName.ToLowerInvariant().Trim();
var query = UserMatch()
.Where((TUser u) => u.UserName == userName)
.OptionalMatch($"(u)-[lr:{Relationship.HasLogin}]->(l:{Labels.Login})")
.OptionalMatch($"(u)-[cr:{Relationship.HasClaim}]->(c:{Labels.Claim})")
.Return((u, c, l) => new FindUserResult<TUser>
{
User = u.As<TUser>(),
Logins = l.CollectAs<Neo4jUserLoginInfo>(),
Claims = c.CollectAs<IdentityUserClaim>()
});
var results = await query.ResultsAsync;
var findUserResult = results.SingleOrDefault();
return findUserResult?.Combine();
}
/// <inheritdoc />
public async Task UpdateAsync(TUser user)
{
Throw.ArgumentException.IfNull(user, "user");
ThrowIfDisposed();
var query = UserMatch()
.Where((TUser u) => u.Id == user.Id)
.Set("u = {userParam}")
.WithParam("userParam", user)
.With("u").OptionalMatch("(u)-[cr:HAS_CLAIM]->(c:Claim)").Delete("c,cr")
.With("u").OptionalMatch("(u)-[lr:HAS_LOGIN]->(l:Login)").Delete("l,lr")
.With("u").OptionalMatch("(u)-[rl:IN_ROLE]->(r:Role)").Delete("rl");
query = AddClaims(query, user.Claims);
query = AddLogins(query, user.Logins);
await query.ExecuteWithoutResultsAsync();
}
private static ICypherFluentQuery AddClaims(ICypherFluentQuery query, IList<IdentityUserClaim> claims)
{
if ((claims == null) || (claims.Count == 0))
return query;
for (var i = 0; i < claims.Count; i++)
{
var claimName = $"claim{i}";
var claimParam = claims[i];
query = query.With("u")
.Create($"(u)-[:HAS_CLAIM]->(c{i}:claim {{{claimName}}})")
.WithParam(claimName, claimParam);
}
return query;
}
private static ICypherFluentQuery AddLogins(ICypherFluentQuery query, IList<UserLoginInfo> logins)
{
if ((logins == null) || (logins.Count == 0))
return query;
for (var i = 0; i < logins.Count; i++)
{
var loginName = $"login{i}";
var loginParam = logins[i];
query = query.With("u")
.Create($"(u)-[:HAS_LOGIN]->(l{i}:Login {{{loginName}}})")
.WithParam(loginName, loginParam);
}
return query;
}
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
}
#endregion
#region IUserClaimStore
/// <inheritdoc />
public async Task AddClaimAsync(TUser user, Claim claim)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(claim, "claim");
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() =>
{
if (!user.Claims.Any(x => (x.ClaimType == claim.Type) && (x.ClaimValue == claim.Value)))
user.Claims.Add(new IdentityUserClaim
{
ClaimType = claim.Type,
ClaimValue = claim.Value
});
});
}
/// <inheritdoc />
public async Task<IList<Claim>> GetClaimsAsync(TUser user)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToList());
}
/// <inheritdoc />
public async Task RemoveClaimAsync(TUser user, Claim claim)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() => user.Claims.RemoveAll(x => (x.ClaimType == claim.Type) && (x.ClaimValue == claim.Value)));
}
#endregion
#region IUserRoleStore
/// <inheritdoc />
public async Task AddToRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() =>
{
if (!user.Roles.Contains(roleName, StringComparer.InvariantCultureIgnoreCase))
user.Roles.Add(roleName);
});
}
/// <inheritdoc />
public async Task<IList<string>> GetRolesAsync(TUser user)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.Roles);
}
/// <inheritdoc />
public async Task<bool> IsInRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.Roles.Contains(roleName, StringComparer.InvariantCultureIgnoreCase));
}
/// <inheritdoc />
public async Task RemoveFromRoleAsync(TUser user, string roleName)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() => user.Roles.RemoveAll(r => string.Equals(r, roleName, StringComparison.InvariantCultureIgnoreCase)));
}
#endregion
#region IUserPasswordStore
/// <inheritdoc />
public async Task<string> GetPasswordHashAsync(TUser user)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.PasswordHash);
}
/// <inheritdoc />
public async Task<bool> HasPasswordAsync(TUser user)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.PasswordHash != null);
}
/// <inheritdoc />
public async Task SetPasswordHashAsync(TUser user, string passwordHash)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() => user.PasswordHash = passwordHash);
}
#endregion
#region IUserSecurityStampStore
/// <inheritdoc />
public async Task<string> GetSecurityStampAsync(TUser user)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
return await Task.Run(() => user.SecurityStamp);
}
/// <inheritdoc />
public async Task SetSecurityStampAsync(TUser user, string stamp)
{
ThrowIfDisposed();
Throw.ArgumentException.IfNull(user, "user");
await Task.Run(() => user.SecurityStamp = stamp);
}
#endregion
#region IUserEmailStore
/// <inheritdoc />
public async Task<TUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
email = email.ToLowerInvariant().Trim();
var query = UserMatch()
.Where((TUser u) => u.Email == email)
.Return(u => u.As<TUser>());
return (await query.ResultsAsync).SingleOrDefault();
}
/// <inheritdoc />
public async Task<string> GetEmailAsync(TUser user)
{
ThrowIfDisposed();
if (user.Id == null)
return user.Email;
var results = await UserMatch()
.Where((TUser u) => u.Id == user.Id)
.Return(u => u.As<TUser>())
.ResultsAsync;
var dbUser = results.SingleOrDefault();
return dbUser?.Email;
}
/// <inheritdoc />
public async Task<bool> GetEmailConfirmedAsync(TUser user)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public async Task SetEmailAsync(TUser user, string email)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public async Task SetEmailConfirmedAsync(TUser user, bool confirmed)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
namespace Rainbow.Framework.Helpers
{
/// <summary>
/// WebPart
/// Added by Jakob Hansen.
/// </summary>
[XmlRoot(Namespace="urn:schemas-microsoft-com:webpart:", IsNullable=false)]
public class WebPart
{
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int AllowMinimize;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int AllowRemove;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement]
public int AutoUpdate;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int CacheBehavior;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int CacheTimeout;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Content;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string ContentLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int ContentType;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string CustomizationLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Description;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string DetailLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int FrameState;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int HasFrame;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Height;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string HelpLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int IsIncluded;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int IsVisible;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string LastModified;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string MasterPartLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Namespace;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string PartImageLarge;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string PartImageSmall;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int PartOrder;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string PartStorage;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int RequiresIsolation;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Title;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string Width;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string XSL;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public string XSLLink;
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
[XmlElement ]
public int Zone;
/*
[XmlElementAttribute ]
public string Resource; // Its an array thingy!!
*/
}
/// <summary>
/// WebPartParser
/// Added by Jakob Hansen.
/// </summary>
public class WebPartParser
{
/// <summary>
///
/// </summary>
/// <param name="fileName" type="string">
/// <para>
///
/// </para>
/// </param>
/// <returns>
/// A Rainbow.Framework.Helpers.WebPart value...
/// </returns>
public static WebPart Load(string fileName)
{
HttpContext context = HttpContext.Current;
WebPart partData = (WebPart) context.Cache[fileName];
if (partData == null)
{
if (File.Exists(fileName))
{
StreamReader reader = File.OpenText(fileName);
try
{
XmlSerializer serializer = new XmlSerializer(typeof(WebPart));
partData = (WebPart) serializer.Deserialize(reader);
}
finally
{
reader.Close();
}
context.Cache.Insert(fileName, partData, new CacheDependency(fileName));
}
}
return partData;
}
}
}
| |
/*
* HebrewCalendar.cs - Implementation of the
* "System.Globalization.HebrewCalendar" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Globalization
{
using System;
public class HebrewCalendar : Calendar
{
// Hebrew era value.
public static readonly int HebrewEra = 1;
// Useful internal constants.
private const int DefaultTwoDigitYearMax = 5790;
private const int MinYear = 5343;
private const int MaxYear = 6000;
// Gregorian 0001/01/01 is Hebrew 3761/10/18. This constant
// indicates the number of days to use to offset a Gregorian
// day number to turn it into a Hebrew day number.
private const long Year1ADDays = 1373428;
// There are 1080 "parts" per hour.
private const int PartsPerHour = 1080;
// Number of "parts" in a day.
private const int PartsPerDay = 24 * PartsPerHour;
// Length of a lunar month in days and parts.
private const int DaysPerMonth = 29;
private const int DaysPerMonthFraction = 12 * PartsPerHour + 793;
private const int DaysPerMonthParts =
DaysPerMonth * PartsPerDay + DaysPerMonthFraction;
// The time of the new moon in parts on the first day in the
// Hebrew calendar (1 Tishri, year 1 which is approx 6 Oct 3761 BC).
private const int FirstNewMoon = 11 * PartsPerHour + 204;
// Number of days in each month for deficient, regular,
// and complete years in both normal and leap variants.
private static readonly int[] daysPerMonthDeficient =
{30, 29, 29, 29, 30, 29, 30, 29, 30, 29, 30, 29};
private static readonly int[] daysPerMonthDeficientLeap =
{30, 29, 29, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29};
private static readonly int[] daysPerMonthRegular =
{30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29};
private static readonly int[] daysPerMonthRegularLeap =
{30, 29, 30, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29};
private static readonly int[] daysPerMonthComplete =
{30, 30, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29};
private static readonly int[] daysPerMonthCompleteLeap =
{30, 30, 30, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29};
// Constructor.
public HebrewCalendar()
{
// Nothing to do here.
}
// Get a list of eras for the calendar.
public override int[] Eras
{
get
{
int[] eras = new int [1];
eras[0] = HebrewEra;
return eras;
}
}
// Set the last year of a 100-year range for 2-digit processing.
public override int TwoDigitYearMax
{
get
{
int value = base.TwoDigitYearMax;
if(value != -1)
{
return value;
}
base.TwoDigitYearMax = DefaultTwoDigitYearMax;
return DefaultTwoDigitYearMax;
}
set
{
base.TwoDigitYearMax = value;
}
}
#if CONFIG_FRAMEWORK_1_2
// Get the minimum DateTime value supported by this calendar.
public override DateTime MinValue
{
get
{
return ToDateTime(MinYear, 1, 1, 0, HebrewEra);
}
}
// Get the maximum DateTime value supported by this calendar.
public override DateTime MaxValue
{
get
{
return GetMaxValue(MaxYear);
}
}
#endif
// Determine if a year value is a Hebrew leap year.
private static bool IsHebrewLeapYear(int year)
{
switch(year % 19)
{
case 0: case 3: case 6: case 8:
case 11: case 14: case 17:
return true;
default:
return false;
}
}
// Get the absolute day number that starts a particular year.
// Based on the algorithm used by "http://www.funaba.org/en/calendar.html".
private static long StartOfYear(int year)
{
// Get the number of months before the year.
int months = (235 * year - 234) / 19;
// Calculate the day number in whole and fractional parts.
long fraction = ((long)months) * ((long)DaysPerMonthFraction) +
((long)FirstNewMoon);
long day = ((long)months) * 29 + (fraction / PartsPerDay);
fraction %= PartsPerDay;
// Adjust the start of the year for the day of the week.
// The value "weekday == 0" indicates Monday.
int weekday = (int)(day % 7);
if(weekday == 2 || weekday == 4 || weekday == 6)
{
// Cannot start on a Sunday, Wednesday, or Friday.
++day;
weekday = (int)(day % 7);
}
if(weekday == 1 &&
fraction > (15 * PartsPerHour + 204) &&
!IsHebrewLeapYear(year))
{
// If the new moon falls after "15 hours, 204 parts"
// from the previous noon on a Tuesday and it is not
// a leap year, postpone by 2 days.
day += 2;
}
else if(weekday == 0 &&
fraction > (21 * PartsPerHour + 589) &&
IsHebrewLeapYear(year - 1))
{
// This happens for years that are 382 days in length,
// which is not a legal year length.
++day;
}
// Return the day number to the caller.
return day;
}
// Get the month table for a specific year.
private static int[] GetMonthTable(int year)
{
switch((int)(StartOfYear(year + 1) - StartOfYear(year)))
{
case 353: return daysPerMonthDeficient;
case 383: return daysPerMonthDeficientLeap;
case 354: return daysPerMonthRegular;
case 384: return daysPerMonthRegularLeap;
case 355: return daysPerMonthComplete;
case 385: return daysPerMonthCompleteLeap;
// Shouldn't happen.
default: throw new ArgumentOutOfRangeException();
}
}
// Add a time period to a DateTime value.
public override DateTime AddMonths(DateTime time, int months)
{
// Pull the time value apart.
int year = GetYear(time);
int month = GetMonth(time);
int day = GetDayOfMonth(time);
// Increment or decrement the month and year values.
int monthsInYear;
if(months > 0)
{
while(months > 0)
{
monthsInYear = GetMonthsInYear(year, CurrentEra);
if(months <= monthsInYear)
{
month += months;
months = 0;
}
else
{
month += monthsInYear;
months -= monthsInYear;
}
if(month > monthsInYear)
{
++year;
month -= monthsInYear;
}
}
}
else if(months < 0)
{
months = -months;
while(months > 0)
{
if(month > months)
{
month -= months;
months = 0;
}
else
{
months -= month;
--year;
month = GetMonthsInYear(year, CurrentEra);
}
}
}
// Adjust the day down if it is beyond the end of the month.
int daysInMonth = GetDaysInMonth(year, month, CurrentEra);
if(day > daysInMonth)
{
day = daysInMonth;
}
// Build and return the new DateTime value.
return ToDateTime(year, month, day,
time.Ticks % TimeSpan.TicksPerDay,
CurrentEra);
}
public override DateTime AddYears(DateTime time, int years)
{
// Pull the time value apart and increment it.
int year = GetYear(time) + years;
int month = GetMonth(time);
int day = GetDayOfMonth(time);
// Range-check the month and day values.
int monthsInYear = GetMonthsInYear(year, CurrentEra);
if(month > monthsInYear)
{
month = monthsInYear;
}
int daysInMonth = GetDaysInMonth(year, month, CurrentEra);
if(day > daysInMonth)
{
day = daysInMonth;
}
// Build and return the new DateTime value.
return ToDateTime(year, month, day,
time.Ticks % TimeSpan.TicksPerDay,
CurrentEra);
}
// Extract the components from a DateTime value.
public override int GetDayOfMonth(DateTime time)
{
// Get the day of the year.
int year = GetYear(time);
long yearDays = StartOfYear(year) - Year1ADDays;
int day = (int)((time.Ticks / TimeSpan.TicksPerDay) - yearDays);
// Get the month table for this year.
int[] table = GetMonthTable(year);
// Scan forward until we find the right month.
int posn = 0;
while(posn < 12 && day >= table[posn])
{
day -= table[posn];
++posn;
}
return day + 1;
}
public override System.DayOfWeek GetDayOfWeek(DateTime time)
{
// The Gregorian and Hebrew weekdays are identical.
return time.DayOfWeek;
}
public override int GetDayOfYear(DateTime time)
{
int year = GetYear(time);
long yearDays = StartOfYear(year) - Year1ADDays;
return (int)(((time.Ticks /
TimeSpan.TicksPerDay) - yearDays) + 1);
}
public override int GetMonth(DateTime time)
{
// Get the day of the year.
int year = GetYear(time);
long yearDays = StartOfYear(year) - Year1ADDays;
int day = (int)((time.Ticks / TimeSpan.TicksPerDay) - yearDays);
// Get the month table for this year.
int[] table = GetMonthTable(year);
// Scan forward until we find the right month.
int posn = 0;
while(posn < 12 && day >= table[posn])
{
day -= table[posn];
++posn;
}
return posn + 1;
}
public override int GetYear(DateTime time)
{
// Get the absolute day number for "time".
long day = time.Ticks / TimeSpan.TicksPerDay;
day += Year1ADDays;
// Perform a range check on MinYear and MaxYear.
if(day < StartOfYear(MinYear) ||
day >= StartOfYear(MaxYear + 1))
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
// Perform a binary search for the year. There is probably
// a smarter way to do this algorithmically, but this version
// is easier to understand and debug. The maximum number
// of search steps will be ceil(log2(MaxYear - MinYear)) = 10.
int left, right, middle;
long start;
left = MinYear;
right = MaxYear;
while(left <= right)
{
middle = (left + right) / 2;
start = StartOfYear(middle);
if(day < start)
{
right = middle - 1;
}
else if(day >= start && day < StartOfYear(middle + 1))
{
return middle;
}
else
{
left = middle + 1;
}
}
return left;
}
// Get the number of days in a particular month.
public override int GetDaysInMonth(int year, int month, int era)
{
// Get the number of months in the year, which will
// also validate "year" and "era".
int monthsInYear = GetMonthsInYear(year, era);
// Validate the month value.
if(month < 1 || month > monthsInYear)
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
// Get the days per month table for this year.
int[] table = GetMonthTable(year);
// Return the number of days in the month.
return table[month - 1];
}
// Get the number of days in a particular year.
public override int GetDaysInYear(int year, int era)
{
if(era != CurrentEra && era != HebrewEra)
{
throw new ArgumentException(_("Arg_InvalidEra"));
}
if(year < MinYear || year > MaxYear)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
return (int)(StartOfYear(year + 1) - StartOfYear(year));
}
// Get the era for a specific DateTime value.
public override int GetEra(DateTime time)
{
return HebrewEra;
}
// Get the number of months in a specific year.
public override int GetMonthsInYear(int year, int era)
{
if(era != CurrentEra && era != HebrewEra)
{
throw new ArgumentException(_("Arg_InvalidEra"));
}
if(year < MinYear || year > MaxYear)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
if(IsHebrewLeapYear(year))
{
return 13;
}
else
{
return 12;
}
}
// Determine if a particular day is a leap day.
public override bool IsLeapDay(int year, int month, int day, int era)
{
// Validate the day value. "GetDaysInMonth" will
// take care of validating the year, month, and era.
if(day > GetDaysInMonth(year, month, era) || day < 1)
{
throw new ArgumentOutOfRangeException
("day", _("ArgRange_Day"));
}
// Every day in a leap month is a leap year.
if(IsLeapMonth(year, month, era))
{
return true;
}
// Is this a leap year?
if(IsHebrewLeapYear(year))
{
// The 30th day of the 6th month is a leap day.
if(month == 6 && day == 30)
{
return true;
}
}
// All other days are regular days.
return false;
}
// Determine if a particular month is a leap month.
public override bool IsLeapMonth(int year, int month, int era)
{
if(era != CurrentEra && era != HebrewEra)
{
throw new ArgumentException(_("Arg_InvalidEra"));
}
if(year < MinYear || year > MaxYear)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
if(month < 1 || month > GetMonthsInYear(year, era))
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
if(!IsHebrewLeapYear(year))
{
return false;
}
return (month == 7);
}
// Determine if a particular year is a leap year.
public override bool IsLeapYear(int year, int era)
{
if(era != CurrentEra && era != HebrewEra)
{
throw new ArgumentException(_("Arg_InvalidEra"));
}
if(year < MinYear || year > MaxYear)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
return IsHebrewLeapYear(year);
}
// Convert a particular time into a DateTime value.
private DateTime ToDateTime(int year, int month, int day,
long tickOffset, int era)
{
// Validate the parameters.
if(era != CurrentEra && era != HebrewEra)
{
throw new ArgumentException(_("Arg_InvalidEra"));
}
if(year < MinYear || year > MaxYear)
{
throw new ArgumentOutOfRangeException
("year", _("ArgRange_Year"));
}
int monthsInYear = GetMonthsInYear(year, era);
if(month < 1 || month > monthsInYear)
{
throw new ArgumentOutOfRangeException
("month", _("ArgRange_Month"));
}
int daysInMonth = GetDaysInMonth(year, month, era);
if(day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException
("day", _("ArgRange_Day"));
}
// Convert the Hebrew date into a Gregorian date.
// We do this by calculating the number of days since
// 1 January 0001 AD, which is Hebrew 01/01/3760.
long days = StartOfYear(year) - Year1ADDays + day - 1;
int[] table = GetMonthTable(year);
int posn;
for(posn = 1; posn < month; ++posn)
{
days += table[posn - 1];
}
// Build the DateTime value and return it.
return new DateTime(days * TimeSpan.TicksPerDay + tickOffset);
}
public override DateTime ToDateTime(int year, int month, int day,
int hour, int minute, int second,
int millisecond, int era)
{
long ticks;
ticks = DateTime.TimeToTicks(hour, minute, second);
ticks += ((long)millisecond) * TimeSpan.TicksPerMillisecond;
return ToDateTime(year, month, day, ticks, era);
}
// Convert a two-digit year value into a four-digit year value.
public override int ToFourDigitYear(int year)
{
return base.ToFourDigitYear(year);
}
}; // class HebrewCalendar
}; // namespace System.Globalization
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Framework.OptionsModel;
using OmniSharp.Models;
using OmniSharp.Options;
using OmniSharp.Roslyn.CSharp.Services.Formatting;
using OmniSharp.Roslyn.CSharp.Workers.Format;
using OmniSharp.Tests;
using Xunit;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class FormattingFacts
{
[Fact]
public void FindFormatTargetAtCurly()
{
AssertFormatTargetKind(SyntaxKind.ClassDeclaration, @"class C {}$");
AssertFormatTargetKind(SyntaxKind.InterfaceDeclaration, @"interface I {}$");
AssertFormatTargetKind(SyntaxKind.EnumDeclaration, @"enum E {}$");
AssertFormatTargetKind(SyntaxKind.StructDeclaration, @"struct S {}$");
AssertFormatTargetKind(SyntaxKind.NamespaceDeclaration, @"namespace N {}$");
AssertFormatTargetKind(SyntaxKind.MethodDeclaration, @"
class C {
public void M(){}$
}");
AssertFormatTargetKind(SyntaxKind.ObjectInitializerExpression, @"
class C {
public void M(){
new T() {
A = 6,
B = 7
}$
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(;;){}$
}
}");
}
[Fact]
public void FindFormatTargetAtSemiColon()
{
AssertFormatTargetKind(SyntaxKind.FieldDeclaration, @"
class C {
private int F;$
}");
AssertFormatTargetKind(SyntaxKind.LocalDeclarationStatement, @"
class C {
public void M()
{
var a = 1234;$
}
}");
AssertFormatTargetKind(SyntaxKind.ReturnStatement, @"
class C {
public int M()
{
return 1234;$
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0;$)
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0;$) {}
}
}");
AssertFormatTargetKind(SyntaxKind.ForStatement, @"
class C {
public void M ()
{
for(var i = 0; i < 8;$)
}
}");
}
private void AssertFormatTargetKind(SyntaxKind kind, string source)
{
var tuple = GetTreeAndOffset(source);
var target = Formatting.FindFormatTarget(tuple.Item1, tuple.Item2);
if (target == null)
{
Assert.Null(kind);
}
else
{
Assert.Equal(kind, target.Kind());
}
}
private Tuple<SyntaxTree, int> GetTreeAndOffset(string value)
{
var idx = value.IndexOf('$');
if (idx <= 0)
{
Assert.True(false);
}
value = value.Remove(idx, 1);
idx = idx - 1;
return Tuple.Create(CSharpSyntaxTree.ParseText(value), idx);
}
[Fact]
public async Task TextChangesAreSortedLastFirst_SingleLine()
{
var source = new[]{
"class Program",
"{",
" public static void Main(){",
"> Thread.Sleep( 25000);<",
" }",
"}",
};
await AssertTextChanges(string.Join(Environment.NewLine, source),
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 21, EndLine = 4, EndColumn = 22, NewText = "" },
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 8, EndLine = 4, EndColumn = 8, NewText = " " });
}
[Fact]
public async Task TextChangesAreSortedLastFirst_MultipleLines()
{
var source = new[]{
"class Program",
"{",
" public static void Main()>{",
" Thread.Sleep( 25000);<",
" }",
"}",
};
await AssertTextChanges(string.Join(Environment.NewLine, source),
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 21, EndLine = 4, EndColumn = 22, NewText = "" },
new LinePositionSpanTextChange() { StartLine = 4, StartColumn = 8, EndLine = 4, EndColumn = 8, NewText = " " },
new LinePositionSpanTextChange() { StartLine = 3, StartColumn = 30, EndLine = 3, EndColumn = 30, NewText = "\r\n" });
}
private static FormatRangeRequest NewRequest(string source)
{
var startLoc = TestHelpers.GetLineAndColumnFromIndex(source, source.IndexOf(">"));
source = source.Replace(">", string.Empty);
var endLoc = TestHelpers.GetLineAndColumnFromIndex(source, source.IndexOf("<"));
source = source.Replace("<", string.Empty);
return new FormatRangeRequest() {
Buffer = source,
FileName = "a.cs",
Line = startLoc.Line,
Column = startLoc.Column,
EndLine = endLoc.Line,
EndColumn = endLoc.Column
};
}
private static async Task AssertTextChanges(string source, params LinePositionSpanTextChange[] expected)
{
var request = NewRequest(source);
var actual = await FormattingChangesForRange(request);
var enumer = actual.GetEnumerator();
for (var i = 0; enumer.MoveNext(); i++)
{
Assert.Equal(expected[i].NewText, enumer.Current.NewText);
Assert.Equal(expected[i].StartLine, enumer.Current.StartLine);
Assert.Equal(expected[i].StartColumn, enumer.Current.StartColumn);
Assert.Equal(expected[i].EndLine, enumer.Current.EndLine);
Assert.Equal(expected[i].EndColumn, enumer.Current.EndColumn);
}
}
private static async Task<IEnumerable<LinePositionSpanTextChange>> FormattingChangesForRange(FormatRangeRequest req)
{
var workspace = await TestHelpers.CreateSimpleWorkspace(req.Buffer, req.FileName);
RequestHandler<FormatRangeRequest, FormatRangeResponse> controller = new FormatRangeService(workspace, new FormattingOptions());
return (await controller.Handle(req)).Changes;
}
[Fact]
public async Task FormatRespectsIndentationSize()
{
var source = "namespace Bar\n{\n class Foo {}\n}";
var workspace = await TestHelpers.CreateSimpleWorkspace(source);
var controller = new CodeFormatService(workspace, new FormattingOptions
{
NewLine = "\n",
IndentationSize = 1
});
var result = await controller.Handle(new CodeFormatRequest
{
FileName = "dummy.cs"
});
Assert.Equal("namespace Bar\n{\n class Foo { }\n}", result.Buffer);
}
}
}
| |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class ArgumentParser
{
static ArgumentParser()
{
var fields = typeof(VariableProvider).GetFields(BindingFlags.Public | BindingFlags.Static);
VersionParts = fields.Select(x => x.Name.ToLower()).ToArray();
}
public static Arguments ParseArguments(string commandLineArguments)
{
return ParseArguments(commandLineArguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList());
}
public static Arguments ParseArguments(List<string> commandLineArguments)
{
if (commandLineArguments.Count == 0)
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory
};
}
var firstArgument = commandLineArguments.First();
if (IsHelp(firstArgument))
{
return new Arguments
{
IsHelp = true
};
}
if (IsInit(firstArgument))
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory,
Init = true
};
}
if (commandLineArguments.Count == 1 && !(commandLineArguments[0].StartsWith("-") || commandLineArguments[0].StartsWith("/")))
{
return new Arguments
{
TargetPath = firstArgument
};
}
List<string> namedArguments;
var arguments = new Arguments();
if (firstArgument.StartsWith("-") || firstArgument.StartsWith("/"))
{
arguments.TargetPath = Environment.CurrentDirectory;
namedArguments = commandLineArguments;
}
else
{
arguments.TargetPath = firstArgument;
namedArguments = commandLineArguments.Skip(1).ToList();
}
for (var index = 0; index < namedArguments.Count; index = index + 2)
{
var name = namedArguments[index];
var value = namedArguments.Count > index + 1 ? namedArguments[index + 1] : null;
if (IsSwitch("l", name))
{
arguments.LogFilePath = value;
continue;
}
if (IsSwitch("targetpath", name))
{
arguments.TargetPath = value;
continue;
}
if (IsSwitch("url", name))
{
arguments.TargetUrl = value;
continue;
}
if (IsSwitch("b", name))
{
arguments.TargetBranch = value;
continue;
}
if (IsSwitch("u", name))
{
arguments.Authentication.Username = value;
continue;
}
if (IsSwitch("p", name))
{
arguments.Authentication.Password = value;
continue;
}
if (IsSwitch("c", name))
{
arguments.CommitId = value;
continue;
}
if (IsSwitch("exec", name))
{
arguments.Exec = value;
continue;
}
if (IsSwitch("execargs", name))
{
arguments.ExecArgs = value;
continue;
}
if (IsSwitch("proj", name))
{
arguments.Proj = value;
continue;
}
if (IsSwitch("projargs", name))
{
arguments.ProjArgs = value;
continue;
}
if (IsSwitch("updateAssemblyInfo", name))
{
if (new[] { "1", "true" }.Contains(value))
{
arguments.UpdateAssemblyInfo = true;
}
else if (new[] { "0", "false" }.Contains(value))
{
arguments.UpdateAssemblyInfo = false;
}
else if (!IsSwitchArgument(value))
{
arguments.UpdateAssemblyInfo = true;
arguments.UpdateAssemblyInfoFileName = value;
}
else
{
arguments.UpdateAssemblyInfo = true;
index--;
}
continue;
}
if (IsSwitch("assemblyversionformat", name))
{
throw new WarningException("assemblyversionformat switch removed, use AssemblyVersioningScheme configuration value instead");
}
if ((IsSwitch("v", name)) && VersionParts.Contains(value.ToLower()))
{
arguments.ShowVariable = value.ToLower();
continue;
}
if (IsSwitch("showConfig", name))
{
if (new[] { "1", "true" }.Contains(value))
{
arguments.ShowConfig = true;
}
else if (new[] { "0", "false" }.Contains(value))
{
arguments.UpdateAssemblyInfo = false;
}
else
{
arguments.ShowConfig = true;
index--;
}
continue;
}
if (IsSwitch("output", name))
{
OutputType outputType;
if (!Enum.TryParse(value, true, out outputType))
{
throw new WarningException(string.Format("Value '{0}' cannot be parsed as output type, please use 'json' or 'buildserver'", value));
}
arguments.Output = outputType;
continue;
}
throw new WarningException(string.Format("Could not parse command line parameter '{0}'.", name));
}
return arguments;
}
static bool IsSwitchArgument(string value)
{
return value != null && (value.StartsWith("-") || value.StartsWith("/"));
}
static bool IsSwitch(string switchName, string value)
{
if (value.StartsWith("-"))
{
value = value.Remove(0, 1);
}
if (value.StartsWith("/"))
{
value = value.Remove(0, 1);
}
return (string.Equals(switchName, value, StringComparison.InvariantCultureIgnoreCase));
}
static bool IsInit(string singleArgument)
{
return singleArgument.Equals("init", StringComparison.InvariantCultureIgnoreCase);
}
static bool IsHelp(string singleArgument)
{
return (singleArgument == "?") ||
IsSwitch("h", singleArgument) ||
IsSwitch("help", singleArgument) ||
IsSwitch("?", singleArgument);
}
static string[] VersionParts;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiSoup.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/// <remarks>Test for ECIES - Elliptic Curve Integrated Encryption Scheme</remarks>
[TestFixture]
public class EcIesTest
: SimpleTest
{
public EcIesTest()
{
}
public override string Name
{
get { return "ECIES"; }
}
private void StaticTest()
{
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECDH",
new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
parameters);
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECDH",
curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
parameters);
AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey);
AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey);
//
// stream test
//
IesEngine i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
IesEngine i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IesParameters p = new IesParameters(d, e, 64);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
byte[] message = Hex.Decode("1234567890abcdef");
byte[] out1 = i1.ProcessBlock(message, 0, message.Length);
if (!AreEqual(out1, Hex.Decode("2442ae1fbf90dd9c06b0dcc3b27e69bd11c9aee4ad4cfc9e50eceb44")))
{
Fail("stream cipher test failed on enc");
}
byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("stream cipher test failed");
}
//
// twofish with CBC
//
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c1);
i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IesWithCipherParameters(d, e, 64, 128);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
message = Hex.Decode("1234567890abcdef");
out1 = i1.ProcessBlock(message, 0, message.Length);
if (!AreEqual(out1, Hex.Decode("2ea288651e21576215f2424bbb3f68816e282e3931b44bd1c429ebdb5f1b290cf1b13309")))
{
Fail("twofish cipher test failed on enc");
}
out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("twofish cipher test failed");
}
}
private void DoTest(
AsymmetricCipherKeyPair p1,
AsymmetricCipherKeyPair p2)
{
//
// stream test
//
IesEngine i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
IesEngine i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IesParameters p = new IesParameters(d, e, 64);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
byte[] message = Hex.Decode("1234567890abcdef");
byte[] out1 = i1.ProcessBlock(message, 0, message.Length);
byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("stream cipher test failed");
}
//
// twofish with CBC
//
BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new TwofishEngine()));
i1 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c1);
i2 = new IesEngine(
new ECDHBasicAgreement(),
new Kdf2BytesGenerator(new Sha1Digest()),
new HMac(new Sha1Digest()),
c2);
d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
p = new IesWithCipherParameters(d, e, 64, 128);
i1.Init(true, p1.Private, p2.Public, p);
i2.Init(false, p2.Private, p1.Public, p);
message = Hex.Decode("1234567890abcdef");
out1 = i1.ProcessBlock(message, 0, message.Length);
out2 = i2.ProcessBlock(out1, 0, out1.Length);
if (!AreEqual(out2, message))
{
Fail("twofish cipher test failed");
}
}
public override void PerformTest()
{
StaticTest();
FpCurve curve = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n
ECKeyPairGenerator eGen = new ECKeyPairGenerator();
KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom());
eGen.Init(gParam);
AsymmetricCipherKeyPair p1 = eGen.GenerateKeyPair();
AsymmetricCipherKeyPair p2 = eGen.GenerateKeyPair();
DoTest(p1, p2);
}
public static void Main(
string[] args)
{
RunTest(new EcIesTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Xml;
using System.Reflection;
using System.Text;
using OpenSource.Utilities;
using OpenSource.UPnP;
using System.Runtime.Serialization;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// Class can represent any ContentDirectory approved
/// upnp or dublin-core metadata elements that are
/// simple integers without any attributes.
/// </summary>
[Serializable()]
public sealed class PropertyUri : ICdsElement, IToXmlData, IDeserializationCallback
{
/// <summary>
/// Returns same value as StringValue
/// </summary>
/// <returns></returns>
public override string ToString() { return this.StringValue; }
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public static IList GetPossibleAttributes()
{
return new object[0];
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList PossibleAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// Returns an empty list.
/// </summary>
/// <returns></returns>
public IList ValidAttributes
{
get
{
return GetPossibleAttributes();
}
}
/// <summary>
/// No attributes, so always returns null
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public IComparable ExtractAttribute(string attribute) { return null; }
/// <summary>
/// Returns the uri as a string or an empty string if null.
/// </summary>
public IComparable ComparableValue { get { return this.StringValue; } }
/// <summary>
/// Returns the underlying Uri object.
/// </summary>
public object Value { get { return this.m_value; } }
/// <summary>
/// Returns the uri as a string or an empty string if null.
/// </summary>
public string StringValue { get { if (m_value != null) { return m_value.ToString(); } return "";} }
/// <summary>
/// Prints the XML representation of the metadata element.
/// <para>
/// Implementation calls the <see cref="ToXmlData.ToXml"/>
/// method for its implementation.
/// </para>
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
public void ToXml (ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData.ToXml(this, formatter, (ToXmlData) data, xmlWriter);
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteStartElement(this.ns_tag);
}
/// <summary>
/// Instructs the "xmlWriter" argument to write the value of
/// the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteValue(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteString(this.StringValue);
}
/// <summary>
/// Instructs the "xmlWriter" argument to close the metadata element.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void EndElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
xmlWriter.WriteEndElement();
}
/// <summary>
/// Empty - this element has no child xml elements.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
public void WriteInnerXml(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
}
/// <summary>
/// Attempts to case compareToThis as an Uri
/// to do the comparison. If the cast
/// fails, then it compares the current
/// value against Uri.MinValue.
/// </summary>
/// <param name="compareToThis"></param>
/// <returns></returns>
public int CompareTo (object compareToThis)
{
return string.Compare(this.m_value.ToString(), compareToThis.ToString());
}
/// <summary>
/// Extracts the Name of the element and uses
/// the InnerText as the value.
/// </summary>
/// <param name="element"></param>
public PropertyUri(XmlElement element)
{
this.m_value = new Uri (element.InnerText);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(element.Name);
}
/// <summary>
/// Instantiates a new property that can represent an xml element with
/// an uri as its value.
/// </summary>
/// <param name="namespace_tag">property obtained from Tags[CommonPropertyNames.value]</param>
/// <param name="val"></param>
public PropertyUri (string namespace_tag, Uri val)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(namespace_tag);
this.m_value = val;
}
/// <summary>
/// Assume the name has been read.
/// </summary>
/// <param name="reader"></param>
public PropertyUri(XmlReader reader)
{
this.m_value = new Uri(reader.Value);
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(reader.Name);
}
/// <summary>
/// underlying Uri object
/// </summary>
public Uri _Value { get { return this.m_value; } }
internal Uri m_value;
/// <summary>
/// namespace and element name to represent
/// </summary>
private string ns_tag;
public void OnDeserialization(object sender)
{
this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(this.ns_tag);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
// SecureChannel - a wrapper on SSPI based functionality.
// Provides an additional abstraction layer over SSPI for SslStream.
internal class SecureChannel
{
// When reading a frame from the wire first read this many bytes for the header.
internal const int ReadHeaderSize = 5;
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private SslConnectionInfo _connectionInfo;
private X509Certificate _selectedClientCertificate;
private bool _isRemoteCertificateAvailable;
// These are the MAX encrypt buffer output sizes, not the actual sizes.
private int _headerSize = 5; //ATTN must be set to at least 5 by default
private int _trailerSize = 16;
private int _maxDataSize = 16354;
private bool _refreshCredentialNeeded;
private SslAuthenticationOptions _sslAuthenticationOptions;
private SslApplicationProtocol _negotiatedApplicationProtocol;
private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
private static readonly Oid s_clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2");
internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates);
NetEventSource.Log.SecureChannelCtor(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
}
SslStreamPal.VerifyPackageInfo();
if (sslAuthenticationOptions.TargetHost == null)
{
NetEventSource.Fail(this, "sslAuthenticationOptions.TargetHost == null");
}
_securityContext = null;
_refreshCredentialNeeded = true;
_sslAuthenticationOptions = sslAuthenticationOptions;
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this);
}
//
// SecureChannel properties
//
// LocalServerCertificate - local certificate for server mode channel
// LocalClientCertificate - selected certificated used in the client channel mode otherwise null
// IsRemoteCertificateAvailable - true if the remote side has provided a certificate
// HeaderSize - Header & trailer sizes used in the TLS stream
// TrailerSize -
//
internal X509Certificate LocalServerCertificate
{
get
{
return _sslAuthenticationOptions.ServerCertificate;
}
}
internal X509Certificate LocalClientCertificate
{
get
{
return _selectedClientCertificate;
}
}
internal bool IsRemoteCertificateAvailable
{
get
{
return _isRemoteCertificateAvailable;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this, kind);
ChannelBinding result = null;
if (_securityContext != null)
{
result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, result);
return result;
}
internal X509RevocationMode CheckCertRevocationStatus
{
get
{
return _sslAuthenticationOptions.CertificateRevocationCheckMode;
}
}
internal int MaxDataSize
{
get
{
return _maxDataSize;
}
}
internal SslConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
internal bool IsValidContext
{
get
{
return !(_securityContext == null || _securityContext.IsInvalid);
}
}
internal bool IsServer
{
get
{
return _sslAuthenticationOptions.IsServer;
}
}
internal bool RemoteCertRequired
{
get
{
return _sslAuthenticationOptions.RemoteCertRequired;
}
}
internal SslApplicationProtocol NegotiatedApplicationProtocol
{
get
{
return _negotiatedApplicationProtocol;
}
}
internal void SetRefreshCredentialNeeded()
{
_refreshCredentialNeeded = true;
}
internal void Close()
{
_securityContext?.Dispose();
_credentialsHandle?.Dispose();
GC.SuppressFinalize(this);
}
//
// SECURITY: we open a private key container on behalf of the caller
// and we require the caller to have permission associated with that operation.
//
private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
{
if (certificate == null)
{
return null;
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.LocatingPrivateKey(certificate, this);
try
{
// Protecting from X509Certificate2 derived classes.
X509Certificate2 certEx = MakeEx(certificate);
if (certEx != null)
{
if (certEx.HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.CertIsType2(this);
return certEx;
}
if ((object)certificate != (object)certEx)
{
certEx.Dispose();
}
}
X509Certificate2Collection collectionEx;
string certHash = certEx.Thumbprint;
// ELSE Try the MY user and machine stores for private key check.
// For server side mode MY machine store takes priority.
X509Store store = CertificateValidationPal.EnsureStoreOpened(_sslAuthenticationOptions.IsServer);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this);
return collectionEx[0];
}
}
store = CertificateValidationPal.EnsureStoreOpened(!_sslAuthenticationOptions.IsServer);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this);
return collectionEx[0];
}
}
}
catch (CryptographicException)
{
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.NotFoundCertInStore(this);
return null;
}
private static X509Certificate2 MakeEx(X509Certificate certificate)
{
Debug.Assert(certificate != null, "certificate != null");
if (certificate.GetType() == typeof(X509Certificate2))
{
return (X509Certificate2)certificate;
}
X509Certificate2 certificateEx = null;
try
{
if (certificate.Handle != IntPtr.Zero)
{
certificateEx = new X509Certificate2(certificate.Handle);
}
}
catch (SecurityException) { }
catch (CryptographicException) { }
return certificateEx;
}
//
// Get certificate_authorities list, according to RFC 5246, Section 7.4.4.
// Used only by client SSL code, never returns null.
//
private string[] GetRequestCertificateAuthorities()
{
string[] issuers = Array.Empty<string>();
if (IsValidContext)
{
issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext);
}
return issuers;
}
/*++
AcquireCredentials - Attempts to find Client Credential
Information, that can be sent to the server. In our case,
this is only Client Certificates, that we have Credential Info.
How it works:
case 0: Cert Selection delegate is present
Always use its result as the client cert answer.
Try to use cached credential handle whenever feasible.
Do not use cached anonymous creds if the delegate has returned null
and the collection is not empty (allow responding with the cert later).
case 1: Certs collection is empty
Always use the same statically acquired anonymous SSL Credential
case 2: Before our Connection with the Server
If we have a cached credential handle keyed by first X509Certificate
**content** in the passed collection, then we use that cached
credential and hoping to restart a session.
Otherwise create a new anonymous (allow responding with the cert later).
case 3: After our Connection with the Server (i.e. during handshake or re-handshake)
The server has requested that we send it a Certificate then
we Enumerate a list of server sent Issuers trying to match against
our list of Certificates, the first match is sent to the server.
Once we got a cert we again try to match cached credential handle if possible.
This will not restart a session but helps minimizing the number of handles we create.
In the case of an error getting a Certificate or checking its private Key we fall back
to the behavior of having no certs, case 1.
Returns: True if cached creds were used, false otherwise.
--*/
private bool AcquireClientCredentials(ref byte[] thumbPrint)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
List<X509Certificate> filteredCerts = null; // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is.
bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds.
if (_sslAuthenticationOptions.CertSelectionDelegate != null)
{
issuers = GetRequestCertificateAuthorities();
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Calling CertificateSelectionCallback");
X509Certificate2 remoteCert = null;
try
{
X509Certificate2Collection dummyCollection;
remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection);
if (_sslAuthenticationOptions.ClientCertificates == null)
{
_sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection();
}
clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers);
}
finally
{
remoteCert?.Dispose();
}
if (clientCertificate != null)
{
if (_credentialsHandle == null)
{
sessionRestartAttempt = true;
}
EnsureInitialized(ref filteredCerts).Add(clientCertificate);
if (NetEventSource.IsEnabled)
NetEventSource.Log.CertificateFromDelegate(this);
}
else
{
if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.NoDelegateNoClientCert(this);
sessionRestartAttempt = true;
}
else
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.NoDelegateButClientCert(this);
}
}
}
else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0)
{
// This is where we attempt to restart a session by picking the FIRST cert from the collection.
// Otherwise it is either server sending a client cert request or the session is renegotiated.
clientCertificate = _sslAuthenticationOptions.ClientCertificates[0];
sessionRestartAttempt = true;
if (clientCertificate != null)
{
EnsureInitialized(ref filteredCerts).Add(clientCertificate);
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this);
}
else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0)
{
//
// This should be a server request for the client cert sent over currently anonymous sessions.
//
issuers = GetRequestCertificateAuthorities();
if (NetEventSource.IsEnabled)
{
if (issuers == null || issuers.Length == 0)
{
NetEventSource.Log.NoIssuersTryAllCerts(this);
}
else
{
NetEventSource.Log.LookForMatchingCerts(issuers.Length, this);
}
}
for (int i = 0; i < _sslAuthenticationOptions.ClientCertificates.Count; ++i)
{
//
// Make sure we add only if the cert matches one of the issuers.
// If no issuers were sent and then try all client certs starting with the first one.
//
if (issuers != null && issuers.Length != 0)
{
X509Certificate2 certificateEx = null;
X509Chain chain = null;
try
{
certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]);
if (certificateEx == null)
{
continue;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Root cert: {certificateEx}");
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
chain.Build(certificateEx);
bool found = false;
//
// We ignore any errors happened with chain.
//
if (chain.ChainElements.Count > 0)
{
int elementsCount = chain.ChainElements.Count;
for (int ii = 0; ii < elementsCount; ++ii)
{
string issuer = chain.ChainElements[ii].Certificate.Issuer;
found = Array.IndexOf(issuers, issuer) != -1;
if (found)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Matched {issuer}");
break;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"No match: {issuer}");
}
}
if (!found)
{
continue;
}
}
finally
{
if (chain != null)
{
chain.Dispose();
int elementsCount = chain.ChainElements.Count;
for (int element = 0; element < elementsCount; element++)
{
chain.ChainElements[element].Certificate.Dispose();
}
}
if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i])
{
certificateEx.Dispose();
}
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.SelectedCert(_sslAuthenticationOptions.ClientCertificates[i], this);
EnsureInitialized(ref filteredCerts).Add(_sslAuthenticationOptions.ClientCertificates[i]);
}
}
bool cachedCred = false; // This is a return result from this method.
X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it).
clientCertificate = null;
if (NetEventSource.IsEnabled)
{
if (filteredCerts != null && filteredCerts.Count != 0)
{
NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this);
NetEventSource.Log.FindingMatchingCerts(this);
}
else
{
NetEventSource.Log.CertsAfterFiltering(0, this);
NetEventSource.Info(this, "No client certificate to choose from");
}
}
//
// ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key,
// THEN anonymous (no client cert) credential will be used.
//
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
if (filteredCerts != null)
{
for (int i = 0; i < filteredCerts.Count; ++i)
{
clientCertificate = filteredCerts[i];
if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
{
break;
}
clientCertificate = null;
selectedCert = null;
}
}
if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert))
{
NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'.");
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Selected cert = {selectedCert}");
try
{
// Try to locate cached creds first.
//
// SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
//
byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash();
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
// We can probably do some optimization here. If the selectedCert is returned by the delegate
// we can always go ahead and use the certificate to create our credential
// (instead of going anonymous as we do here).
if (sessionRestartAttempt &&
cachedCredentialHandle == null &&
selectedCert != null &&
SslStreamPal.StartMutualAuthAsAnonymous)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Reset to anonymous session.");
// IIS does not renegotiate a restarted session if client cert is needed.
// So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
// The following block happens if client did specify a certificate but no cached creds were found in the cache.
// Since we don't restart a session the server side can still challenge for a client cert.
if ((object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
guessedThumbPrint = null;
selectedCert = null;
clientCertificate = null;
}
if (cachedCredentialHandle != null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.UsingCachedCredential(this);
_credentialsHandle = cachedCredentialHandle;
_selectedClientCertificate = clientCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer);
thumbPrint = guessedThumbPrint; // Delay until here in case something above threw.
_selectedClientCertificate = clientCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
private static List<T> EnsureInitialized<T>(ref List<T> list) => list ?? (list = new List<T>());
//
// Acquire Server Side Certificate information and set it on the class.
//
private bool AcquireServerCredentials(ref byte[] thumbPrint, byte[] clientHello)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
X509Certificate localCertificate = null;
bool cachedCred = false;
// There are three options for selecting the server certificate. When
// selecting which to use, we prioritize the new ServerCertSelectionDelegate
// API. If the new API isn't used we call LocalCertSelectionCallback (for compat
// with .NET Framework), and if neither is set we fall back to using ServerCertificate.
if (_sslAuthenticationOptions.ServerCertSelectionDelegate != null)
{
string serverIdentity = SniHelper.GetServerName(clientHello);
localCertificate = _sslAuthenticationOptions.ServerCertSelectionDelegate(serverIdentity);
if (localCertificate == null)
{
throw new AuthenticationException(SR.net_ssl_io_no_server_cert);
}
}
else if (_sslAuthenticationOptions.CertSelectionDelegate != null)
{
X509CertificateCollection tempCollection = new X509CertificateCollection();
tempCollection.Add(_sslAuthenticationOptions.ServerCertificate);
// We pass string.Empty here to maintain strict compatability with .NET Framework.
localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>());
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Use delegate selected Cert");
}
else
{
localCertificate = _sslAuthenticationOptions.ServerCertificate;
}
if (localCertificate == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);
if (selectedCert == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
if (!localCertificate.Equals(selectedCert))
{
NetEventSource.Fail(this, "'selectedCert' does not match 'localCertificate'.");
}
//
// Note selectedCert is a safe ref possibly cloned from the user passed Cert object
//
byte[] guessedThumbPrint = selectedCert.GetCertHash();
try
{
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
if (cachedCredentialHandle != null)
{
_credentialsHandle = cachedCredentialHandle;
_sslAuthenticationOptions.ServerCertificate = localCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer);
thumbPrint = guessedThumbPrint;
_sslAuthenticationOptions.ServerCertificate = localCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if ((object)localCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
internal ProtocolToken NextMessage(byte[] incoming, int offset, int count)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
byte[] nextmsg = null;
SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg);
if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded");
SetRefreshCredentialNeeded();
status = GenerateToken(incoming, offset, count, ref nextmsg);
}
ProtocolToken token = new ProtocolToken(nextmsg, status);
if (NetEventSource.IsEnabled)
{
if (token.Failed)
{
NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException().Message}");
}
NetEventSource.Exit(this, token);
}
return token;
}
/*++
GenerateToken - Called after each successive state
in the Client - Server handshake. This function
generates a set of bytes that will be sent next to
the server. The server responds, each response,
is pass then into this function, again, and the cycle
repeats until successful connection, or failure.
Input:
input - bytes from the wire
output - ref to byte [], what we will send to the
server in response
Return:
status - error information
--*/
private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}");
if (offset < 0 || offset > (input == null ? 0 : input.Length))
{
NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (input == null ? 0 : input.Length - offset))
{
NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
byte[] result = Array.Empty<byte>();
SecurityStatusPal status = default;
bool cachedCreds = false;
byte[] thumbPrint = null;
//
// Looping through ASC or ISC with potentially cached credential that could have been
// already disposed from a different thread before ISC or ASC dir increment a cred ref count.
//
try
{
do
{
thumbPrint = null;
if (_refreshCredentialNeeded)
{
cachedCreds = _sslAuthenticationOptions.IsServer
? AcquireServerCredentials(ref thumbPrint, input)
: AcquireClientCredentials(ref thumbPrint);
}
if (_sslAuthenticationOptions.IsServer)
{
status = SslStreamPal.AcceptSecurityContext(
ref _credentialsHandle,
ref _securityContext,
input != null ? new ArraySegment<byte>(input, offset, count) : default,
ref result,
_sslAuthenticationOptions);
}
else
{
status = SslStreamPal.InitializeSecurityContext(
ref _credentialsHandle,
ref _securityContext,
_sslAuthenticationOptions.TargetHost,
input != null ? new ArraySegment<byte>(input, offset, count) : default,
ref result,
_sslAuthenticationOptions);
}
} while (cachedCreds && _credentialsHandle == null);
}
finally
{
if (_refreshCredentialNeeded)
{
_refreshCredentialNeeded = false;
//
// Assuming the ISC or ASC has referenced the credential,
// we want to call dispose so to decrement the effective ref count.
//
_credentialsHandle?.Dispose();
//
// This call may bump up the credential reference count further.
// Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert.
//
if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid)
{
SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
}
}
}
output = result;
if (_negotiatedApplicationProtocol == default)
{
// try to get ALPN info unless we already have it. (this function can be called multiple times)
byte[] alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext);
_negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false);
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
return status;
}
/*++
ProcessHandshakeSuccess -
Called on successful completion of Handshake -
used to set header/trailer sizes for encryption use
Fills in the information about established protocol
--*/
internal void ProcessHandshakeSuccess()
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
SslStreamPal.QueryContextStreamSizes(_securityContext, out StreamSizes streamSizes);
try
{
_headerSize = streamSizes.Header;
_trailerSize = streamSizes.Trailer;
_maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize));
Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0");
}
catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
NetEventSource.Fail(this, "StreamSizes out of range.");
throw;
}
SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo);
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this);
}
/*++
Encrypt - Encrypts our bytes before we send them over the wire
PERF: make more efficient, this does an extra copy when the offset
is non-zero.
Input:
buffer - bytes for sending
offset -
size -
output - Encrypted bytes
--*/
internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, buffer, buffer.Length);
NetEventSource.DumpBuffer(this, buffer);
}
byte[] writeBuffer = output;
SecurityStatusPal secStatus = SslStreamPal.EncryptMessage(
_securityContext,
buffer,
_headerSize,
_trailerSize,
ref writeBuffer,
out resultSize);
if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, $"ERROR {secStatus}");
}
else
{
output = writeBuffer;
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, $"OK data size:{resultSize}");
}
return secStatus;
}
internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this, payload, offset, count);
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
SecurityStatusPal secStatus = SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count);
return secStatus;
}
/*++
VerifyRemoteCertificate - Validates the content of a Remote Certificate
checkCRL if true, checks the certificate revocation list for validity.
checkCertName, if true checks the CN field of the certificate
--*/
//This method validates a remote certificate.
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
// We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
bool success = false;
X509Chain chain = null;
X509Certificate2 remoteCertificateEx = null;
X509Certificate2Collection remoteCertificateStore = null;
try
{
remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore);
_isRemoteCertificateAvailable = remoteCertificateEx != null;
if (remoteCertificateEx == null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, $"No remote certificate received. RemoteCertRequired: {RemoteCertRequired}");
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
{
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
// Authenticate the remote party: (e.g. when operating in server mode, authenticate the client).
chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? s_clientAuthOid : s_serverAuthOid);
if (remoteCertificateStore != null)
{
chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
}
sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties(
_securityContext,
chain,
remoteCertificateEx,
_sslAuthenticationOptions.CheckCertName,
_sslAuthenticationOptions.IsServer,
_sslAuthenticationOptions.TargetHost);
}
if (remoteCertValidationCallback != null)
{
success = remoteCertValidationCallback(_sslAuthenticationOptions.TargetHost, remoteCertificateEx, chain, sslPolicyErrors);
}
else
{
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_sslAuthenticationOptions.RemoteCertRequired)
{
success = true;
}
else
{
success = (sslPolicyErrors == SslPolicyErrors.None);
}
}
if (NetEventSource.IsEnabled)
{
LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}");
}
if (!success)
{
alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain);
}
}
finally
{
// At least on Win2k server the chain is found to have dependencies on the original cert context.
// So it should be closed first.
if (chain != null)
{
int elementsCount = chain.ChainElements.Count;
for (int i = 0; i < elementsCount; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
chain.Dispose();
}
if (remoteCertificateStore != null)
{
int certCount = remoteCertificateStore.Count;
for (int i = 0; i < certCount; i++)
{
remoteCertificateStore[i].Dispose();
}
}
remoteCertificateEx?.Dispose();
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, success);
return success;
}
public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
TlsAlertMessage alertMessage;
switch (sslPolicyErrors)
{
case SslPolicyErrors.RemoteCertificateChainErrors:
alertMessage = GetAlertMessageFromChain(chain);
break;
case SslPolicyErrors.RemoteCertificateNameMismatch:
alertMessage = TlsAlertMessage.BadCertificate;
break;
case SslPolicyErrors.RemoteCertificateNotAvailable:
default:
alertMessage = TlsAlertMessage.CertificateUnknown;
break;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"alertMessage:{alertMessage}");
SecurityStatusPal status;
status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
ExceptionDispatchInfo.Throw(status.Exception);
}
return null;
}
ProtocolToken token = GenerateAlertToken();
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, token);
return token;
}
public ProtocolToken CreateShutdownToken()
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
SecurityStatusPal status;
status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
ExceptionDispatchInfo.Throw(status.Exception);
}
return null;
}
ProtocolToken token = GenerateAlertToken();
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, token);
return token;
}
private ProtocolToken GenerateAlertToken()
{
byte[] nextmsg = null;
SecurityStatusPal status;
status = GenerateToken(null, 0, 0, ref nextmsg);
ProtocolToken token = new ProtocolToken(nextmsg, status);
return token;
}
private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain)
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
if (chainStatus.Status == X509ChainStatusFlags.NoError)
{
continue;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain |
X509ChainStatusFlags.Cyclic)) != 0)
{
return TlsAlertMessage.UnknownCA;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation)) != 0)
{
return TlsAlertMessage.CertificateRevoked;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested |
X509ChainStatusFlags.NotTimeValid)) != 0)
{
return TlsAlertMessage.CertificateExpired;
}
if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0)
{
return TlsAlertMessage.UnsupportedCert;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension |
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) |
X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0)
{
return TlsAlertMessage.BadCertificate;
}
// All other errors:
return TlsAlertMessage.CertificateUnknown;
}
Debug.Fail("GetAlertMessageFromChain was called but none of the chain elements had errors.");
return TlsAlertMessage.BadCertificate;
}
private void LogCertificateValidation(RemoteCertValidationCallback remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain)
{
if (!NetEventSource.IsEnabled)
return;
if (sslPolicyErrors != SslPolicyErrors.None)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors);
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
string chainStatusString = "ChainStatus: ";
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
chainStatusString += "\t" + chainStatus.StatusInformation;
}
NetEventSource.Log.RemoteCertificateError(this, chainStatusString);
}
}
if (success)
{
if (remoteCertValidationCallback != null)
{
NetEventSource.Log.RemoteCertDeclaredValid(this);
}
else
{
NetEventSource.Log.RemoteCertHasNoErrors(this);
}
}
else
{
if (remoteCertValidationCallback != null)
{
NetEventSource.Log.RemoteCertUserDeclaredInvalid(this);
}
}
}
}
// ProtocolToken - used to process and handle the return codes from the SSPI wrapper
internal class ProtocolToken
{
internal SecurityStatusPal Status;
internal byte[] Payload;
internal int Size;
internal bool Failed
{
get
{
return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded));
}
}
internal bool Done
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.OK);
}
}
internal bool Renegotiate
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate);
}
}
internal bool CloseConnection
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired);
}
}
internal ProtocolToken(byte[] data, SecurityStatusPal status)
{
Status = status;
Payload = data;
Size = data != null ? data.Length : 0;
}
internal Exception GetException()
{
// If it's not done, then there's got to be an error, even if it's
// a Handshake message up, and we only have a Warning message.
return this.Done ? null : SslStreamPal.GetException(Status);
}
#if TRACE_VERBOSE
public override string ToString()
{
return "Status=" + Status.ToString() + ", data size=" + Size;
}
#endif
}
}
| |
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace Lucene.Net.Util
{
/*
* 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>
/// Represents <see cref="T:int[]"/>, as a slice (offset + length) into an
/// existing <see cref="T:int[]"/>. The <see cref="Int32s"/> member should never be <c>null</c>; use
/// <see cref="EMPTY_INT32S"/> if necessary.
/// <para/>
/// NOTE: This was IntsRef in Lucene
/// <para/>
/// @lucene.internal
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public sealed class Int32sRef : IComparable<Int32sRef>
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
/// <summary>
/// An empty integer array for convenience.
/// <para/>
/// NOTE: This was EMPTY_INTS in Lucene
/// </summary>
public static readonly int[] EMPTY_INT32S = new int[0];
/// <summary>
/// The contents of the <see cref="Int32sRef"/>. Should never be <c>null</c>.
/// <para/>
/// NOTE: This was ints (field) in Lucene
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Int32s
{
get { return ints; }
set
{
if (value == null)
{
throw new ArgumentNullException("Ints should never be null");
}
ints = value;
}
}
private int[] ints;
/// <summary>
/// Offset of first valid integer. </summary>
public int Offset { get; set; }
/// <summary>
/// Length of used <see cref="int"/>s. </summary>
public int Length { get; set; }
/// <summary>
/// Create a <see cref="Int32sRef"/> with <see cref="EMPTY_INT32S"/>. </summary>
public Int32sRef()
{
ints = EMPTY_INT32S;
}
/// <summary>
/// Create a <see cref="Int32sRef"/> pointing to a new array of size <paramref name="capacity"/>.
/// Offset and length will both be zero.
/// </summary>
public Int32sRef(int capacity)
{
ints = new int[capacity];
}
/// <summary>
/// This instance will directly reference <paramref name="ints"/> w/o making a copy.
/// <paramref name="ints"/> should not be <c>null</c>.
/// </summary>
public Int32sRef(int[] ints, int offset, int length)
{
this.ints = ints;
this.Offset = offset;
this.Length = length;
Debug.Assert(IsValid());
}
/// <summary>
/// Returns a shallow clone of this instance (the underlying <see cref="int"/>s are
/// <b>not</b> copied and will be shared by both the returned object and this
/// object.
/// </summary>
/// <seealso cref="DeepCopyOf(Int32sRef)"/>
public object Clone()
{
return new Int32sRef(ints, Offset, Length);
}
public override int GetHashCode()
{
const int prime = 31;
int result = 0;
int end = Offset + Length;
for (int i = Offset; i < end; i++)
{
result = prime * result + ints[i];
}
return result;
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (other is Int32sRef)
{
return this.Int32sEquals((Int32sRef)other);
}
return false;
}
/// <summary>
/// NOTE: This was intsEquals() in Lucene
/// </summary>
public bool Int32sEquals(Int32sRef other)
{
if (Length == other.Length)
{
int otherUpto = other.Offset;
int[] otherInts = other.ints;
int end = Offset + Length;
for (int upto = Offset; upto < end; upto++, otherUpto++)
{
if (ints[upto] != otherInts[otherUpto])
{
return false;
}
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// Signed <see cref="int"/> order comparison. </summary>
public int CompareTo(Int32sRef other)
{
if (this == other)
{
return 0;
}
int[] aInts = this.ints;
int aUpto = this.Offset;
int[] bInts = other.ints;
int bUpto = other.Offset;
int aStop = aUpto + Math.Min(this.Length, other.Length);
while (aUpto < aStop)
{
int aInt = aInts[aUpto++];
int bInt = bInts[bUpto++];
if (aInt > bInt)
{
return 1;
}
else if (aInt < bInt)
{
return -1;
}
}
// One is a prefix of the other, or, they are equal:
return this.Length - other.Length;
}
/// <summary>
/// NOTE: This was copyInts() in Lucene
/// </summary>
public void CopyInt32s(Int32sRef other)
{
if (ints.Length - Offset < other.Length)
{
ints = new int[other.Length];
Offset = 0;
}
Array.Copy(other.ints, other.Offset, ints, Offset, other.Length);
Length = other.Length;
}
/// <summary>
/// Used to grow the reference array.
/// <para/>
/// In general this should not be used as it does not take the offset into account.
/// <para/>
/// @lucene.internal
/// </summary>
public void Grow(int newLength)
{
Debug.Assert(Offset == 0);
if (ints.Length < newLength)
{
ints = ArrayUtil.Grow(ints, newLength);
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
int end = Offset + Length;
for (int i = Offset; i < end; i++)
{
if (i > Offset)
{
sb.Append(' ');
}
sb.Append(ints[i].ToString("x"));
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Creates a new <see cref="Int32sRef"/> that points to a copy of the <see cref="int"/>s from
/// <paramref name="other"/>
/// <para/>
/// The returned <see cref="Int32sRef"/> will have a length of <c>other.Length</c>
/// and an offset of zero.
/// </summary>
public static Int32sRef DeepCopyOf(Int32sRef other)
{
Int32sRef clone = new Int32sRef();
clone.CopyInt32s(other);
return clone;
}
/// <summary>
/// Performs internal consistency checks.
/// Always returns true (or throws <see cref="InvalidOperationException"/>)
/// </summary>
public bool IsValid()
{
if (ints == null)
{
throw new InvalidOperationException("ints is null");
}
if (Length < 0)
{
throw new InvalidOperationException("length is negative: " + Length);
}
if (Length > ints.Length)
{
throw new InvalidOperationException("length is out of bounds: " + Length + ",ints.length=" + Int32s.Length);
}
if (Offset < 0)
{
throw new InvalidOperationException("offset is negative: " + Offset);
}
if (Offset > ints.Length)
{
throw new InvalidOperationException("offset out of bounds: " + Offset + ",ints.length=" + Int32s.Length);
}
if (Offset + Length < 0)
{
throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length);
}
if (Offset + Length > Int32s.Length)
{
throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",ints.length=" + Int32s.Length);
}
return true;
}
}
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Cisco.Spark {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
const string HEX_DIGIT = "0123456789ABCDEFabcdef";
public static bool IsHexDigit(char c) {
return HEX_DIGIT.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
case TOKEN.STRING:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
TOKEN valueToken = NextToken;
object value = ParseByToken(valueToken);
if(value==null && valueToken!=TOKEN.NULL)
return null;
table[name] = value;
break;
default:
return null;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
if(value==null && nextToken!=TOKEN.NULL)
return null;
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
if (!IsHexDigit(hex[i]))
return null;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) {
long parsedInt;
Int64.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
} else if ((asStr = value as string) != null) {
SerializeString(asStr);
} else if (value is bool) {
builder.Append((bool) value ? "true" : "false");
} else if ((asList = value as IList) != null) {
SerializeArray(asList);
} else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
} else if (value is char) {
SerializeString(new string((char) value, 1));
} else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
for (int i=0; i<anArray.Count; i++) {
object obj = anArray[i];
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
for (int i=0; i<charArray.Length; i++) {
char c = charArray[i];
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
} else {
SerializeString(value.ToString());
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.RecoveryServices
{
/// <summary>
/// Definition of vault usage operations for the Recovery Services
/// extension.
/// </summary>
internal partial class ReplicationUsagesOperations : IServiceOperations<RecoveryServicesManagementClient>, IReplicationUsagesOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationUsagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ReplicationUsagesOperations(RecoveryServicesManagementClient client)
{
this._client = client;
}
private RecoveryServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient.
/// </summary>
public RecoveryServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the replication usages of a vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource group/ Cloud service containing
/// the resource/ Vault collection.
/// </param>
/// <param name='resourceName'>
/// Required. The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Replication Usgaes.
/// </returns>
public async Task<ReplicationUsagesResponse> GetAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
url = url + "/";
url = url + "vaults";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/replicationUsages";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2015-01-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ReplicationUsagesResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ReplicationUsagesResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ReplicationUsages replicationUsagesInstance = new ReplicationUsages();
result.ReplicationVaultUsages = replicationUsagesInstance;
JToken monitoringSummaryValue = responseDoc["monitoringSummary"];
if (monitoringSummaryValue != null && monitoringSummaryValue.Type != JTokenType.Null)
{
MonitoringSummary monitoringSummaryInstance = new MonitoringSummary();
replicationUsagesInstance.MonitoringSummary = monitoringSummaryInstance;
JToken unHealthyVmCountValue = monitoringSummaryValue["unHealthyVmCount"];
if (unHealthyVmCountValue != null && unHealthyVmCountValue.Type != JTokenType.Null)
{
int unHealthyVmCountInstance = ((int)unHealthyVmCountValue);
monitoringSummaryInstance.UnHealthyVmCount = unHealthyVmCountInstance;
}
JToken unHealthyProviderCountValue = monitoringSummaryValue["unHealthyProviderCount"];
if (unHealthyProviderCountValue != null && unHealthyProviderCountValue.Type != JTokenType.Null)
{
int unHealthyProviderCountInstance = ((int)unHealthyProviderCountValue);
monitoringSummaryInstance.UnHealthyProviderCount = unHealthyProviderCountInstance;
}
JToken eventsCountValue = monitoringSummaryValue["eventsCount"];
if (eventsCountValue != null && eventsCountValue.Type != JTokenType.Null)
{
int eventsCountInstance = ((int)eventsCountValue);
monitoringSummaryInstance.EventsCount = eventsCountInstance;
}
}
JToken jobsSummaryValue = responseDoc["jobsSummary"];
if (jobsSummaryValue != null && jobsSummaryValue.Type != JTokenType.Null)
{
JobsSummary jobsSummaryInstance = new JobsSummary();
replicationUsagesInstance.JobsSummary = jobsSummaryInstance;
JToken failedJobsValue = jobsSummaryValue["failedJobs"];
if (failedJobsValue != null && failedJobsValue.Type != JTokenType.Null)
{
int failedJobsInstance = ((int)failedJobsValue);
jobsSummaryInstance.FailedJobs = failedJobsInstance;
}
JToken suspendedJobsValue = jobsSummaryValue["suspendedJobs"];
if (suspendedJobsValue != null && suspendedJobsValue.Type != JTokenType.Null)
{
int suspendedJobsInstance = ((int)suspendedJobsValue);
jobsSummaryInstance.SuspendedJobs = suspendedJobsInstance;
}
JToken inProgressJobsValue = jobsSummaryValue["inProgressJobs"];
if (inProgressJobsValue != null && inProgressJobsValue.Type != JTokenType.Null)
{
int inProgressJobsInstance = ((int)inProgressJobsValue);
jobsSummaryInstance.InProgressJobs = inProgressJobsInstance;
}
}
JToken protectedItemCountValue = responseDoc["protectedItemCount"];
if (protectedItemCountValue != null && protectedItemCountValue.Type != JTokenType.Null)
{
int protectedItemCountInstance = ((int)protectedItemCountValue);
replicationUsagesInstance.ProtectedItemCount = protectedItemCountInstance;
}
JToken recoveryPlanCountValue = responseDoc["recoveryPlanCount"];
if (recoveryPlanCountValue != null && recoveryPlanCountValue.Type != JTokenType.Null)
{
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyString
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// EnumModel operations.
/// </summary>
public partial class EnumModel : IServiceOperations<AutoRestSwaggerBATService>, IEnumModel
{
/// <summary>
/// Initializes a new instance of the EnumModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public EnumModel(AutoRestSwaggerBATService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATService
/// </summary>
public AutoRestSwaggerBATService Client { get; private set; }
/// <summary>
/// Get enum value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Colors?>> GetNotExpandableWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Colors?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Colors?>(_responseContent, this.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>
/// Sends value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'
/// </summary>
/// <param name='stringBody'>
/// Possible values include: 'red color', 'green-color', 'blue_color'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutNotExpandableWithHttpMessagesAsync(Colors stringBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("stringBody", stringBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
///----------- ----------- ----------- ----------- ----------- ----------- -----------
/// <copyright file="DeflateStream.cs" company="Microsoft">
/// Copyright (c) Microsoft Corporation. All rights reserved.
/// </copyright>
///
///----------- ----------- ----------- ----------- ----------- ----------- -----------
///
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace Custom_Scenery.Compression {
public class DeflateStream : Stream {
internal const int DefaultBufferSize = 8192;
internal delegate void AsyncWriteDelegate(byte[] array, int offset, int count, bool isAsync);
//private const String OrigStackTrace_ExceptionDataKey = "ORIGINAL_STACK_TRACE";
private Stream _stream;
private CompressionMode _mode;
private bool _leaveOpen;
private Inflater inflater;
private IDeflater deflater;
private byte[] buffer;
private int asyncOperations;
#if !NETFX_CORE
private readonly AsyncCallback m_CallBack;
private readonly AsyncWriteDelegate m_AsyncWriterDelegate;
#endif
private IFileFormatWriter formatWriter;
private bool wroteHeader;
private bool wroteBytes;
private enum WorkerType : byte { Managed, Unknown };
public DeflateStream(Stream stream, CompressionMode mode)
: this(stream, mode, false) {
}
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) {
if(stream == null )
throw new ArgumentNullException("stream");
if (CompressionMode.Compress != mode && CompressionMode.Decompress != mode)
throw new ArgumentException(SR.GetString(SR.ArgumentOutOfRange_Enum), "mode");
_stream = stream;
_mode = mode;
_leaveOpen = leaveOpen;
switch (_mode) {
case CompressionMode.Decompress:
if (!_stream.CanRead) {
throw new ArgumentException(SR.GetString(SR.NotReadableStream), "stream");
}
inflater = new Inflater();
#if !NETFX_CORE
m_CallBack = new AsyncCallback(ReadCallback);
#endif
break;
case CompressionMode.Compress:
if (!_stream.CanWrite) {
throw new ArgumentException(SR.GetString(SR.NotWriteableStream), "stream");
}
deflater = CreateDeflater();
#if !NETFX_CORE
m_AsyncWriterDelegate = new AsyncWriteDelegate(this.InternalWrite);
m_CallBack = new AsyncCallback(WriteCallback);
#endif
break;
} // switch (_mode)
buffer = new byte[DefaultBufferSize];
}
private static IDeflater CreateDeflater() {
switch (GetDeflaterType()) {
case WorkerType.Managed:
return new DeflaterManaged();
default:
// We do not expect this to ever be thrown.
// But this is better practice than returning null.
#if NETFX_CORE
throw new Exception("Program entered an unexpected state.");
#else
throw new SystemException("Program entered an unexpected state.");
#endif
}
}
#if !SILVERLIGHT
[System.Security.SecuritySafeCritical]
#endif
private static WorkerType GetDeflaterType() {
return WorkerType.Managed;
}
internal void SetFileFormatReader(IFileFormatReader reader) {
if (reader != null) {
inflater.SetFileFormatReader(reader);
}
}
internal void SetFileFormatWriter(IFileFormatWriter writer) {
if (writer != null) {
formatWriter = writer;
}
}
public Stream BaseStream {
get {
return _stream;
}
}
public override bool CanRead {
get {
if( _stream == null) {
return false;
}
return (_mode == CompressionMode.Decompress && _stream.CanRead);
}
}
public override bool CanWrite {
get {
if( _stream == null) {
return false;
}
return (_mode == CompressionMode.Compress && _stream.CanWrite);
}
}
public override bool CanSeek {
get {
return false;
}
}
public override long Length {
get {
throw new NotSupportedException(SR.GetString(SR.NotSupported));
}
}
public override long Position {
get {
throw new NotSupportedException(SR.GetString(SR.NotSupported));
}
set {
throw new NotSupportedException(SR.GetString(SR.NotSupported));
}
}
public override void Flush() {
EnsureNotDisposed();
return;
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.NotSupported));
}
public override void SetLength(long value) {
throw new NotSupportedException(SR.GetString(SR.NotSupported));
}
public override int Read(byte[] array, int offset, int count) {
EnsureDecompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
int bytesRead;
int currentOffset = offset;
int remainingCount = count;
while(true) {
bytesRead = inflater.Inflate(array, currentOffset, remainingCount);
currentOffset += bytesRead;
remainingCount -= bytesRead;
if( remainingCount == 0) {
break;
}
if (inflater.Finished() ) {
// if we finished decompressing, we can't have anything left in the outputwindow.
Debug.Assert(inflater.AvailableOutput == 0, "We should have copied all stuff out!");
break;
}
Debug.Assert(inflater.NeedsInput(), "We can only run into this case if we are short of input");
int bytes = _stream.Read(buffer, 0, buffer.Length);
if( bytes == 0) {
break; //Do we want to throw an exception here?
}
inflater.SetInput(buffer, 0 , bytes);
}
return count - remainingCount;
}
private void ValidateParameters(byte[] array, int offset, int count) {
if (array==null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (array.Length - offset < count)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentOffsetCount));
}
private void EnsureNotDisposed() {
if (_stream == null)
throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_StreamClosed));
}
private void EnsureDecompressionMode() {
if( _mode != CompressionMode.Decompress)
throw new InvalidOperationException(SR.GetString(SR.CannotReadFromDeflateStream));
}
private void EnsureCompressionMode() {
if( _mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.GetString(SR.CannotWriteToDeflateStream));
}
#if !NETFX_CORE
public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) {
EnsureDecompressionMode();
// We use this checking order for compat to earlier versions:
if (asyncOperations != 0)
throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall));
ValidateParameters(array, offset, count);
EnsureNotDisposed();
Interlocked.Increment(ref asyncOperations);
try {
DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult(
this, asyncState, asyncCallback, array, offset, count);
userResult.isWrite = false;
// Try to read decompressed data in output buffer
int bytesRead = inflater.Inflate(array, offset, count);
if( bytesRead != 0) {
// If decompression output buffer is not empty, return immediately.
// 'true' means we complete synchronously.
userResult.InvokeCallback(true, (object) bytesRead);
return userResult;
}
if (inflater.Finished() ) {
// end of compression stream
userResult.InvokeCallback(true, (object) 0);
return userResult;
}
// If there is no data on the output buffer and we are not at
// the end of the stream, we need to get more data from the base stream
_stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, userResult);
userResult.m_CompletedSynchronously &= userResult.IsCompleted;
return userResult;
} catch {
Interlocked.Decrement( ref asyncOperations);
throw;
}
}
// callback function for asynchrous reading on base stream
private void ReadCallback(IAsyncResult baseStreamResult) {
DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) baseStreamResult.AsyncState;
outerResult.m_CompletedSynchronously &= baseStreamResult.CompletedSynchronously;
int bytesRead = 0;
try {
EnsureNotDisposed();
bytesRead = _stream.EndRead(baseStreamResult);
if (bytesRead <= 0 ) {
// This indicates the base stream has received EOF
outerResult.InvokeCallback((object) 0);
return;
}
// Feed the data from base stream into decompression engine
inflater.SetInput(buffer, 0 , bytesRead);
bytesRead = inflater.Inflate(outerResult.buffer, outerResult.offset, outerResult.count);
if (bytesRead == 0 && !inflater.Finished()) {
// We could have read in head information and didn't get any data.
// Read from the base stream again.
// Need to solve recusion.
_stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, outerResult);
} else {
outerResult.InvokeCallback((object) bytesRead);
}
} catch (Exception exc) {
// Defer throwing this until EndRead where we will likely have user code on the stack.
outerResult.InvokeCallback(exc);
return;
}
}
public override int EndRead(IAsyncResult asyncResult) {
EnsureDecompressionMode();
CheckEndXxxxLegalStateAndParams(asyncResult);
// We checked that this will work in CheckEndXxxxLegalStateAndParams:
DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult;
AwaitAsyncResultCompletion(deflateStrmAsyncResult);
Exception previousException = deflateStrmAsyncResult.Result as Exception;
if (previousException != null) {
// Rethrowing will delete the stack trace. Let's help future debuggers:
//previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
throw previousException;
}
return (int) deflateStrmAsyncResult.Result;
}
#endif
public override void Write(byte[] array, int offset, int count) {
EnsureCompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
InternalWrite(array, offset, count, false);
}
// isAsync always seems to be false. why do we have it?
internal void InternalWrite(byte[] array, int offset, int count, bool isAsync) {
DoMaintenance(array, offset, count);
// Write compressed the bytes we already passed to the deflater:
WriteDeflaterOutput(isAsync);
// Pass new bytes through deflater and write them too:
deflater.SetInput(array, offset, count);
WriteDeflaterOutput(isAsync);
}
private void WriteDeflaterOutput(bool isAsync) {
while (!deflater.NeedsInput()) {
int compressedBytes = deflater.GetDeflateOutput(buffer);
if (compressedBytes > 0)
DoWrite(buffer, 0, compressedBytes, isAsync);
}
}
private void DoWrite(byte[] array, int offset, int count, bool isAsync) {
Debug.Assert(array != null);
Debug.Assert(count != 0);
#if !NETFX_CORE
if (isAsync) {
IAsyncResult result = _stream.BeginWrite(array, offset, count, null, null);
_stream.EndWrite(result);
}
else
#endif
{
_stream.Write(array, offset, count);
}
}
// Perform deflate-mode maintenance required due to custom header and footer writers
// (e.g. set by GZipStream):
private void DoMaintenance(byte[] array, int offset, int count) {
// If no bytes written, do nothing:
if (count <= 0)
return;
// Note that stream contains more than zero data bytes:
wroteBytes = true;
// If no header/footer formatter present, nothing else to do:
if (formatWriter == null)
return;
// If formatter has not yet written a header, do it now:
if (!wroteHeader) {
byte[] b = formatWriter.GetHeader();
_stream.Write(b, 0, b.Length);
wroteHeader = true;
}
// Inform formatter of the data bytes written:
formatWriter.UpdateWithBytesRead(array, offset, count);
}
// This is called by Dispose:
private void PurgeBuffers(bool disposing) {
if (!disposing)
return;
if (_stream == null)
return;
Flush();
if (_mode != CompressionMode.Compress)
return;
// Some deflaters (e.g. ZLib write more than zero bytes for zero bytes inpuits.
// This round-trips and we should be ok with this, but our legacy managed deflater
// always wrote zero output for zero input and upstack code (e.g. GZipStream)
// took dependencies on it. Thus, make sure to only "flush" when we actually had
// some input:
if (wroteBytes) {
// Compress any bytes left:
WriteDeflaterOutput(false);
// Pull out any bytes left inside deflater:
bool finished;
do {
int compressedBytes;
finished = deflater.Finish(buffer, out compressedBytes);
if (compressedBytes > 0)
DoWrite(buffer, 0, compressedBytes, false);
} while (!finished);
}
// Write format footer:
if (formatWriter != null && wroteHeader) {
byte[] b = formatWriter.GetFooter();
_stream.Write(b, 0, b.Length);
}
}
protected override void Dispose(bool disposing) {
try {
PurgeBuffers(disposing);
} finally {
// Close the underlying stream even if PurgeBuffers threw.
// Stream.Close() may throw here (may or may not be due to the same error).
// In this case, we still need to clean up internal resources, hence the inner finally blocks.
try {
if(disposing && !_leaveOpen && _stream != null)
_stream.Dispose();
} finally {
_stream = null;
try {
if (deflater != null)
deflater.Dispose();
} finally {
deflater = null;
base.Dispose(disposing);
}
} // finally
} // finally
} // Dispose
#if !NETFX_CORE
public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) {
EnsureCompressionMode();
// We use this checking order for compat to earlier versions:
if (asyncOperations != 0 )
throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall));
ValidateParameters(array, offset, count);
EnsureNotDisposed();
Interlocked.Increment(ref asyncOperations);
try {
DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult(
this, asyncState, asyncCallback, array, offset, count);
userResult.isWrite = true;
m_AsyncWriterDelegate.BeginInvoke(array, offset, count, true, m_CallBack, userResult);
userResult.m_CompletedSynchronously &= userResult.IsCompleted;
return userResult;
} catch {
Interlocked.Decrement(ref asyncOperations);
throw;
}
}
// Callback function for asynchrous reading on base stream
private void WriteCallback(IAsyncResult asyncResult) {
DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) asyncResult.AsyncState;
outerResult.m_CompletedSynchronously &= asyncResult.CompletedSynchronously;
try {
m_AsyncWriterDelegate.EndInvoke(asyncResult);
} catch (Exception exc) {
// Defer throwing this until EndWrite where there is user code on the stack:
outerResult.InvokeCallback(exc);
return;
}
outerResult.InvokeCallback(null);
}
public override void EndWrite(IAsyncResult asyncResult) {
EnsureCompressionMode();
CheckEndXxxxLegalStateAndParams(asyncResult);
// We checked that this will work in CheckEndXxxxLegalStateAndParams:
DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult;
AwaitAsyncResultCompletion(deflateStrmAsyncResult);
Exception previousException = deflateStrmAsyncResult.Result as Exception;
if (previousException != null) {
// Rethrowing will delete the stack trace. Let's help future debuggers:
//previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
throw previousException;
}
}
private void CheckEndXxxxLegalStateAndParams(IAsyncResult asyncResult) {
if (asyncOperations != 1)
throw new InvalidOperationException(SR.GetString(SR.InvalidEndCall));
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
EnsureNotDisposed();
DeflateStreamAsyncResult myResult = asyncResult as DeflateStreamAsyncResult;
// This should really be an ArgumentException, but we keep this for compat to previous versions:
if (myResult == null)
throw new ArgumentNullException("asyncResult");
}
private void AwaitAsyncResultCompletion(DeflateStreamAsyncResult asyncResult) {
try {
if (!asyncResult.IsCompleted)
asyncResult.AsyncWaitHandle.WaitOne();
} finally {
Interlocked.Decrement(ref asyncOperations);
asyncResult.Close(); // this will just close the wait handle
}
}
#endif
} // public class DeflateStream
} // namespace Unity.IO.Compression
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class MethodTests
{
[Fact]
public static unsafe void TestMethods1()
{
TestMethods1Worker(typeof(ClassWithMethods1<>).Project());
TestMethods1Worker(typeof(ClassWithMethods1<int>).Project());
TestMethods1Worker(typeof(ClassWithMethods1<string>).Project());
}
private static void TestMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = t.GetMethod("Method1", bf);
Assert.Equal("Method1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.False(m.IsGenericMethodDefinition);
Assert.False(m.IsConstructedGenericMethod());
Assert.False(m.IsGenericMethod);
Assert.Equal(MethodAttributes.Public | MethodAttributes.HideBySig, m.Attributes);
Assert.Equal(MethodImplAttributes.IL, m.MethodImplementationFlags);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, m.CallingConvention);
Type theT = t.GetGenericArguments()[0];
Assert.Equal(typeof(bool).Project(), m.ReturnType);
ParameterInfo rp = m.ReturnParameter;
Assert.Null(rp.Name);
Assert.Equal(typeof(bool).Project(), rp.ParameterType);
Assert.Equal(m, rp.Member);
Assert.Equal(-1, rp.Position);
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(2, ps.Length);
{
ParameterInfo p = ps[0];
Assert.Equal("x", p.Name);
Assert.Equal(typeof(int).Project(), p.ParameterType);
Assert.Equal(m, p.Member);
Assert.Equal(0, p.Position);
}
{
ParameterInfo p = ps[1];
Assert.Equal("t", p.Name);
Assert.Equal(theT, p.ParameterType);
Assert.Equal(m, p.Member);
Assert.Equal(1, p.Position);
}
TestUtils.AssertNewObjectReturnedEachTime(() => m.GetParameters());
m.TestMethodInfoInvariants();
}
[Fact]
public static unsafe void TestAllCoreTypes()
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = typeof(ClassWithMethods1<>).Project().GetMethod("TestPrimitives1", bf);
Assert.Equal(typeof(void).Project(), m.ReturnParameter.ParameterType);
ParameterInfo[] ps = m.GetParameters();
{
ParameterInfo p = ps.Single((p1) => p1.Name == "bo");
Assert.Equal(typeof(bool).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "c");
Assert.Equal(typeof(char).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "b");
Assert.Equal(typeof(byte).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "s");
Assert.Equal(typeof(short).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "i");
Assert.Equal(typeof(int).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "l");
Assert.Equal(typeof(long).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ip");
Assert.Equal(typeof(IntPtr).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "sb");
Assert.Equal(typeof(sbyte).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "us");
Assert.Equal(typeof(ushort).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ui");
Assert.Equal(typeof(uint).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "ul");
Assert.Equal(typeof(ulong).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "uip");
Assert.Equal(typeof(UIntPtr).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "fl");
Assert.Equal(typeof(float).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "db");
Assert.Equal(typeof(double).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "o");
Assert.Equal(typeof(object).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "str");
Assert.Equal(typeof(string).Project(), p.ParameterType);
}
{
ParameterInfo p = ps.Single((p1) => p1.Name == "tr");
Assert.Equal(typeof(TypedReference).Project(), p.ParameterType);
}
}
[Fact]
public static void TestGenericMethods1()
{
TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project());
TestGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project());
}
private static void TestGenericMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo m = t.GetMethod("GenericMethod1", bf);
Assert.Equal(m, m.GetGenericMethodDefinition());
Assert.Equal("GenericMethod1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.True(m.IsGenericMethodDefinition);
Assert.False(m.IsConstructedGenericMethod());
Assert.True(m.IsGenericMethod);
Type[] methodGenericParameters = m.GetGenericArguments();
Assert.Equal(2, methodGenericParameters.Length);
Type theT = t.GetGenericArguments()[0];
Type theU = t.GetGenericArguments()[1];
Type theM = m.GetGenericArguments()[0];
Type theN = m.GetGenericArguments()[1];
theM.TestGenericMethodParameterInvariants();
theN.TestGenericMethodParameterInvariants();
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(1, ps.Length);
ParameterInfo p = ps[0];
Type actual = p.ParameterType;
//GenericClass5<N, M[], IEnumerable<U>, T[,], int>
Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType(
theN,
theM.MakeArrayType(),
typeof(IEnumerable<>).Project().MakeGenericType(theU),
theT.MakeArrayType(2),
typeof(int).Project());
Assert.Equal(expected, actual);
m.TestGenericMethodInfoInvariants();
}
[Fact]
public static void TestConstructedGenericMethods1()
{
TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<,>).Project());
TestConstructedGenericMethods1Worker(typeof(GenericClassWithGenericMethods1<int, string>).Project());
}
private static void TestConstructedGenericMethods1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodInfo gm = t.GetMethod("GenericMethod1", bf);
MethodInfo m = gm.MakeGenericMethod(typeof(object).Project(), typeof(string).Project());
Assert.Equal(gm, m.GetGenericMethodDefinition());
Assert.Equal("GenericMethod1", m.Name);
Assert.Equal(t, m.DeclaringType);
Assert.Equal(t, m.ReflectedType);
Assert.False(m.IsGenericMethodDefinition);
Assert.True(m.IsConstructedGenericMethod());
Assert.True(m.IsGenericMethod);
Type[] methodGenericParameters = m.GetGenericArguments();
Assert.Equal(2, methodGenericParameters.Length);
Type theT = t.GetGenericArguments()[0];
Type theU = t.GetGenericArguments()[1];
Type theM = m.GetGenericArguments()[0];
Type theN = m.GetGenericArguments()[1];
Assert.Equal(typeof(object).Project(), theM);
Assert.Equal(typeof(string).Project(), theN);
ParameterInfo[] ps = m.GetParameters();
Assert.Equal(1, ps.Length);
ParameterInfo p = ps[0];
Type actual = p.ParameterType;
//GenericClass5<N, M[], IEnumerable<U>, T[,], int>
Type expected = typeof(GenericClass5<,,,,>).Project().MakeGenericType(
theN,
theM.MakeArrayType(),
typeof(IEnumerable<>).Project().MakeGenericType(theU),
theT.MakeArrayType(2),
typeof(int).Project());
Assert.Equal(expected, actual);
m.TestConstructedGenericMethodInfoInvariants();
}
[Fact]
public static unsafe void TestCustomModifiers1()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
MethodInfo m = t.GetMethod("MyMethod");
ParameterInfo p = m.GetParameters()[0];
Type[] req = p.GetRequiredCustomModifiers();
Type[] opt = p.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req);
Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => p.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => p.GetOptionalCustomModifiers());
}
}
[Fact]
public static void TestMethodBody1()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly coreAssembly = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithMethodBodyImage);
Type nonsense = a.GetType("Nonsense`1", throwOnError: true);
Type theT = nonsense.GetTypeInfo().GenericTypeParameters[0];
MethodInfo m = nonsense.GetMethod("Foo");
Type theM = m.GetGenericArguments()[0];
MethodBody mb = m.GetMethodBody();
byte[] il = mb.GetILAsByteArray();
Assert.Equal<byte>(TestData.s_AssemblyWithMethodBodyILBytes, il);
Assert.Equal(4, mb.MaxStackSize);
Assert.True(mb.InitLocals);
Assert.Equal(0x11000001, mb.LocalSignatureMetadataToken);
IList<LocalVariableInfo> lvis = mb.LocalVariables;
Assert.Equal(10, lvis.Count);
Assert.Equal(0, lvis[0].LocalIndex);
Assert.False(lvis[0].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Single", throwOnError: true), lvis[0].LocalType);
Assert.Equal(1, lvis[1].LocalIndex);
Assert.False(lvis[1].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Double", throwOnError: true), lvis[1].LocalType);
Assert.Equal(2, lvis[2].LocalIndex);
Assert.False(lvis[2].IsPinned);
Assert.Equal(theT, lvis[2].LocalType);
Assert.Equal(3, lvis[3].LocalIndex);
Assert.False(lvis[3].IsPinned);
Assert.Equal(theT.MakeArrayType(), lvis[3].LocalType);
Assert.Equal(4, lvis[4].LocalIndex);
Assert.False(lvis[4].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Collections.Generic.IList`1", throwOnError: true).MakeGenericType(theM), lvis[4].LocalType);
Assert.Equal(5, lvis[5].LocalIndex);
Assert.False(lvis[5].IsPinned);
Assert.Equal(coreAssembly.GetType("System.String", throwOnError: true), lvis[5].LocalType);
Assert.Equal(6, lvis[6].LocalIndex);
Assert.False(lvis[6].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[6].LocalType);
Assert.Equal(7, lvis[7].LocalIndex);
Assert.True(lvis[7].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeByRefType(), lvis[7].LocalType);
Assert.Equal(8, lvis[8].LocalIndex);
Assert.False(lvis[8].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Int32", throwOnError: true).MakeArrayType(), lvis[8].LocalType);
Assert.Equal(9, lvis[9].LocalIndex);
Assert.False(lvis[9].IsPinned);
Assert.Equal(coreAssembly.GetType("System.Boolean", throwOnError: true), lvis[9].LocalType);
IList<ExceptionHandlingClause> ehcs = mb.ExceptionHandlingClauses;
Assert.Equal(2, ehcs.Count);
ExceptionHandlingClause ehc = ehcs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Finally, ehc.Flags);
Assert.Equal(97, ehc.TryOffset);
Assert.Equal(41, ehc.TryLength);
Assert.Equal(138, ehc.HandlerOffset);
Assert.Equal(5, ehc.HandlerLength);
ehc = ehcs[1];
Assert.Equal(ExceptionHandlingClauseOptions.Filter, ehc.Flags);
Assert.Equal(88, ehc.TryOffset);
Assert.Equal(58, ehc.TryLength);
Assert.Equal(172, ehc.HandlerOffset);
Assert.Equal(16, ehc.HandlerLength);
Assert.Equal(146, ehc.FilterOffset);
}
}
[Fact]
public static void TestEHClauses()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly coreAssembly = lc.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithEhClausesImage);
Type gt = a.GetType("G`1", throwOnError: true);
Type et = a.GetType("MyException`2", throwOnError: true);
Type gtP0 = gt.GetGenericTypeParameters()[0];
Type etP0 = et.GetGenericTypeParameters()[0];
Type etP1 = et.GetGenericTypeParameters()[1];
{
MethodInfo m = gt.GetMethod("Catch");
Type theM = m.GetGenericArguments()[0];
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Equal(et.MakeGenericType(gtP0, theM), eh.CatchType);
}
{
Type sysInt32 = coreAssembly.GetType("System.Int32", throwOnError: true);
Type sysSingle = coreAssembly.GetType("System.Single", throwOnError: true);
MethodInfo m = gt.MakeGenericType(sysInt32).GetMethod("Catch").MakeGenericMethod(sysSingle);
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Clause, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Equal(et.MakeGenericType(sysInt32, sysSingle), eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Finally");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Finally, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(14, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Fault");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Fault, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(16, eh.HandlerOffset);
Assert.Equal(14, eh.HandlerLength);
Assert.Throws<InvalidOperationException>(() => eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
{
MethodInfo m = gt.GetMethod("Filter");
MethodBody body = m.GetMethodBody();
IList<ExceptionHandlingClause> ehs = body.ExceptionHandlingClauses;
Assert.Equal(1, ehs.Count);
ExceptionHandlingClause eh = ehs[0];
Assert.Equal(ExceptionHandlingClauseOptions.Filter, eh.Flags);
Assert.Equal(1, eh.TryOffset);
Assert.Equal(15, eh.TryLength);
Assert.Equal(40, eh.HandlerOffset);
Assert.Equal(16, eh.HandlerLength);
Assert.Equal(16, eh.FilterOffset);
Assert.Throws<InvalidOperationException>(() => eh.CatchType);
}
}
}
[Fact]
public static void TestCallingConventions()
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase[] mbs = (MethodBase[])(typeof(ExerciseCallingConventions).Project().GetMember("*", MemberTypes.Method | MemberTypes.Constructor, bf));
mbs = mbs.OrderBy(m => m.Name).ToArray();
Assert.Equal(5, mbs.Length);
Assert.Equal(".cctor", mbs[0].Name);
Assert.Equal(CallingConventions.Standard, mbs[0].CallingConvention);
Assert.Equal(".ctor", mbs[1].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[1].CallingConvention);
Assert.Equal("InstanceMethod", mbs[2].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[2].CallingConvention);
Assert.Equal("StaticMethod", mbs[3].Name);
Assert.Equal(CallingConventions.Standard, mbs[3].CallingConvention);
Assert.Equal("VirtualMethod", mbs[4].Name);
Assert.Equal(CallingConventions.Standard | CallingConventions.HasThis, mbs[4].CallingConvention);
}
}
}
| |
namespace _03.AjaxWithMvc.Data.Migrations
{
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using Models;
using System;
public sealed class Configuration : DbMigrationsConfiguration<_03.AjaxWithMvc.Data.MoviesDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(_03.AjaxWithMvc.Data.MoviesDbContext context)
{
var databaseIsEmpty = !(context.Movies.Any() && context.People.Any() && context.Studios.Any());
if (databaseIsEmpty)
{
// Add studios
context.Studios.Add(new Studio()
{
Name = "Dreamworks",
Adress = "Some Address 1"
});
context.Studios.Add(new Studio()
{
Name = "MGM",
Adress = "Some Address 1"
});
context.Studios.Add(new Studio()
{
Name = "Sony",
Adress = "Some Address 1"
});
context.Studios.Add(new Studio()
{
Name = "Time Warner",
Adress = "Some Address 1"
});
context.Studios.Add(new Studio()
{
Name = "Walt Disney",
Adress = "Some Address 1"
});
// Add people
var random = new Random();
context.People.Add(new Person()
{
FirstName = "Al",
LastName = "Pacino",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Robert",
LastName = "De Niro",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Jack",
LastName = "Nicholson",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Tom",
LastName = "Hanks",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Cary",
LastName = "Grant",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Johnny",
LastName = "Depp",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Morgan",
LastName = "Freeman",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Anthony",
LastName = "Hopkins",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Leonardo",
LastName = "DiCaprio",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Brad",
LastName = "Pitt",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Russell",
LastName = "Crowe",
Age = random.Next(18, 100),
Gender = Gender.Male
});
context.People.Add(new Person()
{
FirstName = "Scarlett",
LastName = "Johansson",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Jessica",
LastName = "Alba",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Natalie",
LastName = "Portman",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Mila",
LastName = "Kunis",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Jessica",
LastName = "Biel",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Megan",
LastName = "Fox",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Monica",
LastName = "Bellucci",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.People.Add(new Person()
{
FirstName = "Jennifer",
LastName = "Lawrence",
Age = random.Next(18, 100),
Gender = Gender.Female
});
context.SaveChanges();
var allPeople = context.People.ToList();
var males = allPeople.Where(p => p.Gender == Gender.Male).ToList();
var females = allPeople.Where(p => p.Gender == Gender.Female).ToList();
var studios = context.Studios.ToList();
for (int i = 0; i < 5; i++)
{
var movie = new Movie()
{
Title = $"Movie {i}",
Year = i + 2000,
Director = allPeople[random.Next(0, allPeople.Count)],
LeadingFemaleRole = females[random.Next(0, females.Count)],
LeadingMaleRole = males[random.Next(0, males.Count)],
Studio = studios[random.Next(0, studios.Count)]
};
context.Movies.Add(movie);
}
context.SaveChanges();
}
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Medallion.Threading.Internal;
namespace Medallion.Threading.Oracle
{
public partial class OracleDistributedReaderWriterLock
{
// AUTO-GENERATED
IDistributedSynchronizationHandle? IDistributedReaderWriterLock.TryAcquireReadLock(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireReadLock(timeout, cancellationToken);
IDistributedSynchronizationHandle IDistributedReaderWriterLock.AcquireReadLock(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireReadLock(timeout, cancellationToken);
ValueTask<IDistributedSynchronizationHandle?> IDistributedReaderWriterLock.TryAcquireReadLockAsync(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle?>.ValueTask);
ValueTask<IDistributedSynchronizationHandle> IDistributedReaderWriterLock.AcquireReadLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle>.ValueTask);
IDistributedLockUpgradeableHandle? IDistributedUpgradeableReaderWriterLock.TryAcquireUpgradeableReadLock(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireUpgradeableReadLock(timeout, cancellationToken);
IDistributedLockUpgradeableHandle IDistributedUpgradeableReaderWriterLock.AcquireUpgradeableReadLock(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireUpgradeableReadLock(timeout, cancellationToken);
ValueTask<IDistributedLockUpgradeableHandle?> IDistributedUpgradeableReaderWriterLock.TryAcquireUpgradeableReadLockAsync(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireUpgradeableReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedLockUpgradeableHandle?>.ValueTask);
ValueTask<IDistributedLockUpgradeableHandle> IDistributedUpgradeableReaderWriterLock.AcquireUpgradeableReadLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireUpgradeableReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedLockUpgradeableHandle>.ValueTask);
IDistributedSynchronizationHandle? IDistributedReaderWriterLock.TryAcquireWriteLock(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireWriteLock(timeout, cancellationToken);
IDistributedSynchronizationHandle IDistributedReaderWriterLock.AcquireWriteLock(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireWriteLock(timeout, cancellationToken);
ValueTask<IDistributedSynchronizationHandle?> IDistributedReaderWriterLock.TryAcquireWriteLockAsync(TimeSpan timeout, CancellationToken cancellationToken) =>
this.TryAcquireWriteLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle?>.ValueTask);
ValueTask<IDistributedSynchronizationHandle> IDistributedReaderWriterLock.AcquireWriteLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) =>
this.AcquireWriteLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle>.ValueTask);
/// <summary>
/// Attempts to acquire a READ lock synchronously. Multiple readers are allowed. Not compatible with a WRITE lock. Usage:
/// <code>
/// using (var handle = myLock.TryAcquireReadLock(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns>
public OracleDistributedReaderWriterLockHandle? TryAcquireReadLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.TryAcquire(this, timeout, cancellationToken, isWrite: false);
/// <summary>
/// Acquires a READ lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Multiple readers are allowed. Not compatible with a WRITE lock. Usage:
/// <code>
/// using (myLock.AcquireReadLock(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns>
public OracleDistributedReaderWriterLockHandle AcquireReadLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.Acquire(this, timeout, cancellationToken, isWrite: false);
/// <summary>
/// Attempts to acquire a READ lock asynchronously. Multiple readers are allowed. Not compatible with a WRITE lock. Usage:
/// <code>
/// await using (var handle = await myLock.TryAcquireReadLockAsync(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns>
public ValueTask<OracleDistributedReaderWriterLockHandle?> TryAcquireReadLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
this.As<IInternalDistributedReaderWriterLock<OracleDistributedReaderWriterLockHandle>>().InternalTryAcquireAsync(timeout, cancellationToken, isWrite: false);
/// <summary>
/// Acquires a READ lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Multiple readers are allowed. Not compatible with a WRITE lock. Usage:
/// <code>
/// await using (await myLock.AcquireReadLockAsync(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns>
public ValueTask<OracleDistributedReaderWriterLockHandle> AcquireReadLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.AcquireAsync(this, timeout, cancellationToken, isWrite: false);
/// <summary>
/// Attempts to acquire an UPGRADE lock synchronously. Not compatible with another UPGRADE lock or a WRITE lock. Usage:
/// <code>
/// using (var handle = myLock.TryAcquireUpgradeableReadLock(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock or null on failure</returns>
public OracleDistributedReaderWriterLockUpgradeableHandle? TryAcquireUpgradeableReadLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.TryAcquireUpgradeableReadLock(this, timeout, cancellationToken);
/// <summary>
/// Acquires an UPGRADE lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another UPGRADE lock or a WRITE lock. Usage:
/// <code>
/// using (myLock.AcquireUpgradeableReadLock(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock</returns>
public OracleDistributedReaderWriterLockUpgradeableHandle AcquireUpgradeableReadLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.AcquireUpgradeableReadLock(this, timeout, cancellationToken);
/// <summary>
/// Attempts to acquire an UPGRADE lock asynchronously. Not compatible with another UPGRADE lock or a WRITE lock. Usage:
/// <code>
/// await using (var handle = await myLock.TryAcquireUpgradeableReadLockAsync(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock or null on failure</returns>
public ValueTask<OracleDistributedReaderWriterLockUpgradeableHandle?> TryAcquireUpgradeableReadLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
this.As<IInternalDistributedUpgradeableReaderWriterLock<OracleDistributedReaderWriterLockHandle, OracleDistributedReaderWriterLockUpgradeableHandle>>().InternalTryAcquireUpgradeableReadLockAsync(timeout, cancellationToken);
/// <summary>
/// Acquires an UPGRADE lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another UPGRADE lock or a WRITE lock. Usage:
/// <code>
/// await using (await myLock.AcquireUpgradeableReadLockAsync(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock</returns>
public ValueTask<OracleDistributedReaderWriterLockUpgradeableHandle> AcquireUpgradeableReadLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.AcquireUpgradeableReadLockAsync(this, timeout, cancellationToken);
/// <summary>
/// Attempts to acquire a WRITE lock synchronously. Not compatible with another WRITE lock or an UPGRADE lock. Usage:
/// <code>
/// using (var handle = myLock.TryAcquireWriteLock(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns>
public OracleDistributedReaderWriterLockHandle? TryAcquireWriteLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.TryAcquire(this, timeout, cancellationToken, isWrite: true);
/// <summary>
/// Acquires a WRITE lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another WRITE lock or an UPGRADE lock. Usage:
/// <code>
/// using (myLock.AcquireWriteLock(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns>
public OracleDistributedReaderWriterLockHandle AcquireWriteLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.Acquire(this, timeout, cancellationToken, isWrite: true);
/// <summary>
/// Attempts to acquire a WRITE lock asynchronously. Not compatible with another WRITE lock or an UPGRADE lock. Usage:
/// <code>
/// await using (var handle = await myLock.TryAcquireWriteLockAsync(...))
/// {
/// if (handle != null) { /* we have the lock! */ }
/// }
/// // dispose releases the lock if we took it
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns>
public ValueTask<OracleDistributedReaderWriterLockHandle?> TryAcquireWriteLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) =>
this.As<IInternalDistributedReaderWriterLock<OracleDistributedReaderWriterLockHandle>>().InternalTryAcquireAsync(timeout, cancellationToken, isWrite: true);
/// <summary>
/// Acquires a WRITE lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another WRITE lock or an UPGRADE lock. Usage:
/// <code>
/// await using (await myLock.AcquireWriteLockAsync(...))
/// {
/// /* we have the lock! */
/// }
/// // dispose releases the lock
/// </code>
/// </summary>
/// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param>
/// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param>
/// <returns>An <see cref="OracleDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns>
public ValueTask<OracleDistributedReaderWriterLockHandle> AcquireWriteLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) =>
DistributedLockHelpers.AcquireAsync(this, timeout, cancellationToken, isWrite: true);
}
}
| |
//
// 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.
//
#if !SILVERLIGHT
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.IO;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using Xunit;
using Xunit.Extensions;
public class DatabaseTargetTests : NLogTestBase
{
#if !MONO
static DatabaseTargetTests()
{
var data = (DataSet)ConfigurationManager.GetSection("system.data");
var providerFactories = data.Tables["DBProviderFactories"];
providerFactories.Rows.Add("MockDb Provider", "MockDb Provider", "MockDb", typeof(MockDbFactory).AssemblyQualifiedName);
providerFactories.AcceptChanges();
}
#endif
[Fact]
public void SimpleDatabaseTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
Close()
Dispose()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Dispose()
Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void SimpleBatchedDatabaseTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void KeepConnectionOpenTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void KeepConnectionOpenBatchedTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "FooBar",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('FooBar').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void KeepConnectionOpenTest2()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "Database=${logger}",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
List<Exception> exceptions = new List<Exception>();
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add));
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add));
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
Close()
Dispose()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
Close()
Dispose()
Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void KeepConnectionOpenBatchedTest2()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES('${message}')",
ConnectionString = "Database=${logger}",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('Database=MyLogger').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2')
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4')
Close()
Dispose()
Open('Database=MyLogger2').
ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3')
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void ParameterTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
Parameters =
{
new DatabaseParameterInfo("msg", "${message}"),
new DatabaseParameterInfo("lvl", "${level}"),
new DatabaseParameterInfo("lg", "${logger}")
}
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
List<Exception> exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
";
AssertLog(expectedLog);
MockDbConnection.ClearLog();
dt.Close();
expectedLog = @"Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void ParameterFacetTest()
{
MockDbConnection.ClearLog();
DatabaseTarget dt = new DatabaseTarget()
{
CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)",
DBProvider = typeof(MockDbConnection).AssemblyQualifiedName,
KeepConnection = true,
Parameters =
{
new DatabaseParameterInfo("msg", "${message}")
{
Precision = 3,
Scale = 7,
Size = 9,
},
new DatabaseParameterInfo("lvl", "${level}")
{
Scale = 7
},
new DatabaseParameterInfo("lg", "${logger}")
{
Precision = 0
},
}
};
dt.Initialize(null);
Assert.Same(typeof(MockDbConnection), dt.ConnectionType);
// when we pass multiple log events in an array, the target will bucket-sort them by
// connection string and group all commands for the same connection string together
// to minimize number of db open/close operations
// in this case msg1, msg2 and msg4 will be written together to MyLogger database
// and msg3 will be written to MyLogger2 database
var exceptions = new List<Exception>();
var events = new[]
{
new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add),
};
dt.WriteAsyncLogEvents(events);
dt.Close();
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;').
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg1
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Info
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
CreateParameter(0)
Parameter #0 Direction=Input
Parameter #0 Name=msg
Parameter #0 Size=9
Parameter #0 Precision=3
Parameter #0 Scale=7
Parameter #0 Value=msg3
Add Parameter Parameter #0
CreateParameter(1)
Parameter #1 Direction=Input
Parameter #1 Name=lvl
Parameter #1 Scale=7
Parameter #1 Value=Debug
Add Parameter Parameter #1
CreateParameter(2)
Parameter #2 Direction=Input
Parameter #2 Name=lg
Parameter #2 Value=MyLogger2
Add Parameter Parameter #2
ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg)
Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void ConnectionStringBuilderTest1()
{
DatabaseTarget dt;
dt = new DatabaseTarget();
Assert.Equal("Server=.;Trusted_Connection=SSPI;", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "${logger}";
Assert.Equal("Server=Logger1;Trusted_Connection=SSPI;", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "HOST1";
dt.DBDatabase = "${logger}";
Assert.Equal("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.DBHost = "HOST1";
dt.DBDatabase = "${logger}";
dt.DBUserName = "user1";
dt.DBPassword = "password1";
Assert.Equal("Server=HOST1;User id=user1;Password=password1;Database=Logger1", this.GetConnectionString(dt));
dt = new DatabaseTarget();
dt.ConnectionString = "customConnectionString42";
dt.DBHost = "HOST1";
dt.DBDatabase = "${logger}";
dt.DBUserName = "user1";
dt.DBPassword = "password1";
Assert.Equal("customConnectionString42", this.GetConnectionString(dt));
}
[Fact]
public void DatabaseExceptionTest1()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotconnect";
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Equal("Cannot open fake database.", exceptions[0].Message);
Assert.Equal("Open('cannotconnect').\r\n", MockDbConnection.Log);
}
[Fact]
public void DatabaseExceptionTest2()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotexecute";
db.KeepConnection = true;
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.Equal(3, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.NotNull(exceptions[1]);
Assert.NotNull(exceptions[2]);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message);
string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void DatabaseExceptionTest3()
{
MockDbConnection.ClearLog();
var exceptions = new List<Exception>();
var db = new DatabaseTarget();
db.CommandText = "not important";
db.ConnectionString = "cannotexecute";
db.KeepConnection = true;
db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
db.Initialize(null);
db.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
db.Close();
Assert.Equal(3, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.NotNull(exceptions[1]);
Assert.NotNull(exceptions[2]);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message);
Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message);
string expectedLog = @"Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
Open('cannotexecute').
ExecuteNonQuery: not important
Close()
Dispose()
";
AssertLog(expectedLog);
}
[Fact]
public void ConnectionStringNameInitTest()
{
var dt = new DatabaseTarget
{
ConnectionStringName = "MyConnectionString",
CommandText = "notimportant",
};
Assert.Same(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings);
dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
{
new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"),
};
dt.Initialize(null);
Assert.Same(MockDbFactory.Instance, dt.ProviderFactory);
Assert.Equal("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent()));
}
[Fact]
public void ConnectionStringNameNegativeTest_if_ThrowConfigExceptions()
{
LogManager.ThrowConfigExceptions = true;
var dt = new DatabaseTarget
{
ConnectionStringName = "MyConnectionString",
CommandText = "notimportant",
ConnectionStringsSettings = new ConnectionStringSettingsCollection(),
};
try
{
dt.Initialize(null);
Assert.True(false, "Exception expected.");
}
catch (NLogConfigurationException configurationException)
{
Assert.Equal("Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.", configurationException.Message);
}
}
[Fact]
public void ProviderFactoryInitTest()
{
var dt = new DatabaseTarget();
dt.DBProvider = "MockDb";
dt.CommandText = "Notimportant";
dt.Initialize(null);
Assert.Same(MockDbFactory.Instance, dt.ProviderFactory);
dt.OpenConnection("myConnectionString");
Assert.Equal(1, MockDbConnection2.OpenCount);
Assert.Equal("myConnectionString", MockDbConnection2.LastOpenConnectionString);
}
[Fact]
public void SqlServerShorthandNotationTest()
{
foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" })
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = provName,
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.Equal(typeof(System.Data.SqlClient.SqlConnection), dt.ConnectionType);
}
}
[Fact]
public void OleDbShorthandNotationTest()
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = "oledb",
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.Equal(typeof(System.Data.OleDb.OleDbConnection), dt.ConnectionType);
}
[Fact]
public void OdbcShorthandNotationTest()
{
var dt = new DatabaseTarget()
{
Name = "myTarget",
DBProvider = "odbc",
ConnectionString = "notimportant",
CommandText = "notimportant",
};
dt.Initialize(null);
Assert.Equal(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType);
}
[Fact]
public void GetProviderNameFromAppConfig()
{
LogManager.ThrowExceptions = true;
var databaseTarget = new DatabaseTarget()
{
Name = "myTarget",
ConnectionStringName = "test_connectionstring_with_providerName",
CommandText = "notimportant",
};
databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
{
new ConnectionStringSettings("test_connectionstring_without_providerName","some connectionstring"),
new ConnectionStringSettings("test_connectionstring_with_providerName","some connectionstring","System.Data.SqlClient"),
};
databaseTarget.Initialize(null);
Assert.NotNull(databaseTarget.ProviderFactory);
Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType());
}
[Fact]
public void DontRequireProviderNameInAppConfig()
{
LogManager.ThrowExceptions = true;
var databaseTarget = new DatabaseTarget()
{
Name = "myTarget",
ConnectionStringName = "test_connectionstring_without_providerName",
CommandText = "notimportant",
DBProvider = "System.Data.SqlClient"
};
databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection()
{
new ConnectionStringSettings("test_connectionstring_without_providerName","some connectionstring"),
new ConnectionStringSettings("test_connectionstring_with_providerName","some connectionstring","System.Data.SqlClient"),
};
databaseTarget.Initialize(null);
Assert.NotNull(databaseTarget.ProviderFactory);
Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType());
}
[Theory]
[InlineData("usetransactions='false'", true)]
[InlineData("usetransactions='true'", true)]
[InlineData("", false)]
public void WarningForObsoleteUseTransactions(string property, bool printWarning)
{
LoggingConfiguration c = CreateConfigurationFromString(string.Format(@"
<nlog ThrowExceptions='true'>
<targets>
<target type='database' {0} name='t1' commandtext='fake sql' connectionstring='somewhere' />
</targets>
<rules>
<logger name='*' writeTo='t1'>
</logger>
</rules>
</nlog>", property));
StringWriter writer1 = new StringWriter()
{
NewLine = "\n"
};
InternalLogger.LogWriter = writer1;
var t = c.FindTargetByName<DatabaseTarget>("t1");
t.Initialize(null);
var internalLog = writer1.ToString();
if (printWarning)
{
Assert.Contains("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase);
Assert.Contains("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase);
}
else
{
Assert.DoesNotContain("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase);
Assert.DoesNotContain("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase);
}
}
private static void AssertLog(string expectedLog)
{
Assert.Equal(expectedLog.Replace("\r", ""), MockDbConnection.Log.Replace("\r", ""));
}
private string GetConnectionString(DatabaseTarget dt)
{
MockDbConnection.ClearLog();
dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName;
dt.CommandText = "NotImportant";
var exceptions = new List<Exception>();
dt.Initialize(null);
dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add));
dt.Close();
return MockDbConnection.LastConnectionString;
}
public class MockDbConnection : IDbConnection
{
public static string Log { get; private set; }
public static string LastConnectionString { get; private set; }
public MockDbConnection()
{
}
public MockDbConnection(string connectionString)
{
this.ConnectionString = connectionString;
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
throw new NotImplementedException();
}
public IDbTransaction BeginTransaction()
{
throw new NotImplementedException();
}
public void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public void Close()
{
AddToLog("Close()");
}
public string ConnectionString { get; set; }
public int ConnectionTimeout
{
get { throw new NotImplementedException(); }
}
public IDbCommand CreateCommand()
{
return new MockDbCommand() { Connection = this };
}
public string Database
{
get { throw new NotImplementedException(); }
}
public void Open()
{
LastConnectionString = this.ConnectionString;
AddToLog("Open('{0}').", this.ConnectionString);
if (this.ConnectionString == "cannotconnect")
{
throw new InvalidOperationException("Cannot open fake database.");
}
}
public ConnectionState State
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
AddToLog("Dispose()");
}
public static void ClearLog()
{
Log = string.Empty;
}
public void AddToLog(string message, params object[] args)
{
if (args.Length > 0)
{
message = string.Format(CultureInfo.InvariantCulture, message, args);
}
Log += message + "\r\n";
}
}
private class MockDbCommand : IDbCommand
{
private int paramCount;
private IDataParameterCollection parameters;
public MockDbCommand()
{
this.parameters = new MockParameterCollection(this);
}
public void Cancel()
{
throw new NotImplementedException();
}
public string CommandText { get; set; }
public int CommandTimeout { get; set; }
public CommandType CommandType { get; set; }
public IDbConnection Connection { get; set; }
public IDbDataParameter CreateParameter()
{
((MockDbConnection)this.Connection).AddToLog("CreateParameter({0})", this.paramCount);
return new MockDbParameter(this, paramCount++);
}
public int ExecuteNonQuery()
{
((MockDbConnection)this.Connection).AddToLog("ExecuteNonQuery: {0}", this.CommandText);
if (this.Connection.ConnectionString == "cannotexecute")
{
throw new InvalidOperationException("Failure during ExecuteNonQuery");
}
return 0;
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
throw new NotImplementedException();
}
public IDataReader ExecuteReader()
{
throw new NotImplementedException();
}
public object ExecuteScalar()
{
throw new NotImplementedException();
}
public IDataParameterCollection Parameters
{
get { return parameters; }
}
public void Prepare()
{
throw new NotImplementedException();
}
public IDbTransaction Transaction { get; set; }
public UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void Dispose()
{
throw new NotImplementedException();
}
}
private class MockDbParameter : IDbDataParameter
{
private readonly MockDbCommand mockDbCommand;
private readonly int paramId;
private string parameterName;
private object parameterValue;
private DbType parameterType;
public MockDbParameter(MockDbCommand mockDbCommand, int paramId)
{
this.mockDbCommand = mockDbCommand;
this.paramId = paramId;
}
public DbType DbType
{
get { return this.parameterType; }
set { this.parameterType = value; }
}
public ParameterDirection Direction
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Direction={1}", paramId, value); }
}
public bool IsNullable
{
get { throw new NotImplementedException(); }
}
public string ParameterName
{
get { return this.parameterName; }
set
{
((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Name={1}", paramId, value);
this.parameterName = value;
}
}
public string SourceColumn
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public DataRowVersion SourceVersion
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public object Value
{
get { return this.parameterValue; }
set
{
((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Value={1}", paramId, value);
this.parameterValue = value;
}
}
public byte Precision
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Precision={1}", paramId, value); }
}
public byte Scale
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Scale={1}", paramId, value); }
}
public int Size
{
get { throw new NotImplementedException(); }
set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Size={1}", paramId, value); }
}
public override string ToString()
{
return "Parameter #" + this.paramId;
}
}
private class MockParameterCollection : IDataParameterCollection
{
private readonly MockDbCommand command;
public MockParameterCollection(MockDbCommand command)
{
this.command = command;
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public int Count
{
get { throw new NotImplementedException(); }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public int Add(object value)
{
((MockDbConnection)command.Connection).AddToLog("Add Parameter {0}", value);
return 0;
}
public bool Contains(object value)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public int IndexOf(object value)
{
throw new NotImplementedException();
}
public void Insert(int index, object value)
{
throw new NotImplementedException();
}
public void Remove(object value)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
object IList.this[int index]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool IsFixedSize
{
get { throw new NotImplementedException(); }
}
public bool Contains(string parameterName)
{
throw new NotImplementedException();
}
public int IndexOf(string parameterName)
{
throw new NotImplementedException();
}
public void RemoveAt(string parameterName)
{
throw new NotImplementedException();
}
object IDataParameterCollection.this[string parameterName]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
public class MockDbFactory : DbProviderFactory
{
public static readonly MockDbFactory Instance = new MockDbFactory();
public override DbConnection CreateConnection()
{
return new MockDbConnection2();
}
}
public class MockDbConnection2 : DbConnection
{
public static int OpenCount { get; private set; }
public static string LastOpenConnectionString { get; private set; }
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}
public override void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public override void Close()
{
throw new NotImplementedException();
}
public override string ConnectionString { get; set; }
protected override DbCommand CreateDbCommand()
{
throw new NotImplementedException();
}
public override string DataSource
{
get { throw new NotImplementedException(); }
}
public override string Database
{
get { throw new NotImplementedException(); }
}
public override void Open()
{
LastOpenConnectionString = this.ConnectionString;
OpenCount++;
}
public override string ServerVersion
{
get { throw new NotImplementedException(); }
}
public override ConnectionState State
{
get { throw new NotImplementedException(); }
}
}
}
}
#endif
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2010 Leopold Bushkin. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
public static partial class MoreEnumerable
{
/// <summary>
/// The private implementation class that produces permutations of a sequence.
/// </summary>
class PermutationEnumerator<T> : IEnumerator<IList<T>>
{
// NOTE: The algorithm used to generate permutations uses the fact that any set
// can be put into 1-to-1 correspondence with the set of ordinals number (0..n).
// The implementation here is based on the algorithm described by Kenneth H. Rosen,
// in Discrete Mathematics and Its Applications, 2nd edition, pp. 282-284.
//
// There are two significant changes from the original implementation.
// First, the algorithm uses lazy evaluation and streaming to fit well into the
// nature of most LINQ evaluations.
//
// Second, the algorithm has been modified to use dynamically generated nested loop
// state machines, rather than an integral computation of the factorial function
// to determine when to terminate. The original algorithm required a priori knowledge
// of the number of iterations necessary to produce all permutations. This is a
// necessary step to avoid overflowing the range of the permutation arrays used.
// The number of permutation iterations is defined as the factorial of the original
// set size minus 1.
//
// However, there's a fly in the ointment. The factorial function grows VERY rapidly.
// 13! overflows the range of a Int32; while 28! overflows the range of decimal.
// To overcome these limitations, the algorithm relies on the fact that the factorial
// of N is equivalent to the evaluation of N-1 nested loops. Unfortunatley, you can't
// just code up a variable number of nested loops ... this is where .NET generators
// with their elegant 'yield return' syntax come to the rescue.
//
// The methods of the Loop extension class (For and NestedLoops) provide the implementation
// of dynamic nested loops using generators and sequence composition. In a nutshell,
// the two Repeat() functions are the constructor of loops and nested loops, respectively.
// The NestedLoops() function produces a composition of loops where the loop counter
// for each nesting level is defined in a separate sequence passed in the call.
//
// For example: NestedLoops( () => DoSomething(), new[] { 6, 8 } )
//
// is equivalent to: for( int i = 0; i < 6; i++ )
// for( int j = 0; j < 8; j++ )
// DoSomething();
readonly IList<T> _valueSet;
readonly int[] _permutation;
readonly IEnumerable<Action> _generator;
IEnumerator<Action> _generatorIterator;
bool _hasMoreResults;
IList<T>? _current;
public PermutationEnumerator(IEnumerable<T> valueSet)
{
_valueSet = valueSet.ToArray();
_permutation = new int[_valueSet.Count];
// The nested loop construction below takes into account the fact that:
// 1) for empty sets and sets of cardinality 1, there exists only a single permutation.
// 2) for sets larger than 1 element, the number of nested loops needed is: set.Count-1
_generator = NestedLoops(NextPermutation, Enumerable.Range(2, Math.Max(0, _valueSet.Count - 1)));
Reset();
}
[MemberNotNull(nameof(_generatorIterator))]
public void Reset()
{
_current = null;
_generatorIterator?.Dispose();
// restore lexographic ordering of the permutation indexes
for (var i = 0; i < _permutation.Length; i++)
_permutation[i] = i;
// start a newiteration over the nested loop generator
_generatorIterator = _generator.GetEnumerator();
// we must advance the nestedloop iterator to the initial element,
// this ensures that we only ever produce N!-1 calls to NextPermutation()
_generatorIterator.MoveNext();
_hasMoreResults = true; // there's always at least one permutation: the original set itself
}
public IList<T> Current => _current!;
object IEnumerator.Current => Current;
public bool MoveNext()
{
_current = PermuteValueSet();
// check if more permutation left to enumerate
var prevResult = _hasMoreResults;
_hasMoreResults = _generatorIterator.MoveNext();
if (_hasMoreResults)
_generatorIterator.Current(); // produce the next permutation ordering
// we return prevResult rather than m_HasMoreResults because there is always
// at least one permtuation: the original set. Also, this provides a simple way
// to deal with the disparity between sets that have only one loop level (size 0-2)
// and those that have two or more (size > 2).
return prevResult;
}
void IDisposable.Dispose() { }
/// <summary>
/// Transposes elements in the cached permutation array to produce the next permutation
/// </summary>
void NextPermutation()
{
// find the largest index j with m_Permutation[j] < m_Permutation[j+1]
var j = _permutation.Length - 2;
while (_permutation[j] > _permutation[j + 1])
j--;
// find index k such that m_Permutation[k] is the smallest integer
// greater than m_Permutation[j] to the right of m_Permutation[j]
var k = _permutation.Length - 1;
while (_permutation[j] > _permutation[k])
k--;
// interchange m_Permutation[j] and m_Permutation[k]
var oldValue = _permutation[k];
_permutation[k] = _permutation[j];
_permutation[j] = oldValue;
// move the tail of the permutation after the jth position in increasing order
var x = _permutation.Length - 1;
var y = j + 1;
while (x > y)
{
oldValue = _permutation[y];
_permutation[y] = _permutation[x];
_permutation[x] = oldValue;
x--;
y++;
}
}
/// <summary>
/// Creates a new list containing the values from the original
/// set in their new permuted order.
/// </summary>
/// <remarks>
/// The reason we return a new permuted value set, rather than reuse
/// an existing collection, is that we have no control over what the
/// consumer will do with the results produced. They could very easily
/// generate and store a set of permutations and only then begin to
/// process them. If we reused the same collection, the caller would
/// be surprised to discover that all of the permutations looked the
/// same.
/// </remarks>
/// <returns>List of permuted source sequence values</returns>
IList<T> PermuteValueSet()
{
var permutedSet = new T[_permutation.Length];
for (var i = 0; i < _permutation.Length; i++)
permutedSet[i] = _valueSet[_permutation[i]];
return permutedSet;
}
}
/// <summary>
/// Generates a sequence of lists that represent the permutations of the original sequence.
/// </summary>
/// <remarks>
/// A permutation is a unique re-ordering of the elements of the sequence.<br/>
/// This operator returns permutations in a deferred, streaming fashion; however, each
/// permutation is materialized into a new list. There are N! permutations of a sequence,
/// where N => sequence.Count().<br/>
/// Be aware that the original sequence is considered one of the permutations and will be
/// returned as one of the results.
/// </remarks>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <param name="sequence">The original sequence to permute</param>
/// <returns>A sequence of lists representing permutations of the original sequence</returns>
public static IEnumerable<IList<T>> Permutations<T>(this IEnumerable<T> sequence)
{
if (sequence == null) throw new ArgumentNullException(nameof(sequence));
return _(); IEnumerable<IList<T>> _()
{
using var iter = new PermutationEnumerator<T>(sequence);
while (iter.MoveNext())
yield return iter.Current;
}
}
}
}
| |
//
// File : ApiDefinition.cs
//
// Author: Simon CORSIN <simoncorsin@gmail.com>
//
// Copyright (c) 2012 Ever SAS
//
// Using or modifying this source code is strictly reserved to Ever SAS.
using System;
using System.Drawing;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AVFoundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreMedia;
using MonoTouch.CoreImage;
using MonoTouch.GLKit;
namespace SCorsin {
[BaseType(typeof(NSObject))]
interface SCPhotoConfiguration {
[Export("enabled")]
bool Enabled { get; set; }
[Export("options")]
NSDictionary Options { get; set; }
}
[BaseType(typeof(NSObject))]
interface SCMediaTypeConfiguration {
[Export("enabled")]
bool Enabled { get; set; }
[Export("shouldIgnore")]
bool ShouldIgnore { get; set; }
[Export("options")]
NSDictionary Options { get; set; }
[Export("bitrate")]
ulong Bitrate { get; set; }
[Export("preset")]
NSString Preset { get; set; }
}
[BaseType(typeof(SCMediaTypeConfiguration))]
interface SCVideoConfiguration {
[Export("size")]
SizeF Size { get; set; }
[Export("affineTransform")]
CGAffineTransform AffineTransform { get; set; }
[Export("codec")]
NSString Codec { get; set; }
[Export("scalingMode")]
NSString ScalingMode { get; set; }
[Export("maxFrameRate")]
int MaxFrameRate { get; set; }
[Export("timeScale")]
float TimeScale { get; set; }
[Export("sizeAsSquare")]
bool SizeAsSquare { get; set; }
[Export("shouldKeepOnlyKeyFrames")]
bool ShouldKeepOnlyKeyFrames { get; set; }
[Export("keepInputAffineTransform")]
bool KeepInputAffineTransform { get; set; }
[Export("filterGroup")]
SCFilterGroup FilterGroup { get; set; }
[Export("composition")]
AVVideoComposition Composition { get; set; }
[Export("watermarkImage")]
UIImage WatermarkImage { get; set; }
[Export("watermarkFrame")]
RectangleF WatermarkFrame { get; set; }
[Export("watermarkAnchorLocation")]
int WatermarkAnchorLocation { get; set; }
}
[BaseType(typeof(SCMediaTypeConfiguration))]
interface SCAudioConfiguration {
[Export("sampleRate")]
int SampleRate { get; set; }
[Export("channelsCount")]
int ChannelsCount { get; set; }
[Export("format")]
int Format { get; set; }
[Export("audioMix")]
AVAudioMix AudioMix { get; set; }
}
public delegate void EndRecordSegmentDelegate(int segmentIndex, NSError errore);
public delegate void GenericErrorDelegate(NSUrl outputUrl, NSError error);
[BaseType(typeof(NSObject))]
interface SCRecordSession {
[Export("initWithDictionaryRepresentation:")]
IntPtr Constructor(NSDictionary dictionaryRepresentation);
[Export("identifier")]
string Identifier { get; }
[Export("date")]
NSDate Date { get; }
[Export("outputUrl")]
NSUrl OutputUrl { get; }
[Export("fileType"), NullAllowed]
NSString FileType { get; set; }
[Export("fileExtension"), NullAllowed]
NSString FileExtension { get; set; }
[Export("recordSegments")]
NSUrl[] RecordSegments { get; }
[Export("currentRecordDuration")]
CMTime CurrentRecordDuration { get; }
[Export("segmentsDuration")]
CMTime SegmentsDuration { get; }
[Export("currentSegmentDuration")]
CMTime CurrentSegmentDuration { get; }
[Export("recordSegmentBegan")]
bool RecordSegmentBegan { get; }
[Export("beginRecordSegment:")]
void BeginRecordSegment(out NSError error);
[Export("endRecordSegment:")]
void EndRecordSegment([NullAllowed] EndRecordSegmentDelegate completionHandler);
[Export("removeSegmentAtIndex:deleteFile:")]
void RemoveSegmentAtIndex(int segmentIndex, bool deleteFile);
[Export("addSegment:")]
void AddSegment(NSUrl fileUrl);
[Export("insertSegment:atIndex:")]
void InsertSegment(NSUrl fileUrl, int segmentIndex);
[Export("removeAllSegments")]
void RemoveAllSegments();
[Export("mergeRecordSegmentsUsingPreset:completionHandler:")]
void MergeRecordSegments(NSString exportSessionPreset, [NullAllowed] GenericErrorDelegate completionHandler);
[Export("cancelSession:")]
void CancelSession([NullAllowed] Action completionHandler);
[Export("removeLastSegment")]
void RemoveLastSegment();
[Export("deinitialize")]
void Deinitialize();
[Export("assetRepresentingRecordSegments")]
AVAsset AssetRepresentingRecordSegments { get; }
[Export("dictionaryRepresentation")]
NSDictionary DictionaryRepresentation { get; }
[Export("recorder")]
SCRecorder Recorder { get; }
}
[Model, BaseType(typeof(NSObject)), Protocol]
interface SCRecorderDelegate {
[Abstract, Export("recorder:didReconfigureVideoInput:"), EventArgs("RecorderDidReconfigureVideoInputDelegate")]
void DidReconfigureVideoInput(SCRecorder recorder, NSError videoInputError);
[Abstract, Export("recorder:didReconfigureAudioInput:"), EventArgs("RecorderDidReconfigureAudioInputDelegate")]
void DidReconfigureAudioInput(SCRecorder recorder, NSError audioInputError);
[Export("recorder:didChangeFlashMode:error:"), Abstract, EventArgs("RecorderDidChangeFlashModeDelegate")]
void DidChangeFlashMode(SCRecorder recorder, int flashMode, NSError error);
[Export("recorder:didChangeSessionPreset:error:"), Abstract, EventArgs("RecorderDidChangeSessionPresetDelegate")]
void DidChangeSessionPreset(SCRecorder recorder, string sessionPreset, NSError error);
[Export("recorderWillStartFocus:"), Abstract, EventArgs("RecorderWillStartFocusDelegate")]
void WillStartFocus(SCRecorder recorder);
[Export("recorderDidStartFocus:"), Abstract, EventArgs("RecorderDidStartFocusDelegate")]
void DidStartFocus(SCRecorder recorder);
[Export("recorderDidEndFocus:"), Abstract, EventArgs("RecorderDidEndFocusDelegate")]
void DidEndFocus(SCRecorder recorder);
[Export("recorder:didInitializeAudioInRecordSession:error:"), Abstract, EventArgs("RecorderDidInitializeAudioInRecordSessionDelegate")]
void DidInitializeAudioInRecordSession(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didInitializeVideoInRecordSession:error:"), Abstract, EventArgs("RecorderDidInitializeVideoInRecordSessionDelegate")]
void DidInitializeVideoInRecordSession(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didBeginRecordSegment:error:"), Abstract, EventArgs("RecorderDidBeginRecordSegmentDelegate")]
void DidBeginRecordSegment(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didEndRecordSegment:segmentIndex:error:"), Abstract, EventArgs("RecorderDidEndRecordSegmentDelegate")]
void DidEndRecordSegment(SCRecorder recorder, SCRecordSession recordSession, int segmentIndex, NSError error);
[Export("recorder:didAppendVideoSampleBuffer:"), Abstract, EventArgs("RecorderDidAppendVideoSampleBufferDelegate")]
void DidAppendVideoSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didAppendAudioSampleBuffer:"), Abstract, EventArgs("RecorderDidAppendAudioSampleBufferDelegate")]
void DidAppendAudioSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didSkipAudioSampleBuffer:"), Abstract, EventArgs("RecorderDidSkip")]
void DidSkipAudioSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didSkipVideoSampleBuffer:"), Abstract, EventArgs("RecorderDidSkip")]
void DidSkipVideoSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didCompleteRecordSession:"), Abstract, EventArgs("RecorderDidCompleteRecordSessionDelegate")]
void DidCompleteRecordSession(SCRecorder recorder, SCRecordSession recordSession);
}
public delegate void OpenSessionDelegate(NSError sessionError, NSError audioError, NSError videoError, NSError photoError);
public delegate void CapturePhotoDelegate(NSError error, UIImage image);
[BaseType(typeof(NSObject), Delegates = new string [] { "Delegate" }, Events = new Type [] { typeof(SCRecorderDelegate) })]
interface SCRecorder {
[Export("videoConfiguration")]
SCVideoConfiguration VideoConfiguration { get; }
[Export("audioConfiguration")]
SCAudioConfiguration AudioConfiguration { get; }
[Export("photoConfiguration")]
SCPhotoConfiguration PhotoConfiguration { get; }
[Export("delegate")]
NSObject WeakDelegate { get; set; }
[Wrap("WeakDelegate")]
SCRecorderDelegate Delegate { get; set; }
[Export("videoEnabledAndReady")]
bool VideoEnabledAndReady { get; }
[Export("audioEnabledAndReady")]
bool AudioEnabledAndReady { get; }
[Export("fastRecordMethodEnabled")]
bool FastRecordMethodEnabled { get; set; }
[Export("isRecording")]
bool IsRecording { get; }
[Export("deviceHasFlash")]
bool DeviceHasFlash { get; }
[Export("flashMode")]
int FlashMode { get; set; }
[Export("device")]
AVCaptureDevicePosition Device { get; set; }
[Export("focusMode")]
AVCaptureFocusMode FocusMode { get; }
[Export("photoOutputSettings"), NullAllowed]
NSDictionary PhotoOutputSettings { get; set; }
[Export("sessionPreset")]
NSString SessionPreset { get; set; }
[Export("captureSession")]
AVCaptureSession CaptureSession { get; }
[Export("isCaptureSessionOpened")]
bool IsCaptureSessionOpened { get; }
[Export("previewLayer")]
AVCaptureVideoPreviewLayer PreviewLayer { get; }
[Export("previewView"), NullAllowed]
UIView PreviewView { get; set; }
[Export("recordSession"), NullAllowed]
SCRecordSession RecordSession { get; set; }
[Export("videoOrientation")]
AVCaptureVideoOrientation VideoOrientation { get; set; }
[Export("autoSetVideoOrientation")]
bool AutoSetVideoOrientation { get; set; }
[Export("initializeRecordSessionLazily")]
bool InitializeRecordSessionLazily { get; set; }
[Export("frameRate")]
int FrameRate { get; set; }
[Export("focusSupported")]
bool FocusSupported { get; }
[Export("openSession:")]
void OpenSession([NullAllowed] OpenSessionDelegate completionHandler);
[Export("previewViewFrameChanged")]
void PreviewViewFrameChanged();
[Export("closeSession")]
void CloseSession();
[Export("startRunningSession")]
void StartRunningSession();
[Export("endRunningSession")]
void EndRunningSession();
[Export("beginSessionConfiguration")]
void BeginSessionConfiguration();
[Export("endSessionConfiguration")]
void EndSessionConfiguration();
[Export("switchCaptureDevices")]
void SwitchCaptureDevices();
[Export("convertToPointOfInterestFromViewCoordinates:")]
PointF ConvertToPointOfInterestFromViewCoordinates(PointF viewCoordinates);
[Export("autoFocusAtPoint:")]
void AutoFocusAtPoint(PointF point);
[Export("continuousFocusAtPoint:")]
void ContinuousFocusAtPoint(PointF point);
[Export("setActiveFormatWithFrameRate:width:andHeight:error:")]
bool SetActiveFormatWithFrameRate(int frameRate, int width, int height, out NSError error);
[Export("focusCenter")]
void FocusCenter();
[Export("record")]
void Record();
[Export("pause")]
void Pause();
[Export("pause:")]
void Pause(Action completionHandler);
[Export("capturePhoto:")]
void CapturePhoto([NullAllowed] CapturePhotoDelegate completionHandler);
[Export("snapshotOfLastVideoBuffer")]
UIImage SnapshotOfLastVideoBuffer();
[Export("snapshotOfLastAppendedVideoBuffer")]
UIImage SnapshotOfLastAppendedVideoBuffer();
[Export("CIImageRenderer"), NullAllowed]
NSObject CIImageRenderer { get; set; }
[Export("ratioRecorded")]
float RatioRecorder { get; }
[Export("maxRecordDuration")]
CMTime MaxRecordDuration { get; set; }
}
delegate void CompletionHandler(NSError error);
[BaseType(typeof(NSObject))]
interface SCAudioTools {
[Static]
[Export("overrideCategoryMixWithOthers")]
void OverrideCategoryMixWithOthers();
[Static]
[Export("mixAudio:startTime:withVideo:affineTransform:toUrl:outputFileType:withMaxDuration:withCompletionBlock:")]
void MixAudioWithVideo(AVAsset audioAsset, CMTime audioStartTime, NSUrl inputUrl, CGAffineTransform affineTransform, NSUrl outputUrl, NSString outputFileType, CMTime maxDuration, CompletionHandler completionHandler);
}
[BaseType(typeof(NSObject))]
interface SCFilter {
[Export("initWithCIFilter:")]
IntPtr Constructor(CIFilter filter);
[Export("coreImageFilter")]
CIFilter CoreImageFilter { get; }
}
[BaseType(typeof(NSObject))]
interface SCFilterGroup {
[Export("initWithFilter:")]
IntPtr Constructor(SCFilter filter);
[Export("addFilter:")]
void AddFilter(SCFilter filter);
[Export("removeFilter:")]
void RemoveFilter(SCFilter filter);
[Export("imageByProcessingImage:")]
CIImage ImageByProcessingImage(CIImage image);
[Export("filters")]
SCFilter[] Filters { get; }
[Export("name")]
string Name { get; set; }
[Export("filterGroupWithData:"), Static]
SCFilterGroup FromData(NSData data);
[Export("filterGroupWithData:error:"), Static]
SCFilterGroup FromData(NSData data, out NSError error);
[Export("filterGroupWithContentsOfUrl:"), Static]
SCFilterGroup FromUrl(NSUrl url);
}
[BaseType(typeof(NSObject))]
[Model, Protocol]
interface SCPlayerDelegate {
[Abstract]
[Export("player:didPlay:loopsCount:"), EventArgs("PlayerDidPlay")]
void DidPlay(SCPlayer player, double secondsElapsed, int loopCount);
[Abstract]
[Export("player:didChangeItem:"), EventArgs("PlayerChangedItem")]
void DidChangeItem(SCPlayer player, [NullAllowed] AVPlayerItem item);
}
[BaseType(typeof(AVPlayer), Delegates = new string [] { "Delegate" }, Events = new Type [] { typeof(SCPlayerDelegate) })]
interface SCPlayer {
[Export("delegate")]
NSObject WeakDelegate { get; set; }
[Wrap("WeakDelegate")]
SCPlayerDelegate Delegate { get; set; }
[Export("setItemByStringPath:")]
void SetItem([NullAllowed] string stringPath);
[Export("setItemByUrl:")]
void SetItem([NullAllowed] NSUrl url);
[Export("setItemByAsset:")]
void SetItem([NullAllowed] AVAsset asset);
[Export("setItem:")]
void SetItem([NullAllowed] AVPlayerItem item);
[Export("setSmoothLoopItemByStringPath:smoothLoopCount:")]
void SetSmoothLoopItem(string stringPath, uint loopCount);
[Export("setSmoothLoopItemByUrl:smoothLoopCount:")]
void SetSmoothLoopItem(NSUrl assetUrl, uint loopCount);
[Export("setSmoothLoopItemByAsset:smoothLoopCount:")]
void SetSmoothLoopItem(AVAsset asset, uint loopCount);
[Export("playableDuration")]
CMTime PlayableDuration { get; }
[Export("isPlaying")]
bool IsPlaying { get; }
[Export("loopEnabled")]
bool LoopEnabled { get; set; }
[Export("beginSendingPlayMessages")]
void BeginSendingPlayMessages();
[Export("endSendingPlayMessages")]
void EndSendingPlayMessages();
[Export("isSendingPlayMessages")]
bool IsSendingPlayMessages { get; }
[Export("autoRotate")]
bool AutoRotate { get; set; }
[Export("CIImageRenderer"), NullAllowed]
NSObject CIImageRenderer { get; set; }
}
[BaseType(typeof(UIView))]
interface SCVideoPlayerView : SCPlayerDelegate {
[Export("player"), NullAllowed]
SCPlayer Player { get; set; }
[Export("playerLayer")]
AVPlayerLayer PlayerLayer { get; }
[Export("SCImageViewEnabled")]
bool SCImageViewEnabled { get; set; }
[Export("SCImageView")]
SCImageView SCImageView { get; }
}
[BaseType(typeof(UIView))]
interface SCRecorderFocusView {
[Export("recorder")]
SCRecorder Recorder { get; set; }
[Export("outsideFocusTargetImage")]
UIImage OutsideFocusTargetImage { get; set; }
[Export("insideFocusTargetImage")]
UIImage InsideFocusTargetImage { get; set; }
[Export("focusTargetSize")]
SizeF FocusTargetSize { get; set; }
[Export("showFocusAnimation")]
void ShowFocusAnimation();
[Export("hideFocusAnimation")]
void HideFocusAnimation();
}
[BaseType(typeof(NSObject))]
interface SCAssetExportSession {
[Export("inputAsset")]
AVAsset InputAsset { get; set; }
[Export("outputUrl")]
NSUrl OutputUrl { get; set; }
[Export("outputFileType")]
NSString OutputFileType { get; set; }
[Export("videoConfiguration")]
SCVideoConfiguration VideoConfiguration { get;}
[Export("audioConfiguration")]
SCAudioConfiguration AudioConfiguration { get; }
[Export("error")]
NSError Error { get; }
[Export("initWithAsset:")]
IntPtr Constructor(AVAsset inputAsset);
[Export("exportAsynchronouslyWithCompletionHandler:")]
void ExportAsynchronously(Action completionHandler);
[Export("useGPUForRenderingFilters")]
bool UseGPUForRenderingFilters { get; set; }
}
[BaseType(typeof(UIView))]
interface SCFilterSelectorView {
[Export("filterGroups"), NullAllowed]
SCFilterGroup[] FilterGroups { get; set; }
[Export("CIImage"), NullAllowed]
CIImage CIImage { get; set; }
[Export("selectedFilterGroup")]
SCFilterGroup SelectedFilterGroup { get; }
[Export("preferredCIImageTransform")]
CGAffineTransform PreferredCIImageTransform { get; set; }
[Export("currentlyDisplayedImageWithScale:orientation:")]
UIImage CurrentlyDisplayedImage(float scale, UIImageOrientation orientation);
}
[BaseType(typeof(SCFilterSelectorView))]
interface SCSwipeableFilterView {
[Export("selectFilterScrollView")]
UIScrollView SelectFilterScrollView { get; }
[Export("refreshAutomaticallyWhenScrolling")]
bool RefreshAutomaticallyWhenScrolling { get; set; }
}
[BaseType(typeof(GLKView))]
interface SCImageView {
[Export("CIImage"), NullAllowed]
CIImage CIImage { get; set; }
[Export("filterGroup"), NullAllowed]
SCFilterGroup FilterGroup { get; set; }
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Gallio.Runtime.Conversions;
using Gallio.Runtime.Formatting;
using Gallio.Common.Reflection;
namespace Gallio.Framework.Data
{
/// <summary>
/// A data binding specification describes how values are bound to slots (<see cref="ISlotInfo"/>)
/// of a type or method. The specification can then be used to create new objects or invoke
/// methods.
/// </summary>
/// <remarks>
/// <para>
/// A specification automatically converts values to the correct types
/// for data binding using a <see cref="IConverter" />. It can also format
/// the specification to a string using a <see cref="IFormatter" />.
/// </para>
/// </remarks>
/// <seealso cref="ObjectCreationSpec"/>
public abstract class DataBindingSpec
{
private readonly IEnumerable<KeyValuePair<ISlotInfo, object>> slotValues;
private readonly IConverter converter;
/// <summary>
/// Creates a data binding spec.
/// </summary>
/// <param name="slotValues">The slot values.</param>
/// <param name="converter">The converter to use for converting slot values
/// to the required types.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="slotValues"/>
/// or <paramref name="converter"/> is null or if <paramref name="slotValues"/>
/// contains a null slot.</exception>
protected DataBindingSpec(IEnumerable<KeyValuePair<ISlotInfo, object>> slotValues, IConverter converter)
{
if (slotValues == null)
throw new ArgumentNullException("slotValues");
if (converter == null)
throw new ArgumentNullException("converter");
foreach (KeyValuePair<ISlotInfo, object> slotValue in slotValues)
if (slotValue.Key == null)
throw new ArgumentNullException("slotValues", "Slots must not be null.");
this.slotValues = slotValues;
this.converter = converter;
}
/// <summary>
/// Gets the slot values.
/// </summary>
public IEnumerable<KeyValuePair<ISlotInfo, object>> SlotValues
{
get { return slotValues; }
}
/// <summary>
/// Gets the converter.
/// </summary>
public IConverter Converter
{
get { return converter; }
}
/// <summary>
/// Formats the specification to a string for presentation.
/// </summary>
/// <remarks>
/// <para>
/// The values are listed sequentially as follows:
/// <list type="bullet">
/// <item>The <paramref name="entity"/>.</item>
/// <item>The <see cref="IGenericParameterInfo" /> slot values, if any, are ordered by index
/// and enclosed within angle bracket.</item>
/// <item>The <see cref="IParameterInfo" /> slot values, if any, are ordered by index
/// and enclosed within parentheses.</item>
/// <item>All other slot values, if any, are sorted by name and formatted as name-value
/// pair assignments following a colon and delimited by a comma</item>
/// </list>
/// Example: 'SomeType<int, string>(42, "deep thought"): Author="Douglas Adams", Book="HGTTG"'.
/// </para>
/// <para>
/// If there are no slots of a given kind, then the enclosing angle brackets or
/// parentheses are ignored. Therefore if <see cref="SlotValues"/> is empty
/// then <paramref name="entity"/> will be returned unmodified.
/// </para>
/// <para>
/// This method assumes that the slots all belong to the same declaring type or method
/// which is always the case for <see cref="ObjectCreationSpec" /> and <see cref="MethodInvocationSpec" />.
/// </para>
/// </remarks>
/// <param name="entity">The entity that is qualified by the specification such as the name of a type or method.</param>
/// <param name="formatter">The formatter.</param>
/// <returns>The formatted specification.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="entity"/>
/// or <paramref name="formatter"/> is null.</exception>
public string Format(string entity, IFormatter formatter)
{
if (entity == null)
throw new ArgumentNullException("entity");
if (formatter == null)
throw new ArgumentNullException("formatter");
return FormatImpl(entity, formatter);
}
/// <summary>
/// Internal implementation of <see cref="Format" /> after argument validation.
/// </summary>
/// <param name="entity">The entity that is qualified by the specification such as the name of a type or method.</param>
/// <param name="formatter">The formatter, not null.</param>
/// <returns>The formatted specification.</returns>
protected abstract string FormatImpl(string entity, IFormatter formatter);
/// <summary>
/// Appends formatted generic arguments within angle brackets, if any.
/// </summary>
/// <param name="str">The string builder, not null.</param>
/// <param name="arguments">The arguments, not null.</param>
/// <param name="formatter">The formatter, not null.</param>
protected static void AppendFormattedGenericArguments(StringBuilder str, Type[] arguments, IFormatter formatter)
{
if (arguments.Length != 0)
{
str.Append('<');
AppendFormattedArguments(str, arguments, formatter);
str.Append('>');
}
}
/// <summary>
/// Appends formatted generic arguments within parentheses, if any.
/// </summary>
/// <param name="str">The string builder, not null.</param>
/// <param name="arguments">The arguments, not null.</param>
/// <param name="formatter">The formatter, not null.</param>
protected static void AppendFormattedMethodArguments(StringBuilder str, object[] arguments, IFormatter formatter)
{
if (arguments.Length != 0)
{
str.Append('(');
AppendFormattedArguments(str, arguments, formatter);
str.Append(')');
}
}
/// <summary>
/// Appends formatted values keyed and sorted by name, if any.
/// This method is used with fields and properties.
/// </summary>
/// <param name="str">The string builder, not null.</param>
/// <param name="namedValues">The named values, not null.</param>
/// <param name="formatter">The formatter, not null.</param>
protected static void AppendFormattedNamedValues(StringBuilder str,
IEnumerable<KeyValuePair<string, object>> namedValues, IFormatter formatter)
{
SortedList<string, object> sortedNamedValues = new SortedList<string, object>(StringComparer.InvariantCultureIgnoreCase);
foreach (KeyValuePair<string, object> entry in namedValues)
sortedNamedValues.Add(entry.Key, entry.Value);
if (sortedNamedValues.Count != 0)
{
str.Append(": ");
bool first = true;
foreach (KeyValuePair<string, object> entry in sortedNamedValues)
{
if (first)
first = false;
else
str.Append(", ");
str.Append(entry.Key);
str.Append('=');
str.Append(formatter.Format(entry.Value));
}
}
}
private static void AppendFormattedArguments(StringBuilder str, IEnumerable<object> arguments, IFormatter formatter)
{
bool first = true;
foreach (object value in arguments)
{
if (first)
first = false;
else
str.Append(", ");
str.Append(formatter.Format(value));
}
}
/// <summary>
/// Resolves a member that may be declared by a generic type using the
/// resolved type or one of its subtypes.
/// </summary>
/// <remarks>
/// <para>
/// For example, if <paramref name="member"/> was declared by type Foo<T>
/// and <paramref name="resolvedType"/> is a subtype of Foo<int>, returns
/// a reflection object for the member as declared by Foo<int>.
/// </para>
/// </remarks>
/// <typeparam name="T">The type of member.</typeparam>
/// <param name="resolvedType">The resolved type, not null.</param>
/// <param name="member">The member, not null.</param>
/// <returns>The resolved member.</returns>
protected static T ResolveMember<T>(Type resolvedType, T member)
where T : MemberInfo
{
if (resolvedType.ContainsGenericParameters)
throw new ArgumentException("The resolved type should not contain generic parameters.", "resolvedType");
Type declaringType = member.DeclaringType;
if (!declaringType.ContainsGenericParameters)
return member;
Module desiredModule = member.Module;
int desiredMetadataToken = member.MetadataToken;
MemberInfo[] resolvedMembers = ReflectionUtils.FindMembersWorkaround(resolvedType, member.MemberType,
BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
delegate(MemberInfo candidate, object dummy) {
return candidate.Module == desiredModule
&& candidate.MetadataToken == desiredMetadataToken;
},
null);
if (resolvedMembers.Length != 1)
throw new InvalidOperationException(String.Format("Could not resolve member '{0}' on type '{1}'.", member, resolvedType));
return (T)resolvedMembers[0];
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CommentEmitter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.CodeDom;
using System.Data.Common.Utils;
using System.Data.Metadata.Edm;
using System.Data.Services.Design;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
/// static helper class for emitting comments.
/// </summary>
internal static class CommentEmitter
{
#region Static Fields
private static readonly Regex LeadingBlanks = new Regex(@"^(?<LeadingBlanks>\s{1,})\S", RegexOptions.Singleline | RegexOptions.Compiled);
#endregion
#region Public Methods
/// <summary>
/// emit all the documentation comments for an element's documentation child
/// (if the element does not have a documentation child emit some standard "missing comments" comment
/// </summary>
/// <param name="element">the element whose documenation is to be displayed</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
public static void EmitSummaryComments(MetadataItem item, CodeCommentStatementCollection commentCollection)
{
Debug.Assert(item != null, "item parameter is null");
Debug.Assert(commentCollection != null, "commentCollection parameter is null");
Documentation documentation = GetDocumentation(item);
string [] summaryComments = null;
if (documentation != null && !StringUtil.IsNullOrEmptyOrWhiteSpace(documentation.Summary))
{
// we have documentation to emit
summaryComments = GetFormattedLines(documentation.Summary, true);
}
else
{
string summaryComment;
// no summary content, so use a default
switch (item.BuiltInTypeKind)
{
case BuiltInTypeKind.EdmProperty:
summaryComment = Strings.MissingPropertyDocumentation(((EdmProperty)item).Name);
break;
case BuiltInTypeKind.ComplexType:
summaryComment = Strings.MissingComplexTypeDocumentation(((ComplexType)item).FullName);
break;
default:
{
PropertyInfo pi = item.GetType().GetProperty("FullName");
if (pi == null)
{
pi = item.GetType().GetProperty("Name");
}
object value = null;
if (pi != null)
{
value = pi.GetValue(item, null);
}
if (value != null)
{
summaryComment = Strings.MissingDocumentation(value.ToString());
}
else
{
summaryComment = Strings.MissingDocumentationNoName;
}
}
break;
}
summaryComments = new string[] { summaryComment };
}
EmitSummaryComments(summaryComments, commentCollection);
EmitOtherDocumentationComments(documentation, commentCollection);
}
private static Documentation GetDocumentation(MetadataItem item)
{
if (item is Documentation)
return (Documentation)item;
else
return item.Documentation;
}
/// <summary>
/// Emit summary comments from a string
/// </summary>
/// <param name="summaryComments">the summary comments to be emitted</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
public static void EmitSummaryComments(string summaryComments, CodeCommentStatementCollection commentCollection)
{
Debug.Assert(commentCollection != null, "commentCollection parameter is null");
if (string.IsNullOrEmpty(summaryComments) || string.IsNullOrEmpty(summaryComments = summaryComments.TrimEnd()))
return;
EmitSummaryComments(SplitIntoLines(summaryComments), commentCollection);
}
/// <summary>
/// Emit some lines of comments
/// </summary>
/// <param name="commentLines">the lines of comments to emit</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
/// <param name="docComment">true if the comments are 'documentation' comments</param>
public static void EmitComments(string[] commentLines, CodeCommentStatementCollection commentCollection, bool docComment)
{
Debug.Assert(commentLines != null, "commentLines parameter is null");
Debug.Assert(commentCollection != null, "commentCollection parameter is null");
foreach (string comment in commentLines)
{
commentCollection.Add(new CodeCommentStatement(comment, docComment));
}
}
/// <summary>
/// Emit documentation comments for a method parameter
/// </summary>
/// <param name="parameter">the parameter being commented</param>
/// <param name="comment">the comment text</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization","CA1303:Do not pass literals as localized parameters", MessageId=".ctor", Justification="The generated document comment is not localized")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "param")]
public static void EmitParamComments(CodeParameterDeclarationExpression parameter, string comment,
CodeCommentStatementCollection commentCollection)
{
Debug.Assert(parameter != null, "parameter parameter is null");
Debug.Assert(comment != null, "comment parameter is null");
string paramComment = string.Format(System.Globalization.CultureInfo.CurrentCulture,
"<param name=\"{0}\">{1}</param>", parameter.Name, comment);
commentCollection.Add(new CodeCommentStatement(paramComment, true));
}
/// <summary>
/// 'Format' a string of text into lines: separates in to lines on '\n', removes '\r', and removes common leading blanks.
/// </summary>
/// <param name="escapeForXml">if true characters troublesome for xml are converted to entities</param>
/// <param name="text">the text to be formatted</param>
/// <returns>the formatted lines</returns>
public static string[] GetFormattedLines(string text, bool escapeForXml)
{
#if false
if ( text.IndexOf("\n") >= 0 )
Console.WriteLine("GetFormattedText(\""+text.Replace("\n","\\n").Replace("\r","\\r")+"\","+escapeForXml+")");
#endif
Debug.Assert(!string.IsNullOrEmpty(text));
// nothing in, almost nothing out.
if (StringUtil.IsNullOrEmptyOrWhiteSpace(text))
return new string[] { "" };
// normalize CRLF and LFCRs to LFs (we just remove all the crs, assuming there are no extraneous ones) and remove trailing spaces
text = text.Replace("\r", "");
// remove leading and.or trailing line ends to get single line for:
// <documentation>
// text
// <documentation>
bool trim = false;
int start = text.IndexOf('\n');
if (start >= 0 && StringUtil.IsNullOrEmptyOrWhiteSpace(text, 0, start + 1))
{
++start;
trim = true;
}
else
{
start = 0;
}
int last = text.LastIndexOf('\n');
if (last > start - 1 && StringUtil.IsNullOrEmptyOrWhiteSpace(text, last))
{
--last;
trim = true;
}
else
{
last = text.Length - 1;
}
if (trim)
{
Debug.Assert(start <= last);
text = text.Substring(start, last - start + 1);
}
// break into lines (preversing blank lines and preping text for being in xml comments)
if (escapeForXml)
{
text = System.Security.SecurityElement.Escape(text);
}
string[] lines = SplitIntoLines(text);
if (lines.Length == 1)
{
lines[0] = lines[0].Trim();
return lines;
}
// find the maximum leading whitespace substring (ignoring blank lines)
string leadingBlanks = null;
foreach (string line in lines)
{
// is an empty line
if (StringUtil.IsNullOrEmptyOrWhiteSpace(line))
continue;
// find the leading whitespace substring
Match match = LeadingBlanks.Match(line);
if (!match.Success)
{
//none, we're done
leadingBlanks = "";
break;
}
if (leadingBlanks == null)
{
// this is first non-empty line
leadingBlanks = match.Groups["LeadingBlanks"].Value;
continue;
}
// use the leadingBlanks if it matched the new one or it is a leading substring of the new one
string leadingBlanks2 = match.Groups["LeadingBlanks"].Value;
if (leadingBlanks2 == leadingBlanks || leadingBlanks2.StartsWith(leadingBlanks, StringComparison.Ordinal))
continue;
if (leadingBlanks.StartsWith(leadingBlanks2, StringComparison.OrdinalIgnoreCase))
{
// the current leading whitespace string is a leading substring of leadingBlanks. use the new one
leadingBlanks = leadingBlanks2;
continue;
}
// find longest leading common substring and use that.
int minLength = Math.Min(leadingBlanks.Length, leadingBlanks2.Length);
for (int j = 0; j < minLength; ++j)
{
if (leadingBlanks[j] != leadingBlanks2[j])
{
if (j == 0)
leadingBlanks = "";
else
leadingBlanks = leadingBlanks.Substring(0, j);
break;
}
}
// if we've reduced the leading substring to an empty string, we're done.
if (string.IsNullOrEmpty(leadingBlanks))
break;
}
// remove the leading whitespace substring and remove any trailing blanks.
int numLeadingCharsToRemove = leadingBlanks.Length;
for (int i = 0; i < lines.Length; ++i)
{
if (lines[i].Length >= numLeadingCharsToRemove)
lines[i] = lines[i].Substring(numLeadingCharsToRemove);
lines[i] = lines[i].TrimEnd();
}
return lines;
}
#endregion
#region Private Methods
/// <summary>
/// Emit the other (than Summary) documentation comments from a Documentation element
/// </summary>
/// <param name="documentation">the schema Docuementation element</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
private static void EmitOtherDocumentationComments(Documentation documentation, CodeCommentStatementCollection commentCollection)
{
Debug.Assert(commentCollection != null);
if (documentation == null)
return;
if (!string.IsNullOrEmpty(documentation.LongDescription))
EmitXmlComments("LongDescription", GetFormattedLines(documentation.LongDescription, true), commentCollection);
}
/// <summary>
/// Emit the summary comments
/// </summary>
/// <param name="summaryComments"></param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = ".ctor", Justification = "The generated document comment is not localized")]
private static void EmitSummaryComments(string[] summaryComments, CodeCommentStatementCollection commentCollection)
{
Debug.Assert(summaryComments != null);
Debug.Assert(commentCollection != null);
EmitXmlComments("summary", summaryComments, commentCollection);
}
/// <summary>
/// emit documentation comments between xml open and close tags
/// </summary>
/// <param name="tag">the xml tag name</param>
/// <param name="summaryComments">the lines of comments to emit</param>
/// <param name="commentCollection">the comment collection of the CodeDom object to be commented</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = ".ctor", Justification = "The generated document comment is not localized")]
private static void EmitXmlComments(string tag, string[] summaryComments, CodeCommentStatementCollection commentCollection)
{
Debug.Assert(tag != null);
Debug.Assert(summaryComments != null);
Debug.Assert(commentCollection != null);
commentCollection.Add(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "<{0}>", tag), true));
EmitComments(summaryComments, commentCollection, true);
commentCollection.Add(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "</{0}>", tag), true));
}
/// <summary>
/// split a string into lines on '\n' chars and remove '\r' chars
/// </summary>
/// <param name="text">the string to split</param>
/// <returns>the split string</returns>
private static string[] SplitIntoLines(string text)
{
if (string.IsNullOrEmpty(text))
return new string[] { "" };
return text.Replace("\r", "").Split('\n');
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;
using GameStateManagement;
#endregion
namespace GameStateManagementSample
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen
{
#region Fields
List<MenuEntry> menuEntries = new List<MenuEntry>();
int selectedEntry = 0;
string menuTitle;
InputAction menuUp;
InputAction menuDown;
InputAction menuSelect;
InputAction menuCancel;
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entries, so derived classes can add
/// or change the menu contents.
/// </summary>
protected IList<MenuEntry> MenuEntries
{
get { return menuEntries; }
}
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public MenuScreen(string menuTitle)
{
this.menuTitle = menuTitle;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
menuUp = new InputAction(
new Buttons[] { Buttons.DPadUp, Buttons.LeftThumbstickUp },
new Keys[] { Keys.Up },
true);
menuDown = new InputAction(
new Buttons[] { Buttons.DPadDown, Buttons.LeftThumbstickDown },
new Keys[] { Keys.Down },
true);
menuSelect = new InputAction(
new Buttons[] { Buttons.A, Buttons.Start },
new Keys[] { Keys.Enter, Keys.Space },
true);
menuCancel = new InputAction(
new Buttons[] { Buttons.B, Buttons.Back },
new Keys[] { Keys.Escape },
true);
}
#endregion
#region Handle Input
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(GameTime gameTime, InputState input)
{
// For input tests we pass in our ControllingPlayer, which may
// either be null (to accept input from any player) or a specific index.
// If we pass a null controlling player, the InputState helper returns to
// us which player actually provided the input. We pass that through to
// OnSelectEntry and OnCancel, so they can tell which player triggered them.
PlayerIndex playerIndex;
// Move to the previous menu entry?
if (menuUp.Evaluate(input, ControllingPlayer, out playerIndex))
{
selectedEntry--;
if (selectedEntry < 0)
selectedEntry = menuEntries.Count - 1;
}
// Move to the next menu entry?
if (menuDown.Evaluate(input, ControllingPlayer, out playerIndex))
{
selectedEntry++;
if (selectedEntry >= menuEntries.Count)
selectedEntry = 0;
}
if (menuSelect.Evaluate(input, ControllingPlayer, out playerIndex))
{
OnSelectEntry(selectedEntry, playerIndex);
}
else if (menuCancel.Evaluate(input, ControllingPlayer, out playerIndex))
{
OnCancel(playerIndex);
}
}
/// <summary>
/// Handler for when the user has chosen a menu entry.
/// </summary>
protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
{
menuEntries[entryIndex].OnSelectEntry(playerIndex);
}
/// <summary>
/// Handler for when the user has cancelled the menu.
/// </summary>
protected virtual void OnCancel(PlayerIndex playerIndex)
{
ExitScreen();
}
/// <summary>
/// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
/// </summary>
protected void OnCancel(object sender, PlayerIndexEventArgs e)
{
OnCancel(e.PlayerIndex);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen the chance to position the menu entries. By default
/// all menu entries are lined up in a vertical list, centered on the screen.
/// </summary>
protected virtual void UpdateMenuEntryLocations()
{
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// start at Y = 175; each X value is generated per entry
Vector2 position = new Vector2(0f, 175f);
// update each menu entry's location in turn
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
// each entry is to be centered horizontally
position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
if (ScreenState == ScreenState.TransitionOn)
position.X -= transitionOffset * 256;
else
position.X += transitionOffset * 512;
// set the entry's position
menuEntry.Position = position;
// move down for the next entry the size of this entry
position.Y += menuEntry.GetHeight(this);
}
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < menuEntries.Count; i++)
{
bool isSelected = IsActive && (i == selectedEntry);
menuEntries[i].Update(this, isSelected, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
// make sure our entries are in the right place before we draw them
UpdateMenuEntryLocations();
GraphicsDevice graphics = ScreenManager.GraphicsDevice;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
spriteBatch.Begin();
// Draw each menu entry in turn.
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
bool isSelected = IsActive && (i == selectedEntry);
menuEntry.Draw(this, isSelected, gameTime);
}
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// Draw the menu title centered on the screen
Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80);
Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
float titleScale = 1.25f;
titlePosition.Y -= transitionOffset * 100;
spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
titleOrigin, titleScale, SpriteEffects.None, 0);
spriteBatch.End();
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Execution;
using GraphQL.Validation;
using GraphQL.Validation.Complexity;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using OrchardCore.Apis.GraphQL.Queries;
using OrchardCore.Apis.GraphQL.ValidationRules;
using OrchardCore.Routing;
namespace OrchardCore.Apis.GraphQL
{
public class GraphQLMiddleware
{
private readonly RequestDelegate _next;
private readonly GraphQLSettings _settings;
private readonly IDocumentExecuter _executer;
internal static readonly Encoding _utf8Encoding = new UTF8Encoding(false);
private readonly static MediaType _jsonMediaType = new MediaType("application/json");
private readonly static MediaType _graphQlMediaType = new MediaType("application/graphql");
public GraphQLMiddleware(
RequestDelegate next,
GraphQLSettings settings,
IDocumentExecuter executer)
{
_next = next;
_settings = settings;
_executer = executer;
}
public async Task Invoke(HttpContext context, IAuthorizationService authorizationService, IAuthenticationService authenticationService, ISchemaFactory schemaService)
{
if (!IsGraphQLRequest(context))
{
await _next(context);
}
else
{
var authenticateResult = await authenticationService.AuthenticateAsync(context, "Api");
if (authenticateResult.Succeeded)
{
context.User = authenticateResult.Principal;
}
var authorized = await authorizationService.AuthorizeAsync(context.User, Permissions.ExecuteGraphQL);
if (authorized)
{
await ExecuteAsync(context, schemaService);
}
else
{
await context.ChallengeAsync("Api");
}
}
}
private bool IsGraphQLRequest(HttpContext context)
{
return context.Request.Path.StartsWithNormalizedSegments(_settings.Path, StringComparison.OrdinalIgnoreCase);
}
private async Task ExecuteAsync(HttpContext context, ISchemaFactory schemaService)
{
var schema = await schemaService.GetSchemaAsync();
GraphQLRequest request = null;
// c.f. https://graphql.org/learn/serving-over-http/#post-request
if (HttpMethods.IsPost(context.Request.Method))
{
if (string.IsNullOrEmpty(context.Request.ContentType))
{
await WriteErrorAsync(context, "Missing content-type");
return;
}
var mediaType = new MediaType(context.Request.ContentType);
try
{
if (mediaType.IsSubsetOf(_jsonMediaType))
{
using (var sr = new StreamReader(context.Request.Body))
{
// Asynchronous read is mandatory.
var json = await sr.ReadToEndAsync();
request = JObject.Parse(json).ToObject<GraphQLRequest>();
}
}
else if (mediaType.IsSubsetOf(_graphQlMediaType))
{
request = new GraphQLRequest();
using (var sr = new StreamReader(context.Request.Body))
{
request.Query = await sr.ReadToEndAsync();
}
}
else if (context.Request.Query.ContainsKey("query"))
{
request = new GraphQLRequest
{
Query = context.Request.Query["query"]
};
if (context.Request.Query.ContainsKey("variables"))
{
request.Variables = JObject.Parse(context.Request.Query["variables"]);
}
if (context.Request.Query.ContainsKey("operationName"))
{
request.OperationName = context.Request.Query["operationName"];
}
}
else
{
await WriteErrorAsync(context, "The request needs a valid content-type or a query argument");
return;
}
}
catch (Exception e)
{
await WriteErrorAsync(context, "An error occurred while processing the GraphQL query", e);
return;
}
}
else if (HttpMethods.IsGet(context.Request.Method))
{
if (!context.Request.Query.ContainsKey("query"))
{
await WriteErrorAsync(context, "The 'query' query string parameter is missing");
return;
}
request = new GraphQLRequest
{
Query = context.Request.Query["query"]
};
}
var queryToExecute = request.Query;
if (!String.IsNullOrEmpty(request.NamedQuery))
{
var namedQueries = context.RequestServices.GetServices<INamedQueryProvider>();
var queries = namedQueries
.SelectMany(dict => dict.Resolve())
.ToDictionary(pair => pair.Key, pair => pair.Value);
queryToExecute = queries[request.NamedQuery];
}
var dataLoaderDocumentListener = context.RequestServices.GetRequiredService<IDocumentExecutionListener>();
var result = await _executer.ExecuteAsync(_ =>
{
_.Schema = schema;
_.Query = queryToExecute;
_.OperationName = request.OperationName;
_.Inputs = request.Variables.ToInputs();
_.UserContext = _settings.BuildUserContext?.Invoke(context);
_.ExposeExceptions = _settings.ExposeExceptions;
_.ValidationRules = DocumentValidator.CoreRules()
.Concat(context.RequestServices.GetServices<IValidationRule>());
_.ComplexityConfiguration = new ComplexityConfiguration
{
MaxDepth = _settings.MaxDepth,
MaxComplexity = _settings.MaxComplexity,
FieldImpact = _settings.FieldImpact
};
_.Listeners.Add(dataLoaderDocumentListener);
});
context.Response.StatusCode = (int)(result.Errors == null || result.Errors.Count == 0
? HttpStatusCode.OK
: result.Errors.Any(x => x.Code == RequiresPermissionValidationRule.ErrorCode)
? HttpStatusCode.Unauthorized
: HttpStatusCode.BadRequest);
context.Response.ContentType = "application/json";
// Asynchronous write to the response body is mandatory.
var encodedBytes = _utf8Encoding.GetBytes(JObject.FromObject(result).ToString());
await context.Response.Body.WriteAsync(encodedBytes, 0, encodedBytes.Length);
}
private async Task WriteErrorAsync(HttpContext context, string message, Exception e = null)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
var errorResult = new ExecutionResult
{
Errors = new ExecutionErrors()
};
if (e == null)
{
errorResult.Errors.Add(new ExecutionError(message));
}
else
{
errorResult.Errors.Add(new ExecutionError(message, e));
}
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
// Asynchronous write to the response body is mandatory.
var encodedBytes = _utf8Encoding.GetBytes(JObject.FromObject(errorResult).ToString());
await context.Response.Body.WriteAsync(encodedBytes, 0, encodedBytes.Length);
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace DBus
{
using Protocol;
public class BusObject
{
static Dictionary<object,BusObject> boCache = new Dictionary<object,BusObject>();
protected Connection conn;
string bus_name;
ObjectPath object_path;
public BusObject ()
{
}
public BusObject (Connection conn, string bus_name, ObjectPath object_path)
{
this.conn = conn;
this.bus_name = bus_name;
this.object_path = object_path;
}
public Connection Connection
{
get {
return conn;
}
}
public string BusName
{
get {
return bus_name;
}
}
public ObjectPath Path
{
get {
return object_path;
}
}
public void ToggleSignal (string iface, string member, Delegate dlg, bool adding)
{
MatchRule rule = new MatchRule ();
rule.MessageType = MessageType.Signal;
rule.Fields.Add (FieldCode.Interface, new MatchTest (iface));
rule.Fields.Add (FieldCode.Member, new MatchTest (member));
rule.Fields.Add (FieldCode.Path, new MatchTest (object_path));
// FIXME: Cause a regression compared to 0.6 as name wasn't matched before
// the problem arises because busname is not used by DBus daemon and
// instead it uses the canonical name of the sender (i.e. similar to ':1.13')
// rule.Fields.Add (FieldCode.Sender, new MatchTest (bus_name));
if (adding) {
if (conn.Handlers.ContainsKey (rule))
conn.Handlers[rule] = Delegate.Combine (conn.Handlers[rule], dlg);
else {
conn.Handlers[rule] = dlg;
conn.AddMatch (rule.ToString ());
}
} else if (conn.Handlers.ContainsKey (rule)) {
conn.Handlers[rule] = Delegate.Remove (conn.Handlers[rule], dlg);
if (conn.Handlers[rule] == null) {
conn.RemoveMatch (rule.ToString ());
conn.Handlers.Remove (rule);
}
}
}
public void SendSignal (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
exception = null;
Signature outSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer signal = new MessageContainer {
Type = MessageType.Signal,
Path = object_path,
Interface = iface,
Member = member,
Signature = outSig,
};
Message signalMsg = signal.Message;
signalMsg.AttachBodyTo (writer);
conn.Send (signalMsg);
}
public MessageReader SendMethodCall (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
if (string.IsNullOrEmpty (bus_name))
throw new ArgumentNullException ("bus_name");
if (object_path == null)
throw new ArgumentNullException ("object_path");
exception = null;
Signature inSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer method_call = new MessageContainer {
Path = object_path,
Interface = iface,
Member = member,
Destination = bus_name,
Signature = inSig
};
Message callMsg = method_call.Message;
callMsg.AttachBodyTo (writer);
bool needsReply = true;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply) {
conn.Send (callMsg);
return null;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (retType);
callMsg.Header[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = conn.SendWithReplyAndBlock (callMsg);
MessageReader retVal = null;
//handle the reply message
switch (retMsg.Header.MessageType) {
case MessageType.MethodReturn:
retVal = new MessageReader (retMsg);
break;
case MessageType.Error:
MessageContainer error = MessageContainer.FromMessage (retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (retMsg);
errMsg = reader.ReadString ();
}
exception = new Exception (error.ErrorName + ": " + errMsg);
break;
default:
throw new Exception ("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return retVal;
}
public object SendPropertyGet (string iface, string property)
{
Exception exception;
MessageWriter writer = new MessageWriter ();
writer.Write (iface);
writer.Write (property);
MessageReader reader = SendMethodCall ("org.freedesktop.DBus.Properties", "Get", "ss", writer, typeof(object), out exception);
return reader.ReadValues ().FirstOrDefault ();
}
public void SendPropertySet (string iface, string property, object value)
{
Exception exception;
MessageWriter writer = new MessageWriter ();
writer.Write (iface);
writer.Write (property);
writer.Write (typeof(object), value);
SendMethodCall ("org.freedesktop.DBus.Properties", "Set", "ssv", writer, typeof(void), out exception);
}
public void Invoke (MethodBase methodBase, string methodName, object[] inArgs, out object[] outArgs, out object retVal, out Exception exception)
{
outArgs = new object[0];
retVal = null;
exception = null;
MethodInfo mi = methodBase as MethodInfo;
if (mi != null && mi.IsSpecialName && (methodName.StartsWith ("add_") || methodName.StartsWith ("remove_"))) {
string[] parts = methodName.Split (new char[]{'_'}, 2);
string ename = parts[1];
Delegate dlg = (Delegate)inArgs[0];
ToggleSignal (Mapper.GetInterfaceName (mi), ename, dlg, parts[0] == "add");
return;
}
Type[] inTypes = Mapper.GetTypes (ArgDirection.In, mi.GetParameters ());
Signature inSig = Signature.GetSig (inTypes);
string iface = null;
if (mi != null)
iface = Mapper.GetInterfaceName (mi);
if (mi != null && mi.IsSpecialName) {
methodName = methodName.Replace ("get_", "Get");
methodName = methodName.Replace ("set_", "Set");
}
MessageWriter writer = new MessageWriter (conn);
if (inArgs != null && inArgs.Length != 0) {
for (int i = 0 ; i != inTypes.Length ; i++)
writer.Write (inTypes[i], inArgs[i]);
}
MessageReader reader = SendMethodCall (iface, methodName, inSig.Value, writer, mi.ReturnType, out exception);
if (reader == null)
return;
retVal = reader.ReadValue (mi.ReturnType);
}
public static object GetObject (Connection conn, string bus_name, ObjectPath object_path, Type declType)
{
Type proxyType = TypeImplementer.Root.GetImplementation (declType);
object instObj = Activator.CreateInstance (proxyType);
BusObject inst = GetBusObject (instObj);
inst.conn = conn;
inst.bus_name = bus_name;
inst.object_path = object_path;
return instObj;
}
public static BusObject GetBusObject (object instObj)
{
if (instObj is BusObject)
return (BusObject)instObj;
BusObject inst;
if (boCache.TryGetValue (instObj, out inst))
return inst;
inst = new BusObject ();
boCache[instObj] = inst;
return inst;
}
public Delegate GetHookupDelegate (EventInfo ei)
{
DynamicMethod hookupMethod = TypeImplementer.GetHookupMethod (ei);
Delegate d = hookupMethod.CreateDelegate (ei.EventHandlerType, this);
return d;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR || !UNITY_FLASH
namespace tk2dRuntime.TileMap
{
public static class RenderMeshBuilder
{
public static void BuildForChunk(tk2dTileMap tileMap, SpriteChunk chunk, ColorChunk colorChunk, bool useColor, bool skipPrefabs, int baseX, int baseY)
{
List<Vector3> meshVertices = new List<Vector3>();
List<Color> meshColors = new List<Color>();
List<Vector2> meshUvs = new List<Vector2>();
//List<int> meshIndices = new List<int>();
int[] spriteIds = chunk.spriteIds;
Vector3 tileSize = tileMap.data.tileSize;
int spriteCount = tileMap.SpriteCollectionInst.spriteDefinitions.Length;
Object[] tilePrefabs = tileMap.data.tilePrefabs;
tk2dSpriteDefinition firstSprite = tileMap.SpriteCollectionInst.FirstValidDefinition;
bool buildNormals = (firstSprite != null && firstSprite.normals != null && firstSprite.normals.Length > 0);
Color32 clearColor = (useColor && tileMap.ColorChannel != null)?tileMap.ColorChannel.clearColor:Color.white;
// revert to no color mode (i.e. fill with clear color) when there isn't a color channel, or it is empty
if (colorChunk == null || colorChunk.colors.Length == 0)
useColor = false;
int x0, x1, dx;
int y0, y1, dy;
BuilderUtil.GetLoopOrder(tileMap.data.sortMethod,
tileMap.partitionSizeX, tileMap.partitionSizeY,
out x0, out x1, out dx,
out y0, out y1, out dy);
float xOffsetMult = 0.0f, yOffsetMult = 0.0f;
tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult);
List<int>[] meshIndices = new List<int>[tileMap.SpriteCollectionInst.materials.Length];
for (int j = 0; j < meshIndices.Length; ++j)
meshIndices[j] = new List<int>();
int colorChunkSize = tileMap.partitionSizeX + 1;
for (int y = y0; y != y1; y += dy)
{
float xOffset = ((baseY + y) & 1) * xOffsetMult;
for (int x = x0; x != x1; x += dx)
{
int spriteId = spriteIds[y * tileMap.partitionSizeX + x];
int tile = BuilderUtil.GetTileFromRawTile(spriteId);
bool flipH = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.FlipX);
bool flipV = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.FlipY);
bool rot90 = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.Rot90);
Vector3 currentPos = new Vector3(tileSize.x * (x + xOffset), tileSize.y * y, 0);
if (tile < 0 || tile >= spriteCount)
continue;
if (skipPrefabs && tilePrefabs[tile])
continue;
var sprite = tileMap.SpriteCollectionInst.spriteDefinitions[tile];
int baseVertex = meshVertices.Count;
for (int v = 0; v < sprite.positions.Length; ++v)
{
Vector3 flippedPos = BuilderUtil.ApplySpriteVertexTileFlags(tileMap, sprite, sprite.positions[v], flipH, flipV, rot90);
if (useColor)
{
Color tileColorx0y0 = colorChunk.colors[y * colorChunkSize + x];
Color tileColorx1y0 = colorChunk.colors[y * colorChunkSize + x + 1];
Color tileColorx0y1 = colorChunk.colors[(y + 1) * colorChunkSize + x];
Color tileColorx1y1 = colorChunk.colors[(y + 1) * colorChunkSize + (x + 1)];
Vector3 centeredSpriteVertex = flippedPos - sprite.untrimmedBoundsData[0];
Vector3 alignedSpriteVertex = centeredSpriteVertex + tileMap.data.tileSize * 0.5f;
float tileColorX = Mathf.Clamp01(alignedSpriteVertex.x / tileMap.data.tileSize.x);
float tileColorY = Mathf.Clamp01(alignedSpriteVertex.y / tileMap.data.tileSize.y);
Color color = Color.Lerp(
Color.Lerp(tileColorx0y0, tileColorx1y0, tileColorX),
Color.Lerp(tileColorx0y1, tileColorx1y1, tileColorX),
tileColorY);
meshColors.Add(color);
}
else
{
meshColors.Add(clearColor);
}
meshVertices.Add(currentPos + flippedPos);
meshUvs.Add(sprite.uvs[v]);
}
bool reverseIndices = false; // flipped?
if (flipH) reverseIndices = !reverseIndices;
if (flipV) reverseIndices = !reverseIndices;
List<int> indices = meshIndices[sprite.materialId];
for (int i = 0; i < sprite.indices.Length; ++i) {
int j = reverseIndices ? (sprite.indices.Length - 1 - i) : i;
indices.Add(baseVertex + sprite.indices[j]);
}
}
}
if (chunk.mesh == null)
chunk.mesh = tk2dUtil.CreateMesh();
chunk.mesh.vertices = meshVertices.ToArray();
chunk.mesh.uv = meshUvs.ToArray();
chunk.mesh.colors = meshColors.ToArray();
List<Material> materials = new List<Material>();
int materialId = 0;
int subMeshCount = 0;
foreach (var indices in meshIndices)
{
if (indices.Count > 0)
{
materials.Add(tileMap.SpriteCollectionInst.materialInsts[materialId]);
subMeshCount++;
}
materialId++;
}
if (subMeshCount > 0)
{
chunk.mesh.subMeshCount = subMeshCount;
chunk.gameObject.renderer.materials = materials.ToArray();
int subMeshId = 0;
foreach (var indices in meshIndices)
{
if (indices.Count > 0)
{
chunk.mesh.SetTriangles(indices.ToArray(), subMeshId);
subMeshId++;
}
}
}
chunk.mesh.RecalculateBounds();
if (buildNormals) {
chunk.mesh.RecalculateNormals();
}
var meshFilter = chunk.gameObject.GetComponent<MeshFilter>();
meshFilter.sharedMesh = chunk.mesh;
}
public static void Build(tk2dTileMap tileMap, bool editMode, bool forceBuild)
{
bool skipPrefabs = editMode?false:true;
bool incremental = !forceBuild;
int numLayers = tileMap.data.NumLayers;
for (int layerId = 0; layerId < numLayers; ++layerId)
{
var layer = tileMap.Layers[layerId];
if (layer.IsEmpty)
continue;
var layerData = tileMap.data.Layers[layerId];
bool useColor = !tileMap.ColorChannel.IsEmpty && tileMap.data.Layers[layerId].useColor;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
bool useSortingLayer = tileMap.data.useSortingLayers;
#endif
for (int cellY = 0; cellY < layer.numRows; ++cellY)
{
int baseY = cellY * layer.divY;
for (int cellX = 0; cellX < layer.numColumns; ++cellX)
{
int baseX = cellX * layer.divX;
var chunk = layer.GetChunk(cellX, cellY);
ColorChunk colorChunk = tileMap.ColorChannel.GetChunk(cellX, cellY);
bool colorChunkDirty = (colorChunk != null) && colorChunk.Dirty;
if (incremental && !colorChunkDirty && !chunk.Dirty)
continue;
if (chunk.mesh != null)
chunk.mesh.Clear();
if (chunk.IsEmpty)
continue;
if (editMode ||
(!editMode && !layerData.skipMeshGeneration)) {
BuildForChunk(tileMap, chunk, colorChunk, useColor, skipPrefabs, baseX, baseY);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (chunk.gameObject != null && useSortingLayer) {
Renderer r = chunk.gameObject.renderer;
if (r != null) {
r.sortingLayerName = layerData.sortingLayerName;
r.sortingOrder = layerData.sortingOrder;
}
}
#endif
}
if (chunk.mesh != null)
tileMap.TouchMesh(chunk.mesh);
}
}
}
}
}
}
#endif
| |
#if !UNITY_EDITOR_OSX || MAC_FORCE_TESTS
using System;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Experimental.VFX;
using UnityEditor.Experimental.VFX;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.VFX.UI;
using UnityEditor.VFX.Block.Test;
using System.IO;
namespace UnityEditor.VFX.Test
{
[TestFixture]
public class VFXGUITests
{
//[MenuItem("VFX Editor/Run GUI Tests")]
public static void RunGUITests()
{
VFXGUITests tests = new VFXGUITests();
tests.CreateTestAsset("GUITest");
var initContext = tests.CreateAllInitializeBlocks();
var updateContext = tests.CreateAllUpdateBlocks();
var outputContext = tests.CreateAllOutputBlocks();
tests.CreateFlowEdges(new VFXContextController[] {initContext, updateContext, outputContext});
tests.CreateAllOperators();
List<VFXParameter> parameters = tests.CreateAllParameters();
tests.CreateDataEdges(updateContext, parameters);
}
VFXViewController m_ViewController;
VFXViewWindow m_Window;
const string testAssetName = "Assets/TmpTests/{0}.vfx";
[Test]
public void CreateFlowEdgesTest()
{
CreateTestAsset("GUITest4");
var eventContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == VFXContextType.kEvent).First();
var eventContext = m_ViewController.AddVFXContext(new Vector2(300, 100), eventContextDesc);
var spawnerContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == VFXContextType.kSpawner).First();
var spawnerContext = m_ViewController.AddVFXContext(new Vector2(300, 100), spawnerContextDesc);
var initContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == VFXContextType.kInit).First();
var initContext = m_ViewController.AddVFXContext(new Vector2(300, 100), initContextDesc);
var updateContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == VFXContextType.kUpdate).First();
var updateContext = m_ViewController.AddVFXContext(new Vector2(300, 1000), updateContextDesc);
var outputContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == VFXContextType.kOutput).First();
var outputContext = m_ViewController.AddVFXContext(new Vector2(300, 2000), outputContextDesc);
m_ViewController.ApplyChanges();
var contextControllers = new List<VFXContextController>();
contextControllers.Add(m_ViewController.allChildren.OfType<VFXContextController>().First(t => t.model == eventContext) as VFXContextController);
contextControllers.Add(m_ViewController.allChildren.OfType<VFXContextController>().First(t => t.model == spawnerContext) as VFXContextController);
contextControllers.Add(m_ViewController.allChildren.OfType<VFXContextController>().First(t => t.model == initContext) as VFXContextController);
contextControllers.Add(m_ViewController.allChildren.OfType<VFXContextController>().First(t => t.model == updateContext) as VFXContextController);
contextControllers.Add(m_ViewController.allChildren.OfType<VFXContextController>().First(t => t.model == outputContext) as VFXContextController);
CreateFlowEdges(contextControllers);
DestroyTestAsset("GUITest4");
}
void CreateFlowEdges(IList<VFXContextController> contextControllers)
{
for (int i = 0; i < contextControllers.Count() - 1; ++i)
{
VFXFlowEdgeController edgeController = new VFXFlowEdgeController(contextControllers[i + 1].flowInputAnchors.First(), contextControllers[i].flowOutputAnchors.First());
m_ViewController.AddElement(edgeController);
}
m_ViewController.ApplyChanges();
}
void CreateDataEdges(VFXContextController updateContext, List<VFXParameter> parameters)
{
m_ViewController.ApplyChanges();
foreach (var param in parameters)
{
VFXParameterNodeController paramController = m_ViewController.allChildren.OfType<VFXParameterNodeController>().First(t => t.model == param);
VFXDataAnchorController outputAnchor = paramController.outputPorts.First() as VFXDataAnchorController;
System.Type type = outputAnchor.portType;
bool found = false;
foreach (var block in updateContext.blockControllers)
{
foreach (var anchor in block.inputPorts)
{
if (anchor.portType == type)
{
found = true;
(anchor as VFXDataAnchorController).model.Link(outputAnchor.model);
break;
}
}
if (found)
break;
}
}
}
public VisualEffectAsset m_Asset;
public void CreateTestAsset(string name)
{
var filePath = string.Format(testAssetName, name);
var directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
m_Asset = VisualEffectAssetEditorUtility.CreateNewAsset(filePath);
VFXViewWindow window = EditorWindow.GetWindow<VFXViewWindow>();
window.Close();
window = EditorWindow.GetWindow<VFXViewWindow>();
m_ViewController = VFXViewController.GetController(m_Asset.GetResource(), true);
window.graphView.controller = m_ViewController;
}
void DestroyTestAsset(string name)
{
var filePath = string.Format(testAssetName, name);
AssetDatabase.DeleteAsset(filePath);
VFXViewWindow window = EditorWindow.GetWindow<VFXViewWindow>();
window.Close();
}
[Test]
public void CreateAllInitializeBlocksTest()
{
CreateTestAsset("TestGUI1");
CreateAllInitializeBlocks();
DestroyTestAsset("TestGUI1");
}
VFXContextController CreateAllInitializeBlocks()
{
return CreateAllBlocks(VFXContextType.kInit);
}
[Test]
public void CreateAllUpdateBlocksTest()
{
CreateTestAsset("TestGUI2");
CreateAllUpdateBlocks();
DestroyTestAsset("TestGUI2");
}
VFXContextController CreateAllUpdateBlocks()
{
return CreateAllBlocks(VFXContextType.kUpdate);
}
[Test]
public void CreateAllOutputBlocksTest()
{
CreateTestAsset("TestGUI3");
CreateAllOutputBlocks();
DestroyTestAsset("TestGUI3");
}
[Test]
public void CreateAllSpawnerBlocksTest()
{
CreateTestAsset("TestGUI1");
CreateAllBlocks(VFXContextType.kSpawner);
DestroyTestAsset("TestGUI1");
}
[Test]
public void CreateAllEventBlocksTest()
{
CreateTestAsset("TestGUI1");
CreateAllBlocks(VFXContextType.kEvent);
DestroyTestAsset("TestGUI1");
}
VFXContextController CreateAllBlocks(VFXContextType type)
{
var initContextDesc = VFXLibrary.GetContexts().Where(t => t.model.contextType == type).First();
var newContext = m_ViewController.AddVFXContext(new Vector2(300, 2000), initContextDesc);
m_ViewController.ApplyChanges();
var contextController = m_ViewController.nodes.Where(t => t is VFXContextController && (t as VFXContextController).model == newContext).First() as VFXContextController;
Assert.AreEqual(contextController.model, newContext);
// Adding every block compatible with an init context
var newBlocks = new List<VFXBlock>();
foreach (var block in VFXLibrary.GetBlocks().Where(t => t.AcceptParent(newContext)))
{
var newBlock = block.CreateInstance();
contextController.AddBlock(0, newBlock);
newBlocks.Add(newBlock);
}
m_ViewController.ApplyChanges();
foreach (var newBlock in newBlocks)
{
Assert.AreEqual(contextController.blockControllers.Where(t => t.model == newBlock).Count(), 1, "Failing Block" + newBlock.name + "in context" + newContext.name);
var blockController = contextController.blockControllers.Where(t => t.model == newBlock).First() as VFXBlockController;
Assert.NotNull(blockController);
}
return contextController;
}
VFXContextController CreateAllOutputBlocks()
{
return CreateAllBlocks(VFXContextType.kOutput);
}
[Test]
public void ExpandRetractAndSetPropertyValue()
{
CreateTestAsset("TestGUI4");
var initContextDesc = VFXLibrary.GetContexts().Where(t => t.name == "Initialize").First();
var newContext = m_ViewController.AddVFXContext(new Vector2(300, 100), initContextDesc);
m_ViewController.ApplyChanges();
Assert.AreEqual(m_ViewController.allChildren.Where(t => t is VFXContextController).Count(), 1);
var contextController = m_ViewController.allChildren.Where(t => t is VFXContextController).First() as VFXContextController;
Assert.AreEqual(contextController.model, newContext);
// Adding every block compatible with an init context
var blockDesc = new VFXModelDescriptor<VFXBlock>(ScriptableObject.CreateInstance<AllType>());
var newBlock = blockDesc.CreateInstance();
contextController.AddBlock(0, newBlock);
Assert.IsTrue(newBlock is AllType);
m_ViewController.ApplyChanges();
Assert.AreEqual(contextController.blockControllers.Where(t => t.model == newBlock).Count(), 1);
var blockController = contextController.blockControllers.Where(t => t.model == newBlock).First();
Assert.NotNull(blockController);
Assert.NotZero(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).name == "aVector3").Count());
VFXSlot slot = blockController.model.inputSlots.First(t => t.name == "aVector3");
var aVector3Controller = blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).name == "aVector3").First() as VFXContextDataInputAnchorController;
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);
aVector3Controller.ExpandPath();
m_ViewController.ApplyChanges();
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);
aVector3Controller.RetractPath();
m_ViewController.ApplyChanges();
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.x").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").Count(), 1);
Assert.AreEqual(blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.z").Count(), 1);
aVector3Controller.SetPropertyValue(new Vector3(1.2f, 3.4f, 5.6f));
Assert.AreEqual(slot.value, new Vector3(1.2f, 3.4f, 5.6f));
aVector3Controller.ExpandPath();
m_ViewController.ApplyChanges();
var vector3yController = blockController.inputPorts.Where(t => t is VFXContextDataInputAnchorController && (t as VFXContextDataInputAnchorController).path == "aVector3.y").First() as VFXContextDataInputAnchorController;
vector3yController.SetPropertyValue(7.8f);
Assert.AreEqual(slot.value, new Vector3(1.2f, 7.8f, 5.6f));
DestroyTestAsset("TestGUI4");
}
[Test]
public void CreateAllOperatorsTest()
{
CreateTestAsset("TestGUI5");
CreateAllOperators();
DestroyTestAsset("TestGUI5");
}
List<VFXOperator> CreateAllOperators()
{
List<VFXOperator> operators = new List<VFXOperator>();
int cpt = 0;
foreach (var op in VFXLibrary.GetOperators())
{
operators.Add(m_ViewController.AddVFXOperator(new Vector2(700, 150 * cpt), op));
++cpt;
}
return operators;
}
List<VFXParameter> CreateAllParameters()
{
List<VFXParameter> parameters = new List<VFXParameter>();
int cpt = 0;
foreach (var param in VFXLibrary.GetParameters())
{
parameters.Add(m_ViewController.AddVFXParameter(new Vector2(-400, 150 * cpt), param));
++cpt;
}
return parameters;
}
[Test]
public void CreateAllParametersTest()
{
CreateTestAsset("TestGUI6");
CreateAllParameters();
DestroyTestAsset("TestGUI6");
}
[Test]
public void CreateAllDataEdgesTest()
{
CreateTestAsset("TestGUI7");
CreateDataEdges(CreateAllOutputBlocks(), CreateAllParameters());
DestroyTestAsset("TestGUI7");
}
}
}
#endif
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Utilities
{
internal interface IWrappedCollection : IList
{
object UnderlyingCollection { get; }
}
internal class CollectionWrapper<T> : ICollection<T>, IWrappedCollection
{
private readonly IList _list;
private readonly ICollection<T> _genericCollection;
private object _syncRoot;
public CollectionWrapper(IList list)
{
ValidationUtils.ArgumentNotNull(list, "list");
if (list is ICollection<T>)
_genericCollection = (ICollection<T>)list;
else
_list = list;
}
public CollectionWrapper(ICollection<T> list)
{
ValidationUtils.ArgumentNotNull(list, "list");
_genericCollection = list;
}
public virtual void Add(T item)
{
if (_genericCollection != null)
_genericCollection.Add(item);
else
_list.Add(item);
}
public virtual void Clear()
{
if (_genericCollection != null)
_genericCollection.Clear();
else
_list.Clear();
}
public virtual bool Contains(T item)
{
if (_genericCollection != null)
return _genericCollection.Contains(item);
else
return _list.Contains(item);
}
public virtual void CopyTo(T[] array, int arrayIndex)
{
if (_genericCollection != null)
_genericCollection.CopyTo(array, arrayIndex);
else
_list.CopyTo(array, arrayIndex);
}
public virtual int Count
{
get
{
if (_genericCollection != null)
return _genericCollection.Count;
else
return _list.Count;
}
}
public virtual bool IsReadOnly
{
get
{
if (_genericCollection != null)
return _genericCollection.IsReadOnly;
else
return _list.IsReadOnly;
}
}
public virtual bool Remove(T item)
{
if (_genericCollection != null)
{
return _genericCollection.Remove(item);
}
else
{
bool contains = _list.Contains(item);
if (contains)
_list.Remove(item);
return contains;
}
}
public virtual IEnumerator<T> GetEnumerator()
{
if (_genericCollection != null)
return _genericCollection.GetEnumerator();
return _list.Cast<T>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (_genericCollection != null)
return _genericCollection.GetEnumerator();
else
return _list.GetEnumerator();
}
int IList.Add(object value)
{
VerifyValueType(value);
Add((T)value);
return (Count - 1);
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
return Contains((T)value);
return false;
}
int IList.IndexOf(object value)
{
if (_genericCollection != null)
throw new InvalidOperationException("Wrapped ICollection<T> does not support IndexOf.");
if (IsCompatibleObject(value))
return _list.IndexOf((T)value);
return -1;
}
void IList.RemoveAt(int index)
{
if (_genericCollection != null)
throw new InvalidOperationException("Wrapped ICollection<T> does not support RemoveAt.");
_list.RemoveAt(index);
}
void IList.Insert(int index, object value)
{
if (_genericCollection != null)
throw new InvalidOperationException("Wrapped ICollection<T> does not support Insert.");
VerifyValueType(value);
_list.Insert(index, (T)value);
}
bool IList.IsFixedSize
{
get
{
if (_genericCollection != null)
// ICollection<T> only has IsReadOnly
return _genericCollection.IsReadOnly;
else
return _list.IsFixedSize;
}
}
void IList.Remove(object value)
{
if (IsCompatibleObject(value))
Remove((T)value);
}
object IList.this[int index]
{
get
{
if (_genericCollection != null)
throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
return _list[index];
}
set
{
if (_genericCollection != null)
throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
VerifyValueType(value);
_list[index] = (T)value;
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
CopyTo((T[])array, arrayIndex);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
private static void VerifyValueType(object value)
{
if (!IsCompatibleObject(value))
throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), "value");
}
private static bool IsCompatibleObject(object value)
{
if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T)))))
return false;
return true;
}
public object UnderlyingCollection
{
get
{
if (_genericCollection != null)
return _genericCollection;
else
return _list;
}
}
}
}
| |
//------------------------------------------------------------------------------
//
// zf - A command line archiver using the ZipFile class from SharpZipLib
// for compression
//
// Copyright 2006, 2010 John Reilly
//
//------------------------------------------------------------------------------
// Version History
// 1 Initial version ported from sz sample. Some stuff is not used or commented still
// 2 Display files during extract. --env Now shows .NET version information.
// 3 Add usezip64 option as a testing aid.
// 4 Fix format bug in output, remove unused code and other minor refactoring
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Samples.CS.ZF
{
/// <summary>
/// A command line archiver using the <see cref="ZipFile"/> class from the SharpZipLib compression library
/// </summary>
public class ZipFileArchiver
{
#region Enumerations
/// <summary>
/// Options for handling overwriting of files.
/// </summary>
enum Overwrite
{
Prompt,
Never,
Always
}
/// <summary>
/// Operations that can be performed
/// </summary>
enum Operation
{
Create, // add files to new archive
Extract, // extract files from existing archive
List, // show contents of existing archive
Delete, // Delete from archive
Add, // Add to archive.
Test, // Test the archive for validity.
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ZipFileArchiver"/> class.
/// </summary>
public ZipFileArchiver()
{
// Do nothing.
}
#endregion
#region Argument Parsing
/// <summary>
/// Parse command line arguments.
/// This is fairly flexible without using any custom classes. Arguments and options can appear
/// in any order and are case insensitive. Arguments for options are signalled with an '='
/// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
/// Grouping of single character options is supported.
/// </summary>
/// <returns>
/// true if arguments are valid such that processing should continue
/// </returns>
bool SetArgs(string[] args)
{
bool result = true;
int argIndex = 0;
while (argIndex < args.Length)
{
if (args[argIndex][0] == '-' || args[argIndex][0] == '/')
{
string option = args[argIndex].Substring(1).ToLower();
string optArg = "";
int parameterIndex = option.IndexOf('=');
if (parameterIndex >= 0)
{
if (parameterIndex < option.Length - 1)
{
optArg = option.Substring(parameterIndex + 1);
}
option = option.Substring(0, parameterIndex);
}
#if OPTIONTEST
Console.WriteLine("args index [{0}] option [{1}] argument [{2}]", argIndex, option, optArg);
#endif
if (option.Length == 0)
{
Console.Error.WriteLine("Invalid argument '{0}'", args[argIndex]);
result = false;
}
else
{
int optionIndex = 0;
while (optionIndex < option.Length)
{
#if OPTIONTEST
Console.WriteLine("optionIndex {0}", optionIndex);
#endif
switch(option[optionIndex])
{
case '-': // long option
optionIndex = option.Length;
switch (option)
{
case "-add":
operation_ = Operation.Add;
break;
case "-create":
operation_ = Operation.Create;
break;
case "-list":
operation_ = Operation.List;
break;
case "-extract":
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
break;
case "-delete":
operation_ = Operation.Delete;
break;
case "-test":
operation_ = Operation.Test;
break;
case "-dryrun":
dryRun_ = true;
break;
case "-env":
ShowEnvironment();
break;
case "-emptydirs":
addEmptyDirectoryEntries_ = true;
break;
case "-data":
testData_ = true;
break;
case "-zip64":
if ( optArg.Length > 0 )
{
switch ( optArg )
{
case "on":
useZip64_ = UseZip64.On;
break;
case "off":
useZip64_ = UseZip64.Off;
break;
case "auto":
useZip64_ = UseZip64.Dynamic;
break;
}
}
break;
case "-encoding":
if (optArg.Length > 0)
{
if (IsNumeric(optArg))
{
try
{
int enc = int.Parse(optArg);
if (Encoding.GetEncoding(enc) != null)
{
#if OPTIONTEST
Console.WriteLine("Encoding set to {0}", enc);
#endif
ZipConstants.DefaultCodePage = enc;
}
else
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
catch (Exception)
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
else
{
try
{
ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
}
catch (Exception)
{
result = false;
Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
}
else
{
result = false;
Console.Error.WriteLine("Missing encoding parameter");
}
break;
case "-version":
ShowVersion();
break;
case "-help":
ShowHelp();
break;
case "-restore-dates":
restoreDateTime_ = true;
break;
default:
Console.Error.WriteLine("Invalid long argument " + args[argIndex]);
result = false;
break;
}
break;
case '?':
ShowHelp();
break;
case 's':
if (optionIndex != 0)
{
result = false;
Console.Error.WriteLine("-s cannot be in a group");
}
else
{
if (optArg.Length > 0)
{
password_ = optArg;
}
else if (option.Length > 1)
{
password_ = option.Substring(1);
}
else
{
Console.Error.WriteLine("Missing argument to " + args[argIndex]);
}
}
optionIndex = option.Length;
break;
case 't':
operation_ = Operation.Test;
break;
case 'c':
operation_ = Operation.Create;
break;
case 'o':
optionIndex += 1;
overwriteFiles = optionIndex < option.Length ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
break;
case 'q':
silent_ = true;
if (overwriteFiles == Overwrite.Prompt)
{
overwriteFiles = Overwrite.Never;
}
break;
case 'r':
recursive_ = true;
break;
case 'v':
operation_ = Operation.List;
break;
case 'x':
if (optionIndex != 0)
{
result = false;
Console.Error.WriteLine("-x cannot be in a group");
}
else
{
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
}
optionIndex = option.Length;
break;
default:
Console.Error.WriteLine("Invalid argument: " + args[argIndex]);
result = false;
break;
}
++optionIndex;
}
}
}
else
{
#if OPTIONTEST
Console.WriteLine("file spec {0} = '{1}'", argIndex, args[argIndex]);
#endif
fileSpecs_.Add(args[argIndex]);
}
++argIndex;
}
if (fileSpecs_.Count > 0)
{
string checkPath = (string)fileSpecs_[0];
int deviceCheck = checkPath.IndexOf(':');
#if NET_VER_1
if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
#else
if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
#endif
|| checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
|| ((deviceCheck >= 0) && (deviceCheck != 1)))
{
Console.WriteLine("There are invalid characters in the specified zip file name");
result = false;
}
}
return result && (fileSpecs_.Count > 0);
}
#endregion
#region Show - Help/Environment/Version
/// <summary>
/// Show encoding/locale information
/// </summary>
void ShowEnvironment()
{
seenHelp_ = true;
Console.Out.WriteLine("");
Console.Out.WriteLine(
"Current encoding is {0}, code page {1}, windows code page {2}",
Console.Out.Encoding.EncodingName,
Console.Out.Encoding.CodePage,
Console.Out.Encoding.WindowsCodePage);
Console.WriteLine("Default code page is {0}",
Encoding.Default.CodePage);
Console.WriteLine( "Current culture LCID 0x{0:X}, {1}", CultureInfo.CurrentCulture.LCID, CultureInfo.CurrentCulture.EnglishName);
Console.WriteLine( "Current thread OEM codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);
Console.WriteLine( "Current thread Mac codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.MacCodePage);
Console.WriteLine( "Current thread Ansi codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
Console.WriteLine(".NET version {0}", Environment.Version);
}
/// <summary>
/// Display version information
/// </summary>
void ShowVersion()
{
seenHelp_ = true;
Console.Out.WriteLine("ZipFile Archiver v0.3 Copyright 2006 John Reilly");
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.GetName().Name == "ICSharpCode.SharpZipLib")
{
Console.Out.WriteLine("#ZipLib v{0} {1}", assembly.GetName().Version,
assembly.GlobalAssemblyCache ? "Running from GAC" : "Running from DLL"
);
}
}
Console.Out.WriteLine();
}
/// <summary>
/// Show help on possible options and arguments
/// </summary>
void ShowHelp()
{
if (seenHelp_)
{
return;
}
seenHelp_ = true;
ShowVersion();
Console.Out.WriteLine("usage zf {options} archive files");
Console.Out.WriteLine("");
Console.Out.WriteLine("Options:");
Console.Out.WriteLine("--add Add files to archive");
Console.Out.WriteLine("--create Create new archive");
Console.Out.WriteLine("--data Test archive data");
Console.Out.WriteLine("--delete Delete files from archive");
Console.Out.WriteLine("--encoding=codepage|name Set code page for encoding by name or number");
Console.Out.WriteLine("--extract{=dir} Extract archive contents to dir(default .)");
Console.Out.WriteLine("--help Show this help");
Console.Out.WriteLine("--env Show current environment information" );
Console.Out.WriteLine("--list List archive contents extended format");
Console.Out.WriteLine("--test Test archive for validity");
Console.Out.WriteLine("--version Show version information");
Console.Out.WriteLine("-r Recurse sub-folders");
Console.Out.WriteLine("-s=password Set archive password");
Console.Out.WriteLine("--zip64=[on|off|auto] Zip64 extension handling to use");
/*
Console.Out.WriteLine("--store Store entries (default=deflate)");
Console.Out.WriteLine("--emptydirs Create entries for empty directories");
Console.Out.WriteLine("--restore-dates Restore dates on extraction");
Console.Out.WriteLine("-o+ Overwrite files without prompting");
Console.Out.WriteLine("-o- Never overwrite files");
Console.Out.WriteLine("-q Quiet mode");
*/
Console.Out.WriteLine("");
}
#endregion
#region Archive Listing
void ListArchiveContents(ZipFile zipFile, FileInfo fileInfo)
{
const string headerTitles = "Name Length Ratio Size Date & time CRC-32 Attr";
const string headerUnderline = "------------ ---------- ----- ---------- ------------------- -------- ------";
int entryCount = 0;
long totalCompressedSize = 0;
long totalSize = 0;
foreach (ZipEntry theEntry in zipFile)
{
if ( theEntry.IsDirectory )
{
Console.Out.WriteLine("Directory {0}", theEntry.Name);
}
else if ( !theEntry.IsFile )
{
Console.Out.WriteLine("Non file entry {0}", theEntry.Name);
continue;
}
else
{
if (entryCount == 0)
{
Console.Out.WriteLine(headerTitles);
Console.Out.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
totalCompressedSize += theEntry.CompressedSize;
char cryptoDisplay = ( theEntry.IsCrypted ) ? '*' : ' ';
if (theEntry.Name.Length > 12)
{
Console.Out.WriteLine(theEntry.Name);
Console.Out.WriteLine(
"{0,-12}{7} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes),
cryptoDisplay);
}
else
{
Console.Out.WriteLine(
"{0,-12}{7} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes),
cryptoDisplay);
}
}
}
if (entryCount == 0)
{
Console.Out.WriteLine("Archive is empty!");
}
else
{
Console.Out.WriteLine(headerUnderline);
Console.Out.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount + " entries", totalSize, GetCompressionRatio(totalCompressedSize, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
/// <summary>
/// List zip file contents using ZipFile class
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListArchiveContents(string fileName)
{
try
{
FileInfo fileInfo = new FileInfo(fileName);
if (!fileInfo.Exists)
{
Console.Error.WriteLine("No such file exists {0}", fileName);
}
else
{
Console.Out.WriteLine(fileName);
try
{
using (ZipFile zipFile = new ZipFile(fileName))
{
ListArchiveContents(zipFile, fileInfo);
}
}
catch(Exception ex)
{
Console.Out.WriteLine("Problem reading archive - '{0}'", ex.Message);
}
}
}
catch(Exception exception)
{
Console.Error.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
/// <summary>
/// Execute List operation
/// Currently only Zip files are supported
/// </summary>
/// <param name="fileSpecs">Files to list</param>
void List(ArrayList fileSpecs)
{
foreach (string spec in fileSpecs)
{
string pathName = Path.GetDirectoryName(spec);
if ( (pathName == null) || (pathName.Length == 0) )
{
pathName = @".\";
}
string[] names = Directory.GetFiles(pathName, Path.GetFileName(spec));
if (names.Length == 0)
{
Console.Error.WriteLine("No files found matching {0}", spec);
}
else
{
foreach (string file in names)
{
ListArchiveContents(file);
}
Console.Out.WriteLine("");
}
}
}
#endregion
#region Creation
/// <summary>
/// Create archives based on specifications passed and internal state
/// </summary>
void Create(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
fileSpecs.RemoveAt(0);
if ( (overwriteFiles == Overwrite.Never) && File.Exists(zipFileName))
{
Console.Error.WriteLine("File {0} already exists", zipFileName);
return;
}
try
{
using (ZipFile zf = ZipFile.Create(zipFileName) )
{
zf.Password = password_;
zf.UseZip64 = useZip64_;
zf.BeginUpdate();
activeZipFile_ = zf;
foreach (string spec in fileSpecs)
{
// This can fail with wildcards in spec...
string path = Path.GetDirectoryName(Path.GetFullPath(spec));
string fileSpec = Path.GetFileName(spec);
zf.NameTransform = new ZipNameTransform(path);
FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec));
scanner.ProcessFile = new ProcessFileHandler(ProcessFile);
scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory);
scanner.Scan(path, recursive_);
}
zf.CommitUpdate();
}
}
catch (Exception ex)
{
Console.WriteLine("Problem creating archive - '{0}'", ex.Message);
}
}
#endregion
#region Extraction
/// <summary>
/// Extract a file storing its contents.
/// </summary>
/// <param name="inputStream">The input stream to source file contents from.</param>
/// <param name="theEntry">The <see cref="ZipEntry"/> representing the stored file details </param>
/// <param name="targetDir">The directory to store the output.</param>
/// <returns>True if operation is successful; false otherwise.</returns>
bool ExtractFile(Stream inputStream, ZipEntry theEntry, string targetDir)
{
if (inputStream == null)
{
throw new ArgumentNullException("inputStream");
}
if (theEntry == null)
{
throw new ArgumentNullException("theEntry");
}
if (!theEntry.IsFile)
{
throw new ArgumentException("Not a file", "theEntry");
}
if (targetDir == null)
{
throw new ArgumentNullException("targetDir");
}
// try and sort out the correct place to save this entry
bool result = true;
bool process = theEntry.Name.Length > 0;
if (!process)
{
// A fuller program would generate or prompt for a filename here...
if (!silent_)
{
Console.WriteLine("Ignoring empty name");
}
return false;
}
string entryFileName;
if (Path.IsPathRooted(theEntry.Name))
{
string workName = Path.GetPathRoot(theEntry.Name);
workName = theEntry.Name.Substring(workName.Length);
entryFileName = Path.Combine(Path.GetDirectoryName(workName), Path.GetFileName(theEntry.Name));
}
else
{
entryFileName = theEntry.Name;
}
string targetName = Path.Combine(targetDir, entryFileName);
string fullDirectoryName = Path.GetDirectoryName(Path.GetFullPath(targetName));
#if TEST
Console.WriteLine("Decompress targetfile name " + entryFileName);
Console.WriteLine("Decompress targetpath " + fullDirectoryName);
#endif
// Could be an option or parameter to allow failure or try creation
if (process)
{
if (Directory.Exists(fullDirectoryName) == false)
{
try
{
Directory.CreateDirectory(fullDirectoryName);
}
catch (Exception ex)
{
if (!silent_)
{
Console.Write("Exception creating directory '{0}' - {1}", fullDirectoryName, ex.Message);
}
result = false;
process = false;
}
}
else if (overwriteFiles == Overwrite.Prompt)
{
if (File.Exists(targetName))
{
Console.Write("File " + targetName + " already exists. Overwrite? ");
string readValue;
try
{
readValue = Console.ReadLine();
}
catch
{
readValue = null;
}
if ((readValue == null) || (readValue.ToLower() != "y"))
{
process = false;
}
}
}
}
if (process)
{
if ( !silent_ )
{
Console.Write("{0}", targetName);
}
if (!dryRun_)
{
using (FileStream outputStream = File.Create(targetName))
{
StreamUtils.Copy(inputStream, outputStream, GetBuffer());
}
if (restoreDateTime_)
{
File.SetLastWriteTime(targetName, theEntry.DateTime);
}
}
if ( !silent_ )
{
Console.WriteLine(" OK");
}
}
return result;
}
/// <summary>
/// Decompress a file
/// </summary>
/// <param name="fileName">File to decompress</param>
/// <param name="targetDir">Directory to create output in</param>
/// <returns>true iff all has been done successfully</returns>
bool DecompressArchive(string fileName, string targetDir)
{
bool result = true;
try
{
using (ZipFile zf = new ZipFile(fileName))
{
zf.Password = password_;
foreach ( ZipEntry entry in zf )
{
if (entry.IsFile)
{
if (!ExtractFile(zf.GetInputStream(entry), entry, targetDir))
{
if (!silent_)
{
Console.WriteLine("Extraction failed {0}", entry.Name);
}
}
}
else
{
if (!silent_)
{
Console.WriteLine("Skipping {0}", entry.Name);
}
}
}
if ( !silent_ )
{
Console.WriteLine("Done");
}
}
}
catch(Exception ex)
{
Console.WriteLine("Exception decompressing - '{0}'", ex);
result = false;
}
return result;
}
/// <summary>
/// Extract archives based on user input
/// Allows simple wildcards to specify multiple archives
/// </summary>
void Extract(ArrayList fileSpecs)
{
if ( (targetOutputDirectory_ == null) || (targetOutputDirectory_.Length == 0) )
{
targetOutputDirectory_ = @".\";
}
foreach(string spec in fileSpecs)
{
string [] names;
if ( (spec.IndexOf('*') >= 0) || (spec.IndexOf('?') >= 0) )
{
string pathName = Path.GetDirectoryName(spec);
if ( (pathName == null) || (pathName.Length == 0) )
{
pathName = @".\";
}
names = Directory.GetFiles(pathName, Path.GetFileName(spec));
}
else
{
names = new string[] { spec };
}
foreach (string fileName in names)
{
if (File.Exists(fileName) == false)
{
Console.Error.WriteLine("No such file exists {0}", fileName);
}
else
{
DecompressArchive(fileName, targetOutputDirectory_);
}
}
}
}
#endregion
#region Testing
/// <summary>
/// Handler for test result callbacks.
/// </summary>
/// <param name="status">The current <see cref="TestStatus"/>.</param>
/// <param name="message">The message applicable for this result.</param>
void TestResultHandler(TestStatus status, string message)
{
switch ( status.Operation )
{
case TestOperation.Initialising:
Console.WriteLine("Testing");
break;
case TestOperation.Complete:
Console.WriteLine("Testing complete");
break;
case TestOperation.EntryHeader:
// Not an error if message is null.
if ( message == null )
{
Console.Write("{0} - ", status.Entry.Name);
}
else
{
Console.WriteLine(message);
}
break;
case TestOperation.EntryData:
if ( message != null )
{
Console.WriteLine(message);
}
break;
case TestOperation.EntryComplete:
if ( status.EntryValid )
{
Console.WriteLine("OK");
}
break;
case TestOperation.MiscellaneousTests:
if ( message != null )
{
Console.WriteLine(message);
}
break;
}
}
/// <summary>
/// Test an archive to see if its valid.
/// </summary>
/// <param name="fileSpecs">The files to test.</param>
void Test(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
try
{
using (ZipFile zipFile = new ZipFile(zipFileName))
{
zipFile.Password = password_;
if ( zipFile.TestArchive(testData_, TestStrategy.FindAllErrors,
new ZipTestResultHandler(TestResultHandler)) )
{
Console.Out.WriteLine("Archive test passed");
}
else
{
Console.Out.WriteLine("Archive test failure");
}
}
}
catch(Exception ex)
{
Console.Out.WriteLine("Error list files - '{0}'", ex.Message);
}
}
#endregion
#region Deleting
/// <summary>
/// Delete entries from an archive
/// </summary>
/// <param name="fileSpecs">The file specs to operate on.</param>
void Delete(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
try
{
using (ZipFile zipFile = new ZipFile(zipFileName))
{
zipFile.BeginUpdate();
for ( int i = 1; i < fileSpecs.Count; ++i )
{
zipFile.Delete((string)fileSpecs[i]);
}
zipFile.CommitUpdate();
}
}
catch(Exception ex)
{
Console.WriteLine("Problem deleting files - '{0}'", ex.Message);
}
}
#endregion
#region Adding
/// <summary>
/// Callback for adding a new file.
/// </summary>
/// <param name="sender">The scanner calling this delegate.</param>
/// <param name="args">The event arguments.</param>
void ProcessFile(object sender, ScanEventArgs args)
{
if ( !silent_ )
{
Console.WriteLine(args.Name);
}
activeZipFile_.Add(args.Name);
}
/// <summary>
/// Callback for adding a new directory.
/// </summary>
/// <param name="sender">The scanner calling this delegate.</param>
/// <param name="args">The event arguments.</param>
/// <remarks>Directories are only added if they are empty and
/// the user has specified that empty directories are to be added.</remarks>
void ProcessDirectory(object sender, DirectoryEventArgs args)
{
if ( !args.HasMatchingFiles && addEmptyDirectoryEntries_ )
{
activeZipFile_.AddDirectory(args.Name);
}
}
/// <summary>
/// Add files to an archive
/// </summary>
/// <param name="fileSpecs">The specification for files to add.</param>
void Add(ArrayList fileSpecs)
{
string zipFileName = fileSpecs[0] as string;
if (Path.GetExtension(zipFileName).Length == 0)
{
zipFileName = Path.ChangeExtension(zipFileName, ".zip");
}
fileSpecs.RemoveAt(0);
ZipFile zipFile;
try
{
if ( File.Exists(zipFileName) )
{
zipFile = new ZipFile(zipFileName);
}
else
{
zipFile = ZipFile.Create(zipFileName);
}
using (zipFile)
{
zipFile.Password = password_;
zipFile.UseZip64 = useZip64_;
zipFile.BeginUpdate();
activeZipFile_ = zipFile;
foreach (string spec in fileSpecs)
{
string path = Path.GetDirectoryName(Path.GetFullPath(spec));
string fileSpec = Path.GetFileName(spec);
zipFile.NameTransform = new ZipNameTransform(path);
FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec));
scanner.ProcessFile = new ProcessFileHandler(ProcessFile);
scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory);
scanner.Scan(path, recursive_);
}
zipFile.CommitUpdate();
}
}
catch(Exception ex)
{
Console.WriteLine("Problem adding to archive - '{0}'", ex.Message);
}
}
#endregion
#region Class Execute Command
/// <summary>
/// Parse command line arguments and 'execute' them.
/// </summary>
void Execute(string[] args)
{
if (SetArgs(args))
{
if (fileSpecs_.Count == 0)
{
if (!silent_)
{
Console.Out.WriteLine("Nothing to do");
}
}
else
{
switch (operation_)
{
case Operation.List:
List(fileSpecs_);
break;
case Operation.Create:
Create(fileSpecs_);
break;
case Operation.Extract:
Extract(fileSpecs_);
break;
case Operation.Delete:
Delete(fileSpecs_);
break;
case Operation.Add:
Add(fileSpecs_);
break;
case Operation.Test:
Test(fileSpecs_);
break;
}
}
}
else
{
if ( !silent_ )
{
ShowHelp();
}
}
}
#endregion
#region Support Routines
byte[] GetBuffer()
{
if ( buffer_ == null )
{
buffer_ = new byte[bufferSize_];
}
return buffer_;
}
#endregion
#region Static support routines
///<summary>
/// Calculate compression ratio as a percentage
/// This wont allow for expansion (ratio > 100) as the resulting strings can get huge easily
/// </summary>
static int GetCompressionRatio(long packedSize, long unpackedSize)
{
int result = 0;
if ( (unpackedSize > 0) && (unpackedSize >= packedSize) )
{
result = (int) Math.Round((1.0 - ((double)packedSize / (double)unpackedSize)) * 100.0);
}
return result;
}
/// <summary>
/// Interpret attributes in conjunction with operatingSystem
/// </summary>
/// <param name="operatingSystem">The operating system.</param>
/// <param name="attributes">The external attributes.</param>
/// <returns>A string representation of the attributres passed.</returns>
static string InterpretExternalAttributes(int operatingSystem, int attributes)
{
string result = string.Empty;
if ((operatingSystem == 0) || (operatingSystem == 10))
{
if ((attributes & 0x10) != 0)
result = result + "D";
else
result = result + "-";
if ((attributes & 0x08) != 0)
result = result + "V";
else
result = result + "-";
if ((attributes & 0x01) != 0)
result = result + "r";
else
result = result + "-";
if ((attributes & 0x20) != 0)
result = result + "a";
else
result = result + "-";
if ((attributes & 0x04) != 0)
result = result + "s";
else
result = result + "-";
if ((attributes & 0x02) != 0)
result = result + "h";
else
result = result + "-";
// Device
if ((attributes & 0x4) != 0)
result = result + "d";
else
result = result + "-";
// OS is NTFS
if ( operatingSystem == 10 )
{
// Encrypted
if ( (attributes & 0x4000) != 0 )
{
result += "E";
}
else
{
result += "-";
}
// Not content indexed
if ( (attributes & 0x2000) != 0 )
{
result += "n";
}
else
{
result += "-";
}
// Offline
if ( (attributes & 0x1000) != 0 )
{
result += "O";
}
else
{
result += "-";
}
// Compressed
if ( (attributes & 0x0800) != 0 )
{
result += "C";
}
else
{
result += "-";
}
// Reparse point
if ( (attributes & 0x0400) != 0 )
{
result += "R";
}
else
{
result += "-";
}
// Sparse
if ( (attributes & 0x0200) != 0 )
{
result += "S";
}
else
{
result += "-";
}
// Temporary
if ( (attributes & 0x0100) != 0 )
{
result += "T";
}
else
{
result += "-";
}
}
}
return result;
}
/// <summary>
/// Determine if string is numeric [0-9]+
/// </summary>
/// <param name="rhs">string to test</param>
/// <returns>true iff rhs is numeric</returns>
static bool IsNumeric(string rhs)
{
bool result;
if (rhs != null && rhs.Length > 0)
{
result = true;
for (int i = 0; i < rhs.Length; ++i)
{
if (!char.IsDigit(rhs[i]))
{
result = false;
break;
}
}
}
else
{
result = false;
}
return result;
}
/// <summary>
/// Make external attributes suitable for a <see cref="ZipEntry"/>
/// </summary>
/// <param name="info">The <see cref="FileInfo"/> to convert</param>
/// <returns>Returns External Attributes for Zip use</returns>
static int MakeExternalAttributes(FileInfo info)
{
return (int)info.Attributes;
}
/// <summary>
/// Convert a wildcard expression to a regular expression
/// </summary>
/// <param name="wildcard">The wildcard expression to convert.</param>
/// <returns>A regular expression representing the converted wildcard expression.</returns>
static string WildcardToRegex(string wildcard)
{
int dotPos = wildcard.IndexOf('.');
bool dotted = (dotPos >= 0) && (dotPos < wildcard.Length - 1);
string converted = wildcard.Replace(".", @"\.");
converted = converted.Replace("?", ".");
converted = converted.Replace("*", ".*");
converted = converted.Replace("(", @"\(");
converted = converted.Replace(")", @"\)");
if ( dotted )
{
converted += "$";
}
return converted;
}
#endregion
#region Main
/// <summary>
/// Entry point for program, creates archiver and runs it
/// </summary>
/// <param name="args">
/// Command line argument to process
/// </param>
public static void Main(string[] args)
{
ZipFileArchiver zf = new ZipFileArchiver();
zf.Execute(args);
}
#endregion
#region Instance Fields
/// <summary>
/// Has user already seen help output?
/// </summary>
bool seenHelp_;
/// <summary>
/// File specifications possibly with wildcards from command line
/// </summary>
ArrayList fileSpecs_ = new ArrayList();
/// <summary>
/// Create entries for directories with no files
/// </summary>
bool addEmptyDirectoryEntries_;
/// <summary>
/// Apply operations recursively
/// </summary>
bool recursive_;
/// <summary>
/// Operate silently
/// </summary>
bool silent_;
/// <summary>
/// Restore file date and time to that stored in zip file on extraction
/// </summary>
bool restoreDateTime_;
/// <summary>
/// Overwrite files handling
/// </summary>
Overwrite overwriteFiles = Overwrite.Prompt;
/// <summary>
/// Optional password for archive
/// </summary>
string password_;
/// <summary>
/// Where things will go when decompressed.
/// </summary>
string targetOutputDirectory_;
/// <summary>
/// What to do based on parsed command line arguments
/// </summary>
Operation operation_ = Operation.List;
/// <summary>
/// Flag whose value is true if data should be tested; false if it should not.
/// </summary>
bool testData_;
/// <summary>
/// Dont extract or compress just display what would be done - testing
/// </summary>
private bool dryRun_;
/// <summary>
/// The currently active <see cref="ZipFile"/>.
/// </summary>
/// <remarks>Used for callbacks/delegates</remarks>
ZipFile activeZipFile_;
/// <summary>
/// Buffer used during some operations
/// </summary>
byte[] buffer_;
/// <summary>
/// The size of buffer to provide. <see cref="GetBuffer"></see>
/// </summary>
int bufferSize_ = 4096;
/// <summary>
/// The Zip64 extension use to apply.
/// </summary>
UseZip64 useZip64_ = UseZip64.Off;
#endregion
}
}
| |
using UnityEngine;
using Pathfinding;
using System.Collections.Generic;
using Pathfinding.WindowsStore;
using System;
#if NETFX_CORE
using System.Linq;
using WinRTLegacy;
#endif
namespace Pathfinding.Serialization {
public class JsonMemberAttribute : System.Attribute {}
public class JsonOptInAttribute : System.Attribute {}
/** A very tiny json serializer.
* It is not supposed to have lots of features, it is only intended to be able to serialize graph settings
* well enough.
*/
public class TinyJsonSerializer {
System.Text.StringBuilder output = new System.Text.StringBuilder();
Dictionary<Type, Action<System.Object> > serializers = new Dictionary<Type, Action<object> >();
static readonly System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture;
public static void Serialize (System.Object obj, System.Text.StringBuilder output) {
new TinyJsonSerializer() {
output = output
}.Serialize(obj);
}
TinyJsonSerializer () {
serializers[typeof(float)] = v => output.Append(((float)v).ToString("R", invariantCulture));
serializers[typeof(Version)] = serializers[typeof(bool)] = serializers[typeof(uint)] = serializers[typeof(int)] = v => output.Append(v.ToString());
serializers[typeof(string)] = v => output.AppendFormat("\"{0}\"", v);
serializers[typeof(Vector2)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1} }}", ((Vector2)v).x.ToString("R", invariantCulture), ((Vector2)v).y.ToString("R", invariantCulture));
serializers[typeof(Vector3)] = v => output.AppendFormat("{{ \"x\": {0}, \"y\": {1}, \"z\": {2} }}", ((Vector3)v).x.ToString("R", invariantCulture), ((Vector3)v).y.ToString("R", invariantCulture), ((Vector3)v).z.ToString("R", invariantCulture));
serializers[typeof(Pathfinding.Util.Guid)] = v => output.AppendFormat("{{ \"value\": \"{0}\" }}", v.ToString());
serializers[typeof(LayerMask)] = v => output.AppendFormat("{{ \"value\": {0} }}", ((int)(LayerMask)v).ToString());
}
void Serialize (System.Object obj) {
if (obj == null) {
output.Append("null");
return;
}
var tp = obj.GetType();
var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);
if (serializers.ContainsKey(tp)) {
serializers[tp] (obj);
} else if (tpInfo.IsEnum) {
output.Append('"' + obj.ToString() + '"');
} else if (obj is System.Collections.IList) {
output.Append("[");
var arr = obj as System.Collections.IList;
for (int i = 0; i < arr.Count; i++) {
if (i != 0)
output.Append(", ");
Serialize(arr[i]);
}
output.Append("]");
} else if (obj is UnityEngine.Object) {
SerializeUnityObject(obj as UnityEngine.Object);
} else {
#if NETFX_CORE
var optIn = tpInfo.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonOptInAttribute));
#else
var optIn = tpInfo.GetCustomAttributes(typeof(JsonOptInAttribute), true).Length > 0;
#endif
output.Append("{");
#if NETFX_CORE
var fields = tpInfo.DeclaredFields.Where(f => !f.IsStatic).ToArray();
#else
var fields = tp.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
#endif
bool earlier = false;
foreach (var field in fields) {
if ((!optIn && field.IsPublic) ||
#if NETFX_CORE
field.CustomAttributes.Any(attr => attr.GetType() == typeof(JsonMemberAttribute))
#else
field.GetCustomAttributes(typeof(JsonMemberAttribute), true).Length > 0
#endif
) {
if (earlier) {
output.Append(", ");
}
earlier = true;
output.AppendFormat("\"{0}\": ", field.Name);
Serialize(field.GetValue(obj));
}
}
output.Append("}");
}
}
void QuotedField (string name, string contents) {
output.AppendFormat("\"{0}\": \"{1}\"", name, contents);
}
void SerializeUnityObject (UnityEngine.Object obj) {
// Note that a unityengine can be destroyed as well
if (obj == null) {
Serialize(null);
return;
}
output.Append("{");
QuotedField("Name", obj.name);
output.Append(", ");
QuotedField("Type", obj.GetType().FullName);
//Write scene path if the object is a Component or GameObject
var component = obj as Component;
var go = obj as GameObject;
if (component != null || go != null) {
if (component != null && go == null) {
go = component.gameObject;
}
var helper = go.GetComponent<UnityReferenceHelper>();
if (helper == null) {
Debug.Log("Adding UnityReferenceHelper to Unity Reference '"+obj.name+"'");
helper = go.AddComponent<UnityReferenceHelper>();
}
//Make sure it has a unique GUID
helper.Reset();
output.Append(", ");
QuotedField("GUID", helper.GetGUID().ToString());
}
output.Append("}");
}
}
/** A very tiny json deserializer.
* It is not supposed to have lots of features, it is only intended to be able to deserialize graph settings
* well enough. Not much validation of the input is done.
*/
public class TinyJsonDeserializer {
System.IO.TextReader reader;
static readonly System.Globalization.NumberFormatInfo numberFormat = System.Globalization.NumberFormatInfo.InvariantInfo;
/** Deserializes an object of the specified type.
* Will load all fields into the \a populate object if it is set (only works for classes).
*/
public static System.Object Deserialize (string text, Type type, System.Object populate = null) {
return new TinyJsonDeserializer() {
reader = new System.IO.StringReader(text)
}.Deserialize(type, populate);
}
/** Deserializes an object of type tp.
* Will load all fields into the \a populate object if it is set (only works for classes).
*/
System.Object Deserialize (Type tp, System.Object populate = null) {
var tpInfo = WindowsStoreCompatibility.GetTypeInfo(tp);
if (tpInfo.IsEnum) {
return Enum.Parse(tp, EatField());
} else if (TryEat('n')) {
Eat("ull");
return null;
} else if (Type.Equals(tp, typeof(float))) {
return float.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(int))) {
return int.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(uint))) {
return uint.Parse(EatField(), numberFormat);
} else if (Type.Equals(tp, typeof(bool))) {
return bool.Parse(EatField());
} else if (Type.Equals(tp, typeof(string))) {
return EatField();
} else if (Type.Equals(tp, typeof(Version))) {
return new Version(EatField());
} else if (Type.Equals(tp, typeof(Vector2))) {
Eat("{");
var res = new Vector2();
EatField();
res.x = float.Parse(EatField(), numberFormat);
EatField();
res.y = float.Parse(EatField(), numberFormat);
Eat("}");
return res;
} else if (Type.Equals(tp, typeof(Vector3))) {
Eat("{");
var res = new Vector3();
EatField();
res.x = float.Parse(EatField(), numberFormat);
EatField();
res.y = float.Parse(EatField(), numberFormat);
EatField();
res.z = float.Parse(EatField(), numberFormat);
Eat("}");
return res;
} else if (Type.Equals(tp, typeof(Pathfinding.Util.Guid))) {
Eat("{");
EatField();
var res = Pathfinding.Util.Guid.Parse(EatField());
Eat("}");
return res;
} else if (Type.Equals(tp, typeof(LayerMask))) {
Eat("{");
EatField();
var res = (LayerMask)int.Parse(EatField());
Eat("}");
return res;
} else if (Type.Equals(tp, typeof(List<string>))) {
System.Collections.IList ls;
ls = new List<string>();
Eat("[");
while (!TryEat(']')) {
ls.Add(Deserialize(typeof(string)));
}
return ls;
} else if (tpInfo.IsArray) {
List<System.Object> ls = new List<System.Object>();
Eat("[");
while (!TryEat(']')) {
ls.Add(Deserialize(tp.GetElementType()));
}
var arr = Array.CreateInstance(tp.GetElementType(), ls.Count);
ls.ToArray().CopyTo(arr, 0);
return arr;
} else if (Type.Equals(tp, typeof(Mesh)) || Type.Equals(tp, typeof(Texture2D)) || Type.Equals(tp, typeof(Transform)) || Type.Equals(tp, typeof(GameObject))) {
return DeserializeUnityObject();
} else {
var obj = populate ?? Activator.CreateInstance(tp);
Eat("{");
while (!TryEat('}')) {
var name = EatField();
var field = tp.GetField(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
if (field == null) {
SkipFieldData();
} else {
field.SetValue(obj, Deserialize(field.FieldType));
}
TryEat(',');
}
return obj;
}
}
UnityEngine.Object DeserializeUnityObject () {
Eat("{");
var res = DeserializeUnityObjectInner();
Eat("}");
return res;
}
UnityEngine.Object DeserializeUnityObjectInner () {
if (EatField() != "Name") throw new Exception("Expected 'Name' field");
string name = EatField();
if (name == null) return null;
if (EatField() != "Type") throw new Exception("Expected 'Type' field");
string typename = EatField();
// Remove assembly information
if (typename.IndexOf(',') != -1) {
typename = typename.Substring(0, typename.IndexOf(','));
}
// Note calling through assembly is more stable on e.g WebGL
var type = WindowsStoreCompatibility.GetTypeInfo(typeof(AstarPath)).Assembly.GetType(typename);
type = type ?? WindowsStoreCompatibility.GetTypeInfo(typeof(Transform)).Assembly.GetType(typename);
if (Type.Equals(type, null)) {
Debug.LogError("Could not find type '"+typename+"'. Cannot deserialize Unity reference");
return null;
}
// Check if there is another field there
EatWhitespace();
if ((char)reader.Peek() == '"') {
if (EatField() != "GUID") throw new Exception("Expected 'GUID' field");
string guid = EatField();
foreach (var helper in UnityEngine.Object.FindObjectsOfType<UnityReferenceHelper>()) {
if (helper.GetGUID() == guid) {
if (Type.Equals(type, typeof(GameObject))) {
return helper.gameObject;
} else {
return helper.GetComponent(type);
}
}
}
}
// Try to load from resources
UnityEngine.Object[] objs = Resources.LoadAll(name, type);
for (int i = 0; i < objs.Length; i++) {
if (objs[i].name == name || objs.Length == 1) {
return objs[i];
}
}
return null;
}
void EatWhitespace () {
while (char.IsWhiteSpace((char)reader.Peek()))
reader.Read();
}
void Eat (string s) {
EatWhitespace();
for (int i = 0; i < s.Length; i++) {
var c = (char)reader.Read();
if (c != s[i]) {
throw new Exception("Expected '" + s[i] + "' found '" + c + "'\n\n..." + reader.ReadLine());
}
}
}
System.Text.StringBuilder builder = new System.Text.StringBuilder();
string EatUntil (string c, bool inString) {
builder.Length = 0;
bool escape = false;
while (true) {
var readInt = reader.Peek();
if (!escape && (char)readInt == '"') {
inString = !inString;
}
var readChar = (char)readInt;
if (readInt == -1) {
throw new Exception("Unexpected EOF");
} else if (!escape && readChar == '\\') {
escape = true;
reader.Read();
} else if (!inString && c.IndexOf(readChar) != -1) {
break;
} else {
builder.Append(readChar);
reader.Read();
escape = false;
}
}
return builder.ToString();
}
bool TryEat (char c) {
EatWhitespace();
if ((char)reader.Peek() == c) {
reader.Read();
return true;
}
return false;
}
string EatField () {
var res = EatUntil("\",}]", TryEat('"'));
TryEat('\"');
TryEat(':');
TryEat(',');
return res;
}
void SkipFieldData () {
var indent = 0;
while (true) {
EatUntil(",{}[]", false);
var last = (char)reader.Peek();
switch (last) {
case '{':
case '[':
indent++;
break;
case '}':
case ']':
indent--;
if (indent < 0) return;
break;
case ',':
if (indent == 0) {
reader.Read();
return;
}
break;
default:
throw new System.Exception("Should not reach this part");
}
reader.Read();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Cytoid.Storyboard.Controllers;
using Cytoid.Storyboard.Lines;
using Cytoid.Storyboard.Notes;
using Cytoid.Storyboard.Sprites;
using Cytoid.Storyboard.Texts;
using Cytoid.Storyboard.Videos;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Cysharp.Threading.Tasks;
using UnityEngine;
namespace Cytoid.Storyboard
{
public class Storyboard
{
public Game Game { get; }
public StoryboardRenderer Renderer { get; }
public StoryboardConfig Config { get; }
public readonly JObject RootObject;
public readonly Dictionary<string, Text> Texts = new Dictionary<string, Text>();
public readonly Dictionary<string, Sprite> Sprites = new Dictionary<string, Sprite>();
public readonly Dictionary<string, Controller> Controllers = new Dictionary<string, Controller>();
public readonly Dictionary<string, NoteController> NoteControllers = new Dictionary<string, NoteController>();
public readonly Dictionary<string, Line> Lines = new Dictionary<string, Line>();
public readonly Dictionary<string, Video> Videos = new Dictionary<string, Video>();
public readonly List<Trigger> Triggers = new List<Trigger>();
public readonly Dictionary<string, JObject> Templates = new Dictionary<string, JObject>();
public Storyboard(Game game, string content)
{
Game = game;
Renderer = new StoryboardRenderer(this);
Config = new StoryboardConfig(this);
UnitFloat.Storyboard = this;
RootObject = JObject.Parse(content);
/*JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};*/ // Moved to Context.cs
}
public void Parse()
{
if ((bool?) RootObject["compiled"] == true)
{
// Directly load into memory
((JArray) RootObject["texts"]).Select(it => it.ToObject<Text>()).ForEach(it => Texts[it.Id] = it);
((JArray) RootObject["sprites"]).Select(it => it.ToObject<Sprite>()).ForEach(it => Sprites[it.Id] = it);
((JArray) RootObject["videos"]).Select(it => it.ToObject<Video>()).ForEach(it => Videos[it.Id] = it);
((JArray) RootObject["lines"]).Select(it => it.ToObject<Line>()).ForEach(it => Lines[it.Id] = it);
((JArray) RootObject["controllers"]).Select(it => it.ToObject<Controller>()).ForEach(it => Controllers[it.Id] = it);
((JArray) RootObject["note_controllers"]).Select(it => it.ToObject<NoteController>()).ForEach(it => NoteControllers[it.Id] = it);
}
else
{
// Parse
// Templates
if (RootObject["templates"] != null)
{
foreach (var templateProperty in RootObject["templates"].Children<JProperty>())
{
Templates[templateProperty.Name] = templateProperty.Value.ToObject<JObject>();
}
}
void ParseStateObjects<TO, TS>(string rootTokenName, Dictionary<string, TO> addToDictionary,
Action<JObject> tokenPreprocessor = null)
where TO : Object<TS>, new() where TS : ObjectState, new()
{
if (RootObject[rootTokenName] == null) return;
foreach (var childToken in (JArray) RootObject[rootTokenName])
{
foreach (var objectToken in PopulateJObjects((JObject) childToken))
{
tokenPreprocessor?.Invoke(objectToken);
var obj = LoadObject<TO, TS>(objectToken);
if (obj != null)
{
if (addToDictionary.ContainsKey(obj.Id))
{
Debug.LogError($"Storyboard: Redefinition of element {obj.Id}");
continue;
}
addToDictionary[obj.Id] = obj;
}
}
}
}
var timer = new BenchmarkTimer("Storyboard parsing");
ParseStateObjects<Text, TextState>("texts", Texts);
timer.Time("Text");
ParseStateObjects<Sprite, SpriteState>("sprites", Sprites);
timer.Time("Sprite");
ParseStateObjects<Video, VideoState>("videos", Videos);
timer.Time("Videos");
ParseStateObjects<Line, LineState>("lines", Lines);
timer.Time("Lines");
ParseStateObjects<NoteController, NoteControllerState>("note_controllers", NoteControllers, token =>
{
// Note controllers have time default to zero
if (token["time"] == null) token["time"] = 0;
});
timer.Time("NoteController");
ParseStateObjects<Controller, ControllerState>("controllers", Controllers, token =>
{
// Controllers have time default to zero
if (token["time"] == null) token["time"] = 0;
});
timer.Time("Controller");
timer.Time();
// Trigger
if (RootObject["triggers"] != null)
foreach (var objectToken in (JArray) RootObject["triggers"])
Triggers.Add(LoadTrigger(objectToken));
}
}
public void Dispose()
{
Texts.Clear();
Sprites.Clear();
Controllers.Clear();
NoteControllers.Clear();
Triggers.Clear();
Templates.Clear();
Game.onGameLateUpdate.RemoveListener(Renderer.OnGameUpdate);
}
public async UniTask Initialize()
{
await Renderer.Initialize();
// Register note clear listener for triggers
Game.onNoteClear.AddListener(OnNoteClear);
Game.onGameDisposed.AddListener(_ => Dispose());
Game.onGameLateUpdate.AddListener(Renderer.OnGameUpdate);
}
public void OnNoteClear(Game game, Note note)
{
foreach (var trigger in Triggers)
{
if (trigger.Type == TriggerType.NoteClear && trigger.Notes.Contains(note.Model.id))
{
trigger.Triggerer = note;
OnTrigger(trigger);
}
if (trigger.Type == TriggerType.Combo && Game.State.Combo == trigger.Combo)
{
trigger.Triggerer = note;
OnTrigger(trigger);
}
if (trigger.Type == TriggerType.Score && Game.State.Score >= trigger.Score)
{
trigger.Triggerer = note;
OnTrigger(trigger);
Triggers.Remove(trigger);
}
}
}
public void OnTrigger(Trigger trigger)
{
Renderer.OnTrigger(trigger);
// Destroy trigger if needed
trigger.CurrentUses++;
if (trigger.CurrentUses == trigger.Uses)
{
Triggers.Remove(trigger);
}
}
public JObject Compile()
{
var serializer = new JsonSerializer
{
NullValueHandling = NullValueHandling.Ignore
};
var root = new JObject();
root["compiled"] = true;
var texts = new JArray();
Texts.Values.ForEach(it => texts.Add(JObject.FromObject(it, serializer)));
root["texts"] = texts;
var sprites = new JArray();
Sprites.Values.ForEach(it => sprites.Add(JObject.FromObject(it, serializer)));
root["sprites"] = sprites;
var videos = new JArray();
Videos.Values.ForEach(it => videos.Add(JObject.FromObject(it, serializer)));
root["videos"] = videos;
var lines = new JArray();
Lines.Values.ForEach(it => lines.Add(JObject.FromObject(it, serializer)));
root["lines"] = lines;
var controllers = new JArray();
Controllers.Values.ForEach(it => controllers.Add(JObject.FromObject(it, serializer)));
root["controllers"] = controllers;
var noteControllers = new JArray();
NoteControllers.Values.ForEach(it => noteControllers.Add(JObject.FromObject(it, serializer)));
root["note_controllers"] = noteControllers;
return root;
}
private void RecursivelyParseTime(JObject obj)
{
foreach (var x in obj)
{
var name = x.Key;
var value = x.Value;
if (name == "time")
{
value.Replace(ParseTime(obj, value));
}
else
{
switch (value)
{
case JArray array:
RecursivelyParseTime(array);
break;
case JObject jObject:
RecursivelyParseTime(jObject);
break;
}
}
}
}
private void RecursivelyParseTime(JArray array)
{
foreach (var x in array)
{
switch (x)
{
case JArray jArray:
RecursivelyParseTime(jArray);
break;
case JObject jObject:
RecursivelyParseTime(jObject);
break;
}
}
}
/**
* Convert an object with an array of `time` to multiple objects.
*/
private List<JObject> PopulateJObjects(JObject obj)
{
var timePopulatedObjects = new List<JObject>();
var timeToken = obj.SelectToken("relative_time");
if (timeToken != null && timeToken.Type == JTokenType.Array)
foreach (var time in timeToken.Values())
{
var newObj = (JObject) obj.DeepClone();
newObj["relative_time"] = time;
timePopulatedObjects.Add(newObj);
}
timeToken = obj.SelectToken("add_time");
if (timeToken != null && timeToken.Type == JTokenType.Array)
foreach (var time in timeToken.Values())
{
var newObj = (JObject) obj.DeepClone();
newObj["add_time"] = time;
timePopulatedObjects.Add(newObj);
}
timeToken = obj.SelectToken("time");
if (timeToken != null && timeToken.Type == JTokenType.Array)
foreach (var time in timeToken.Values())
{
var newObj = (JObject) obj.DeepClone();
newObj["time"] = time;
timePopulatedObjects.Add(newObj);
}
timePopulatedObjects = timePopulatedObjects.Count == 0 ? new List<JObject> {obj} : timePopulatedObjects;
var populatedObjects = new List<JObject>();
foreach (var obj2 in timePopulatedObjects)
{
var noteSpecifierToken = obj.SelectToken("note");
if (noteSpecifierToken != null)
{
if (noteSpecifierToken.Type == JTokenType.Object)
{
// Note selector
var noteSelector = new NoteSelector();
noteSelector.Start = (int?) noteSpecifierToken.SelectToken("start") ?? noteSelector.Start;
noteSelector.End = (int?) noteSpecifierToken.SelectToken("end") ?? noteSelector.End;
noteSelector.Direction = (int?) noteSpecifierToken.SelectToken("direction") ?? noteSelector.Direction;
noteSelector.MinX = (float?) noteSpecifierToken.SelectToken("min_x") ?? noteSelector.MinX;
noteSelector.MaxX = (float?) noteSpecifierToken.SelectToken("max_x") ?? noteSelector.MaxX;
var typeToken = noteSpecifierToken.SelectToken("type");
if (typeToken != null)
{
if (typeToken.Type == JTokenType.Integer)
{
noteSelector.Types.Add((int) typeToken);
}
else if (typeToken.Type == JTokenType.Array)
{
foreach (var noteToken in typeToken.Values())
{
noteSelector.Types.Add((int) noteToken);
}
}
}
else
{
((NoteType[]) Enum.GetValues(typeof(NoteType))).ForEach(it =>
noteSelector.Types.Add((int) it));
}
var noteIds = new List<int>();
foreach (var chartNote in Game.Chart.Model.note_list)
{
if (noteSelector.Types.Contains(chartNote.type)
&& noteSelector.Start <= chartNote.id
&& noteSelector.End >= chartNote.id
&& noteSelector.MinX <= chartNote.x
&& noteSelector.MaxX >= chartNote.x)
{
if (noteSelector.Direction == null || noteSelector.Direction == chartNote.direction)
{
noteIds.Add(chartNote.id);
}
}
}
foreach (var noteId in noteIds)
{
var newObj = (JObject) obj2.DeepClone();
newObj["note"] = noteId;
populatedObjects.Add(newObj);
}
}
else if (noteSpecifierToken.Type == JTokenType.Array)
{
foreach (var noteToken in noteSpecifierToken.Values())
{
var newObj = (JObject) obj2.DeepClone();
newObj["note"] = (int) noteToken;
populatedObjects.Add(newObj);
}
}
else if (noteSpecifierToken.Type == JTokenType.Integer)
{
var newObj = (JObject) obj2.DeepClone();
newObj["note"] = (int) noteSpecifierToken;
populatedObjects.Add(newObj);
}
}
else
{
populatedObjects.Add(obj2);
}
}
return populatedObjects;
}
private Trigger LoadTrigger(JToken token)
{
var json = token.ToObject<JObject>();
var trigger = new Trigger();
trigger.Type = json["type"] != null
? (TriggerType) Enum.Parse(typeof(TriggerType), (string) json["type"], true)
: TriggerType.None;
trigger.Uses = (int?) json.SelectToken("uses") ?? trigger.Uses;
trigger.Notes = json["notes"] != null ? json.SelectToken("notes").Values<int>().ToList() : trigger.Notes;
trigger.Spawn = json["spawn"] != null ? json.SelectToken("spawn").Values<string>().ToList() : trigger.Spawn;
trigger.Destroy = json["destroy"] != null
? json.SelectToken("destroy").Values<string>().ToList()
: trigger.Destroy;
trigger.Combo = (int?) json.SelectToken("combo") ?? trigger.Combo;
trigger.Score = (int?) json.SelectToken("score") ?? trigger.Score;
return trigger;
}
private TO LoadObject<TO, TS>(JToken token) where TO : Object<TS>, new() where TS : ObjectState, new()
{
var states = new List<TS>();
var obj = token.ToObject<JObject>();
// Create initial state
var initialState = (TS) CreateState((TS) null, obj);
states.Add(initialState);
// TODO: gfsd storyboard issue: template's first state should override initial state?
// Create template states
if (obj.TryGetValue("template", out var tmp))
{
var templateId = (string) tmp;
var templateObject = Templates[templateId];
// Template has states?
if (templateObject["states"] != null)
AddStates(states, initialState, templateObject, ParseTime(obj, obj.SelectToken("time")));
}
// Create inline states
AddStates(states, initialState, obj, ParseTime(obj, obj.SelectToken("time")));
var id = (string) obj["id"] ?? Path.GetRandomFileName();
var targetId = (string) obj.SelectToken("target_id");
if (targetId != null && obj["id"] != null) throw new ArgumentException("Storyboard: A stage object cannot have both id and target_id");
var parentId = (string) obj.SelectToken("parent_id");
if (targetId != null && parentId != null) throw new ArgumentException("Storyboard: A stage object cannot have both target_id and parent_id");
if (id.Contains("$note")) id = id.Replace("$note", ((int) replacements["note"]).ToString());
if (targetId != null && targetId.Contains("$note")) targetId = targetId.Replace("$note", ((int) replacements["note"]).ToString());
if (parentId != null && parentId.Contains("$note")) parentId = parentId.Replace("$note", ((int) replacements["note"]).ToString());
return new TO
{
Id = id,
TargetId = targetId,
ParentId = parentId,
States = states.OrderBy(state => state.Time).ToList() // Must sort by time
};
}
private void AddStates<TS>(List<TS> states, TS baseState, JObject rootObject, float? rootBaseTime)
where TS : ObjectState, new()
{
var baseTime = ParseTime(rootObject, rootObject.SelectToken("time")) ?? rootBaseTime ?? float.MaxValue; // We set this to float.MaxValue, so if time is not set, the object is not displayed
if (rootObject["states"] != null && rootObject["states"].Type != JTokenType.Null)
{
var lastTime = baseTime;
var allStates = new JArray();
foreach (var childToken in (JArray) rootObject["states"])
{
var populatedChildren = PopulateJObjects((JObject) childToken);
foreach (var child in populatedChildren) allStates.Add(child);
}
foreach (var stateJson in allStates)
{
var stateObject = stateJson.ToObject<JObject>();
var objectState = CreateState(baseState, stateObject);
if (objectState.Time != float.MaxValue) baseTime = objectState.Time;
var relativeTime = (float?) stateObject["relative_time"];
if (relativeTime != null)
{
objectState.RelativeTime = (float) relativeTime;
// Use base time + relative time
objectState.Time = baseTime + (float) relativeTime;
}
var addTime = (float?) stateObject["add_time"];
if (addTime != null)
{
objectState.AddTime = (float) addTime;
// Use last time + add time
objectState.Time = lastTime + (float) addTime;
}
states.Add((TS) objectState);
baseState = (TS) objectState;
lastTime = objectState.Time;
// Add inline states
if (stateObject["states"] != null) AddStates(states, baseState, stateObject, rootBaseTime);
}
}
}
private ObjectState CreateState<TS>(TS baseState, JObject stateObject) where TS : ObjectState, new()
{
if ((bool?) stateObject["reset"] == true) baseState = null; // Allow resetting states
// Load template
JObject templateObject = null;
if (stateObject["template"] != null)
{
var templateId = (string) stateObject["template"];
templateObject = Templates[templateId];
if (templateObject != null)
{
// Put relative time and add time
if (stateObject["relative_time"] == null)
stateObject["relative_time"] = templateObject["relative_time"];
if (stateObject["add_time"] == null) stateObject["add_time"] = templateObject["add_time"];
// Put template states
if (stateObject["states"] == null) stateObject["states"] = templateObject["states"];
}
}
var parser = CreateStateParser(typeof(TS));
var state = baseState != null ? baseState.JsonDeepCopy() : new TS();
if (templateObject != null) parser.Parse(state, templateObject, baseState);
parser.Parse(state, stateObject, baseState);
return state;
}
private readonly Dictionary<string, object> replacements = new Dictionary<string, object>();
public float? ParseTime(JObject obj, JToken token)
{
if (token == null) return null;
// var noteToken = obj.SelectToken("note");
// if (noteToken != null)
// {
// var value = (int) noteToken;
// replacements["note"] = value;
// return value;
// }
if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer) return (float) token;
if (token.Type == JTokenType.String)
{
var split = ((string) token).Split(':');
var type = split[0].ToLower();
var offset = 0f;
if (split.Length == 3) offset = float.Parse(split[2]);
var id = split[1].Let(it =>
{
if (it == "$note")
{
var noteToken = obj.SelectToken("note");
if (noteToken != null)
{
var value = (int) noteToken;
replacements["note"] = value;
return value;
}
if (!replacements.ContainsKey("note"))
{
throw new Exception("$note not found");
}
return (int) replacements["note"];
}
return int.Parse(it);
});
var note = Game.Chart.Model.note_map[id];
switch (type)
{
case "intro":
return note.intro_time + offset;
case "start":
return note.start_time + offset;
case "end":
return note.end_time + offset;
case "at":
return note.start_time + (note.end_time - note.start_time) * offset;
}
}
return null;
}
private StateParser CreateStateParser(Type stateType)
{
if (stateType == typeof(TextState)) return new TextStateParser(this);
if (stateType == typeof(SpriteState)) return new SpriteStateParser(this);
if (stateType == typeof(LineState)) return new LineStateParser(this);
if (stateType == typeof(VideoState)) return new VideoStateParser(this);
if (stateType == typeof(NoteControllerState)) return new NoteControllerStateParser(this);
if (stateType == typeof(ControllerState)) return new ControllerStateParser(this);
throw new ArgumentException();
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using ASC.Common.Logging;
using ASC.Files.Core;
using ASC.Mail.Data.Contracts;
using ASC.Mail.Data.Contracts.Base;
using ASC.Mail.Data.Storage;
using ASC.Mail.Exceptions;
using ASC.Mail.Utils;
using ASC.Web.Files.Services.WCFService;
using HtmlAgilityPack;
using MimeKit;
namespace ASC.Mail.Extensions
{
public static class MailDraftExtensions
{
public static MailMessageData ToMailMessage(this MailComposeBase draft)
{
MailboxAddress fromVerified;
if (string.IsNullOrEmpty(draft.From))
throw new DraftException(DraftException.ErrorTypes.EmptyField, "Empty email address in {0} field",
DraftFieldTypes.From);
if (!MailboxAddress.TryParse(ParserOptions.Default, draft.From, out fromVerified))
throw new DraftException(DraftException.ErrorTypes.IncorrectField, "Incorrect email address",
DraftFieldTypes.From);
if (string.IsNullOrEmpty(fromVerified.Name))
fromVerified.Name = draft.Mailbox.Name;
if (string.IsNullOrEmpty(draft.MimeMessageId))
throw new ArgumentException("MimeMessageId");
var messageItem = new MailMessageData
{
From = fromVerified.ToString(),
FromEmail = fromVerified.Address,
To = string.Join(", ", draft.To.ToArray()),
Cc = draft.Cc != null ? string.Join(", ", draft.Cc.ToArray()) : "",
Bcc = draft.Bcc != null ? string.Join(", ", draft.Bcc.ToArray()) : "",
Subject = draft.Subject,
Date = DateTime.UtcNow,
Important = draft.Important,
HtmlBody = draft.HtmlBody,
Introduction = MailUtil.GetIntroduction(draft.HtmlBody),
StreamId = draft.StreamId,
TagIds = draft.Labels != null && draft.Labels.Count != 0 ? new List<int>(draft.Labels) : null,
Size = draft.HtmlBody.Length,
MimeReplyToId = draft.MimeReplyToId,
MimeMessageId = draft.MimeMessageId,
IsNew = false,
Folder = draft.Folder,
ChainId = draft.MimeMessageId,
CalendarUid = draft.CalendarEventUid,
CalendarEventIcs = draft.CalendarIcs,
MailboxId = draft.Mailbox.MailBoxId
};
if (messageItem.Attachments == null)
{
messageItem.Attachments = new List<MailAttachmentData>();
}
draft.Attachments.ForEach(attachment =>
{
attachment.tenant = draft.Mailbox.TenantId;
attachment.user = draft.Mailbox.UserId;
});
messageItem.Attachments.AddRange(draft.Attachments);
messageItem.HasAttachments = messageItem.Attachments.Count > 0;
return messageItem;
}
public static MimeMessage ToMimeMessage(this MailDraftData draft)
{
var mimeMessage = new MimeMessage
{
Date = DateTime.UtcNow,
Subject = !string.IsNullOrEmpty(draft.Subject) ? draft.Subject : "",
MessageId = draft.MimeMessageId
};
var from = MailboxAddress.Parse(ParserOptions.Default, draft.From);
mimeMessage.From.Add(from);
if (draft.To.Any())
mimeMessage.To.AddRange(draft.To.ConvertAll(MailboxAddress.Parse));
if (draft.Cc.Any())
mimeMessage.Cc.AddRange(draft.Cc.ConvertAll(MailboxAddress.Parse));
if (draft.Bcc.Any())
mimeMessage.Bcc.AddRange(draft.Bcc.ConvertAll(MailboxAddress.Parse));
if (draft.Important)
mimeMessage.Importance = MessageImportance.High;
if (!string.IsNullOrEmpty(draft.MimeReplyToId))
mimeMessage.InReplyTo = draft.MimeReplyToId;
mimeMessage.Body = ToMimeMessageBody(draft);
if (draft.IsAutogenerated)
{
mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");
}
if (draft.IsAutoreplied)
{
mimeMessage.Headers.Add("Auto-Submitted", "auto-replied");
}
if (draft.RequestReceipt)
{
mimeMessage.Headers[HeaderId.ReturnReceiptTo] = from.ToString(true);
}
if (draft.RequestRead)
{
mimeMessage.Headers[HeaderId.DispositionNotificationTo] = from.ToString(true);
}
return mimeMessage;
}
private static MimePart ConvertToMimePart(MailAttachmentData mailAttachmentData, string contentId = null)
{
var contentType = ContentType.Parse(
!string.IsNullOrEmpty(mailAttachmentData.contentType)
? mailAttachmentData.contentType
: MimeMapping.GetMimeMapping(mailAttachmentData.fileName));
var mimePart = new MimePart(contentType)
{
ContentTransferEncoding = ContentEncoding.Base64,
FileName = mailAttachmentData.fileName
};
if (string.IsNullOrEmpty(contentId))
{
mimePart.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment);
}
else
{
mimePart.ContentDisposition = new ContentDisposition(ContentDisposition.Inline);
mimePart.ContentId = contentId;
mimePart.ContentType.Name = mailAttachmentData.fileName;
}
MemoryStream ms;
if (mailAttachmentData.data == null)
{
var s3Key = MailStoragePathCombiner.GerStoredFilePath(mailAttachmentData);
ms = new MemoryStream();
using (var stream = StorageManager
.GetDataStoreForAttachments(mailAttachmentData.tenant)
.GetReadStream(s3Key))
{
stream.CopyTo(ms);
}
}
else
{
ms = new MemoryStream(mailAttachmentData.data);
}
mimePart.Content = new MimeContent(ms);
Parameter param;
if (mimePart.ContentDisposition != null && mimePart.ContentDisposition.Parameters.TryGetValue("filename", out param))
param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
if (mimePart.ContentType.Parameters.TryGetValue("name", out param))
param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
return mimePart;
}
private static MimeEntity ToMimeMessageBody(MailDraftData draft)
{
string textBody;
MailUtil.TryExtractTextFromHtml(draft.HtmlBody, out textBody);
MultipartAlternative alternative = null;
MimeEntity body = null;
if (!string.IsNullOrEmpty(textBody))
{
var textPart = new TextPart("plain")
{
Text = textBody,
ContentTransferEncoding = ContentEncoding.QuotedPrintable
};
if (!string.IsNullOrEmpty(draft.HtmlBody))
{
alternative = new MultipartAlternative { textPart };
body = alternative;
}
else
body = textPart;
}
if (!string.IsNullOrEmpty(draft.HtmlBody))
{
var htmlPart = new TextPart("html")
{
Text = draft.HtmlBody,
ContentTransferEncoding = ContentEncoding.QuotedPrintable
};
MimeEntity html;
if (draft.AttachmentsEmbedded.Any())
{
htmlPart.ContentTransferEncoding = ContentEncoding.Base64;
var related = new MultipartRelated
{
Root = htmlPart
};
related.Root.ContentId = null;
foreach (var emb in draft.AttachmentsEmbedded)
{
var linkedResource = ConvertToMimePart(emb, emb.contentId);
related.Add(linkedResource);
}
html = related;
}
else
html = htmlPart;
if (alternative != null)
alternative.Add(html);
else
body = html;
}
if (!string.IsNullOrEmpty(draft.CalendarIcs))
{
var calendarPart = new TextPart("calendar")
{
Text = draft.CalendarIcs,
ContentTransferEncoding = ContentEncoding.QuotedPrintable
};
calendarPart.ContentType.Parameters.Add("method", draft.CalendarMethod);
if (alternative != null)
alternative.Add(calendarPart);
else
body = calendarPart;
}
if (draft.Attachments.Any() || !string.IsNullOrEmpty(draft.CalendarIcs))
{
var mixed = new Multipart("mixed");
if (body != null)
mixed.Add(body);
foreach (var att in draft.Attachments)
{
var attachment = ConvertToMimePart(att);
mixed.Add(attachment);
}
if (!string.IsNullOrEmpty(draft.CalendarIcs))
{
var filename = "calendar.ics";
switch (draft.CalendarMethod)
{
case Defines.ICAL_REQUEST:
filename = "invite.ics";
break;
case Defines.ICAL_REPLY:
filename = "reply.ics";
break;
case Defines.ICAL_CANCEL:
filename = "cancel.ics";
break;
}
var contentType = new ContentType("application", "ics");
contentType.Parameters.Add("method", draft.CalendarMethod);
contentType.Parameters.Add("name", filename);
var calendarResource = new MimePart(contentType)
{
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = filename
};
var data = Encoding.UTF8.GetBytes(draft.CalendarIcs);
var ms = new MemoryStream(data);
calendarResource.Content = new MimeContent(ms);
mixed.Add(calendarResource);
}
body = mixed;
}
if (body != null)
return body;
return new TextPart("plain")
{
Text = string.Empty
};
}
public static void ChangeAttachedFileLinksAddresses(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes("//a[contains(@class,'mailmessage-filelink-link')]");
if (linkNodes == null) return;
var fileStorageService = new FileStorageServiceController();
var setLinks = new List<Tuple<string, string>>();
foreach (var linkNode in linkNodes)
{
var fileId = linkNode.Attributes["data-fileid"].Value;
var objectId = "file_" + fileId;
linkNode.Attributes["class"].Remove(); // 'mailmessage-filelink-link'
linkNode.Attributes["data-fileid"].Remove(); // 'data-fileid'
var setLink = setLinks.SingleOrDefault(x => x.Item1 == fileId);
if (setLink != null)
{
linkNode.SetAttributeValue("href", setLink.Item2);
log.InfoFormat("ChangeAttachedFileLinks() Change file link href: {0}", fileId);
continue;
}
var aceCollection = new AceCollection
{
Entries = new ItemList<string> { objectId },
Aces = new ItemList<AceWrapper>
{
new AceWrapper
{
SubjectId = FileConstant.ShareLinkId,
SubjectGroup = true,
Share = draft.FileLinksShareMode
}
}
};
fileStorageService.SetAceObject(aceCollection, false);
log.InfoFormat("ChangeAttachedFileLinks() Set public accees to file: {0}", fileId);
var sharedInfo =
fileStorageService.GetSharedInfo(new ItemList<string> { objectId })
.Find(r => r.SubjectId == FileConstant.ShareLinkId);
linkNode.SetAttributeValue("href", sharedInfo.Link);
log.InfoFormat("ChangeAttachedFileLinks() Change file link href: {0}", fileId);
setLinks.Add(new Tuple<string, string>(fileId, sharedInfo.Link));
}
linkNodes = doc.DocumentNode.SelectNodes("//div[contains(@class,'mailmessage-filelink')]");
foreach (var linkNode in linkNodes)
{
linkNode.Attributes["class"].Remove();
}
draft.HtmlBody = doc.DocumentNode.OuterHtml;
}
public static List<string> GetEmbeddedAttachmentLinks(this MailComposeBase draft)
{
var links = new List<string>();
var fckStorage = StorageManager.GetDataStoreForCkImages(draft.Mailbox.TenantId);
//todo: replace selector
var currentMailFckeditorUrl = fckStorage.GetUri(StorageManager.CKEDITOR_IMAGES_DOMAIN, "").ToString();
var currentMailAttachmentFolderUrl = MailStoragePathCombiner.GetMessageDirectory(draft.Mailbox.UserId,
draft.StreamId);
var currentUserStorageUrl = MailStoragePathCombiner.GetUserMailsDirectory(draft.Mailbox.UserId);
var xpathQuery = StorageManager.GetXpathQueryForAttachmentsToResaving(currentMailFckeditorUrl,
currentMailAttachmentFolderUrl,
currentUserStorageUrl);
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes(xpathQuery);
if (linkNodes == null)
return links;
links.AddRange(linkNodes.Select(linkNode => linkNode.Attributes["src"].Value));
return links;
}
public static void ChangeEmbeddedAttachmentLinks(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
var baseAttachmentFolder = MailStoragePathCombiner.GetMessageDirectory(draft.Mailbox.UserId, draft.StreamId);
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes("//img[@src and (contains(@src,'" + baseAttachmentFolder + "'))]");
if (linkNodes == null) return;
foreach (var linkNode in linkNodes)
{
var link = linkNode.Attributes["src"].Value;
log.InfoFormat("ChangeEmbededAttachmentLinks() Embeded attachment link for changing to cid: {0}", link);
var fileLink = HttpUtility.UrlDecode(link.Substring(baseAttachmentFolder.Length));
var fileName = Path.GetFileName(fileLink);
var attach = CreateEmbbededAttachment(fileName, link, fileLink, draft.Mailbox.UserId, draft.Mailbox.TenantId, draft.Mailbox.MailBoxId, draft.StreamId);
draft.AttachmentsEmbedded.Add(attach);
linkNode.SetAttributeValue("src", "cid:" + attach.contentId);
log.InfoFormat("ChangeEmbededAttachmentLinks() Attachment cid: {0}", attach.contentId);
}
draft.HtmlBody = doc.DocumentNode.OuterHtml;
}
public static void ChangeSmileLinks(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
var baseSmileUrl = MailStoragePathCombiner.GetEditorSmileBaseUrl();
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes("//img[@src and (contains(@src,'" + baseSmileUrl + "'))]");
if (linkNodes == null) return;
foreach (var linkNode in linkNodes)
{
var link = linkNode.Attributes["src"].Value;
log.InfoFormat("ChangeSmileLinks() Link to smile: {0}", link);
var fileName = Path.GetFileName(link);
var data = StorageManager.LoadLinkData(link, log);
if (!data.Any())
continue;
var attach = new MailAttachmentData
{
fileName = fileName,
storedName = fileName,
contentId = link.GetMd5(),
data = data
};
log.InfoFormat("ChangeSmileLinks() Embedded smile contentId: {0}", attach.contentId);
linkNode.SetAttributeValue("src", "cid:" + attach.contentId);
if (draft.AttachmentsEmbedded.All(x => x.contentId != attach.contentId))
{
draft.AttachmentsEmbedded.Add(attach);
}
}
draft.HtmlBody = doc.DocumentNode.OuterHtml;
}
public static void ChangeUrlProxyLinks(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
try
{
draft.HtmlBody = HtmlSanitizer.RemoveProxyHttpUrls(draft.HtmlBody);
}
catch (Exception ex)
{
log.ErrorFormat("ChangeUrlProxyLinks(): Exception: {0}", ex.ToString());
}
}
public static void ChangeAttachedFileLinksImages(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
var baseSmileUrl = MailStoragePathCombiner.GetEditorImagesBaseUrl();
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes("//img[@src and (contains(@src,'" + baseSmileUrl + "'))]");
if (linkNodes == null) return;
foreach (var linkNode in linkNodes)
{
var link = linkNode.Attributes["src"].Value;
log.InfoFormat("ChangeAttachedFileLinksImages() Link to file link: {0}", link);
var fileName = Path.GetFileName(link);
var data = StorageManager.LoadLinkData(link, log);
if (!data.Any())
continue;
var attach = new MailAttachmentData
{
fileName = fileName,
storedName = fileName,
contentId = link.GetMd5(),
data = data
};
log.InfoFormat("ChangeAttachedFileLinksImages() Embedded file link contentId: {0}", attach.contentId);
linkNode.SetAttributeValue("src", "cid:" + attach.contentId);
if (draft.AttachmentsEmbedded.All(x => x.contentId != attach.contentId))
{
draft.AttachmentsEmbedded.Add(attach);
}
}
draft.HtmlBody = doc.DocumentNode.OuterHtml;
}
public static void ChangeAllImagesLinksToEmbedded(this MailDraftData draft, ILog log = null)
{
if (log == null)
log = new NullLog();
try
{
var doc = new HtmlDocument();
doc.LoadHtml(draft.HtmlBody);
var linkNodes = doc.DocumentNode.SelectNodes("//img[@src]");
if (linkNodes == null) return;
foreach (var linkNode in linkNodes)
{
var link = linkNode.Attributes["src"].Value;
log.InfoFormat("ChangeAllImagesLinksToEmbedded() Link to img link: {0}", link);
var fileName = Path.GetFileName(link);
var data = StorageManager.LoadLinkData(link, log);
if (!data.Any())
continue;
var attach = new MailAttachmentData
{
fileName = fileName,
storedName = fileName,
contentId = link.GetMd5(),
data = data
};
log.InfoFormat("ChangeAllImagesLinksToEmbedded() Embedded img link contentId: {0}", attach.contentId);
linkNode.SetAttributeValue("src", "cid:" + attach.contentId);
if (draft.AttachmentsEmbedded.All(x => x.contentId != attach.contentId))
{
draft.AttachmentsEmbedded.Add(attach);
}
}
draft.HtmlBody = doc.DocumentNode.OuterHtml;
}
catch (Exception ex)
{
log.ErrorFormat("ChangeAllImagesLinksToEmbedded(): Exception: {0}", ex.ToString());
}
}
private static MailAttachmentData CreateEmbbededAttachment(string fileName, string link, string fileLink, string user,
int tenant, int mailboxId, string streamId)
{
return new MailAttachmentData
{
fileName = fileName,
storedName = fileName,
contentId = link.GetMd5(),
storedFileUrl = fileLink,
streamId = streamId,
user = user,
tenant = tenant,
mailboxId = mailboxId
};
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.